From c0d17b19d3037919152895d606440d3e13919061 Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Fri, 15 Jan 2021 09:58:26 -0800 Subject: [PATCH 001/694] Add NativeMediaDrmClearkeyTest to TreeHugger presubmit Adding 8 or more tests to cover media drm ndk APIs for TreeHugger presubmit. Test: atest run atest in this directory which invokes the presubmit tests Bug: 173646795 Change-Id: I036b1c56437568904826f8085848ffa5e911f658 --- drm/mediadrm/plugins/TEST_MAPPING | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drm/mediadrm/plugins/TEST_MAPPING b/drm/mediadrm/plugins/TEST_MAPPING index 7bd15687b3..87becb6112 100644 --- a/drm/mediadrm/plugins/TEST_MAPPING +++ b/drm/mediadrm/plugins/TEST_MAPPING @@ -11,6 +11,9 @@ }, { "include-filter": "android.media.cts.MediaDrmMetricsTest" + }, + { + "include-filter": "android.media.cts.NativeMediaDrmClearkeyTest" } ] } -- GitLab From d9cb9b7de5cba9bc12b90ec2f001f9634dd294d6 Mon Sep 17 00:00:00 2001 From: Harish Mahendrakar Date: Tue, 22 Dec 2020 12:49:17 -0800 Subject: [PATCH 002/694] C2SoftAvcEnc: Use dimensions from mSize instead of input buffer Bug: 172908358 Test: poc in bug Test: atest MediaTrackTranscoderTests Test: atest CtsMediaV2TestCases Change-Id: I84ffe9e93e782f40686db676bea7091966ff4dff --- media/codec2/components/avc/C2SoftAvcEnc.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/media/codec2/components/avc/C2SoftAvcEnc.cpp b/media/codec2/components/avc/C2SoftAvcEnc.cpp index cfaeb66077..274f19ad97 100644 --- a/media/codec2/components/avc/C2SoftAvcEnc.cpp +++ b/media/codec2/components/avc/C2SoftAvcEnc.cpp @@ -1328,13 +1328,13 @@ c2_status_t C2SoftAvcEnc::setEncodeArgs( ps_inp_raw_buf->apv_bufs[1] = uPlane; ps_inp_raw_buf->apv_bufs[2] = vPlane; - ps_inp_raw_buf->au4_wd[0] = input->width(); - ps_inp_raw_buf->au4_wd[1] = input->width() / 2; - ps_inp_raw_buf->au4_wd[2] = input->width() / 2; + ps_inp_raw_buf->au4_wd[0] = mSize->width; + ps_inp_raw_buf->au4_wd[1] = mSize->width / 2; + ps_inp_raw_buf->au4_wd[2] = mSize->width / 2; - ps_inp_raw_buf->au4_ht[0] = input->height(); - ps_inp_raw_buf->au4_ht[1] = input->height() / 2; - ps_inp_raw_buf->au4_ht[2] = input->height() / 2; + ps_inp_raw_buf->au4_ht[0] = mSize->height; + ps_inp_raw_buf->au4_ht[1] = mSize->height / 2; + ps_inp_raw_buf->au4_ht[2] = mSize->height / 2; ps_inp_raw_buf->au4_strd[0] = yStride; ps_inp_raw_buf->au4_strd[1] = uStride; @@ -1359,11 +1359,11 @@ c2_status_t C2SoftAvcEnc::setEncodeArgs( ps_inp_raw_buf->apv_bufs[0] = yPlane; ps_inp_raw_buf->apv_bufs[1] = uPlane; - ps_inp_raw_buf->au4_wd[0] = input->width(); - ps_inp_raw_buf->au4_wd[1] = input->width(); + ps_inp_raw_buf->au4_wd[0] = mSize->width; + ps_inp_raw_buf->au4_wd[1] = mSize->width; - ps_inp_raw_buf->au4_ht[0] = input->height(); - ps_inp_raw_buf->au4_ht[1] = input->height() / 2; + ps_inp_raw_buf->au4_ht[0] = mSize->height; + ps_inp_raw_buf->au4_ht[1] = mSize->height / 2; ps_inp_raw_buf->au4_strd[0] = yStride; ps_inp_raw_buf->au4_strd[1] = uStride; -- GitLab From ccdb64a26992b2b6d3885e6df9216c38c28df65a Mon Sep 17 00:00:00 2001 From: Hyundo Moon Date: Tue, 5 Jan 2021 10:50:04 +0900 Subject: [PATCH 003/694] Include "service-media-s" in media apex Bug: 175511943 Test: MediaCommunicationService can run. 'adb shell service list' shows the service. Change-Id: I4f87f3c1d3131ef6749712c7cc62297ba2c54b65 --- apex/Android.bp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apex/Android.bp b/apex/Android.bp index bf91bf7150..d8a0b91f86 100644 --- a/apex/Android.bp +++ b/apex/Android.bp @@ -15,7 +15,10 @@ apex_defaults { name: "com.android.media-defaults", updatable: true, - java_libs: ["updatable-media"], + java_libs: [ + "updatable-media", + "service-media-s", + ], multilib: { first: { // Extractor process runs only with the primary ABI. -- GitLab From 4ad3465293ee4865231f8e078ce269e7bf393e75 Mon Sep 17 00:00:00 2001 From: Vignesh Venkatasubramanian Date: Mon, 25 Jan 2021 09:42:44 -0800 Subject: [PATCH 004/694] gav1: Increase max supported resolution to 4096x4096 This brings the AV1 decoder in line with other modern codecs. It also helps the software decoder to decode most practical AVIF images. Bug: 141654151 Test: Media CTS tests still pass Change-Id: Iedbd41f2336585a5d769b1d9c94e40d6e0d155ed --- media/codec2/components/gav1/C2SoftGav1Dec.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/media/codec2/components/gav1/C2SoftGav1Dec.cpp b/media/codec2/components/gav1/C2SoftGav1Dec.cpp index 76345ae77e..1cf361035d 100644 --- a/media/codec2/components/gav1/C2SoftGav1Dec.cpp +++ b/media/codec2/components/gav1/C2SoftGav1Dec.cpp @@ -51,8 +51,8 @@ class C2SoftGav1Dec::IntfImpl : public SimpleInterface::BaseParams { DefineParam(mSize, C2_PARAMKEY_PICTURE_SIZE) .withDefault(new C2StreamPictureSizeInfo::output(0u, 320, 240)) .withFields({ - C2F(mSize, width).inRange(2, 2048, 2), - C2F(mSize, height).inRange(2, 2048, 2), + C2F(mSize, width).inRange(2, 4096, 2), + C2F(mSize, height).inRange(2, 4096, 2), }) .withSetter(SizeSetter) .build()); -- GitLab From 9b884e681b83f69a0b775564bf4190c39fa4c686 Mon Sep 17 00:00:00 2001 From: Neelkamal Semwal Date: Mon, 14 Dec 2020 18:28:51 +0530 Subject: [PATCH 005/694] AMRNB Encoder: Restrict pitch to a valid value Valid pitch value is required to prevent out of bound access Test: poc in bug description Bug: 172312730 Change-Id: I3cbb5d5fb9a3c5ad204f2af52bef72daea1b429f --- media/codecs/amrnb/enc/src/pitch_fr.cpp | 48 ++++++++++++++++++------- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/media/codecs/amrnb/enc/src/pitch_fr.cpp b/media/codecs/amrnb/enc/src/pitch_fr.cpp index 5a846fa624..584f79b727 100644 --- a/media/codecs/amrnb/enc/src/pitch_fr.cpp +++ b/media/codecs/amrnb/enc/src/pitch_fr.cpp @@ -570,12 +570,14 @@ static void searchFrac( Word16 corr[], /* i : normalized correlation */ Word16 flag3, /* i : subsample resolution (3: =1 / 6: =0) */ - Flag *pOverflow + Flag *pOverflow, + enum Mode mode ) { Word16 i; Word16 max; Word16 corr_int; + Word16 minPitch; /* Test the fractions around T0 and choose the one which maximizes */ /* the interpolated normalized correlation. */ @@ -593,14 +595,22 @@ static void searchFrac( } } + minPitch = (mode == MR122) ? PIT_MIN_MR122 : PIT_MIN; if (flag3 == 0) { /* Limit the fraction value in the interval [-2,-1,0,1,2,3] */ if (*frac == -3) { - *frac = 3; - (*lag)--; + if (*lag > minPitch) + { + *frac = 3; + (*lag)--; + } + else + { + *frac = -2; + } } } else @@ -609,13 +619,27 @@ static void searchFrac( if (*frac == -2) { - *frac = 1; - (*lag)--; + if (*lag > minPitch) + { + *frac = 1; + (*lag)--; + } + else + { + *frac = -1; + } } - if (*frac == 2) + else if (*frac == 2) { - *frac = -1; - (*lag)++; + if (*lag < PIT_MAX) + { + *frac = -1; + (*lag)++; + } + else + { + *frac = 1; + } } } } @@ -1533,20 +1557,20 @@ Word16 Pitch_fr( /* o : pitch period (integer) */ /* normal search in fractions around T0 */ - searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow); + searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow, mode); } else if (lag == (tmp_lag - 2)) { /* limit search around T0 to the right side */ frac = 0; - searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow); + searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow, mode); } else if (lag == (tmp_lag + 1)) { /* limit search around T0 to the left side */ last_frac = 0; - searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow); + searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow, mode); } else { @@ -1556,7 +1580,7 @@ Word16 Pitch_fr( /* o : pitch period (integer) */ } else /* test the fractions around T0 */ - searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow); + searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow, mode); } /*-----------------------------------------------------------------------* -- GitLab From af152a4a16aa40fa40b06b59ae2b885519787de7 Mon Sep 17 00:00:00 2001 From: Amy Zhang Date: Tue, 26 Jan 2021 16:28:19 -0800 Subject: [PATCH 006/694] Implement MediaFilter/MediaEvents core path in Tuner Service Test: tuner sample tis on cuttlefish Bug: 159067322 Change-Id: I37b7338e8c7b02bbf562f67da81088d07b2a807f --- services/tuner/TunerDemux.cpp | 13 + services/tuner/TunerDemux.h | 1 + services/tuner/TunerFilter.cpp | 68 +++- services/tuner/TunerFilter.h | 7 +- services/tuner/TunerFrontend.cpp | 376 ++++++++++-------- services/tuner/TunerFrontend.h | 2 + .../android/media/tv/tuner/ITunerDemux.aidl | 5 + .../android/media/tv/tuner/ITunerFilter.aidl | 17 + .../media/tv/tuner/ITunerFilterCallback.aidl | 2 +- .../tv/tuner/TunerFilterSharedHandleInfo.aidl | 29 ++ 10 files changed, 346 insertions(+), 174 deletions(-) create mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl diff --git a/services/tuner/TunerDemux.cpp b/services/tuner/TunerDemux.cpp index 0e0cd3b64a..1f8b70dbed 100644 --- a/services/tuner/TunerDemux.cpp +++ b/services/tuner/TunerDemux.cpp @@ -124,4 +124,17 @@ Status TunerDemux::openDvr(int dvrType, int bufferSize, const shared_ptr(hidlDvr, dvrType); return Status::ok(); } + +Status TunerDemux::close() { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result res = mDemux->close(); + if (res != Result::SUCCESS) { + return Status::fromServiceSpecificError(static_cast(res)); + } + return Status::ok(); +} } // namespace android diff --git a/services/tuner/TunerDemux.h b/services/tuner/TunerDemux.h index 675bb7c471..594fd66fc3 100644 --- a/services/tuner/TunerDemux.h +++ b/services/tuner/TunerDemux.h @@ -47,6 +47,7 @@ public: Status openDvr( int dvbType, int bufferSize, const shared_ptr& cb, shared_ptr* _aidl_return) override; + Status close() override; private: sp mDemux; diff --git a/services/tuner/TunerFilter.cpp b/services/tuner/TunerFilter.cpp index 722d36d51b..edfc291333 100644 --- a/services/tuner/TunerFilter.cpp +++ b/services/tuner/TunerFilter.cpp @@ -16,16 +16,19 @@ #define LOG_TAG "TunerFilter" -#include #include "TunerFilter.h" +using ::android::hardware::hidl_handle; +using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings; +using ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterType; using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings; +using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; using ::android::hardware::tv::tuner::V1_0::Result; - namespace android { -TunerFilter::TunerFilter(sp filter, sp callback) { +TunerFilter::TunerFilter( + sp filter, sp callback) { mFilter = filter; mFilter_1_1 = ::android::hardware::tv::tuner::V1_1::IFilter::castFrom(filter); mFilterCallback = callback; @@ -103,6 +106,7 @@ Status TunerFilter::configure(const TunerFilterConfiguration& config) { break; } } + halSettings.ts(ts); break; } } @@ -113,6 +117,44 @@ Status TunerFilter::configure(const TunerFilterConfiguration& config) { return Status::ok(); } +Status TunerFilter::getAvSharedHandleInfo(TunerFilterSharedHandleInfo* _aidl_return) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result res; + mFilter_1_1->getAvSharedHandle([&](Result r, hidl_handle avMemory, uint64_t avMemSize) { + res = r; + if (res == Result::SUCCESS) { + TunerFilterSharedHandleInfo info{ + .handle = dupToAidl(hidl_handle(avMemory.getNativeHandle())), + .size = static_cast(avMemSize), + }; + *_aidl_return = std::move(info); + } else { + _aidl_return = NULL; + } + }); + + return Status::fromServiceSpecificError(static_cast(res)); +} + +Status TunerFilter::releaseAvHandle( + const ::aidl::android::hardware::common::NativeHandle& handle, int64_t avDataId) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result res = mFilter->releaseAvHandle(hidl_handle(makeFromAidl(handle)), avDataId); + if (res != Result::SUCCESS) { + return Status::fromServiceSpecificError(static_cast(res)); + } + return Status::ok(); +} + + Status TunerFilter::start() { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); @@ -149,6 +191,18 @@ Status TunerFilter::flush() { return Status::ok(); } +Status TunerFilter::close() { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + Result res = mFilter->close(); + if (res != Result::SUCCESS) { + return Status::fromServiceSpecificError(static_cast(res)); + } + return Status::ok(); +} + sp TunerFilter::getHalFilter() { return mFilter; } @@ -164,8 +218,8 @@ void TunerFilter::FilterCallback::getMediaEvent( tunerMedia.streamId = static_cast(mediaEvent.streamId); tunerMedia.isPtsPresent = mediaEvent.isPtsPresent; tunerMedia.pts = static_cast(mediaEvent.pts); - tunerMedia.dataLength = static_cast(mediaEvent.dataLength); - tunerMedia.offset = static_cast(mediaEvent.offset); + tunerMedia.dataLength = static_cast(mediaEvent.dataLength); + tunerMedia.offset = static_cast(mediaEvent.offset); tunerMedia.isSecureMemory = mediaEvent.isSecureMemory; tunerMedia.avDataId = static_cast(mediaEvent.avDataId); tunerMedia.mpuSequenceNumber = static_cast(mediaEvent.mpuSequenceNumber); @@ -187,7 +241,6 @@ Return TunerFilter::FilterCallback::onFilterStatus(DemuxFilterStatus statu } Return TunerFilter::FilterCallback::onFilterEvent(const DemuxFilterEvent& filterEvent) { - ALOGD("FilterCallback::onFilterEvent"); std::vector events = filterEvent.events; std::vector tunerEvent; @@ -203,7 +256,8 @@ Return TunerFilter::FilterCallback::onFilterEvent(const DemuxFilterEvent& } } } - mTunerFilterCallback->onFilterEvent(&tunerEvent); + + mTunerFilterCallback->onFilterEvent(tunerEvent); return Void(); } diff --git a/services/tuner/TunerFilter.h b/services/tuner/TunerFilter.h index 7f5838c377..2f10435b4b 100644 --- a/services/tuner/TunerFilter.h +++ b/services/tuner/TunerFilter.h @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -29,6 +30,7 @@ using ::aidl::android::media::tv::tuner::ITunerFilterCallback; using ::aidl::android::media::tv::tuner::TunerFilterConfiguration; using ::aidl::android::media::tv::tuner::TunerFilterEvent; using ::aidl::android::media::tv::tuner::TunerFilterMediaEvent; +using ::aidl::android::media::tv::tuner::TunerFilterSharedHandleInfo; using ::aidl::android::media::tv::tuner::TunerFilterSettings; using ::android::hardware::Return; using ::android::hardware::Void; @@ -39,7 +41,6 @@ using ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; using ::android::hardware::tv::tuner::V1_0::IFilter; using ::android::hardware::tv::tuner::V1_0::IFilterCallback; - namespace android { class TunerFilter : public BnTunerFilter { @@ -50,9 +51,13 @@ public: Status getId(int32_t* _aidl_return) override; Status getId64Bit(int64_t* _aidl_return) override; Status configure(const TunerFilterConfiguration& config) override; + Status getAvSharedHandleInfo(TunerFilterSharedHandleInfo* _aidl_return) override; + Status releaseAvHandle(const ::aidl::android::hardware::common::NativeHandle& handle, + int64_t avDataId) override; Status start() override; Status stop() override; Status flush() override; + Status close() override; sp getHalFilter(); struct FilterCallback : public IFilterCallback { diff --git a/services/tuner/TunerFrontend.cpp b/services/tuner/TunerFrontend.cpp index e92489d6e6..bb8b07da56 100644 --- a/services/tuner/TunerFrontend.cpp +++ b/services/tuner/TunerFrontend.cpp @@ -66,7 +66,6 @@ using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtModulation; using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtSettings; using ::android::hardware::tv::tuner::V1_0::FrontendScanAtsc3PlpInfo; using ::android::hardware::tv::tuner::V1_0::FrontendScanType; -using ::android::hardware::tv::tuner::V1_0::FrontendSettings;; using ::android::hardware::tv::tuner::V1_0::Result; using ::android::hardware::tv::tuner::V1_1::FrontendModulation; @@ -80,6 +79,7 @@ TunerFrontend::TunerFrontend(sp frontend, int id) { TunerFrontend::~TunerFrontend() { mFrontend = NULL; + mFrontend_1_1 = NULL; mId = -1; } @@ -103,12 +103,33 @@ Status TunerFrontend::setCallback( return Status::fromServiceSpecificError(static_cast(status)); } -Status TunerFrontend::tune(const TunerFrontendSettings& /*settings*/) { - return Status::ok(); +Status TunerFrontend::tune(const TunerFrontendSettings& settings) { + if (mFrontend == NULL) { + ALOGD("IFrontend is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + FrontendSettings frontendSettings = getHidlFrontendSettings(settings); + Result status = mFrontend->tune(frontendSettings); + if (status == Result::SUCCESS) { + return Status::ok(); + } + + return Status::fromServiceSpecificError(static_cast(status)); } Status TunerFrontend::stopTune() { - return Status::ok(); + if (mFrontend == NULL) { + ALOGD("IFrontend is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result status = mFrontend->stopTune(); + if (status == Result::SUCCESS) { + return Status::ok(); + } + + return Status::fromServiceSpecificError(static_cast(status)); } Status TunerFrontend::scan(const TunerFrontendSettings& settings, int frontendScanType) { @@ -117,165 +138,7 @@ Status TunerFrontend::scan(const TunerFrontendSettings& settings, int frontendSc return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); } - // TODO: extend TunerFrontendSettings to use 1.1 types - FrontendSettings frontendSettings; - switch (settings.getTag()) { - case TunerFrontendSettings::analog: - frontendSettings.analog({ - .frequency = static_cast( - settings.get().frequency), - .type = static_cast( - settings.get().signalType), - .sifStandard = static_cast( - settings.get().sifStandard), - }); - break; - case TunerFrontendSettings::atsc: - frontendSettings.atsc({ - .frequency = static_cast( - settings.get().frequency), - .modulation = static_cast( - settings.get().modulation), - }); - break; - case TunerFrontendSettings::atsc3: - frontendSettings.atsc3({ - .frequency = static_cast( - settings.get().frequency), - .bandwidth = static_cast( - settings.get().bandwidth), - .demodOutputFormat = static_cast( - settings.get().demodOutputFormat), - .plpSettings = getAtsc3PlpSettings(settings.get()), - }); - break; - case TunerFrontendSettings::cable: - frontendSettings.dvbc({ - .frequency = static_cast( - settings.get().frequency), - .modulation = static_cast( - settings.get().modulation), - .fec = static_cast( - settings.get().innerFec), - .symbolRate = static_cast( - settings.get().symbolRate), - .outerFec = static_cast( - settings.get().outerFec), - .annex = static_cast( - settings.get().annex), - .spectralInversion = static_cast( - settings.get().spectralInversion), - }); - break; - case TunerFrontendSettings::dvbs: - frontendSettings.dvbs({ - .frequency = static_cast( - settings.get().frequency), - .modulation = static_cast( - settings.get().modulation), - .coderate = getDvbsCodeRate( - settings.get().codeRate), - .symbolRate = static_cast( - settings.get().symbolRate), - .rolloff = static_cast( - settings.get().rolloff), - .pilot = static_cast( - settings.get().pilot), - .inputStreamId = static_cast( - settings.get().inputStreamId), - .standard = static_cast( - settings.get().standard), - .vcmMode = static_cast( - settings.get().vcm), - }); - break; - case TunerFrontendSettings::dvbt: - frontendSettings.dvbt({ - .frequency = static_cast( - settings.get().frequency), - .transmissionMode = static_cast( - settings.get().transmissionMode), - .bandwidth = static_cast( - settings.get().bandwidth), - .constellation = static_cast( - settings.get().constellation), - .hierarchy = static_cast( - settings.get().hierarchy), - .hpCoderate = static_cast( - settings.get().hpCodeRate), - .lpCoderate = static_cast( - settings.get().lpCodeRate), - .guardInterval = static_cast( - settings.get().guardInterval), - .isHighPriority = settings.get().isHighPriority, - .standard = static_cast( - settings.get().standard), - .isMiso = settings.get().isMiso, - .plpMode = static_cast( - settings.get().plpMode), - .plpId = static_cast( - settings.get().plpId), - .plpGroupId = static_cast( - settings.get().plpGroupId), - }); - break; - case TunerFrontendSettings::isdbs: - frontendSettings.isdbs({ - .frequency = static_cast( - settings.get().frequency), - .streamId = static_cast( - settings.get().streamId), - .streamIdType = static_cast( - settings.get().streamIdType), - .modulation = static_cast( - settings.get().modulation), - .coderate = static_cast( - settings.get().codeRate), - .symbolRate = static_cast( - settings.get().symbolRate), - .rolloff = static_cast( - settings.get().rolloff), - }); - break; - case TunerFrontendSettings::isdbs3: - frontendSettings.isdbs3({ - .frequency = static_cast( - settings.get().frequency), - .streamId = static_cast( - settings.get().streamId), - .streamIdType = static_cast( - settings.get().streamIdType), - .modulation = static_cast( - settings.get().modulation), - .coderate = static_cast( - settings.get().codeRate), - .symbolRate = static_cast( - settings.get().symbolRate), - .rolloff = static_cast( - settings.get().rolloff), - }); - break; - case TunerFrontendSettings::isdbt: - frontendSettings.isdbt({ - .frequency = static_cast( - settings.get().frequency), - .modulation = static_cast( - settings.get().modulation), - .bandwidth = static_cast( - settings.get().bandwidth), - .mode = static_cast( - settings.get().mode), - .coderate = static_cast( - settings.get().codeRate), - .guardInterval = static_cast( - settings.get().guardInterval), - .serviceAreaId = static_cast( - settings.get().serviceAreaId), - }); - break; - default: - break; - } + FrontendSettings frontendSettings = getHidlFrontendSettings(settings); Result status = mFrontend->scan( frontendSettings, static_cast(frontendScanType)); if (status == Result::SUCCESS) { @@ -286,7 +149,17 @@ Status TunerFrontend::scan(const TunerFrontendSettings& settings, int frontendSc } Status TunerFrontend::stopScan() { - return Status::ok(); + if (mFrontend == NULL) { + ALOGD("IFrontend is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result status = mFrontend->stopScan(); + if (status == Result::SUCCESS) { + return Status::ok(); + } + + return Status::fromServiceSpecificError(static_cast(status)); } Status TunerFrontend::setLnb(int /*lnbHandle*/) { @@ -298,7 +171,17 @@ Status TunerFrontend::setLna(bool /*bEnable*/) { } Status TunerFrontend::close() { - return Status::ok(); + if (mFrontend == NULL) { + ALOGD("IFrontend is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result status = mFrontend->close(); + if (status == Result::SUCCESS) { + return Status::ok(); + } + + return Status::fromServiceSpecificError(static_cast(status)); } Status TunerFrontend::getStatus(const vector& /*statusTypes*/, @@ -500,4 +383,167 @@ FrontendDvbsCodeRate TunerFrontend::getDvbsCodeRate(const TunerFrontendDvbsCodeR }; return coderate; } + +FrontendSettings TunerFrontend::getHidlFrontendSettings(const TunerFrontendSettings& settings) { + // TODO: extend TunerFrontendSettings to use 1.1 types + FrontendSettings frontendSettings; + switch (settings.getTag()) { + case TunerFrontendSettings::analog: + frontendSettings.analog({ + .frequency = static_cast( + settings.get().frequency), + .type = static_cast( + settings.get().signalType), + .sifStandard = static_cast( + settings.get().sifStandard), + }); + break; + case TunerFrontendSettings::atsc: + frontendSettings.atsc({ + .frequency = static_cast( + settings.get().frequency), + .modulation = static_cast( + settings.get().modulation), + }); + break; + case TunerFrontendSettings::atsc3: + frontendSettings.atsc3({ + .frequency = static_cast( + settings.get().frequency), + .bandwidth = static_cast( + settings.get().bandwidth), + .demodOutputFormat = static_cast( + settings.get().demodOutputFormat), + .plpSettings = getAtsc3PlpSettings(settings.get()), + }); + break; + case TunerFrontendSettings::cable: + frontendSettings.dvbc({ + .frequency = static_cast( + settings.get().frequency), + .modulation = static_cast( + settings.get().modulation), + .fec = static_cast( + settings.get().innerFec), + .symbolRate = static_cast( + settings.get().symbolRate), + .outerFec = static_cast( + settings.get().outerFec), + .annex = static_cast( + settings.get().annex), + .spectralInversion = static_cast( + settings.get().spectralInversion), + }); + break; + case TunerFrontendSettings::dvbs: + frontendSettings.dvbs({ + .frequency = static_cast( + settings.get().frequency), + .modulation = static_cast( + settings.get().modulation), + .coderate = getDvbsCodeRate( + settings.get().codeRate), + .symbolRate = static_cast( + settings.get().symbolRate), + .rolloff = static_cast( + settings.get().rolloff), + .pilot = static_cast( + settings.get().pilot), + .inputStreamId = static_cast( + settings.get().inputStreamId), + .standard = static_cast( + settings.get().standard), + .vcmMode = static_cast( + settings.get().vcm), + }); + break; + case TunerFrontendSettings::dvbt: + frontendSettings.dvbt({ + .frequency = static_cast( + settings.get().frequency), + .transmissionMode = static_cast( + settings.get().transmissionMode), + .bandwidth = static_cast( + settings.get().bandwidth), + .constellation = static_cast( + settings.get().constellation), + .hierarchy = static_cast( + settings.get().hierarchy), + .hpCoderate = static_cast( + settings.get().hpCodeRate), + .lpCoderate = static_cast( + settings.get().lpCodeRate), + .guardInterval = static_cast( + settings.get().guardInterval), + .isHighPriority = settings.get().isHighPriority, + .standard = static_cast( + settings.get().standard), + .isMiso = settings.get().isMiso, + .plpMode = static_cast( + settings.get().plpMode), + .plpId = static_cast( + settings.get().plpId), + .plpGroupId = static_cast( + settings.get().plpGroupId), + }); + break; + case TunerFrontendSettings::isdbs: + frontendSettings.isdbs({ + .frequency = static_cast( + settings.get().frequency), + .streamId = static_cast( + settings.get().streamId), + .streamIdType = static_cast( + settings.get().streamIdType), + .modulation = static_cast( + settings.get().modulation), + .coderate = static_cast( + settings.get().codeRate), + .symbolRate = static_cast( + settings.get().symbolRate), + .rolloff = static_cast( + settings.get().rolloff), + }); + break; + case TunerFrontendSettings::isdbs3: + frontendSettings.isdbs3({ + .frequency = static_cast( + settings.get().frequency), + .streamId = static_cast( + settings.get().streamId), + .streamIdType = static_cast( + settings.get().streamIdType), + .modulation = static_cast( + settings.get().modulation), + .coderate = static_cast( + settings.get().codeRate), + .symbolRate = static_cast( + settings.get().symbolRate), + .rolloff = static_cast( + settings.get().rolloff), + }); + break; + case TunerFrontendSettings::isdbt: + frontendSettings.isdbt({ + .frequency = static_cast( + settings.get().frequency), + .modulation = static_cast( + settings.get().modulation), + .bandwidth = static_cast( + settings.get().bandwidth), + .mode = static_cast( + settings.get().mode), + .coderate = static_cast( + settings.get().codeRate), + .guardInterval = static_cast( + settings.get().guardInterval), + .serviceAreaId = static_cast( + settings.get().serviceAreaId), + }); + break; + default: + break; + } + return frontendSettings; +} } // namespace android diff --git a/services/tuner/TunerFrontend.h b/services/tuner/TunerFrontend.h index 99cdcdf3b7..431022d359 100644 --- a/services/tuner/TunerFrontend.h +++ b/services/tuner/TunerFrontend.h @@ -41,6 +41,7 @@ using ::android::hardware::tv::tuner::V1_0::FrontendEventType; using ::android::hardware::tv::tuner::V1_0::FrontendId; using ::android::hardware::tv::tuner::V1_0::FrontendScanMessage; using ::android::hardware::tv::tuner::V1_0::FrontendScanMessageType; +using ::android::hardware::tv::tuner::V1_0::FrontendSettings;; using ::android::hardware::tv::tuner::V1_0::IFrontend; using ::android::hardware::tv::tuner::V1_1::IFrontendCallback; using ::android::hardware::tv::tuner::V1_1::FrontendScanMessageExt1_1; @@ -85,6 +86,7 @@ private: hidl_vec getAtsc3PlpSettings( const TunerFrontendAtsc3Settings& settings); FrontendDvbsCodeRate getDvbsCodeRate(const TunerFrontendDvbsCodeRate& codeRate); + FrontendSettings getHidlFrontendSettings(const TunerFrontendSettings& settings); int mId; sp mFrontend; diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl index f6de6182e8..fa2c1ff3d7 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl @@ -44,4 +44,9 @@ interface ITunerDemux { * Open a DVR (Digital Video Record) instance in the demux. */ ITunerDvr openDvr(in int dvbType, in int bufferSize, in ITunerDvrCallback cb); + + /** + * Releases the ITunerDemux instance. + */ + void close(); } diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl index 37166aaf59..1d5544f221 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl @@ -16,7 +16,9 @@ package android.media.tv.tuner; +import android.hardware.common.NativeHandle; import android.media.tv.tuner.TunerFilterConfiguration; +import android.media.tv.tuner.TunerFilterSharedHandleInfo; /** * Tuner Filter interface handles tuner related operations. @@ -39,6 +41,16 @@ interface ITunerFilter { */ void configure(in TunerFilterConfiguration config); + /** + * Get the a/v shared memory handle + */ + TunerFilterSharedHandleInfo getAvSharedHandleInfo(); + + /** + * Release the handle reported by the HAL for AV memory. + */ + void releaseAvHandle(in NativeHandle handle, in long avDataId); + /** * Start the filter. */ @@ -53,4 +65,9 @@ interface ITunerFilter { * Flush the filter. */ void flush(); + + /** + * Close the filter. + */ + void close(); } diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl index f9f86ac764..e7a52a7cd7 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl @@ -32,5 +32,5 @@ interface ITunerFilterCallback { /** * Notify the client that a new filter event happened. */ - void onFilterEvent(out TunerFilterEvent[] filterEvent); + void onFilterEvent(in TunerFilterEvent[] filterEvent); } diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl new file mode 100644 index 0000000000..122dfc35ef --- /dev/null +++ b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl @@ -0,0 +1,29 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media.tv.tuner; + +import android.hardware.common.NativeHandle; + +/** + * Filter Shared Handle Information. + * + * {@hide} + */ +parcelable TunerFilterSharedHandleInfo { + NativeHandle handle; + long size; +} \ No newline at end of file -- GitLab From 499faed90b16ce8a09eff353ab71b6383f8b9908 Mon Sep 17 00:00:00 2001 From: Bhalchandra Gajare Date: Wed, 27 Jan 2021 17:28:30 -0800 Subject: [PATCH 007/694] audio policy: check permissions for AUDIO_INPUT_FLAG_HW_HOTWORD Allow audio capture with AUDIO_INPUT_FLAG_HW_HOTWORD only if the caller has CAPTURE_AUDIO_HOTWORD permission granted. While at it, update the return code to PERMISSION_DENIED for other permission checks as well. Bug: 178654411 Test: tested by setting hotword mode from AGSA application that has the required permission. Able to see hal opened with correct flag. Test: Forced to always return error if flag was set and verified AudioRecord starting in application fails. Change-Id: I827ab5933621bff71a96164e40026ecccf1ba44f --- .../audiopolicy/service/AudioPolicyInterfaceImpl.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index fed88a4940..0ab63cf8f6 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -590,7 +590,14 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& bool canCaptureHotword = captureHotwordAllowed(opPackageName, pid, uid); if ((inputSource == AUDIO_SOURCE_HOTWORD) && !canCaptureHotword) { - return binderStatusFromStatusT(BAD_VALUE); + return binderStatusFromStatusT(PERMISSION_DENIED); + } + + if (((flags & AUDIO_INPUT_FLAG_HW_HOTWORD) != 0) + && !canCaptureHotword) { + ALOGE("%s: permission denied: hotword mode not allowed" + " for uid %d pid %d", __func__, uid, pid); + return binderStatusFromStatusT(PERMISSION_DENIED); } spaudioPolicyEffects; -- GitLab From 7cb0a716c882871b966d2f3c8e6cd294db4bceff Mon Sep 17 00:00:00 2001 From: Josh Hou Date: Tue, 2 Feb 2021 16:26:53 +0800 Subject: [PATCH 008/694] VT: print debug logs between nalunits -> decoder -> renderer Use the property to control whether to print FPS information. 1) Following log will be printed for every nal units which are going to be provided to decoder 10-08 15:23:44.660 D 5626 8278 AAVCAssembler: Access unit complete (1 nal units) 10-08 15:23:44.700 D 5626 8278 AAVCAssembler: Access unit complete (1 nal units) 2) Following log will be printed for every frame which is going to be rendered. 10-08 15:23:44.865 D 5626 8282 CCodecBufferChannel: [c2.exynos.h264.decoder#49] queue buffer successful 10-08 15:23:44.865 D 5626 8282 CCodecBufferChannel: [c2.exynos.h264.decoder#49] queue buffer successful Bug: 179124671 Test: Verify the property works Change-Id: I0aa848bb75c0db1821c5a40577c5ca90984753e7 --- media/codec2/sfplugin/CCodecBufferChannel.cpp | 8 +++++++- media/libstagefright/rtsp/AAVCAssembler.cpp | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/media/codec2/sfplugin/CCodecBufferChannel.cpp b/media/codec2/sfplugin/CCodecBufferChannel.cpp index c697b80134..5c6cd55765 100644 --- a/media/codec2/sfplugin/CCodecBufferChannel.cpp +++ b/media/codec2/sfplugin/CCodecBufferChannel.cpp @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -837,7 +838,12 @@ status_t CCodecBufferChannel::renderOutputBuffer( } return result; } - ALOGV("[%s] queue buffer successful", mName); + + if(android::base::GetBoolProperty("debug.stagefright.fps", false)) { + ALOGD("[%s] queue buffer successful", mName); + } else { + ALOGV("[%s] queue buffer successful", mName); + } int64_t mediaTimeUs = 0; (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs); diff --git a/media/libstagefright/rtsp/AAVCAssembler.cpp b/media/libstagefright/rtsp/AAVCAssembler.cpp index cccb63a2c6..72a377d704 100644 --- a/media/libstagefright/rtsp/AAVCAssembler.cpp +++ b/media/libstagefright/rtsp/AAVCAssembler.cpp @@ -28,6 +28,8 @@ #include #include +#include + #include namespace android { @@ -513,7 +515,11 @@ ARTPAssembler::AssemblyStatus AAVCAssembler::addFragmentedNALUnit( void AAVCAssembler::submitAccessUnit() { CHECK(!mNALUnits.empty()); - ALOGV("Access unit complete (%zu nal units)", mNALUnits.size()); + if(android::base::GetBoolProperty("debug.stagefright.fps", false)) { + ALOGD("Access unit complete (%zu nal units)", mNALUnits.size()); + } else { + ALOGV("Access unit complete (%zu nal units)", mNALUnits.size()); + } size_t totalSize = 0; for (List >::iterator it = mNALUnits.begin(); -- GitLab From 0976a12397c2f583837538095e96e67ade3b54cd Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Thu, 4 Feb 2021 00:03:08 -0800 Subject: [PATCH 009/694] Fix possible uaf of play policy state Access to the play policy state may happen after the state is freed in a race condition, which will result in a SIGARBT. SafetyNet logging is not added to avoid log spamming. queryKeyStatus can be called often. The crash was reproduced on the device before the fix. Verified the test passes after the fix. Test: sts-tradefed sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176486806#testPocBug_176486806 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-17648680664 Test: sts-tradefed sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176444154#testPocBug_176444154 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-17644415464 Bug: 176444154 Bug: 176486806 Change-Id: I07cc93c255942d56e866d0b08fb786f154f6e0d3 --- drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp | 1 + drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h | 2 +- drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp | 3 ++- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp b/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp index 6ac3510c7c..089eb1cdc9 100644 --- a/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp +++ b/drm/mediadrm/plugins/clearkey/default/DrmPlugin.cpp @@ -207,6 +207,7 @@ status_t DrmPlugin::queryKeyStatus( } infoMap.clear(); + android::Mutex::Autolock lock(mPlayPolicyLock); for (size_t i = 0; i < mPlayPolicy.size(); ++i) { infoMap.add(mPlayPolicy.keyAt(i), mPlayPolicy.valueAt(i)); } diff --git a/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h b/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h index aa9b59ddbb..95f15caffe 100644 --- a/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h +++ b/drm/mediadrm/plugins/clearkey/default/include/DrmPlugin.h @@ -262,7 +262,7 @@ private: void initProperties(); void setPlayPolicy(); - android::Mutex mPlayPolicyLock; + mutable android::Mutex mPlayPolicyLock; android::KeyedVector mPlayPolicy; android::KeyedVector mStringProperties; android::KeyedVector> mByteArrayProperties; diff --git a/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp b/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp index a77759eaef..97a62be7f1 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp +++ b/drm/mediadrm/plugins/clearkey/hidl/DrmPlugin.cpp @@ -576,7 +576,6 @@ Return DrmPlugin::setPropertyByteArray( Return DrmPlugin::queryKeyStatus( const hidl_vec& sessionId, queryKeyStatus_cb _hidl_cb) { - if (sessionId.size() == 0) { // Returns empty key status KeyValue pair _hidl_cb(Status::BAD_VALUE, hidl_vec()); @@ -586,12 +585,14 @@ Return DrmPlugin::queryKeyStatus( std::vector infoMapVec; infoMapVec.clear(); + mPlayPolicyLock.lock(); KeyValue keyValuePair; for (size_t i = 0; i < mPlayPolicy.size(); ++i) { keyValuePair.key = mPlayPolicy[i].key; keyValuePair.value = mPlayPolicy[i].value; infoMapVec.push_back(keyValuePair); } + mPlayPolicyLock.unlock(); _hidl_cb(Status::OK, toHidlVec(infoMapVec)); return Void(); } -- GitLab From 1564b4699c6370b4509486f1eb8cd914d5a471db Mon Sep 17 00:00:00 2001 From: Nick Chalko Date: Fri, 5 Feb 2021 11:54:38 -0800 Subject: [PATCH 010/694] Add CodecListTest to mts Change-Id: Id3f4b7ff63e0e9e50f48d146db974808f7a4d58a Test: m -j mts && mts-tradefed run mts-media -m CodecListTest Bug: 178861474 --- media/libmedia/tests/codeclist/Android.bp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/media/libmedia/tests/codeclist/Android.bp b/media/libmedia/tests/codeclist/Android.bp index a930d6ee08..ce85c1a836 100644 --- a/media/libmedia/tests/codeclist/Android.bp +++ b/media/libmedia/tests/codeclist/Android.bp @@ -16,7 +16,7 @@ cc_test { name: "CodecListTest", - test_suites: ["device-tests"], + test_suites: ["device-tests", "mts"], gtest: true, srcs: [ @@ -32,7 +32,7 @@ cc_test { "libstagefright_xmlparser", "libutils", ], - + compile_multilib: "first", cflags: [ "-Werror", "-Wall", -- GitLab From 96ae963ea8703fcf9d20fc46327d0dabf538fde5 Mon Sep 17 00:00:00 2001 From: Guang Qiao Date: Thu, 26 Sep 2019 15:36:29 +0800 Subject: [PATCH 011/694] Modify MediaRecorder stopping process to avoid blocking 1. Puller.setStopTimeUs() and Puller.stopSource() should not traverse the looper thread because the thread may be blocked by MediaSource.read(). 2. Encoder should always be released before stopping MediaSource because MediaSource.stop() would be blocked if there are still some input buffers being encoding. Bug: 143046445 Bug: 148988986 Test: atest android.media.cts.MediaRecorderTest Test: atest android.mediastress.cts.MediaRecorderStressTest Test: atest android.hardware.cts.CameraTest Change-Id: Ia576619dfb40c45fc7840d8febd1614d5ef09118 --- media/libstagefright/MediaCodecSource.cpp | 35 +++++++---------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/media/libstagefright/MediaCodecSource.cpp b/media/libstagefright/MediaCodecSource.cpp index bc656a28bb..78024a9f90 100644 --- a/media/libstagefright/MediaCodecSource.cpp +++ b/media/libstagefright/MediaCodecSource.cpp @@ -168,9 +168,7 @@ status_t MediaCodecSource::Puller::postSynchronouslyAndReturnError( } status_t MediaCodecSource::Puller::setStopTimeUs(int64_t stopTimeUs) { - sp msg = new AMessage(kWhatSetStopTimeUs, this); - msg->setInt64("stop-time-us", stopTimeUs); - return postSynchronouslyAndReturnError(msg); + return mSource->setStopTimeUs(stopTimeUs); } status_t MediaCodecSource::Puller::start(const sp &meta, const sp ¬ify) { @@ -188,19 +186,11 @@ status_t MediaCodecSource::Puller::start(const sp &meta, const sp::Locked queue(mQueue); - queue->mPulling = false; - interrupt = queue->mReadPendingSince && (queue->mReadPendingSince < ALooper::GetNowUs() - 1000000); - queue->flush(); // flush any unprocessed pulled buffers - } - - if (interrupt) { - interruptSource(); - } + // mark stopping before actually reaching kWhatStop on the looper, so the pulling will + // stop. + Mutexed::Locked queue(mQueue); + queue->mPulling = false; + queue->flush(); // flush any unprocessed pulled buffers } void MediaCodecSource::Puller::interruptSource() { @@ -684,9 +674,9 @@ void MediaCodecSource::signalEOS(status_t err) { if (mStopping && reachedEOS) { ALOGI("encoder (%s) stopped", mIsVideo ? "video" : "audio"); if (mPuller != NULL) { - mPuller->stopSource(); + mPuller->interruptSource(); } - ALOGV("source (%s) stopped", mIsVideo ? "video" : "audio"); + ALOGI("source (%s) stopped", mIsVideo ? "video" : "audio"); // posting reply to everyone that's waiting List>::iterator it; for (it = mStopReplyIDQueue.begin(); @@ -875,7 +865,7 @@ void MediaCodecSource::onMessageReceived(const sp &msg) { { int32_t eos = 0; if (msg->findInt32("eos", &eos) && eos) { - ALOGV("puller (%s) reached EOS", mIsVideo ? "video" : "audio"); + ALOGI("puller (%s) reached EOS", mIsVideo ? "video" : "audio"); signalEOS(); break; } @@ -1093,12 +1083,7 @@ void MediaCodecSource::onMessageReceived(const sp &msg) { if (generation != mGeneration) { break; } - - if (!(mFlags & FLAG_USE_SURFACE_INPUT)) { - ALOGV("source (%s) stopping", mIsVideo ? "video" : "audio"); - mPuller->interruptSource(); - ALOGV("source (%s) stopped", mIsVideo ? "video" : "audio"); - } + ALOGD("source (%s) stopping stalled", mIsVideo ? "video" : "audio"); signalEOS(); break; } -- GitLab From 42a97f5648e9345461422310039fc9d1def0a91a Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Mon, 8 Feb 2021 16:09:38 +0000 Subject: [PATCH 012/694] Prevent read of uninitialized memory Bug: 173720767 Test: atest MediaPlayerTest Change-Id: Ib6a3d24e07915e8af9d019e54d0501b74aa4671d --- media/libmedia/IMediaPlayer.cpp | 42 +++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp index 8a4b17c805..8fc5a4c2e9 100644 --- a/media/libmedia/IMediaPlayer.cpp +++ b/media/libmedia/IMediaPlayer.cpp @@ -17,9 +17,9 @@ #include #include -#include #include +#include #include #include #include @@ -83,10 +83,36 @@ enum { }; // ModDrm helpers -static void readVector(const Parcel& reply, Vector& vector) { - uint32_t size = reply.readUint32(); - vector.insertAt((size_t)0, size); - reply.read(vector.editArray(), size); +static status_t readVector(const Parcel& reply, Vector& vector) { + uint32_t size = 0; + status_t status = reply.readUint32(&size); + if (status == OK) { + status = size <= reply.dataAvail() ? OK : BAD_VALUE; + } + if (status == OK) { + status = vector.insertAt((size_t) 0, size) >= 0 ? OK : NO_MEMORY; + } + if (status == OK) { + status = reply.read(vector.editArray(), size); + } + if (status != OK) { + char errorMsg[100]; + char buganizerId[] = "173720767"; + snprintf(errorMsg, + sizeof(errorMsg), + "%s: failed to read array. Size: %d, status: %d.", + __func__, + size, + status); + android_errorWriteWithInfoLog( + /* safetyNet tag= */ 0x534e4554, + buganizerId, + IPCThreadState::self()->getCallingUid(), + errorMsg, + strlen(errorMsg)); + ALOGE("%s (b/%s)", errorMsg, buganizerId); + } + return status; } static void writeVector(Parcel& data, Vector const& vector) { @@ -977,8 +1003,10 @@ status_t BnMediaPlayer::onTransact( uint8_t uuid[16] = {}; data.read(uuid, sizeof(uuid)); Vector drmSessionId; - readVector(data, drmSessionId); - + status_t status = readVector(data, drmSessionId); + if (status != OK) { + return status; + } uint32_t result = prepareDrm(uuid, drmSessionId); reply->writeInt32(result); return OK; -- GitLab From aa76e3e6f16ce92aa8bc10a09cf47c603cf5cbfe Mon Sep 17 00:00:00 2001 From: Dichen Zhang Date: Mon, 1 Feb 2021 17:44:15 -0800 Subject: [PATCH 013/694] Add session ID Add new session-id key to MediaFormat and MediaMetrics. Test: set session ID in app and print log in native code. Test: make Change-Id: I0354bc3ddc51b69716da47b45431b7b214e60e9d --- media/libstagefright/MediaCodec.cpp | 4 ++++ media/libstagefright/include/media/stagefright/MediaCodec.h | 1 + services/mediametrics/statsd_codec.cpp | 5 +++++ 3 files changed, 10 insertions(+) diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp index 358c5e35c7..518f03a24a 100644 --- a/media/libstagefright/MediaCodec.cpp +++ b/media/libstagefright/MediaCodec.cpp @@ -84,6 +84,7 @@ static const char *kCodecKeyName = "codec"; // NB: these are matched with public Java API constants defined // in frameworks/base/media/java/android/media/MediaCodec.java // These must be kept synchronized with the constants there. +static const char *kCodecLogSessionId = "android.media.mediacodec.log-session-id"; static const char *kCodecCodec = "android.media.mediacodec.codec"; /* e.g. OMX.google.aac.decoder */ static const char *kCodecMime = "android.media.mediacodec.mime"; /* e.g. audio/mime */ static const char *kCodecMode = "android.media.mediacodec.mode"; /* audio, video */ @@ -1298,6 +1299,8 @@ status_t MediaCodec::configure( } if (mIsVideo) { + // TODO: validity check log-session-id: it should be a 32-hex-digit. + format->findString("log-session-id", &mLogSessionId); format->findInt32("width", &mVideoWidth); format->findInt32("height", &mVideoHeight); if (!format->findInt32("rotation-degrees", &mRotationDegrees)) { @@ -1305,6 +1308,7 @@ status_t MediaCodec::configure( } if (mMetricsHandle != 0) { + mediametrics_setCString(mMetricsHandle, kCodecLogSessionId, mLogSessionId.c_str()); mediametrics_setInt32(mMetricsHandle, kCodecWidth, mVideoWidth); mediametrics_setInt32(mMetricsHandle, kCodecHeight, mVideoHeight); mediametrics_setInt32(mMetricsHandle, kCodecRotation, mRotationDegrees); diff --git a/media/libstagefright/include/media/stagefright/MediaCodec.h b/media/libstagefright/include/media/stagefright/MediaCodec.h index a28d479614..922bff6cf7 100644 --- a/media/libstagefright/include/media/stagefright/MediaCodec.h +++ b/media/libstagefright/include/media/stagefright/MediaCodec.h @@ -397,6 +397,7 @@ private: sp mResourceManagerProxy; bool mIsVideo; + AString mLogSessionId; int32_t mVideoWidth; int32_t mVideoHeight; int32_t mRotationDegrees; diff --git a/services/mediametrics/statsd_codec.cpp b/services/mediametrics/statsd_codec.cpp index d502b3010c..b1cf7aa17e 100644 --- a/services/mediametrics/statsd_codec.cpp +++ b/services/mediametrics/statsd_codec.cpp @@ -55,6 +55,11 @@ bool statsd_codec(const mediametrics::Item *item) // flesh out the protobuf we'll hand off with our data // + //android.media.mediacodec.videoSessionId string + std::string sessionId; + if (item->getString("android.media.mediacodec.log-session_id", &sessionId)) { + metrics_proto.set_log_session_id(std::move(sessionId)); + } // android.media.mediacodec.codec string std::string codec; if (item->getString("android.media.mediacodec.codec", &codec)) { -- GitLab From 2aebc81ccc40f5229a2a903fc2d52b12aead6e5b Mon Sep 17 00:00:00 2001 From: Dichen Zhang Date: Wed, 10 Feb 2021 02:14:34 -0800 Subject: [PATCH 014/694] Add Recorder Session ID Add new session ID key to MediaRecorder and MediaMetrics. Test: make CTS MediaRecorderTest Set session ID manually and print log Change-Id: Ie2a1744f92f626d8919f07d40eacdd04d37ee954 --- media/libmediaplayerservice/StagefrightRecorder.cpp | 13 +++++++++++++ media/libmediaplayerservice/StagefrightRecorder.h | 2 ++ services/mediametrics/statsd_recorder.cpp | 5 +++++ 3 files changed, 20 insertions(+) diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp index b2f6407fde..b4f3b36ed6 100644 --- a/media/libmediaplayerservice/StagefrightRecorder.cpp +++ b/media/libmediaplayerservice/StagefrightRecorder.cpp @@ -78,6 +78,7 @@ static const char *kKeyRecorder = "recorder"; // NB: these are matched with public Java API constants defined // in frameworks/base/media/java/android/media/MediaRecorder.java // These must be kept synchronized with the constants there. +static const char *kRecorderLogSessionId = "android.media.mediarecorder.log-session-id"; static const char *kRecorderAudioBitrate = "android.media.mediarecorder.audio-bitrate"; static const char *kRecorderAudioChannels = "android.media.mediarecorder.audio-channels"; static const char *kRecorderAudioSampleRate = "android.media.mediarecorder.audio-samplerate"; @@ -159,6 +160,8 @@ void StagefrightRecorder::updateMetrics() { // know is the app which requested the recording. mMetricsItem->setUid(mClientUid); + mMetricsItem->setCString(kRecorderLogSessionId, mLogSessionId.c_str()); + // populate the values from the raw fields. // TBD mOutputFormat = OUTPUT_FORMAT_THREE_GPP; @@ -913,6 +916,14 @@ status_t StagefrightRecorder::requestIDRFrame() { return ret; } +status_t StagefrightRecorder::setLogSessionId(const String8 &log_session_id) { + ALOGV("setLogSessionId: %s", log_session_id.string()); + + // TODO: validity check that log_session_id is a 32-byte hex digit. + mLogSessionId.setTo(log_session_id.string()); + return OK; +} + status_t StagefrightRecorder::setParameter( const String8 &key, const String8 &value) { ALOGV("setParameter: key (%s) => value (%s)", key.string(), value.string()); @@ -1081,6 +1092,8 @@ status_t StagefrightRecorder::setParameter( if (safe_strtoi64(value.string(), &networkHandle)) { return setSocketNetwork(networkHandle); } + } else if (key == "log-session-id") { + return setLogSessionId(value); } else { ALOGE("setParameter: failed to find key %s", key.string()); } diff --git a/media/libmediaplayerservice/StagefrightRecorder.h b/media/libmediaplayerservice/StagefrightRecorder.h index 0362eddd04..ebca320200 100644 --- a/media/libmediaplayerservice/StagefrightRecorder.h +++ b/media/libmediaplayerservice/StagefrightRecorder.h @@ -45,6 +45,7 @@ struct StagefrightRecorder : public MediaRecorderBase { explicit StagefrightRecorder(const String16 &opPackageName); virtual ~StagefrightRecorder(); virtual status_t init(); + virtual status_t setLogSessionId(const String8 &id); virtual status_t setAudioSource(audio_source_t as); status_t setPrivacySensitive(bool privacySensitive) override; status_t isPrivacySensitive(bool *privacySensitive) const override; @@ -109,6 +110,7 @@ private: void flushAndResetMetrics(bool reinitialize); void updateMetrics(); + AString mLogSessionId; audio_source_t mAudioSource; privacy_sensitive_t mPrivacySensitive; video_source mVideoSource; diff --git a/services/mediametrics/statsd_recorder.cpp b/services/mediametrics/statsd_recorder.cpp index 2e5ada4e38..538adc5631 100644 --- a/services/mediametrics/statsd_recorder.cpp +++ b/services/mediametrics/statsd_recorder.cpp @@ -55,6 +55,11 @@ bool statsd_recorder(const mediametrics::Item *item) // flesh out the protobuf we'll hand off with our data // + // string kRecorderLogSessionId = "android.media.mediarecorder.log-session-id"; + std::string log_session_id; + if (item->getString("android.media.mediarecorder.log_session_id", &log_session_id)) { + metrics_proto.set_log_session_id(std::move(log_session_id)); + } // string kRecorderAudioMime = "android.media.mediarecorder.audio.mime"; std::string audio_mime; if (item->getString("android.media.mediarecorder.audio.mime", &audio_mime)) { -- GitLab From f811d448096baf3bb5fe21d3c77649171fda43eb Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Sun, 14 Feb 2021 14:30:31 -0800 Subject: [PATCH 015/694] Fix JsonWebKey potential null pointer dereference In extractKeysFromJsonWebKeySet, if mJsonObjects size is zero, mJsonObjects[0] will result in a null pointer dereference. Test: sts-tradefed sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176496483#testPocBug_176496483 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-17649648364 Bug: 176496483 Bug: 175955261 Change-Id: Ib70f1c6f9abb8f2628abb229fc389b83bf6e7552 --- drm/mediadrm/plugins/clearkey/default/JsonWebKey.cpp | 2 +- drm/mediadrm/plugins/clearkey/hidl/JsonWebKey.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/drm/mediadrm/plugins/clearkey/default/JsonWebKey.cpp b/drm/mediadrm/plugins/clearkey/default/JsonWebKey.cpp index 53ffae4ccd..a2d506da44 100644 --- a/drm/mediadrm/plugins/clearkey/default/JsonWebKey.cpp +++ b/drm/mediadrm/plugins/clearkey/default/JsonWebKey.cpp @@ -61,7 +61,7 @@ bool JsonWebKey::extractKeysFromJsonWebKeySet(const String8& jsonWebKeySet, // all the base64 encoded keys. Each key is also stored separately as // a JSON object in mJsonObjects[1..n] where n is the total // number of keys in the set. - if (!isJsonWebKeySet(mJsonObjects[0])) { + if (mJsonObjects.size() == 0 || !isJsonWebKeySet(mJsonObjects[0])) { return false; } diff --git a/drm/mediadrm/plugins/clearkey/hidl/JsonWebKey.cpp b/drm/mediadrm/plugins/clearkey/hidl/JsonWebKey.cpp index d93777d9d9..99668a77fc 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/JsonWebKey.cpp +++ b/drm/mediadrm/plugins/clearkey/hidl/JsonWebKey.cpp @@ -65,7 +65,7 @@ bool JsonWebKey::extractKeysFromJsonWebKeySet(const std::string& jsonWebKeySet, // all the base64 encoded keys. Each key is also stored separately as // a JSON object in mJsonObjects[1..n] where n is the total // number of keys in the set. - if (!isJsonWebKeySet(mJsonObjects[0])) { + if (mJsonObjects.size() == 0 || !isJsonWebKeySet(mJsonObjects[0])) { return false; } -- GitLab From 031ab1aab362ec800b2b5b3073de048653cb0936 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Thu, 18 Feb 2021 14:55:50 +0000 Subject: [PATCH 016/694] Add playback session id to MediaExtractor Bug: 167036690 Test: atest CtsMediaHostTestCases Change-Id: If43a1dd036851c0a0505867a346db0d714e9b34d --- media/libmedia/IMediaExtractor.cpp | 20 ++++++++++++++++++- .../include/android/IMediaExtractor.h | 2 ++ media/libstagefright/NuMediaExtractor.cpp | 11 ++++++++++ media/libstagefright/RemoteMediaExtractor.cpp | 6 ++++++ .../media/stagefright/NuMediaExtractor.h | 2 ++ .../media/stagefright/RemoteMediaExtractor.h | 1 + services/mediametrics/statsd_extractor.cpp | 6 ++++++ services/mediametrics/statsd_mediaparser.cpp | 6 +++++- 8 files changed, 52 insertions(+), 2 deletions(-) diff --git a/media/libmedia/IMediaExtractor.cpp b/media/libmedia/IMediaExtractor.cpp index 7ed76d8b20..5999e516cb 100644 --- a/media/libmedia/IMediaExtractor.cpp +++ b/media/libmedia/IMediaExtractor.cpp @@ -39,7 +39,8 @@ enum { SETMEDIACAS, NAME, GETMETRICS, - SETENTRYPOINT + SETENTRYPOINT, + SETPLAYBACKID }; class BpMediaExtractor : public BpInterface { @@ -150,6 +151,13 @@ public: data.writeInt32(static_cast(entryPoint)); return remote()->transact(SETENTRYPOINT, data, &reply); } + + virtual status_t setPlaybackId(const String8& playbackId) { + Parcel data, reply; + data.writeInterfaceToken(BpMediaExtractor::getInterfaceDescriptor()); + data.writeString8(playbackId); + return remote()->transact(SETPLAYBACKID, data, &reply); + } }; IMPLEMENT_META_INTERFACE(MediaExtractor, "android.media.IMediaExtractor"); @@ -250,6 +258,16 @@ status_t BnMediaExtractor::onTransact( } return err; } + case SETPLAYBACKID: { + ALOGV("setPlaybackId"); + CHECK_INTERFACE(IMediaExtractor, data, reply); + String8 playbackId; + status_t status = data.readString8(&playbackId); + if (status == OK) { + setPlaybackId(playbackId); + } + return status; + } default: return BBinder::onTransact(code, data, reply, flags); } diff --git a/media/libmedia/include/android/IMediaExtractor.h b/media/libmedia/include/android/IMediaExtractor.h index f9cafdeafd..8a5d24dad5 100644 --- a/media/libmedia/include/android/IMediaExtractor.h +++ b/media/libmedia/include/android/IMediaExtractor.h @@ -72,6 +72,8 @@ public: }; virtual status_t setEntryPoint(EntryPoint entryPoint) = 0; + + virtual status_t setPlaybackId(const String8& playbackId) = 0; }; diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp index f2c7dd623f..3ee78d04f5 100644 --- a/media/libstagefright/NuMediaExtractor.cpp +++ b/media/libstagefright/NuMediaExtractor.cpp @@ -880,4 +880,15 @@ status_t NuMediaExtractor::getAudioPresentations( return ERROR_UNSUPPORTED; } +status_t NuMediaExtractor::setPlaybackId(const String8& playbackId) { + if (mImpl == nullptr) { + return ERROR_UNSUPPORTED; + } + status_t status = mImpl->setPlaybackId(playbackId); + if (status != OK) { + ALOGW("Failed to set playback session id: %d.", status); + } + return status; +} + } // namespace android diff --git a/media/libstagefright/RemoteMediaExtractor.cpp b/media/libstagefright/RemoteMediaExtractor.cpp index 381eb1ad95..c4bde7e021 100644 --- a/media/libstagefright/RemoteMediaExtractor.cpp +++ b/media/libstagefright/RemoteMediaExtractor.cpp @@ -40,6 +40,7 @@ static const char *kExtractorFormat = "android.media.mediaextractor.fmt"; static const char *kExtractorMime = "android.media.mediaextractor.mime"; static const char *kExtractorTracks = "android.media.mediaextractor.ntrk"; static const char *kExtractorEntryPoint = "android.media.mediaextractor.entry"; +static const char *kExtractorPlaybackId = "android.media.mediaextractor.playbackId"; static const char *kEntryPointSdk = "sdk"; static const char *kEntryPointWithJvm = "ndk-with-jvm"; @@ -174,6 +175,11 @@ status_t RemoteMediaExtractor::setEntryPoint(EntryPoint entryPoint) { return OK; } +status_t RemoteMediaExtractor::setPlaybackId(const String8& playbackId) { + mMetricsItem->setCString(kExtractorPlaybackId, playbackId.c_str()); + return OK; +} + //////////////////////////////////////////////////////////////////////////////// // static diff --git a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h index d8f2b001b9..1cad140b03 100644 --- a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h @@ -100,6 +100,8 @@ struct NuMediaExtractor : public RefBase { status_t getAudioPresentations(size_t trackIdx, AudioPresentationCollection *presentations); + status_t setPlaybackId(const String8& playbackId); + protected: virtual ~NuMediaExtractor(); diff --git a/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h index 25125f2659..9b2841f0d4 100644 --- a/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h @@ -43,6 +43,7 @@ public: virtual status_t setMediaCas(const HInterfaceToken &casToken); virtual String8 name(); virtual status_t setEntryPoint(EntryPoint entryPoint); + virtual status_t setPlaybackId(const String8& playbackId); private: MediaExtractor *mExtractor; diff --git a/services/mediametrics/statsd_extractor.cpp b/services/mediametrics/statsd_extractor.cpp index 4180e0c388..8102ded4c9 100644 --- a/services/mediametrics/statsd_extractor.cpp +++ b/services/mediametrics/statsd_extractor.cpp @@ -87,6 +87,12 @@ bool statsd_extractor(const mediametrics::Item *item) metrics_proto.set_entry_point(entry_point); } + // android.media.mediaextractor.playbackId string + std::string playback_id; + if (item->getString("android.media.mediaextractor.playbackId", &playback_id)) { + metrics_proto.set_playback_id(std::move(playback_id)); + } + std::string serialized; if (!metrics_proto.SerializeToString(&serialized)) { ALOGE("Failed to serialize extractor metrics"); diff --git a/services/mediametrics/statsd_mediaparser.cpp b/services/mediametrics/statsd_mediaparser.cpp index 262b2aee34..236ba20092 100644 --- a/services/mediametrics/statsd_mediaparser.cpp +++ b/services/mediametrics/statsd_mediaparser.cpp @@ -80,6 +80,9 @@ bool statsd_mediaparser(const mediametrics::Item *item) int32_t videoHeight = -1; item->getInt32("android.media.mediaparser.videoHeight", &videoHeight); + std::string playbackSessionId; + item->getString("android.media.mediaparser.playbackId", &playbackSessionId); + if (enabled_statsd) { (void) android::util::stats_write(android::util::MEDIAMETRICS_MEDIAPARSER_REPORTED, timestamp, @@ -95,7 +98,8 @@ bool statsd_mediaparser(const mediametrics::Item *item) trackCodecs.c_str(), alteredParameters.c_str(), videoWidth, - videoHeight); + videoHeight, + playbackSessionId.c_str()); } else { ALOGV("NOT sending MediaParser media metrics."); } -- GitLab From f8905e67d4373a6765911604eb306ca212a68ca8 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Wed, 17 Feb 2021 11:07:04 +0000 Subject: [PATCH 017/694] Add unit test for uninitialized read fix Bug: 173720767 Test: atest IMediaPlayerTest Change-Id: Ia3cbc0626d38ffec7a37760b984d521eb9c9874e --- media/libmedia/IMediaPlayer.cpp | 48 ------------ media/libmedia/include/media/IMediaPlayer.h | 50 +++++++++++++ media/libmedia/tests/mediaplayer/Android.bp | 39 ++++++++++ .../tests/mediaplayer/IMediaPlayerTest.cpp | 73 +++++++++++++++++++ 4 files changed, 162 insertions(+), 48 deletions(-) create mode 100644 media/libmedia/tests/mediaplayer/Android.bp create mode 100644 media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp index 8fc5a4c2e9..c9f361e075 100644 --- a/media/libmedia/IMediaPlayer.cpp +++ b/media/libmedia/IMediaPlayer.cpp @@ -34,54 +34,6 @@ namespace android { using media::VolumeShaper; -enum { - DISCONNECT = IBinder::FIRST_CALL_TRANSACTION, - SET_DATA_SOURCE_URL, - SET_DATA_SOURCE_FD, - SET_DATA_SOURCE_STREAM, - SET_DATA_SOURCE_CALLBACK, - SET_DATA_SOURCE_RTP, - SET_BUFFERING_SETTINGS, - GET_BUFFERING_SETTINGS, - PREPARE_ASYNC, - START, - STOP, - IS_PLAYING, - SET_PLAYBACK_SETTINGS, - GET_PLAYBACK_SETTINGS, - SET_SYNC_SETTINGS, - GET_SYNC_SETTINGS, - PAUSE, - SEEK_TO, - GET_CURRENT_POSITION, - GET_DURATION, - RESET, - NOTIFY_AT, - SET_AUDIO_STREAM_TYPE, - SET_LOOPING, - SET_VOLUME, - INVOKE, - SET_METADATA_FILTER, - GET_METADATA, - SET_AUX_EFFECT_SEND_LEVEL, - ATTACH_AUX_EFFECT, - SET_VIDEO_SURFACETEXTURE, - SET_PARAMETER, - GET_PARAMETER, - SET_RETRANSMIT_ENDPOINT, - GET_RETRANSMIT_ENDPOINT, - SET_NEXT_PLAYER, - APPLY_VOLUME_SHAPER, - GET_VOLUME_SHAPER_STATE, - // Modular DRM - PREPARE_DRM, - RELEASE_DRM, - // AudioRouting - SET_OUTPUT_DEVICE, - GET_ROUTED_DEVICE_ID, - ENABLE_AUDIO_DEVICE_CALLBACK, -}; - // ModDrm helpers static status_t readVector(const Parcel& reply, Vector& vector) { uint32_t size = 0; diff --git a/media/libmedia/include/media/IMediaPlayer.h b/media/libmedia/include/media/IMediaPlayer.h index 3548a1e3fb..28684d1d73 100644 --- a/media/libmedia/include/media/IMediaPlayer.h +++ b/media/libmedia/include/media/IMediaPlayer.h @@ -137,6 +137,56 @@ public: virtual status_t setOutputDevice(audio_port_handle_t deviceId) = 0; virtual status_t getRoutedDeviceId(audio_port_handle_t *deviceId) = 0; virtual status_t enableAudioDeviceCallback(bool enabled) = 0; +protected: + + friend class IMediaPlayerTest; + enum { + DISCONNECT = IBinder::FIRST_CALL_TRANSACTION, + SET_DATA_SOURCE_URL, + SET_DATA_SOURCE_FD, + SET_DATA_SOURCE_STREAM, + SET_DATA_SOURCE_CALLBACK, + SET_DATA_SOURCE_RTP, + SET_BUFFERING_SETTINGS, + GET_BUFFERING_SETTINGS, + PREPARE_ASYNC, + START, + STOP, + IS_PLAYING, + SET_PLAYBACK_SETTINGS, + GET_PLAYBACK_SETTINGS, + SET_SYNC_SETTINGS, + GET_SYNC_SETTINGS, + PAUSE, + SEEK_TO, + GET_CURRENT_POSITION, + GET_DURATION, + RESET, + NOTIFY_AT, + SET_AUDIO_STREAM_TYPE, + SET_LOOPING, + SET_VOLUME, + INVOKE, + SET_METADATA_FILTER, + GET_METADATA, + SET_AUX_EFFECT_SEND_LEVEL, + ATTACH_AUX_EFFECT, + SET_VIDEO_SURFACETEXTURE, + SET_PARAMETER, + GET_PARAMETER, + SET_RETRANSMIT_ENDPOINT, + GET_RETRANSMIT_ENDPOINT, + SET_NEXT_PLAYER, + APPLY_VOLUME_SHAPER, + GET_VOLUME_SHAPER_STATE, + // Modular DRM + PREPARE_DRM, + RELEASE_DRM, + // AudioRouting + SET_OUTPUT_DEVICE, + GET_ROUTED_DEVICE_ID, + ENABLE_AUDIO_DEVICE_CALLBACK, + }; }; // ---------------------------------------------------------------------------- diff --git a/media/libmedia/tests/mediaplayer/Android.bp b/media/libmedia/tests/mediaplayer/Android.bp new file mode 100644 index 0000000000..5538ea0908 --- /dev/null +++ b/media/libmedia/tests/mediaplayer/Android.bp @@ -0,0 +1,39 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +cc_test { + name: "IMediaPlayerTest", + test_suites: ["device-tests", "mts"], + gtest: true, + + srcs: [ + "IMediaPlayerTest.cpp", + ], + + shared_libs: [ + "libbinder", + "liblog", + "libmedia", + "libstagefright", + "libstagefright_foundation", + "libutils", + ], + compile_multilib: "first", + cflags: [ + "-Werror", + "-Wall", + ], +} diff --git a/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp b/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp new file mode 100644 index 0000000000..cc609336c9 --- /dev/null +++ b/media/libmedia/tests/mediaplayer/IMediaPlayerTest.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace android { + +constexpr uint8_t kMockByteArray[16] = {}; + + class IMediaPlayerTest : public testing::Test { + protected: + static constexpr uint32_t PREPARE_DRM = IMediaPlayer::PREPARE_DRM; + + void SetUp() override { + mediaPlayer_ = sp::make(); + sp serviceManager = defaultServiceManager(); + sp mediaPlayerService = serviceManager->getService(String16("media.player")); + sp iMediaPlayerService = + IMediaPlayerService::asInterface(mediaPlayerService); + iMediaPlayer_ = iMediaPlayerService->create(mediaPlayer_); + } + + sp mediaPlayer_; + sp iMediaPlayer_; + }; + +TEST_F(IMediaPlayerTest, PrepareDrmInvalidTransaction) { + Parcel data, reply; + data.writeInterfaceToken(iMediaPlayer_->getInterfaceDescriptor()); + data.write(kMockByteArray, 16); + + // We write a length greater than the following session id array. Should be discarded. + data.writeUint32(2); + data.writeUnpadded(kMockByteArray, 1); + + status_t result = IMediaPlayer::asBinder(iMediaPlayer_) + ->transact(PREPARE_DRM, data, &reply); + ASSERT_EQ(result, BAD_VALUE); +} + +TEST_F(IMediaPlayerTest, PrepareDrmValidTransaction) { + Parcel data, reply; + data.writeInterfaceToken(iMediaPlayer_->getInterfaceDescriptor()); + data.write(kMockByteArray, 16); + + // We write a length equal to the length of the following data. The transaction should be valid. + data.writeUint32(1); + data.write(kMockByteArray, 1); + + status_t result = IMediaPlayer::asBinder(iMediaPlayer_) + ->transact(PREPARE_DRM, data, &reply); + ASSERT_EQ(result, OK); +} +} // namespace android -- GitLab From ca96e2b028c8b113f88223d80d1bde8eb05418d7 Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Tue, 2 Feb 2021 21:36:34 -0800 Subject: [PATCH 018/694] Fix potential decrypt destPtr overflow. There is a potential integer overflow to bypass the destination base size check in decrypt. The destPtr can then point to the outside of the destination buffer. Test: sts-tradefed sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176444622#testPocBug_176444622 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-17644462264 Bug: 176444622 Bug: 176496353 Change-Id: Idac48307edd45fc8282902c4beeb2c8ca94f8cf3 --- drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp b/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp index d278633482..005e551383 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp +++ b/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp @@ -142,12 +142,14 @@ Return CryptoPlugin::decrypt_1_2( base = static_cast(static_cast(destBase->getPointer())); - if (destBuffer.offset + destBuffer.size > destBase->getSize()) { + totalSize = 0; + if (__builtin_add_overflow(destBuffer.offset, destBuffer.size, &totalSize) || + totalSize > destBase->getSize()) { + android_errorWriteLog(0x534e4554, "176444622"); _hidl_cb(Status_V1_2::ERROR_DRM_FRAME_TOO_LARGE, 0, "invalid buffer size"); return Void(); } - destPtr = static_cast(base + destination.nonsecureMemory.offset); - + destPtr = static_cast(base + destination.nonsecureMemory.offset); // Calculate the output buffer size and determine if any subsamples are // encrypted. -- GitLab From 67a1e61dc27667e09f8cf18caeff8f07db65ff0d Mon Sep 17 00:00:00 2001 From: Bob Badour Date: Tue, 23 Feb 2021 23:02:43 -0800 Subject: [PATCH 019/694] [LSC] Add LOCAL_LICENSE_KINDS to frameworks/av Added SPDX-license-identifier-Apache-2.0 to: apex/Android.bp apex/testing/Android.bp camera/cameraserver/Android.bp camera/tests/Android.mk cmds/screenrecord/Android.bp cmds/stagefright/Android.mk drm/common/Android.bp drm/drmserver/Android.bp drm/libdrmframework/Android.bp drm/libdrmframework/plugins/common/util/Android.bp drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp drm/libdrmframework/plugins/passthru/Android.bp drm/libmediadrm/Android.bp drm/libmediadrm/fuzzer/Android.bp drm/libmediadrm/protos/Android.bp drm/libmediadrm/tests/Android.bp drm/mediacas/plugins/clearkey/Android.bp drm/mediacas/plugins/clearkey/tests/Android.bp drm/mediacas/plugins/mock/Android.bp drm/mediadrm/plugins/clearkey/common/Android.bp drm/mediadrm/plugins/clearkey/default/Android.bp drm/mediadrm/plugins/clearkey/default/tests/Android.bp drm/mediadrm/plugins/mock/Android.bp media/audioserver/Android.bp media/bufferpool/1.0/Android.bp media/bufferpool/1.0/vts/Android.bp media/bufferpool/2.0/Android.bp media/bufferpool/2.0/tests/Android.bp media/codec2/components/aac/Android.bp media/codec2/components/amr_nb_wb/Android.bp media/codec2/components/aom/Android.bp media/codec2/components/avc/Android.bp media/codec2/components/base/Android.bp media/codec2/components/cmds/Android.bp media/codec2/components/flac/Android.bp media/codec2/components/g711/Android.bp media/codec2/components/gav1/Android.bp media/codec2/components/gsm/Android.bp media/codec2/components/hevc/Android.bp media/codec2/components/mp3/Android.bp media/codec2/components/mpeg2/Android.bp media/codec2/components/mpeg4_h263/Android.bp media/codec2/components/opus/Android.bp media/codec2/components/raw/Android.bp media/codec2/components/vorbis/Android.bp media/codec2/components/vpx/Android.bp media/codec2/components/xaac/Android.bp media/codec2/core/Android.bp media/codec2/faultinjection/Android.bp media/codec2/fuzzer/Android.bp media/codec2/hidl/1.0/utils/Android.bp media/codec2/hidl/1.0/vts/functional/Android.bp media/codec2/hidl/1.0/vts/functional/audio/Android.bp media/codec2/hidl/1.0/vts/functional/common/Android.bp media/codec2/hidl/1.0/vts/functional/component/Android.bp media/codec2/hidl/1.0/vts/functional/master/Android.bp media/codec2/hidl/1.0/vts/functional/video/Android.bp media/codec2/hidl/1.1/utils/Android.bp media/codec2/hidl/client/Android.bp media/codec2/hidl/plugin/Android.bp media/codec2/hidl/plugin/samples/Android.bp media/codec2/hidl/services/Android.bp media/codec2/sfplugin/Android.bp media/codec2/sfplugin/tests/Android.bp media/codec2/sfplugin/utils/Android.bp media/codec2/tests/Android.bp media/codec2/vndk/Android.bp media/codecs/amrnb/common/Android.bp media/codecs/amrnb/enc/fuzzer/Android.bp media/codecs/amrnb/fuzzer/Android.bp media/codecs/amrwb/dec/fuzzer/Android.bp media/codecs/amrwb/enc/Android.bp media/codecs/amrwb/enc/SampleCode/Android.bp media/codecs/amrwb/enc/fuzzer/Android.bp media/codecs/amrwb/enc/test/Android.bp media/codecs/g711/decoder/Android.bp media/codecs/g711/fuzzer/Android.bp media/codecs/m4v_h263/dec/Android.bp media/codecs/m4v_h263/dec/test/Android.bp media/codecs/m4v_h263/fuzzer/Android.bp media/codecs/mp3dec/fuzzer/Android.bp media/extractors/Android.bp media/extractors/aac/Android.bp media/extractors/amr/Android.bp media/extractors/flac/Android.bp media/extractors/fuzzers/Android.bp media/extractors/midi/Android.bp media/extractors/mkv/Android.bp media/extractors/mp3/Android.bp media/extractors/mp4/Android.bp media/extractors/mpeg2/Android.bp media/extractors/ogg/Android.bp media/extractors/tests/Android.bp media/extractors/wav/Android.bp media/img_utils/Android.bp media/libaaudio/Android.bp media/libaaudio/examples/Android.bp media/libaaudio/examples/input_monitor/Android.bp media/libaaudio/examples/loopback/Android.bp media/libaaudio/examples/write_sine/Android.bp media/libaaudio/src/Android.bp media/libaaudio/tests/Android.bp media/libaudioclient/Android.bp media/libaudioclient/fuzzer/Android.bp media/libaudioclient/tests/Android.bp media/libaudiofoundation/Android.bp media/libaudiofoundation/tests/Android.bp media/libaudiohal/Android.bp media/libaudiohal/impl/Android.bp media/libaudioprocessing/Android.bp media/libaudioprocessing/audio-resampler/Android.bp media/libaudioprocessing/tests/Android.bp media/libaudioprocessing/tests/fuzzer/Android.bp media/libcpustats/Android.bp media/libdatasource/Android.bp media/libeffects/config/Android.bp media/libeffects/downmix/Android.bp media/libeffects/downmix/tests/Android.bp media/libeffects/dynamicsproc/Android.bp media/libeffects/factory/Android.bp media/libeffects/hapticgenerator/Android.bp media/libeffects/loudness/Android.bp media/libeffects/lvm/benchmarks/Android.bp media/libeffects/lvm/lib/Android.bp media/libeffects/lvm/tests/Android.bp media/libeffects/lvm/wrapper/Android.bp media/libeffects/preprocessing/Android.bp media/libeffects/preprocessing/benchmarks/Android.bp media/libeffects/preprocessing/tests/Android.bp media/libeffects/proxy/Android.bp media/libeffects/visualizer/Android.bp media/libheif/Android.bp media/libmedia/Android.bp media/libmedia/tests/codeclist/Android.bp media/libmedia/tests/mediaplayer/Android.bp media/libmedia/xsd/Android.bp media/libmedia/xsd/vts/Android.bp media/libmediahelper/Android.bp media/libmediahelper/tests/Android.bp media/libmediametrics/Android.bp media/libmediaplayerservice/Android.bp media/libmediaplayerservice/datasource/Android.bp media/libmediaplayerservice/nuplayer/Android.bp media/libmediaplayerservice/tests/Android.bp media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp media/libmediatranscoding/Android.bp media/libmediatranscoding/tests/Android.bp media/libmediatranscoding/transcoder/Android.bp media/libmediatranscoding/transcoder/benchmark/Android.bp media/libmediatranscoding/transcoder/tests/Android.bp media/libmediatranscoding/transcoder/tests/fuzzer/Android.bp media/libnbaio/Android.bp media/libnblog/Android.bp media/libshmem/Android.bp media/libstagefright/Android.bp media/libstagefright/bqhelper/Android.bp media/libstagefright/bqhelper/tests/Android.bp media/libstagefright/codecs/aacdec/Android.bp media/libstagefright/codecs/aacenc/Android.bp media/libstagefright/codecs/amrnb/dec/Android.bp media/libstagefright/codecs/amrnb/enc/Android.bp media/libstagefright/codecs/amrwbenc/Android.bp media/libstagefright/codecs/avcdec/Android.bp media/libstagefright/codecs/avcenc/Android.bp media/libstagefright/codecs/common/Android.bp media/libstagefright/codecs/flac/dec/Android.bp media/libstagefright/codecs/flac/enc/Android.bp media/libstagefright/codecs/g711/dec/Android.bp media/libstagefright/codecs/gsm/dec/Android.bp media/libstagefright/codecs/hevcdec/Android.bp media/libstagefright/codecs/m4v_h263/dec/Android.bp media/libstagefright/codecs/m4v_h263/enc/Android.bp media/libstagefright/codecs/mp3dec/Android.bp media/libstagefright/codecs/mpeg2dec/Android.bp media/libstagefright/codecs/on2/dec/Android.bp media/libstagefright/codecs/on2/enc/Android.bp media/libstagefright/codecs/opus/dec/Android.bp media/libstagefright/codecs/raw/Android.bp media/libstagefright/codecs/vorbis/dec/Android.bp media/libstagefright/codecs/xaacdec/Android.bp media/libstagefright/colorconversion/Android.bp media/libstagefright/data/Android.bp media/libstagefright/filters/Android.bp media/libstagefright/flac/dec/Android.bp media/libstagefright/flac/dec/test/Android.bp media/libstagefright/foundation/Android.bp media/libstagefright/foundation/tests/AVCUtils/Android.bp media/libstagefright/foundation/tests/Android.bp media/libstagefright/foundation/tests/OpusHeader/Android.bp media/libstagefright/foundation/tests/colorutils/Android.bp media/libstagefright/http/Android.bp media/libstagefright/httplive/Android.bp media/libstagefright/id3/Android.bp media/libstagefright/id3/test/Android.bp media/libstagefright/mpeg2ts/Android.bp media/libstagefright/mpeg2ts/test/Android.bp media/libstagefright/omx/Android.bp media/libstagefright/omx/tests/Android.bp media/libstagefright/renderfright/Android.bp media/libstagefright/renderfright/tests/Android.bp media/libstagefright/rtsp/Android.bp media/libstagefright/tests/Android.bp media/libstagefright/tests/ESDS/Android.bp media/libstagefright/tests/HEVC/Android.bp media/libstagefright/tests/extractorFactory/Android.bp media/libstagefright/tests/fuzzers/Android.bp media/libstagefright/tests/mediacodec/Android.bp media/libstagefright/tests/metadatautils/Android.bp media/libstagefright/tests/writer/Android.bp media/libstagefright/timedtext/Android.bp media/libstagefright/timedtext/test/Android.bp media/libstagefright/webm/Android.bp media/libstagefright/webm/tests/Android.bp media/libstagefright/writer_fuzzers/Android.bp media/libstagefright/xmlparser/Android.bp media/libstagefright/xmlparser/test/Android.bp media/libstagefright/xmlparser/vts/Android.bp media/libwatchdog/Android.bp media/mediaserver/Android.bp media/mtp/Android.bp media/mtp/tests/MtpFfsHandleTest/Android.bp media/mtp/tests/MtpFuzzer/Android.bp media/mtp/tests/PosixAsyncIOTest/Android.bp media/tests/benchmark/Android.bp media/tests/benchmark/MediaBenchmarkTest/Android.bp media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp media/tests/benchmark/src/native/common/Android.bp media/tests/benchmark/src/native/decoder/Android.bp media/tests/benchmark/src/native/encoder/Android.bp media/tests/benchmark/src/native/extractor/Android.bp media/tests/benchmark/src/native/muxer/Android.bp media/tests/benchmark/tests/Android.bp media/utils/Android.bp media/utils/fuzzers/Android.bp media/utils/tests/Android.bp services/audioflinger/Android.bp services/audiopolicy/Android.bp services/audiopolicy/common/Android.bp services/audiopolicy/common/managerdefinitions/Android.bp services/audiopolicy/config/Android.bp services/audiopolicy/engine/common/Android.bp services/audiopolicy/engine/config/Android.bp services/audiopolicy/engine/config/tests/Android.bp services/audiopolicy/engine/config/tests/resources/Android.bp services/audiopolicy/engine/interface/Android.bp services/audiopolicy/engineconfigurable/Android.bp services/audiopolicy/engineconfigurable/config/Android.bp services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp services/audiopolicy/engineconfigurable/config/example/phone/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp services/audiopolicy/engineconfigurable/tools/Android.bp services/audiopolicy/engineconfigurable/wrapper/Android.bp services/audiopolicy/enginedefault/Android.bp services/audiopolicy/enginedefault/config/example/Android.bp services/audiopolicy/fuzzer/Android.bp services/audiopolicy/fuzzer/resources/Android.bp services/audiopolicy/managerdefault/Android.bp services/audiopolicy/service/Android.bp services/audiopolicy/tests/Android.bp services/audiopolicy/tests/resources/Android.bp services/camera/libcameraservice/Android.bp services/camera/libcameraservice/fuzzer/Android.bp services/camera/libcameraservice/tests/Android.mk services/mediacodec/Android.bp services/mediacodec/registrant/Android.bp services/mediaextractor/Android.bp services/medialog/Android.bp services/medialog/fuzzer/Android.bp services/mediametrics/Android.bp services/mediametrics/benchmarks/Android.bp services/mediametrics/fuzzer/Android.bp services/mediametrics/tests/Android.bp services/mediaresourcemanager/Android.bp services/mediaresourcemanager/fuzzer/Android.bp services/mediaresourcemanager/test/Android.bp services/mediatranscoding/Android.bp services/mediatranscoding/tests/Android.bp services/mediatranscoding/tests/TranscodingUidPolicyTestApp/Android.bp services/minijail/Android.bp services/oboeservice/Android.bp services/tuner/Android.bp Added SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD to: media/codecs/amrnb/dec/Android.bp media/codecs/amrnb/dec/test/Android.bp media/codecs/amrnb/enc/Android.bp media/codecs/amrnb/enc/test/Android.bp media/codecs/amrwb/dec/Android.bp media/codecs/amrwb/dec/test/Android.bp media/codecs/m4v_h263/enc/Android.bp media/codecs/m4v_h263/enc/test/Android.bp media/codecs/mp3dec/Android.bp media/codecs/mp3dec/test/Android.bp Added SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD SPDX-license-identifier-MIT SPDX-license-identifier-Unicode-DFS legacy_by_exception_only to: Android.bp Added SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-MIT SPDX-license-identifier-Unicode-DFS to: camera/Android.bp camera/ndk/Android.bp media/ndk/Android.bp Added SPDX-license-identifier-Apache-2.0 legacy_by_exception_only to: drm/mediadrm/plugins/clearkey/hidl/Android.bp Bug: 68860345 Bug: 151177513 Bug: 151953481 Test: m all Exempt-From-Owner-Approval: janitorial work Change-Id: I1c597c0977f3d1f7e067d0797397291a58dacd18 --- Android.bp | 36 +++++++++++++++++++ apex/Android.bp | 9 +++++ apex/testing/Android.bp | 9 +++++ camera/Android.bp | 31 ++++++++++++++++ camera/cameraserver/Android.bp | 9 +++++ camera/ndk/Android.bp | 31 ++++++++++++++++ camera/tests/Android.mk | 3 ++ cmds/screenrecord/Android.bp | 9 +++++ cmds/stagefright/Android.mk | 24 +++++++++++++ drm/common/Android.bp | 17 +++++++++ drm/drmserver/Android.bp | 17 +++++++++ drm/libdrmframework/Android.bp | 18 +++++++++- .../plugins/common/util/Android.bp | 19 ++++++++++ .../forward-lock/FwdLockEngine/Android.bp | 19 ++++++++++ .../internal-format/common/Android.bp | 9 +++++ .../internal-format/converter/Android.bp | 9 +++++ .../internal-format/decoder/Android.bp | 9 +++++ .../plugins/passthru/Android.bp | 19 ++++++++++ drm/libmediadrm/Android.bp | 9 +++++ drm/libmediadrm/fuzzer/Android.bp | 9 +++++ drm/libmediadrm/protos/Android.bp | 9 +++++ drm/libmediadrm/tests/Android.bp | 9 +++++ drm/mediacas/plugins/clearkey/Android.bp | 9 +++++ .../plugins/clearkey/tests/Android.bp | 9 +++++ drm/mediacas/plugins/mock/Android.bp | 9 +++++ .../plugins/clearkey/common/Android.bp | 10 +++++- .../plugins/clearkey/default/Android.bp | 10 +++++- .../plugins/clearkey/default/tests/Android.bp | 9 +++++ drm/mediadrm/plugins/clearkey/hidl/Android.bp | 13 +++++++ drm/mediadrm/plugins/mock/Android.bp | 9 +++++ media/audioserver/Android.bp | 9 +++++ media/bufferpool/1.0/Android.bp | 9 +++++ media/bufferpool/1.0/vts/Android.bp | 9 +++++ media/bufferpool/2.0/Android.bp | 10 +++++- media/bufferpool/2.0/tests/Android.bp | 9 +++++ media/codec2/components/aac/Android.bp | 19 ++++++++++ media/codec2/components/amr_nb_wb/Android.bp | 19 ++++++++++ media/codec2/components/aom/Android.bp | 9 +++++ media/codec2/components/avc/Android.bp | 9 +++++ media/codec2/components/base/Android.bp | 9 +++++ media/codec2/components/cmds/Android.bp | 9 +++++ media/codec2/components/flac/Android.bp | 19 ++++++++++ media/codec2/components/g711/Android.bp | 19 ++++++++++ media/codec2/components/gav1/Android.bp | 9 +++++ media/codec2/components/gsm/Android.bp | 19 ++++++++++ media/codec2/components/hevc/Android.bp | 9 +++++ media/codec2/components/mp3/Android.bp | 19 ++++++++++ media/codec2/components/mpeg2/Android.bp | 9 +++++ media/codec2/components/mpeg4_h263/Android.bp | 19 ++++++++++ media/codec2/components/opus/Android.bp | 9 +++++ media/codec2/components/raw/Android.bp | 19 ++++++++++ media/codec2/components/vorbis/Android.bp | 19 ++++++++++ media/codec2/components/vpx/Android.bp | 20 ++++++++++- media/codec2/components/xaac/Android.bp | 9 +++++ media/codec2/core/Android.bp | 10 +++++- media/codec2/faultinjection/Android.bp | 10 +++++- media/codec2/fuzzer/Android.bp | 9 +++++ media/codec2/hidl/1.0/utils/Android.bp | 9 +++++ .../codec2/hidl/1.0/vts/functional/Android.bp | 11 +++++- .../hidl/1.0/vts/functional/audio/Android.bp | 9 +++++ .../hidl/1.0/vts/functional/common/Android.bp | 9 +++++ .../1.0/vts/functional/component/Android.bp | 10 +++++- .../hidl/1.0/vts/functional/master/Android.bp | 10 +++++- .../hidl/1.0/vts/functional/video/Android.bp | 10 +++++- media/codec2/hidl/1.1/utils/Android.bp | 9 +++++ media/codec2/hidl/client/Android.bp | 10 +++++- media/codec2/hidl/plugin/Android.bp | 9 +++++ media/codec2/hidl/plugin/samples/Android.bp | 9 +++++ media/codec2/hidl/services/Android.bp | 10 +++++- media/codec2/sfplugin/Android.bp | 9 +++++ media/codec2/sfplugin/tests/Android.bp | 9 +++++ media/codec2/sfplugin/utils/Android.bp | 9 +++++ media/codec2/tests/Android.bp | 9 +++++ media/codec2/vndk/Android.bp | 10 +++++- media/codecs/amrnb/common/Android.bp | 19 ++++++++++ media/codecs/amrnb/dec/Android.bp | 32 +++++++++++++++++ media/codecs/amrnb/dec/test/Android.bp | 12 +++++++ media/codecs/amrnb/enc/Android.bp | 32 +++++++++++++++++ media/codecs/amrnb/enc/fuzzer/Android.bp | 11 ++++++ media/codecs/amrnb/enc/test/Android.bp | 12 +++++++ media/codecs/amrnb/fuzzer/Android.bp | 9 +++++ media/codecs/amrwb/dec/Android.bp | 32 +++++++++++++++++ media/codecs/amrwb/dec/fuzzer/Android.bp | 11 ++++++ media/codecs/amrwb/dec/test/Android.bp | 12 +++++++ media/codecs/amrwb/enc/Android.bp | 21 +++++++++-- media/codecs/amrwb/enc/SampleCode/Android.bp | 19 ++++++++++ media/codecs/amrwb/enc/fuzzer/Android.bp | 11 ++++++ media/codecs/amrwb/enc/test/Android.bp | 11 ++++++ media/codecs/g711/decoder/Android.bp | 9 +++++ media/codecs/g711/fuzzer/Android.bp | 9 +++++ media/codecs/m4v_h263/dec/Android.bp | 20 ++++++++++- media/codecs/m4v_h263/dec/test/Android.bp | 11 ++++++ media/codecs/m4v_h263/enc/Android.bp | 32 +++++++++++++++++ media/codecs/m4v_h263/enc/test/Android.bp | 12 +++++++ media/codecs/m4v_h263/fuzzer/Android.bp | 9 +++++ media/codecs/mp3dec/Android.bp | 30 ++++++++++++++++ media/codecs/mp3dec/fuzzer/Android.bp | 9 +++++ media/codecs/mp3dec/test/Android.bp | 10 ++++++ media/extractors/Android.bp | 11 +++++- media/extractors/aac/Android.bp | 17 +++++++++ media/extractors/amr/Android.bp | 17 +++++++++ media/extractors/flac/Android.bp | 19 ++++++++++ media/extractors/fuzzers/Android.bp | 9 +++++ media/extractors/midi/Android.bp | 19 ++++++++++ media/extractors/mkv/Android.bp | 17 +++++++++ media/extractors/mp3/Android.bp | 9 +++++ media/extractors/mp4/Android.bp | 17 +++++++++ media/extractors/mpeg2/Android.bp | 19 ++++++++++ media/extractors/ogg/Android.bp | 17 +++++++++ media/extractors/tests/Android.bp | 9 +++++ media/extractors/wav/Android.bp | 17 +++++++++ media/img_utils/Android.bp | 9 +++++ media/libaaudio/Android.bp | 9 +++++ media/libaaudio/examples/Android.bp | 9 +++++ .../examples/input_monitor/Android.bp | 9 +++++ media/libaaudio/examples/loopback/Android.bp | 9 +++++ .../libaaudio/examples/write_sine/Android.bp | 9 +++++ media/libaaudio/src/Android.bp | 9 +++++ media/libaaudio/tests/Android.bp | 9 +++++ media/libaudioclient/Android.bp | 9 +++++ media/libaudioclient/fuzzer/Android.bp | 9 +++++ media/libaudioclient/tests/Android.bp | 9 +++++ media/libaudiofoundation/Android.bp | 9 +++++ media/libaudiofoundation/tests/Android.bp | 9 +++++ media/libaudiohal/Android.bp | 9 +++++ media/libaudiohal/impl/Android.bp | 9 +++++ media/libaudioprocessing/Android.bp | 9 +++++ .../audio-resampler/Android.bp | 9 +++++ media/libaudioprocessing/tests/Android.bp | 9 +++++ .../tests/fuzzer/Android.bp | 9 +++++ media/libcpustats/Android.bp | 9 +++++ media/libdatasource/Android.bp | 9 +++++ media/libeffects/config/Android.bp | 9 +++++ media/libeffects/downmix/Android.bp | 19 ++++++++++ media/libeffects/downmix/tests/Android.bp | 11 ++++++ media/libeffects/dynamicsproc/Android.bp | 19 ++++++++++ media/libeffects/factory/Android.bp | 9 +++++ media/libeffects/hapticgenerator/Android.bp | 10 +++++- media/libeffects/loudness/Android.bp | 19 ++++++++++ media/libeffects/lvm/benchmarks/Android.bp | 9 +++++ media/libeffects/lvm/lib/Android.bp | 19 ++++++++++ media/libeffects/lvm/tests/Android.bp | 9 +++++ media/libeffects/lvm/wrapper/Android.bp | 19 ++++++++++ media/libeffects/preprocessing/Android.bp | 19 ++++++++++ .../preprocessing/benchmarks/Android.bp | 11 ++++++ .../libeffects/preprocessing/tests/Android.bp | 11 ++++++ media/libeffects/proxy/Android.bp | 9 +++++ media/libeffects/visualizer/Android.bp | 19 ++++++++++ media/libheif/Android.bp | 9 +++++ media/libmedia/Android.bp | 17 +++++++++ media/libmedia/tests/codeclist/Android.bp | 9 +++++ media/libmedia/tests/mediaplayer/Android.bp | 9 +++++ media/libmedia/xsd/Android.bp | 9 +++++ media/libmedia/xsd/vts/Android.bp | 9 +++++ media/libmediahelper/Android.bp | 9 +++++ media/libmediahelper/tests/Android.bp | 9 +++++ media/libmediametrics/Android.bp | 9 +++++ media/libmediaplayerservice/Android.bp | 20 ++++++++++- .../datasource/Android.bp | 11 ++++++ .../libmediaplayerservice/nuplayer/Android.bp | 19 ++++++++++ media/libmediaplayerservice/tests/Android.bp | 11 ++++++ .../tests/stagefrightRecorder/Android.bp | 11 ++++++ media/libmediatranscoding/Android.bp | 9 +++++ media/libmediatranscoding/tests/Android.bp | 9 +++++ .../libmediatranscoding/transcoder/Android.bp | 10 +++++- .../transcoder/benchmark/Android.bp | 9 +++++ .../transcoder/tests/Android.bp | 9 +++++ .../transcoder/tests/fuzzer/Android.bp | 9 +++++ media/libnbaio/Android.bp | 9 +++++ media/libnblog/Android.bp | 9 +++++ media/libshmem/Android.bp | 9 +++++ media/libstagefright/Android.bp | 17 +++++++++ media/libstagefright/bqhelper/Android.bp | 9 +++++ .../libstagefright/bqhelper/tests/Android.bp | 9 +++++ media/libstagefright/codecs/aacdec/Android.bp | 19 ++++++++++ media/libstagefright/codecs/aacenc/Android.bp | 19 ++++++++++ .../codecs/amrnb/dec/Android.bp | 10 +++++- .../codecs/amrnb/enc/Android.bp | 10 +++++- .../libstagefright/codecs/amrwbenc/Android.bp | 10 +++++- media/libstagefright/codecs/avcdec/Android.bp | 9 +++++ media/libstagefright/codecs/avcenc/Android.bp | 9 +++++ media/libstagefright/codecs/common/Android.bp | 19 ++++++++++ .../libstagefright/codecs/flac/dec/Android.bp | 19 ++++++++++ .../libstagefright/codecs/flac/enc/Android.bp | 19 ++++++++++ .../libstagefright/codecs/g711/dec/Android.bp | 19 ++++++++++ .../libstagefright/codecs/gsm/dec/Android.bp | 19 ++++++++++ .../libstagefright/codecs/hevcdec/Android.bp | 9 +++++ .../codecs/m4v_h263/dec/Android.bp | 9 +++++ .../codecs/m4v_h263/enc/Android.bp | 10 +++++- media/libstagefright/codecs/mp3dec/Android.bp | 10 +++++- .../libstagefright/codecs/mpeg2dec/Android.bp | 9 +++++ .../libstagefright/codecs/on2/dec/Android.bp | 19 ++++++++++ .../libstagefright/codecs/on2/enc/Android.bp | 19 ++++++++++ .../libstagefright/codecs/opus/dec/Android.bp | 9 +++++ media/libstagefright/codecs/raw/Android.bp | 19 ++++++++++ .../codecs/vorbis/dec/Android.bp | 19 ++++++++++ .../libstagefright/codecs/xaacdec/Android.bp | 9 +++++ .../libstagefright/colorconversion/Android.bp | 19 ++++++++++ media/libstagefright/data/Android.bp | 9 +++++ media/libstagefright/filters/Android.bp | 9 +++++ media/libstagefright/flac/dec/Android.bp | 19 ++++++++++ media/libstagefright/flac/dec/test/Android.bp | 11 ++++++ media/libstagefright/foundation/Android.bp | 19 ++++++++++ .../foundation/tests/AVCUtils/Android.bp | 11 ++++++ .../foundation/tests/Android.bp | 11 ++++++ .../foundation/tests/OpusHeader/Android.bp | 11 ++++++ .../foundation/tests/colorutils/Android.bp | 11 ++++++ media/libstagefright/http/Android.bp | 9 +++++ media/libstagefright/httplive/Android.bp | 19 ++++++++++ media/libstagefright/id3/Android.bp | 19 ++++++++++ media/libstagefright/id3/test/Android.bp | 11 ++++++ media/libstagefright/mpeg2ts/Android.bp | 19 ++++++++++ media/libstagefright/mpeg2ts/test/Android.bp | 11 ++++++ media/libstagefright/omx/Android.bp | 20 ++++++++++- media/libstagefright/omx/tests/Android.bp | 19 ++++++++++ media/libstagefright/renderfright/Android.bp | 9 +++++ .../renderfright/tests/Android.bp | 9 +++++ media/libstagefright/rtsp/Android.bp | 19 ++++++++++ media/libstagefright/tests/Android.bp | 19 ++++++++++ media/libstagefright/tests/ESDS/Android.bp | 11 ++++++ media/libstagefright/tests/HEVC/Android.bp | 11 ++++++ .../tests/extractorFactory/Android.bp | 11 ++++++ media/libstagefright/tests/fuzzers/Android.bp | 11 ++++++ .../tests/mediacodec/Android.bp | 11 ++++++ .../tests/metadatautils/Android.bp | 11 ++++++ media/libstagefright/tests/writer/Android.bp | 11 ++++++ media/libstagefright/timedtext/Android.bp | 21 +++++++++-- .../libstagefright/timedtext/test/Android.bp | 11 ++++++ media/libstagefright/webm/Android.bp | 9 +++++ media/libstagefright/webm/tests/Android.bp | 9 +++++ .../libstagefright/writer_fuzzers/Android.bp | 9 +++++ media/libstagefright/xmlparser/Android.bp | 10 +++++- .../libstagefright/xmlparser/test/Android.bp | 9 +++++ media/libstagefright/xmlparser/vts/Android.bp | 9 +++++ media/libwatchdog/Android.bp | 9 +++++ media/mediaserver/Android.bp | 17 +++++++++ media/mtp/Android.bp | 18 +++++++++- media/mtp/tests/MtpFfsHandleTest/Android.bp | 10 +++++- media/mtp/tests/MtpFuzzer/Android.bp | 9 +++++ media/mtp/tests/PosixAsyncIOTest/Android.bp | 9 +++++ media/ndk/Android.bp | 31 ++++++++++++++++ media/tests/benchmark/Android.bp | 9 +++++ .../benchmark/MediaBenchmarkTest/Android.bp | 9 +++++ .../src/main/cpp/Android.bp | 9 +++++ .../benchmark/src/native/common/Android.bp | 9 +++++ .../benchmark/src/native/decoder/Android.bp | 9 +++++ .../benchmark/src/native/encoder/Android.bp | 9 +++++ .../benchmark/src/native/extractor/Android.bp | 9 +++++ .../benchmark/src/native/muxer/Android.bp | 9 +++++ media/tests/benchmark/tests/Android.bp | 9 +++++ media/utils/Android.bp | 9 +++++ media/utils/fuzzers/Android.bp | 9 +++++ media/utils/tests/Android.bp | 9 +++++ services/audioflinger/Android.bp | 19 ++++++++++ services/audiopolicy/Android.bp | 9 +++++ services/audiopolicy/common/Android.bp | 9 +++++ .../common/managerdefinitions/Android.bp | 9 +++++ services/audiopolicy/config/Android.bp | 9 +++++ services/audiopolicy/engine/common/Android.bp | 9 +++++ services/audiopolicy/engine/config/Android.bp | 9 +++++ .../engine/config/tests/Android.bp | 9 +++++ .../engine/config/tests/resources/Android.bp | 9 +++++ .../audiopolicy/engine/interface/Android.bp | 9 +++++ .../audiopolicy/engineconfigurable/Android.bp | 9 +++++ .../engineconfigurable/config/Android.bp | 9 +++++ .../config/example/automotive/Android.bp | 9 +++++ .../config/example/caremu/Android.bp | 9 +++++ .../config/example/phone/Android.bp | 9 +++++ .../parameter-framework/Android.bp | 9 +++++ .../examples/Car/Android.bp | 9 +++++ .../examples/CarEmu/Android.bp | 9 +++++ .../examples/Phone/Android.bp | 9 +++++ .../examples/SettingsNoInput/Android.bp | 9 +++++ .../examples/SettingsNoOutput/Android.bp | 9 +++++ .../parameter-framework/plugin/Android.bp | 9 +++++ .../engineconfigurable/tools/Android.bp | 9 +++++ .../engineconfigurable/wrapper/Android.bp | 9 +++++ services/audiopolicy/enginedefault/Android.bp | 9 +++++ .../enginedefault/config/example/Android.bp | 9 +++++ services/audiopolicy/fuzzer/Android.bp | 9 +++++ .../audiopolicy/fuzzer/resources/Android.bp | 9 +++++ .../audiopolicy/managerdefault/Android.bp | 9 +++++ services/audiopolicy/service/Android.bp | 9 +++++ services/audiopolicy/tests/Android.bp | 9 +++++ .../audiopolicy/tests/resources/Android.bp | 9 +++++ services/camera/libcameraservice/Android.bp | 20 ++++++++++- .../camera/libcameraservice/fuzzer/Android.bp | 11 ++++++ .../camera/libcameraservice/tests/Android.mk | 3 ++ services/mediacodec/Android.bp | 17 +++++++++ services/mediacodec/registrant/Android.bp | 10 +++++- services/mediaextractor/Android.bp | 20 ++++++++++- services/medialog/Android.bp | 9 +++++ services/medialog/fuzzer/Android.bp | 9 +++++ services/mediametrics/Android.bp | 9 +++++ services/mediametrics/benchmarks/Android.bp | 9 +++++ services/mediametrics/fuzzer/Android.bp | 9 +++++ services/mediametrics/tests/Android.bp | 9 +++++ services/mediaresourcemanager/Android.bp | 9 +++++ .../mediaresourcemanager/fuzzer/Android.bp | 9 +++++ services/mediaresourcemanager/test/Android.bp | 9 +++++ services/mediatranscoding/Android.bp | 19 ++++++++++ services/mediatranscoding/tests/Android.bp | 11 ++++++ .../TranscodingUidPolicyTestApp/Android.bp | 13 ++++++- services/minijail/Android.bp | 9 +++++ services/oboeservice/Android.bp | 9 +++++ services/tuner/Android.bp | 9 +++++ 306 files changed, 3703 insertions(+), 36 deletions(-) diff --git a/Android.bp b/Android.bp index 944cdc115b..60f0ff1b73 100644 --- a/Android.bp +++ b/Android.bp @@ -1,3 +1,39 @@ +// *** THIS PACKAGE HAS SPECIAL LICENSING CONDITIONS. PLEASE +// CONSULT THE OWNERS AND opensource-licensing@google.com BEFORE +// DEPENDING ON IT IN YOUR PROJECT. *** +package { + default_applicable_licenses: ["frameworks_av_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + "SPDX-license-identifier-MIT", + "SPDX-license-identifier-Unicode-DFS", + "legacy_by_exception_only", // by exception only + ], + license_text: [ + "NOTICE", + ], +} + aidl_interface { name: "av-types-aidl", unstable: true, diff --git a/apex/Android.bp b/apex/Android.bp index 729a282596..aacb9a820f 100644 --- a/apex/Android.bp +++ b/apex/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + apex_defaults { name: "com.android.media-defaults", updatable: true, diff --git a/apex/testing/Android.bp b/apex/testing/Android.bp index d86094e3de..8b810901b5 100644 --- a/apex/testing/Android.bp +++ b/apex/testing/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + apex_test { name: "test_com.android.media", manifest: "test_manifest.json", diff --git a/camera/Android.bp b/camera/Android.bp index a9e00d06ae..71c88ab957 100644 --- a/camera/Android.bp +++ b/camera/Android.bp @@ -12,6 +12,37 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + default_applicable_licenses: ["frameworks_av_camera_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_camera_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-MIT", + "SPDX-license-identifier-Unicode-DFS", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libcamera_client", diff --git a/camera/cameraserver/Android.bp b/camera/cameraserver/Android.bp index 5c3e3b0905..9398ec31c2 100644 --- a/camera/cameraserver/Android.bp +++ b/camera/cameraserver/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_camera_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_camera_license"], +} + cc_binary { name: "cameraserver", diff --git a/camera/ndk/Android.bp b/camera/ndk/Android.bp index 5e1e43e0ea..fef873b4c4 100644 --- a/camera/ndk/Android.bp +++ b/camera/ndk/Android.bp @@ -16,6 +16,37 @@ // to refer to headers in parent directories and the headers live in // frameworks/av/include. +package { + default_applicable_licenses: ["frameworks_av_camera_ndk_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_camera_ndk_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-MIT", + "SPDX-license-identifier-Unicode-DFS", + ], + license_text: [ + "NOTICE", + ], +} + ndk_library { name: "libcamera2ndk", symbol_file: "libcamera2ndk.map.txt", diff --git a/camera/tests/Android.mk b/camera/tests/Android.mk index e5c163137c..7f8078e7d3 100644 --- a/camera/tests/Android.mk +++ b/camera/tests/Android.mk @@ -42,6 +42,9 @@ LOCAL_C_INCLUDES += \ LOCAL_CFLAGS += -Wall -Wextra -Werror LOCAL_MODULE:= camera_client_test +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../NOTICE LOCAL_MODULE_TAGS := tests include $(BUILD_NATIVE_TEST) diff --git a/cmds/screenrecord/Android.bp b/cmds/screenrecord/Android.bp index d7d905fbca..359a8350da 100644 --- a/cmds/screenrecord/Android.bp +++ b/cmds/screenrecord/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_binary { name: "screenrecord", diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk index 6470fb1024..ef4c568764 100644 --- a/cmds/stagefright/Android.mk +++ b/cmds/stagefright/Android.mk @@ -28,6 +28,9 @@ LOCAL_MODULE_TAGS := optional LOCAL_SYSTEM_EXT_MODULE:= true LOCAL_MODULE:= stagefright +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -58,6 +61,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= record +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -86,6 +92,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= recordvideo +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -115,6 +124,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= audioloop +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -141,6 +153,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= stream +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -169,6 +184,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= codec +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) @@ -214,6 +232,9 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= mediafilter +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE LOCAL_SANITIZE := cfi @@ -242,5 +263,8 @@ LOCAL_CFLAGS += -Wno-multichar -Werror -Wall LOCAL_MODULE_TAGS := optional LOCAL_MODULE:= muxer +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/NOTICE include $(BUILD_EXECUTABLE) diff --git a/drm/common/Android.bp b/drm/common/Android.bp index 248570e126..76ee22ec7b 100644 --- a/drm/common/Android.bp +++ b/drm/common/Android.bp @@ -14,6 +14,23 @@ // limitations under the License. // +package { + default_applicable_licenses: ["frameworks_av_drm_common_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_common_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libdrmframeworkcommon", diff --git a/drm/drmserver/Android.bp b/drm/drmserver/Android.bp index 8b7c551d37..df3a6a218b 100644 --- a/drm/drmserver/Android.bp +++ b/drm/drmserver/Android.bp @@ -14,6 +14,23 @@ // limitations under the License. // +package { + default_applicable_licenses: ["frameworks_av_drm_drmserver_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_drmserver_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_binary { name: "drmserver", diff --git a/drm/libdrmframework/Android.bp b/drm/libdrmframework/Android.bp index b4a7b2595e..dbce5ea337 100644 --- a/drm/libdrmframework/Android.bp +++ b/drm/libdrmframework/Android.bp @@ -14,6 +14,23 @@ // limitations under the License. // +package { + default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_libdrmframework_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libdrmframework", @@ -37,4 +54,3 @@ cc_library_shared { cflags: ["-Werror"], } - diff --git a/drm/libdrmframework/plugins/common/util/Android.bp b/drm/libdrmframework/plugins/common/util/Android.bp index 7372eb774e..a47b4a1adb 100644 --- a/drm/libdrmframework/plugins/common/util/Android.bp +++ b/drm/libdrmframework/plugins/common/util/Android.bp @@ -14,6 +14,25 @@ // limitations under the License. // +package { + default_applicable_licenses: [ + "frameworks_av_drm_libdrmframework_plugins_common_util_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_libdrmframework_plugins_common_util_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libdrmutility", diff --git a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp index 9f52f7af32..be2b546b33 100644 --- a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp +++ b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.bp @@ -14,6 +14,25 @@ // limitations under the License. // +package { + default_applicable_licenses: [ + "frameworks_av_drm_libdrmframework_plugins_forward-lock_FwdLockEngine_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_libdrmframework_plugins_forward-lock_FwdLockEngine_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libfwdlockengine", diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp index 3be327ad95..2e4070bfd4 100644 --- a/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp +++ b/drm/libdrmframework/plugins/forward-lock/internal-format/common/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"], +} + cc_library_static { name: "libfwdlock-common", diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp index d4e04b8218..51c778fb0b 100644 --- a/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp +++ b/drm/libdrmframework/plugins/forward-lock/internal-format/converter/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"], +} + cc_library_static { name: "libfwdlock-converter", diff --git a/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp b/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp index 0bf2737c6f..6773fe1509 100644 --- a/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp +++ b/drm/libdrmframework/plugins/forward-lock/internal-format/decoder/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_drm_libdrmframework_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_drm_libdrmframework_license"], +} + cc_library_static { name: "libfwdlock-decoder", diff --git a/drm/libdrmframework/plugins/passthru/Android.bp b/drm/libdrmframework/plugins/passthru/Android.bp index 8045586741..6dffd49d7a 100644 --- a/drm/libdrmframework/plugins/passthru/Android.bp +++ b/drm/libdrmframework/plugins/passthru/Android.bp @@ -14,6 +14,25 @@ // limitations under the License. // +package { + default_applicable_licenses: [ + "frameworks_av_drm_libdrmframework_plugins_passthru_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_drm_libdrmframework_plugins_passthru_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libdrmpassthruplugin", diff --git a/drm/libmediadrm/Android.bp b/drm/libmediadrm/Android.bp index b042c27564..0ffe626550 100644 --- a/drm/libmediadrm/Android.bp +++ b/drm/libmediadrm/Android.bp @@ -2,6 +2,15 @@ // libmediadrm // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libmediadrm_headers", diff --git a/drm/libmediadrm/fuzzer/Android.bp b/drm/libmediadrm/fuzzer/Android.bp index 5e389b4d6b..7281066083 100644 --- a/drm/libmediadrm/fuzzer/Android.bp +++ b/drm/libmediadrm/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "mediadrm_fuzzer", srcs: [ diff --git a/drm/libmediadrm/protos/Android.bp b/drm/libmediadrm/protos/Android.bp index b26cda4cee..f8d237ab87 100644 --- a/drm/libmediadrm/protos/Android.bp +++ b/drm/libmediadrm/protos/Android.bp @@ -15,6 +15,15 @@ // This is the version of the drm metrics configured for protobuf full on host. // It is used by the metrics_dump tool. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_host_shared { name: "libdrm_metrics_protos_full_host", vendor_available: true, diff --git a/drm/libmediadrm/tests/Android.bp b/drm/libmediadrm/tests/Android.bp index 6529387e2e..9267e79bd0 100644 --- a/drm/libmediadrm/tests/Android.bp +++ b/drm/libmediadrm/tests/Android.bp @@ -1,5 +1,14 @@ // Build definitions for unit tests. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "CounterMetric_test", srcs: ["CounterMetric_test.cpp"], diff --git a/drm/mediacas/plugins/clearkey/Android.bp b/drm/mediacas/plugins/clearkey/Android.bp index 0113cb88b6..569cdbe604 100644 --- a/drm/mediacas/plugins/clearkey/Android.bp +++ b/drm/mediacas/plugins/clearkey/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libclearkeycasplugin", diff --git a/drm/mediacas/plugins/clearkey/tests/Android.bp b/drm/mediacas/plugins/clearkey/tests/Android.bp index 575863c131..9ad8d1e8ad 100644 --- a/drm/mediacas/plugins/clearkey/tests/Android.bp +++ b/drm/mediacas/plugins/clearkey/tests/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "ClearKeyFetcherTest", diff --git a/drm/mediacas/plugins/mock/Android.bp b/drm/mediacas/plugins/mock/Android.bp index e8a3c6f824..6f68c774d8 100644 --- a/drm/mediacas/plugins/mock/Android.bp +++ b/drm/mediacas/plugins/mock/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libmockcasplugin", diff --git a/drm/mediadrm/plugins/clearkey/common/Android.bp b/drm/mediadrm/plugins/clearkey/common/Android.bp index 2c674e1f29..7ed8b88bf8 100644 --- a/drm/mediadrm/plugins/clearkey/common/Android.bp +++ b/drm/mediadrm/plugins/clearkey/common/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libclearkeycommon", vendor: true, @@ -35,4 +44,3 @@ cc_library_static { integer_overflow: true, }, } - diff --git a/drm/mediadrm/plugins/clearkey/default/Android.bp b/drm/mediadrm/plugins/clearkey/default/Android.bp index 9803d32d96..4b5389ae12 100644 --- a/drm/mediadrm/plugins/clearkey/default/Android.bp +++ b/drm/mediadrm/plugins/clearkey/default/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libdrmclearkeyplugin", vendor: true, @@ -60,4 +69,3 @@ cc_library_shared { integer_overflow: true, }, } - diff --git a/drm/mediadrm/plugins/clearkey/default/tests/Android.bp b/drm/mediadrm/plugins/clearkey/default/tests/Android.bp index 4419865705..b97e924db3 100644 --- a/drm/mediadrm/plugins/clearkey/default/tests/Android.bp +++ b/drm/mediadrm/plugins/clearkey/default/tests/Android.bp @@ -17,6 +17,15 @@ // Builds ClearKey Drm Tests // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "ClearKeyDrmUnitTest", vendor: true, diff --git a/drm/mediadrm/plugins/clearkey/hidl/Android.bp b/drm/mediadrm/plugins/clearkey/hidl/Android.bp index a194416c7f..e6e1f8009f 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/Android.bp +++ b/drm/mediadrm/plugins/clearkey/hidl/Android.bp @@ -14,6 +14,19 @@ // limitations under the License. // +// *** THIS PACKAGE HAS SPECIAL LICENSING CONDITIONS. PLEASE +// CONSULT THE OWNERS AND opensource-licensing@google.com BEFORE +// DEPENDING ON IT IN YOUR PROJECT. *** +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // legacy_by_exception_only (by exception only) + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "clearkey_service_defaults", vendor: true, diff --git a/drm/mediadrm/plugins/mock/Android.bp b/drm/mediadrm/plugins/mock/Android.bp index dd2ad7b454..20dfb4ae30 100644 --- a/drm/mediadrm/plugins/mock/Android.bp +++ b/drm/mediadrm/plugins/mock/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libmockdrmcryptoplugin", diff --git a/media/audioserver/Android.bp b/media/audioserver/Android.bp index ca3c81cc97..be25ffbe38 100644 --- a/media/audioserver/Android.bp +++ b/media/audioserver/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_binary { name: "audioserver", diff --git a/media/bufferpool/1.0/Android.bp b/media/bufferpool/1.0/Android.bp index f817c76dae..16cf9206f4 100644 --- a/media/bufferpool/1.0/Android.bp +++ b/media/bufferpool/1.0/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libstagefright_bufferpool@1.0", vendor_available: true, diff --git a/media/bufferpool/1.0/vts/Android.bp b/media/bufferpool/1.0/vts/Android.bp index 691ed4071d..0977ba5274 100644 --- a/media/bufferpool/1.0/vts/Android.bp +++ b/media/bufferpool/1.0/vts/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsVndkHidlBufferpoolV1_0TargetSingleTest", test_suites: ["device-tests"], diff --git a/media/bufferpool/2.0/Android.bp b/media/bufferpool/2.0/Android.bp index 536f75e64f..0d1fe27623 100644 --- a/media/bufferpool/2.0/Android.bp +++ b/media/bufferpool/2.0/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libstagefright_bufferpool@2.0-default", srcs: [ @@ -49,4 +58,3 @@ cc_library { enabled: true, }, } - diff --git a/media/bufferpool/2.0/tests/Android.bp b/media/bufferpool/2.0/tests/Android.bp index 56bda89b3d..803a813bcc 100644 --- a/media/bufferpool/2.0/tests/Android.bp +++ b/media/bufferpool/2.0/tests/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsVndkHidlBufferpoolV2_0TargetSingleTest", test_suites: ["device-tests"], diff --git a/media/codec2/components/aac/Android.bp b/media/codec2/components/aac/Android.bp index 50495a915b..c547e85946 100644 --- a/media/codec2/components/aac/Android.bp +++ b/media/codec2/components/aac/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_aac_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_aac_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_aacdec", defaults: [ diff --git a/media/codec2/components/amr_nb_wb/Android.bp b/media/codec2/components/amr_nb_wb/Android.bp index b09a50523d..1418ba51c9 100644 --- a/media/codec2/components/amr_nb_wb/Android.bp +++ b/media/codec2/components/amr_nb_wb/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_amr_nb_wb_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_amr_nb_wb_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_amrnbdec", defaults: [ diff --git a/media/codec2/components/aom/Android.bp b/media/codec2/components/aom/Android.bp index fcc45525fa..cb9837f054 100644 --- a/media/codec2/components/aom/Android.bp +++ b/media/codec2/components/aom/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_av1dec_aom", defaults: [ diff --git a/media/codec2/components/avc/Android.bp b/media/codec2/components/avc/Android.bp index 9f8bc68e71..0be1bed4a4 100644 --- a/media/codec2/components/avc/Android.bp +++ b/media/codec2/components/avc/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_avcdec", defaults: [ diff --git a/media/codec2/components/base/Android.bp b/media/codec2/components/base/Android.bp index cfdb9e7988..160e250235 100644 --- a/media/codec2/components/base/Android.bp +++ b/media/codec2/components/base/Android.bp @@ -1,5 +1,14 @@ // DO NOT DEPEND ON THIS DIRECTLY // use libcodec2_soft-defaults instead +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_common", defaults: ["libcodec2-impl-defaults"], diff --git a/media/codec2/components/cmds/Android.bp b/media/codec2/components/cmds/Android.bp index a081e2871c..d6ffd12fc2 100644 --- a/media/codec2/components/cmds/Android.bp +++ b/media/codec2/components/cmds/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_binary { name: "codec2play", defaults: ["libcodec2-impl-defaults"], diff --git a/media/codec2/components/flac/Android.bp b/media/codec2/components/flac/Android.bp index 603c4120f5..1143bedbc6 100644 --- a/media/codec2/components/flac/Android.bp +++ b/media/codec2/components/flac/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_flac_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_flac_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_flacdec", defaults: [ diff --git a/media/codec2/components/g711/Android.bp b/media/codec2/components/g711/Android.bp index c39df7b4c9..45e85a9825 100644 --- a/media/codec2/components/g711/Android.bp +++ b/media/codec2/components/g711/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_g711_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_g711_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_g711alawdec", defaults: [ diff --git a/media/codec2/components/gav1/Android.bp b/media/codec2/components/gav1/Android.bp index 32aa98d9d2..7692d3786d 100644 --- a/media/codec2/components/gav1/Android.bp +++ b/media/codec2/components/gav1/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_av1dec_gav1", defaults: [ diff --git a/media/codec2/components/gsm/Android.bp b/media/codec2/components/gsm/Android.bp index 7f54af8a15..2d0976daba 100644 --- a/media/codec2/components/gsm/Android.bp +++ b/media/codec2/components/gsm/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_gsm_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_gsm_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_gsmdec", defaults: [ diff --git a/media/codec2/components/hevc/Android.bp b/media/codec2/components/hevc/Android.bp index 1be0cfc9b5..d1388b95b4 100644 --- a/media/codec2/components/hevc/Android.bp +++ b/media/codec2/components/hevc/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_hevcdec", defaults: [ diff --git a/media/codec2/components/mp3/Android.bp b/media/codec2/components/mp3/Android.bp index b4fb1b07ea..437d34f0d3 100644 --- a/media/codec2/components/mp3/Android.bp +++ b/media/codec2/components/mp3/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_mp3_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_mp3_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_mp3dec", defaults: [ diff --git a/media/codec2/components/mpeg2/Android.bp b/media/codec2/components/mpeg2/Android.bp index 666e69770b..daa10aef76 100644 --- a/media/codec2/components/mpeg2/Android.bp +++ b/media/codec2/components/mpeg2/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_mpeg2dec", defaults: [ diff --git a/media/codec2/components/mpeg4_h263/Android.bp b/media/codec2/components/mpeg4_h263/Android.bp index 0673709309..e19fa45c10 100644 --- a/media/codec2/components/mpeg4_h263/Android.bp +++ b/media/codec2/components/mpeg4_h263/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_mpeg4_h263_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_mpeg4_h263_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_mpeg4dec", defaults: [ diff --git a/media/codec2/components/opus/Android.bp b/media/codec2/components/opus/Android.bp index 32e2bf8117..bfba45cf00 100644 --- a/media/codec2/components/opus/Android.bp +++ b/media/codec2/components/opus/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_opusdec", defaults: [ diff --git a/media/codec2/components/raw/Android.bp b/media/codec2/components/raw/Android.bp index d4fb8f8e81..c0b7613cc4 100644 --- a/media/codec2/components/raw/Android.bp +++ b/media/codec2/components/raw/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_raw_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_raw_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_rawdec", defaults: [ diff --git a/media/codec2/components/vorbis/Android.bp b/media/codec2/components/vorbis/Android.bp index ff1183f12b..ccf6f20877 100644 --- a/media/codec2/components/vorbis/Android.bp +++ b/media/codec2/components/vorbis/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_vorbis_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_vorbis_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_vorbisdec", defaults: [ diff --git a/media/codec2/components/vpx/Android.bp b/media/codec2/components/vpx/Android.bp index 72178aa88f..bb6a545613 100644 --- a/media/codec2/components/vpx/Android.bp +++ b/media/codec2/components/vpx/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codec2_components_vpx_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codec2_components_vpx_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libcodec2_soft_vp9dec", defaults: [ @@ -57,4 +76,3 @@ cc_library { shared_libs: ["libvpx"], } - diff --git a/media/codec2/components/xaac/Android.bp b/media/codec2/components/xaac/Android.bp index 9b7e2de195..bb3efb5573 100644 --- a/media/codec2/components/xaac/Android.bp +++ b/media/codec2/components/xaac/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_soft_xaacdec", defaults: [ diff --git a/media/codec2/core/Android.bp b/media/codec2/core/Android.bp index beeadb8569..64999b7ebc 100644 --- a/media/codec2/core/Android.bp +++ b/media/codec2/core/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libcodec2_headers", vendor_available: true, @@ -52,4 +61,3 @@ cc_library { ldflags: ["-Wl,-Bsymbolic"], } - diff --git a/media/codec2/faultinjection/Android.bp b/media/codec2/faultinjection/Android.bp index a0ad3cef82..c04ecbe36f 100644 --- a/media/codec2/faultinjection/Android.bp +++ b/media/codec2/faultinjection/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libcodec2_component_wrapper", vendor_available: true, @@ -26,4 +35,3 @@ cc_library_shared { ldflags: ["-Wl,-Bsymbolic"], } - diff --git a/media/codec2/fuzzer/Android.bp b/media/codec2/fuzzer/Android.bp index 2de400da71..bd1fac614d 100644 --- a/media/codec2/fuzzer/Android.bp +++ b/media/codec2/fuzzer/Android.bp @@ -16,6 +16,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "C2Fuzzer-defaults", diff --git a/media/codec2/hidl/1.0/utils/Android.bp b/media/codec2/hidl/1.0/utils/Android.bp index 27592717cc..008def806b 100644 --- a/media/codec2/hidl/1.0/utils/Android.bp +++ b/media/codec2/hidl/1.0/utils/Android.bp @@ -1,5 +1,14 @@ // DO NOT DEPEND ON THIS DIRECTLY // use libcodec2-hidl-client-defaults instead +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_hidl_client@1.0", diff --git a/media/codec2/hidl/1.0/vts/functional/Android.bp b/media/codec2/hidl/1.0/vts/functional/Android.bp index 5ea4825407..0ae133cd79 100644 --- a/media/codec2/hidl/1.0/vts/functional/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "media_c2_v1_audio_decode_res", path: "res", @@ -108,4 +117,4 @@ filegroup { srcs: [ "res/bbb_352x288_420p_30fps_32frames.yuv", ], -} \ No newline at end of file +} diff --git a/media/codec2/hidl/1.0/vts/functional/audio/Android.bp b/media/codec2/hidl/1.0/vts/functional/audio/Android.bp index 014cbe980c..624aad2605 100644 --- a/media/codec2/hidl/1.0/vts/functional/audio/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/audio/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsHalMediaC2V1_0TargetAudioDecTest", stem: "vts_media_c2_v1_0_audio_dec_test", diff --git a/media/codec2/hidl/1.0/vts/functional/common/Android.bp b/media/codec2/hidl/1.0/vts/functional/common/Android.bp index f9ec5aecc1..4106be8403 100644 --- a/media/codec2/hidl/1.0/vts/functional/common/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/common/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "VtsHalMediaC2V1_0CommonUtil", defaults: [ diff --git a/media/codec2/hidl/1.0/vts/functional/component/Android.bp b/media/codec2/hidl/1.0/vts/functional/component/Android.bp index 7ec64ee6e7..cc019dad1e 100644 --- a/media/codec2/hidl/1.0/vts/functional/component/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/component/Android.bp @@ -14,9 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsHalMediaC2V1_0TargetComponentTest", defaults: ["VtsHalMediaC2V1_0Defaults"], srcs: ["VtsHalMediaC2V1_0TargetComponentTest.cpp"], } - diff --git a/media/codec2/hidl/1.0/vts/functional/master/Android.bp b/media/codec2/hidl/1.0/vts/functional/master/Android.bp index 53e323e5db..40f52019df 100644 --- a/media/codec2/hidl/1.0/vts/functional/master/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/master/Android.bp @@ -14,9 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsHalMediaC2V1_0TargetMasterTest", defaults: ["VtsHalMediaC2V1_0Defaults"], srcs: ["VtsHalMediaC2V1_0TargetMasterTest.cpp"], } - diff --git a/media/codec2/hidl/1.0/vts/functional/video/Android.bp b/media/codec2/hidl/1.0/vts/functional/video/Android.bp index c7b0c1268e..f211ecfc91 100644 --- a/media/codec2/hidl/1.0/vts/functional/video/Android.bp +++ b/media/codec2/hidl/1.0/vts/functional/video/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "VtsHalMediaC2V1_0TargetVideoDecTest", stem: "vts_media_c2_v1_0_video_dec_test", @@ -40,4 +49,3 @@ cc_test { data: [":media_c2_v1_video_encode_res"], test_config: "VtsHalMediaC2V1_0TargetVideoEncTest.xml", } - diff --git a/media/codec2/hidl/1.1/utils/Android.bp b/media/codec2/hidl/1.1/utils/Android.bp index 57ac8721d1..839a910de5 100644 --- a/media/codec2/hidl/1.1/utils/Android.bp +++ b/media/codec2/hidl/1.1/utils/Android.bp @@ -1,5 +1,14 @@ // DO NOT DEPEND ON THIS DIRECTLY // use libcodec2-hidl-client-defaults instead +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_hidl_client@1.1", diff --git a/media/codec2/hidl/client/Android.bp b/media/codec2/hidl/client/Android.bp index 3c379909b0..5a34c302d5 100644 --- a/media/codec2/hidl/client/Android.bp +++ b/media/codec2/hidl/client/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libcodec2_client", @@ -39,4 +48,3 @@ cc_library { ], } - diff --git a/media/codec2/hidl/plugin/Android.bp b/media/codec2/hidl/plugin/Android.bp index 4708b12981..873bb028ce 100644 --- a/media/codec2/hidl/plugin/Android.bp +++ b/media/codec2/hidl/plugin/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libcodec2_hidl_plugin_headers", vendor_available: true, diff --git a/media/codec2/hidl/plugin/samples/Android.bp b/media/codec2/hidl/plugin/samples/Android.bp index c823e31869..32b760d1a1 100644 --- a/media/codec2/hidl/plugin/samples/Android.bp +++ b/media/codec2/hidl/plugin/samples/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "sample-codec2-hidl-plugin-defaults", diff --git a/media/codec2/hidl/services/Android.bp b/media/codec2/hidl/services/Android.bp index 3780a5add6..5a23217424 100644 --- a/media/codec2/hidl/services/Android.bp +++ b/media/codec2/hidl/services/Android.bp @@ -29,6 +29,15 @@ // The seccomp_policy file name and its content can be modified, but note that // vendor.cpp also needs to be updated because it needs the absolute path to the // seccomp policy file on the device. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_binary { name: "android.hardware.media.c2@1.1-default-service", vendor: true, @@ -87,4 +96,3 @@ prebuilt_etc { // This may be removed. required: ["crash_dump.policy"], } - diff --git a/media/codec2/sfplugin/Android.bp b/media/codec2/sfplugin/Android.bp index c3cfcceab8..2bc748f50b 100644 --- a/media/codec2/sfplugin/Android.bp +++ b/media/codec2/sfplugin/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libsfplugin_ccodec", diff --git a/media/codec2/sfplugin/tests/Android.bp b/media/codec2/sfplugin/tests/Android.bp index d705cfd219..92f37540aa 100644 --- a/media/codec2/sfplugin/tests/Android.bp +++ b/media/codec2/sfplugin/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "ccodec_unit_test", test_suites: ["device-tests"], diff --git a/media/codec2/sfplugin/utils/Android.bp b/media/codec2/sfplugin/utils/Android.bp index e7dc92a13c..74e7ef1de0 100644 --- a/media/codec2/sfplugin/utils/Android.bp +++ b/media/codec2/sfplugin/utils/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libsfplugin_ccodec_utils", vendor_available: true, diff --git a/media/codec2/tests/Android.bp b/media/codec2/tests/Android.bp index c9169a977d..b858fa56b6 100644 --- a/media/codec2/tests/Android.bp +++ b/media/codec2/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "codec2_core_param_test", test_suites: ["device-tests"], diff --git a/media/codec2/vndk/Android.bp b/media/codec2/vndk/Android.bp index 19afccff21..0401c1d76a 100644 --- a/media/codec2/vndk/Android.bp +++ b/media/codec2/vndk/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libcodec2_internal", @@ -112,4 +121,3 @@ cc_defaults { // TODO: separate internal headers so they can be exposed here } - diff --git a/media/codecs/amrnb/common/Android.bp b/media/codecs/amrnb/common/Android.bp index 59a791dfb0..bae65f3b2c 100644 --- a/media/codecs/amrnb/common/Android.bp +++ b/media/codecs/amrnb/common/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_common_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrnb_common_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libstagefright_amrnb_common", vendor_available: true, diff --git a/media/codecs/amrnb/dec/Android.bp b/media/codecs/amrnb/dec/Android.bp index 944ff7599d..1083b8293b 100644 --- a/media/codecs/amrnb/dec/Android.bp +++ b/media/codecs/amrnb/dec/Android.bp @@ -1,3 +1,35 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_dec_license", + ], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrnb_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_amrnbdec", vendor_available: true, diff --git a/media/codecs/amrnb/dec/test/Android.bp b/media/codecs/amrnb/dec/test/Android.bp index 91c9f86a67..74258e0297 100644 --- a/media/codecs/amrnb/dec/test/Android.bp +++ b/media/codecs/amrnb/dec/test/Android.bp @@ -14,6 +14,18 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // SPDX-license-identifier-BSD + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_dec_license", + ], +} + cc_test { name: "AmrnbDecoderTest", gtest: true, diff --git a/media/codecs/amrnb/enc/Android.bp b/media/codecs/amrnb/enc/Android.bp index 534ce043bf..9e947e9572 100644 --- a/media/codecs/amrnb/enc/Android.bp +++ b/media/codecs/amrnb/enc/Android.bp @@ -1,3 +1,35 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_enc_license", + ], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrnb_enc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_amrnbenc", vendor_available: true, diff --git a/media/codecs/amrnb/enc/fuzzer/Android.bp b/media/codecs/amrnb/enc/fuzzer/Android.bp index e88e5ebf3a..2c041b7c30 100644 --- a/media/codecs/amrnb/enc/fuzzer/Android.bp +++ b/media/codecs/amrnb/enc/fuzzer/Android.bp @@ -18,6 +18,17 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_enc_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_enc_license", + ], +} + cc_fuzz { name: "amrnb_enc_fuzzer", host_supported: true, diff --git a/media/codecs/amrnb/enc/test/Android.bp b/media/codecs/amrnb/enc/test/Android.bp index 7e1b56137a..7e393e3bad 100644 --- a/media/codecs/amrnb/enc/test/Android.bp +++ b/media/codecs/amrnb/enc/test/Android.bp @@ -14,6 +14,18 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrnb_enc_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // SPDX-license-identifier-BSD + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrnb_enc_license", + ], +} + cc_test { name: "AmrnbEncoderTest", gtest: true, diff --git a/media/codecs/amrnb/fuzzer/Android.bp b/media/codecs/amrnb/fuzzer/Android.bp index c1eaa53380..833a7ba8d1 100644 --- a/media/codecs/amrnb/fuzzer/Android.bp +++ b/media/codecs/amrnb/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "amrnb_dec_fuzzer", host_supported: true, diff --git a/media/codecs/amrwb/dec/Android.bp b/media/codecs/amrwb/dec/Android.bp index 204cbe3e83..228ea800b1 100644 --- a/media/codecs/amrwb/dec/Android.bp +++ b/media/codecs/amrwb/dec/Android.bp @@ -1,3 +1,35 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_dec_license", + ], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrwb_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_amrwbdec", vendor_available: true, diff --git a/media/codecs/amrwb/dec/fuzzer/Android.bp b/media/codecs/amrwb/dec/fuzzer/Android.bp index 7106a30684..16f08fa2aa 100644 --- a/media/codecs/amrwb/dec/fuzzer/Android.bp +++ b/media/codecs/amrwb/dec/fuzzer/Android.bp @@ -18,6 +18,17 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_dec_license", + ], +} + cc_fuzz { name: "amrwb_dec_fuzzer", host_supported: true, diff --git a/media/codecs/amrwb/dec/test/Android.bp b/media/codecs/amrwb/dec/test/Android.bp index e8a2aa9cef..7d0c9642c3 100644 --- a/media/codecs/amrwb/dec/test/Android.bp +++ b/media/codecs/amrwb/dec/test/Android.bp @@ -14,6 +14,18 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // SPDX-license-identifier-BSD + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_dec_license", + ], +} + cc_test { name: "AmrwbDecoderTest", test_suites: ["device-tests"], diff --git a/media/codecs/amrwb/enc/Android.bp b/media/codecs/amrwb/enc/Android.bp index 1521a459b1..cc72eb76f8 100644 --- a/media/codecs/amrwb/enc/Android.bp +++ b/media/codecs/amrwb/enc/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_enc_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrwb_enc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_amrwbenc", vendor_available: true, @@ -145,5 +164,3 @@ cc_library_static { }, }, } - - diff --git a/media/codecs/amrwb/enc/SampleCode/Android.bp b/media/codecs/amrwb/enc/SampleCode/Android.bp index 9442fc4a1b..1448364a36 100644 --- a/media/codecs/amrwb/enc/SampleCode/Android.bp +++ b/media/codecs/amrwb/enc/SampleCode/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_enc_SampleCode_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_amrwb_enc_SampleCode_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_test { name: "AMRWBEncTest", gtest: false, diff --git a/media/codecs/amrwb/enc/fuzzer/Android.bp b/media/codecs/amrwb/enc/fuzzer/Android.bp index e3473d69c7..f74fa4faa1 100644 --- a/media/codecs/amrwb/enc/fuzzer/Android.bp +++ b/media/codecs/amrwb/enc/fuzzer/Android.bp @@ -18,6 +18,17 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_enc_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_enc_license", + ], +} + cc_fuzz { name: "amrwb_enc_fuzzer", host_supported: true, diff --git a/media/codecs/amrwb/enc/test/Android.bp b/media/codecs/amrwb/enc/test/Android.bp index 08725700e4..942f6c92d5 100644 --- a/media/codecs/amrwb/enc/test/Android.bp +++ b/media/codecs/amrwb/enc/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_amrwb_enc_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_codecs_amrwb_enc_license", + ], +} + cc_test { name: "AmrwbEncoderTest", test_suites: ["device-tests"], diff --git a/media/codecs/g711/decoder/Android.bp b/media/codecs/g711/decoder/Android.bp index 51f4c38778..0cd97405bf 100644 --- a/media/codecs/g711/decoder/Android.bp +++ b/media/codecs/g711/decoder/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "codecs_g711dec", vendor_available: true, diff --git a/media/codecs/g711/fuzzer/Android.bp b/media/codecs/g711/fuzzer/Android.bp index ff5efa9ba4..376cce721a 100644 --- a/media/codecs/g711/fuzzer/Android.bp +++ b/media/codecs/g711/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "g711alaw_dec_fuzzer", host_supported: true, diff --git a/media/codecs/m4v_h263/dec/Android.bp b/media/codecs/m4v_h263/dec/Android.bp index b40745a675..038d0e1305 100644 --- a/media/codecs/m4v_h263/dec/Android.bp +++ b/media/codecs/m4v_h263/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_m4v_h263_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_m4v_h263_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_m4vh263dec", vendor_available: true, @@ -55,4 +74,3 @@ cc_library_static { }, }, } - diff --git a/media/codecs/m4v_h263/dec/test/Android.bp b/media/codecs/m4v_h263/dec/test/Android.bp index 9c753e609d..9459ed1d66 100644 --- a/media/codecs/m4v_h263/dec/test/Android.bp +++ b/media/codecs/m4v_h263/dec/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_m4v_h263_dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_codecs_m4v_h263_dec_license", + ], +} + cc_test { name: "Mpeg4H263DecoderTest", gtest: true, diff --git a/media/codecs/m4v_h263/enc/Android.bp b/media/codecs/m4v_h263/enc/Android.bp index dd7f005669..e3034047c4 100644 --- a/media/codecs/m4v_h263/enc/Android.bp +++ b/media/codecs/m4v_h263/enc/Android.bp @@ -1,3 +1,35 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_codecs_m4v_h263_enc_license", + ], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_m4v_h263_enc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_m4vh263enc", vendor_available: true, diff --git a/media/codecs/m4v_h263/enc/test/Android.bp b/media/codecs/m4v_h263/enc/test/Android.bp index d2982daaea..2b5e49cb66 100644 --- a/media/codecs/m4v_h263/enc/test/Android.bp +++ b/media/codecs/m4v_h263/enc/test/Android.bp @@ -14,6 +14,18 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_m4v_h263_enc_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // SPDX-license-identifier-BSD + default_applicable_licenses: [ + "frameworks_av_media_codecs_m4v_h263_enc_license", + ], +} + cc_test { name: "Mpeg4H263EncoderTest", gtest: true, diff --git a/media/codecs/m4v_h263/fuzzer/Android.bp b/media/codecs/m4v_h263/fuzzer/Android.bp index 778dafbb3e..a052c11b7e 100644 --- a/media/codecs/m4v_h263/fuzzer/Android.bp +++ b/media/codecs/m4v_h263/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "mpeg4_h263_dec_fuzz_defaults", diff --git a/media/codecs/mp3dec/Android.bp b/media/codecs/mp3dec/Android.bp index f84da218f6..015b8b64cc 100644 --- a/media/codecs/mp3dec/Android.bp +++ b/media/codecs/mp3dec/Android.bp @@ -1,3 +1,33 @@ +package { + default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_codecs_mp3dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-BSD", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_headers { name: "libstagefright_mp3dec_headers", vendor_available: true, diff --git a/media/codecs/mp3dec/fuzzer/Android.bp b/media/codecs/mp3dec/fuzzer/Android.bp index 79fa1e92da..514a8a8f1c 100644 --- a/media/codecs/mp3dec/fuzzer/Android.bp +++ b/media/codecs/mp3dec/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_mp3dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"], +} + cc_fuzz { name: "mp3_dec_fuzzer", host_supported: true, diff --git a/media/codecs/mp3dec/test/Android.bp b/media/codecs/mp3dec/test/Android.bp index 6b92ae930c..f10b6aec17 100644 --- a/media/codecs/mp3dec/test/Android.bp +++ b/media/codecs/mp3dec/test/Android.bp @@ -14,6 +14,16 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_codecs_mp3dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + // SPDX-license-identifier-BSD + default_applicable_licenses: ["frameworks_av_media_codecs_mp3dec_license"], +} + cc_test { name: "Mp3DecoderTest", gtest: true, diff --git a/media/extractors/Android.bp b/media/extractors/Android.bp index f9abfe324c..7513cb15bf 100644 --- a/media/extractors/Android.bp +++ b/media/extractors/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "extractor-defaults", @@ -60,4 +69,4 @@ cc_defaults { "signed-integer-overflow", ], }, -} \ No newline at end of file +} diff --git a/media/extractors/aac/Android.bp b/media/extractors/aac/Android.bp index c036bb5c3a..7bf3a1397d 100644 --- a/media/extractors/aac/Android.bp +++ b/media/extractors/aac/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_aac_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_aac_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libaacextractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/amr/Android.bp b/media/extractors/amr/Android.bp index 440065f34f..712360d10f 100644 --- a/media/extractors/amr/Android.bp +++ b/media/extractors/amr/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_amr_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_amr_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libamrextractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/flac/Android.bp b/media/extractors/flac/Android.bp index d1f92c167a..9a2a76bb48 100644 --- a/media/extractors/flac/Android.bp +++ b/media/extractors/flac/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_extractors_flac_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_flac_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libflacextractor", defaults: ["extractor-defaults", "libbinder_ndk_host_user"], diff --git a/media/extractors/fuzzers/Android.bp b/media/extractors/fuzzers/Android.bp index e900e57262..b731292b58 100644 --- a/media/extractors/fuzzers/Android.bp +++ b/media/extractors/fuzzers/Android.bp @@ -17,6 +17,15 @@ ***************************************************************************** * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "extractor-fuzzerbase-defaults", diff --git a/media/extractors/midi/Android.bp b/media/extractors/midi/Android.bp index 1c69bb8880..08a6fa04e2 100644 --- a/media/extractors/midi/Android.bp +++ b/media/extractors/midi/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_extractors_midi_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_midi_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libmidiextractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/mkv/Android.bp b/media/extractors/mkv/Android.bp index 330d4fe9be..840c9fc0ff 100644 --- a/media/extractors/mkv/Android.bp +++ b/media/extractors/mkv/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_mkv_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_mkv_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libmkvextractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/mp3/Android.bp b/media/extractors/mp3/Android.bp index 7d705483fc..75b9b7b368 100644 --- a/media/extractors/mp3/Android.bp +++ b/media/extractors/mp3/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libmp3extractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/mp4/Android.bp b/media/extractors/mp4/Android.bp index afa055f27c..7fa6bfd423 100644 --- a/media/extractors/mp4/Android.bp +++ b/media/extractors/mp4/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_mp4_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_mp4_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libmp4extractor", defaults: ["extractor-defaults"], diff --git a/media/extractors/mpeg2/Android.bp b/media/extractors/mpeg2/Android.bp index 4c253141e2..7e6247bc86 100644 --- a/media/extractors/mpeg2/Android.bp +++ b/media/extractors/mpeg2/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_extractors_mpeg2_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_mpeg2_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libmpeg2extractor", diff --git a/media/extractors/ogg/Android.bp b/media/extractors/ogg/Android.bp index 579065ed9d..d7540c4b17 100644 --- a/media/extractors/ogg/Android.bp +++ b/media/extractors/ogg/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_ogg_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_ogg_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "liboggextractor", diff --git a/media/extractors/tests/Android.bp b/media/extractors/tests/Android.bp index 0bca6f5177..e17893ef6e 100644 --- a/media/extractors/tests/Android.bp +++ b/media/extractors/tests/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "ExtractorUnitTest", gtest: true, diff --git a/media/extractors/wav/Android.bp b/media/extractors/wav/Android.bp index 6a0ef2255f..cc5e1c7eea 100644 --- a/media/extractors/wav/Android.bp +++ b/media/extractors/wav/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_extractors_wav_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_extractors_wav_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libwavextractor", diff --git a/media/img_utils/Android.bp b/media/img_utils/Android.bp index 64530e198a..237cd2b1ab 100644 --- a/media/img_utils/Android.bp +++ b/media/img_utils/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libimg_utils", diff --git a/media/libaaudio/Android.bp b/media/libaaudio/Android.bp index 7796ed5c19..add28e014a 100644 --- a/media/libaaudio/Android.bp +++ b/media/libaaudio/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + ndk_headers { name: "libAAudio_headers", from: "include", diff --git a/media/libaaudio/examples/Android.bp b/media/libaaudio/examples/Android.bp index 49bd5eef22..e2c187864b 100644 --- a/media/libaaudio/examples/Android.bp +++ b/media/libaaudio/examples/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaaudio_example_utils", export_include_dirs: ["utils"], diff --git a/media/libaaudio/examples/input_monitor/Android.bp b/media/libaaudio/examples/input_monitor/Android.bp index d8c58431fc..72adfd7b69 100644 --- a/media/libaaudio/examples/input_monitor/Android.bp +++ b/media/libaaudio/examples/input_monitor/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "input_monitor", gtest: false, diff --git a/media/libaaudio/examples/loopback/Android.bp b/media/libaaudio/examples/loopback/Android.bp index 4de632fc54..b18aeec4fd 100644 --- a/media/libaaudio/examples/loopback/Android.bp +++ b/media/libaaudio/examples/loopback/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "aaudio_loopback", gtest: false, diff --git a/media/libaaudio/examples/write_sine/Android.bp b/media/libaaudio/examples/write_sine/Android.bp index aa25e67b4b..1c7e0f1e41 100644 --- a/media/libaaudio/examples/write_sine/Android.bp +++ b/media/libaaudio/examples/write_sine/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "write_sine", srcs: ["src/write_sine.cpp"], diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index d02d1b6b9f..47cbbb1c06 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libaaudio", diff --git a/media/libaaudio/tests/Android.bp b/media/libaaudio/tests/Android.bp index 85376ad1ff..62c9b462c2 100644 --- a/media/libaaudio/tests/Android.bp +++ b/media/libaaudio/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libaaudio_tests_defaults", cflags: [ diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 8a575d538b..79c155e57c 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudioclient_headers", vendor_available: true, diff --git a/media/libaudioclient/fuzzer/Android.bp b/media/libaudioclient/fuzzer/Android.bp index a8eb385c45..18a37048c1 100644 --- a/media/libaudioclient/fuzzer/Android.bp +++ b/media/libaudioclient/fuzzer/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "audioflinger_fuzzer", srcs: [ diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp index 21d18d378a..3c1da4d4ef 100644 --- a/media/libaudioclient/tests/Android.bp +++ b/media/libaudioclient/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libaudioclient_tests_defaults", cflags: [ diff --git a/media/libaudiofoundation/Android.bp b/media/libaudiofoundation/Android.bp index a89d086b85..3bef55b3ab 100644 --- a/media/libaudiofoundation/Android.bp +++ b/media/libaudiofoundation/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiofoundation_headers", vendor_available: true, diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp index f258b14424..bb9a5f2ac4 100644 --- a/media/libaudiofoundation/tests/Android.bp +++ b/media/libaudiofoundation/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "audiofoundation_parcelable_test", diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp index 6b1b90a8fa..bd24c84dbc 100644 --- a/media/libaudiohal/Android.bp +++ b/media/libaudiohal/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libaudiohal", diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp index 8975cc30b8..a2c6e8aeba 100644 --- a/media/libaudiohal/impl/Android.bp +++ b/media/libaudiohal/impl/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libaudiohal_default", diff --git a/media/libaudioprocessing/Android.bp b/media/libaudioprocessing/Android.bp index 39b0ceb1b6..309765aeb8 100644 --- a/media/libaudioprocessing/Android.bp +++ b/media/libaudioprocessing/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libaudioprocessing_defaults", diff --git a/media/libaudioprocessing/audio-resampler/Android.bp b/media/libaudioprocessing/audio-resampler/Android.bp index dc703106cf..4ea75e7b19 100644 --- a/media/libaudioprocessing/audio-resampler/Android.bp +++ b/media/libaudioprocessing/audio-resampler/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libaudio-resampler", diff --git a/media/libaudioprocessing/tests/Android.bp b/media/libaudioprocessing/tests/Android.bp index 18acef7be5..3856817eaa 100644 --- a/media/libaudioprocessing/tests/Android.bp +++ b/media/libaudioprocessing/tests/Android.bp @@ -1,5 +1,14 @@ // Build the unit tests for libaudioprocessing +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libaudioprocessing_test_defaults", diff --git a/media/libaudioprocessing/tests/fuzzer/Android.bp b/media/libaudioprocessing/tests/fuzzer/Android.bp index 2a0dec41d7..8fb6fff66f 100644 --- a/media/libaudioprocessing/tests/fuzzer/Android.bp +++ b/media/libaudioprocessing/tests/fuzzer/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "libaudioprocessing_resampler_fuzzer", srcs: [ diff --git a/media/libcpustats/Android.bp b/media/libcpustats/Android.bp index 6e8ca1dda3..1ab1de0d3c 100644 --- a/media/libcpustats/Android.bp +++ b/media/libcpustats/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libcpustats", diff --git a/media/libdatasource/Android.bp b/media/libdatasource/Android.bp index f191c2169e..e0c6808cdf 100644 --- a/media/libdatasource/Android.bp +++ b/media/libdatasource/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libdatasource", diff --git a/media/libeffects/config/Android.bp b/media/libeffects/config/Android.bp index 8493e30469..b02dcb6ca6 100644 --- a/media/libeffects/config/Android.bp +++ b/media/libeffects/config/Android.bp @@ -1,4 +1,13 @@ // Effect configuration +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libeffectsconfig", vendor_available: true, diff --git a/media/libeffects/downmix/Android.bp b/media/libeffects/downmix/Android.bp index 2a2f36e5ba..b40317fcc6 100644 --- a/media/libeffects/downmix/Android.bp +++ b/media/libeffects/downmix/Android.bp @@ -1,4 +1,23 @@ // Multichannel downmix effect library +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_downmix_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_downmix_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libdownmix", diff --git a/media/libeffects/downmix/tests/Android.bp b/media/libeffects/downmix/tests/Android.bp index 63afc540a6..4077312544 100644 --- a/media/libeffects/downmix/tests/Android.bp +++ b/media/libeffects/downmix/tests/Android.bp @@ -1,4 +1,15 @@ // Build testbench for downmix module. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libeffects_downmix_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libeffects_downmix_license", + ], +} + cc_test { name:"downmixtest", host_supported: false, diff --git a/media/libeffects/dynamicsproc/Android.bp b/media/libeffects/dynamicsproc/Android.bp index eafc483272..84131a41fe 100644 --- a/media/libeffects/dynamicsproc/Android.bp +++ b/media/libeffects/dynamicsproc/Android.bp @@ -13,6 +13,25 @@ // limitations under the License. // DynamicsProcessing library +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_dynamicsproc_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_dynamicsproc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libdynproc", diff --git a/media/libeffects/factory/Android.bp b/media/libeffects/factory/Android.bp index ddbfdd8c54..22838a3ef4 100644 --- a/media/libeffects/factory/Android.bp +++ b/media/libeffects/factory/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libeffects_headers", vendor_available: true, diff --git a/media/libeffects/hapticgenerator/Android.bp b/media/libeffects/hapticgenerator/Android.bp index f94733925c..a660957a4a 100644 --- a/media/libeffects/hapticgenerator/Android.bp +++ b/media/libeffects/hapticgenerator/Android.bp @@ -13,6 +13,15 @@ // limitations under the License. // HapticGenerator library +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libhapticgenerator", @@ -48,4 +57,3 @@ cc_library_shared { "libaudioeffects", ], } - diff --git a/media/libeffects/loudness/Android.bp b/media/libeffects/loudness/Android.bp index 5a13af6d0f..bcd69472c5 100644 --- a/media/libeffects/loudness/Android.bp +++ b/media/libeffects/loudness/Android.bp @@ -1,4 +1,23 @@ // LoudnessEnhancer library +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_loudness_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_loudness_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libldnhncr", diff --git a/media/libeffects/lvm/benchmarks/Android.bp b/media/libeffects/lvm/benchmarks/Android.bp index 4f11a8ae4a..60a9772925 100644 --- a/media/libeffects/lvm/benchmarks/Android.bp +++ b/media/libeffects/lvm/benchmarks/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_benchmark { name: "lvm_benchmark", vendor: true, diff --git a/media/libeffects/lvm/lib/Android.bp b/media/libeffects/lvm/lib/Android.bp index 73c913bdc5..ed7ef7f06a 100644 --- a/media/libeffects/lvm/lib/Android.bp +++ b/media/libeffects/lvm/lib/Android.bp @@ -1,4 +1,23 @@ // Music bundle +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_lvm_lib_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_lvm_lib_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libmusicbundle", diff --git a/media/libeffects/lvm/tests/Android.bp b/media/libeffects/lvm/tests/Android.bp index abacc945e6..8627c13da0 100644 --- a/media/libeffects/lvm/tests/Android.bp +++ b/media/libeffects/lvm/tests/Android.bp @@ -1,5 +1,14 @@ // Build the unit tests for effects +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "lvmtest", host_supported: false, diff --git a/media/libeffects/lvm/wrapper/Android.bp b/media/libeffects/lvm/wrapper/Android.bp index bcbe3e6ae8..09c4aef99c 100644 --- a/media/libeffects/lvm/wrapper/Android.bp +++ b/media/libeffects/lvm/wrapper/Android.bp @@ -1,4 +1,23 @@ // music bundle wrapper +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_lvm_wrapper_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_lvm_wrapper_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libbundlewrapper", diff --git a/media/libeffects/preprocessing/Android.bp b/media/libeffects/preprocessing/Android.bp index 681e247b3c..e46a1364f2 100644 --- a/media/libeffects/preprocessing/Android.bp +++ b/media/libeffects/preprocessing/Android.bp @@ -1,4 +1,23 @@ // audio preprocessing wrapper +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_preprocessing_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_preprocessing_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libaudiopreprocessing", vendor: true, diff --git a/media/libeffects/preprocessing/benchmarks/Android.bp b/media/libeffects/preprocessing/benchmarks/Android.bp index 262fd19d36..246d14eb2e 100644 --- a/media/libeffects/preprocessing/benchmarks/Android.bp +++ b/media/libeffects/preprocessing/benchmarks/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libeffects_preprocessing_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libeffects_preprocessing_license", + ], +} + cc_benchmark { name: "preprocessing_benchmark", vendor: true, diff --git a/media/libeffects/preprocessing/tests/Android.bp b/media/libeffects/preprocessing/tests/Android.bp index ff897e89da..cfa6559ab9 100644 --- a/media/libeffects/preprocessing/tests/Android.bp +++ b/media/libeffects/preprocessing/tests/Android.bp @@ -1,4 +1,15 @@ // audio preprocessing unit test +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libeffects_preprocessing_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libeffects_preprocessing_license", + ], +} + cc_test { name: "AudioPreProcessingTest", diff --git a/media/libeffects/proxy/Android.bp b/media/libeffects/proxy/Android.bp index c6abb9ed6e..6256eda3fa 100644 --- a/media/libeffects/proxy/Android.bp +++ b/media/libeffects/proxy/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libeffectproxy", relative_install_path: "soundfx", diff --git a/media/libeffects/visualizer/Android.bp b/media/libeffects/visualizer/Android.bp index f6c585eccf..8dd6789456 100644 --- a/media/libeffects/visualizer/Android.bp +++ b/media/libeffects/visualizer/Android.bp @@ -1,4 +1,23 @@ // Visualizer library +package { + default_applicable_licenses: [ + "frameworks_av_media_libeffects_visualizer_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libeffects_visualizer_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libvisualizer", diff --git a/media/libheif/Android.bp b/media/libheif/Android.bp index 7d5a4ebe32..6a3427e6e1 100644 --- a/media/libheif/Android.bp +++ b/media/libheif/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libheif", diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp index 79d6c0bb7a..0223cfd022 100644 --- a/media/libmedia/Android.bp +++ b/media/libmedia/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libmedia_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_headers { name: "libmedia_headers", vendor_available: true, diff --git a/media/libmedia/tests/codeclist/Android.bp b/media/libmedia/tests/codeclist/Android.bp index ce85c1a836..57af9a99ef 100644 --- a/media/libmedia/tests/codeclist/Android.bp +++ b/media/libmedia/tests/codeclist/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + cc_test { name: "CodecListTest", test_suites: ["device-tests", "mts"], diff --git a/media/libmedia/tests/mediaplayer/Android.bp b/media/libmedia/tests/mediaplayer/Android.bp index 5538ea0908..0fff7b4cbc 100644 --- a/media/libmedia/tests/mediaplayer/Android.bp +++ b/media/libmedia/tests/mediaplayer/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + cc_test { name: "IMediaPlayerTest", test_suites: ["device-tests", "mts"], diff --git a/media/libmedia/xsd/Android.bp b/media/libmedia/xsd/Android.bp index 1635f70afa..36e28087d0 100644 --- a/media/libmedia/xsd/Android.bp +++ b/media/libmedia/xsd/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + xsd_config { name: "media_profiles", srcs: ["media_profiles.xsd"], diff --git a/media/libmedia/xsd/vts/Android.bp b/media/libmedia/xsd/vts/Android.bp index 598e41b547..83ab977239 100644 --- a/media/libmedia/xsd/vts/Android.bp +++ b/media/libmedia/xsd/vts/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + cc_test { name: "vts_mediaProfiles_validate_test", srcs: [ diff --git a/media/libmediahelper/Android.bp b/media/libmediahelper/Android.bp index 849debf611..9b54199d28 100644 --- a/media/libmediahelper/Android.bp +++ b/media/libmediahelper/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libmedia_helper_headers", vendor_available: true, diff --git a/media/libmediahelper/tests/Android.bp b/media/libmediahelper/tests/Android.bp index c5ba1227d1..a5f281910a 100644 --- a/media/libmediahelper/tests/Android.bp +++ b/media/libmediahelper/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "libmedia_helper_tests", diff --git a/media/libmediametrics/Android.bp b/media/libmediametrics/Android.bp index 06e67ad6f7..d758391be9 100644 --- a/media/libmediametrics/Android.bp +++ b/media/libmediametrics/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libmediametrics_headers", export_include_dirs: ["include"], diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp index 45f2f97594..56c8368e02 100644 --- a/media/libmediaplayerservice/Android.bp +++ b/media/libmediaplayerservice/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libmediaplayerservice_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libmediaplayerservice_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { srcs: [ @@ -78,4 +97,3 @@ cc_library { }, } - diff --git a/media/libmediaplayerservice/datasource/Android.bp b/media/libmediaplayerservice/datasource/Android.bp index 71fa50b228..19fc172f71 100644 --- a/media/libmediaplayerservice/datasource/Android.bp +++ b/media/libmediaplayerservice/datasource/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libmediaplayerservice_license", + ], +} + cc_library_static { name: "libplayerservice_datasource", diff --git a/media/libmediaplayerservice/nuplayer/Android.bp b/media/libmediaplayerservice/nuplayer/Android.bp index f5e44c742a..6d338db7c5 100644 --- a/media/libmediaplayerservice/nuplayer/Android.bp +++ b/media/libmediaplayerservice/nuplayer/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libmediaplayerservice_nuplayer_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libmediaplayerservice_nuplayer_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { srcs: [ diff --git a/media/libmediaplayerservice/tests/Android.bp b/media/libmediaplayerservice/tests/Android.bp index e845c33de8..98626fde12 100644 --- a/media/libmediaplayerservice/tests/Android.bp +++ b/media/libmediaplayerservice/tests/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libmediaplayerservice_license", + ], +} + cc_test { name: "DrmSessionManager_test", diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp index 04477c67f3..b84d64b9d6 100644 --- a/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp +++ b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmediaplayerservice_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libmediaplayerservice_license", + ], +} + cc_test { name: "StagefrightRecorderTest", gtest: true, diff --git a/media/libmediatranscoding/Android.bp b/media/libmediatranscoding/Android.bp index e98b7ea94a..534fa91b27 100644 --- a/media/libmediatranscoding/Android.bp +++ b/media/libmediatranscoding/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "libmediatranscoding_aidl", srcs: [ diff --git a/media/libmediatranscoding/tests/Android.bp b/media/libmediatranscoding/tests/Android.bp index 8bff10a32a..06b9b1732c 100644 --- a/media/libmediatranscoding/tests/Android.bp +++ b/media/libmediatranscoding/tests/Android.bp @@ -1,4 +1,13 @@ // Build the unit tests for libmediatranscoding. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "test_assets", path: "assets", diff --git a/media/libmediatranscoding/transcoder/Android.bp b/media/libmediatranscoding/transcoder/Android.bp index bebe6b1e6f..ccb2ec20dc 100644 --- a/media/libmediatranscoding/transcoder/Android.bp +++ b/media/libmediatranscoding/transcoder/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "mediatranscoder_defaults", @@ -72,4 +81,3 @@ cc_library { name: "libmediatranscoder", defaults: ["mediatranscoder_defaults"], } - diff --git a/media/libmediatranscoding/transcoder/benchmark/Android.bp b/media/libmediatranscoding/transcoder/benchmark/Android.bp index 74f65b964a..459f0aeff4 100644 --- a/media/libmediatranscoding/transcoder/benchmark/Android.bp +++ b/media/libmediatranscoding/transcoder/benchmark/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "benchmarkdefaults", shared_libs: [ diff --git a/media/libmediatranscoding/transcoder/tests/Android.bp b/media/libmediatranscoding/transcoder/tests/Android.bp index d0ea802c18..d68c9675e3 100644 --- a/media/libmediatranscoding/transcoder/tests/Android.bp +++ b/media/libmediatranscoding/transcoder/tests/Android.bp @@ -1,4 +1,13 @@ // Unit tests for libmediatranscoder. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "testdefaults", diff --git a/media/libmediatranscoding/transcoder/tests/fuzzer/Android.bp b/media/libmediatranscoding/transcoder/tests/fuzzer/Android.bp index 3ae349b8cf..69b2827be8 100644 --- a/media/libmediatranscoding/transcoder/tests/fuzzer/Android.bp +++ b/media/libmediatranscoding/transcoder/tests/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "media_transcoder_fuzzer", srcs: [ diff --git a/media/libnbaio/Android.bp b/media/libnbaio/Android.bp index 04ddcfffeb..e9422cce48 100644 --- a/media/libnbaio/Android.bp +++ b/media/libnbaio/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libnbaio_mono_defaults", srcs: [ diff --git a/media/libnblog/Android.bp b/media/libnblog/Android.bp index 118832040f..8cfece6502 100644 --- a/media/libnblog/Android.bp +++ b/media/libnblog/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libnblog", diff --git a/media/libshmem/Android.bp b/media/libshmem/Android.bp index c715918ab7..6e48078d58 100644 --- a/media/libshmem/Android.bp +++ b/media/libshmem/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + aidl_interface { name: "shared-file-region-aidl", unstable: true, diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index 16977d7bee..489a4bd4a8 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_headers { name: "libstagefright_headers", export_include_dirs: ["include"], diff --git a/media/libstagefright/bqhelper/Android.bp b/media/libstagefright/bqhelper/Android.bp index 2b0494c4b1..0e2b47227d 100644 --- a/media/libstagefright/bqhelper/Android.bp +++ b/media/libstagefright/bqhelper/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_defaults { name: "libstagefright_bufferqueue-defaults", double_loadable: true, diff --git a/media/libstagefright/bqhelper/tests/Android.bp b/media/libstagefright/bqhelper/tests/Android.bp index f5f0edd2d9..95953eeee9 100644 --- a/media/libstagefright/bqhelper/tests/Android.bp +++ b/media/libstagefright/bqhelper/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_test { name: "FrameDropper_test", test_suites: [ diff --git a/media/libstagefright/codecs/aacdec/Android.bp b/media/libstagefright/codecs/aacdec/Android.bp index 46b3b8fd85..5ab49a7ffa 100644 --- a/media/libstagefright/codecs/aacdec/Android.bp +++ b/media/libstagefright/codecs/aacdec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_aacdec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_aacdec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_aacdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/aacenc/Android.bp b/media/libstagefright/codecs/aacenc/Android.bp index bf789c401c..793125fb7f 100644 --- a/media/libstagefright/codecs/aacenc/Android.bp +++ b/media/libstagefright/codecs/aacenc/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_aacenc_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_aacenc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_aacenc", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/amrnb/dec/Android.bp b/media/libstagefright/codecs/amrnb/dec/Android.bp index 9d0da17b39..2c0954d00c 100644 --- a/media/libstagefright/codecs/amrnb/dec/Android.bp +++ b/media/libstagefright/codecs/amrnb/dec/Android.bp @@ -1,5 +1,14 @@ //############################################################################### +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_amrdec", defaults: ["libstagefright_softomx-defaults"], @@ -28,4 +37,3 @@ cc_library_shared { "libstagefright_amrnb_common", ], } - diff --git a/media/libstagefright/codecs/amrnb/enc/Android.bp b/media/libstagefright/codecs/amrnb/enc/Android.bp index bdd1cdf00c..6bf2d397cb 100644 --- a/media/libstagefright/codecs/amrnb/enc/Android.bp +++ b/media/libstagefright/codecs/amrnb/enc/Android.bp @@ -1,6 +1,15 @@ //############################################################################### +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_amrnbenc", defaults: ["libstagefright_softomx-defaults"], @@ -20,4 +29,3 @@ cc_library_shared { "libstagefright_amrnb_common", ], } - diff --git a/media/libstagefright/codecs/amrwbenc/Android.bp b/media/libstagefright/codecs/amrwbenc/Android.bp index 67a0f4588b..00e7bc93af 100644 --- a/media/libstagefright/codecs/amrwbenc/Android.bp +++ b/media/libstagefright/codecs/amrwbenc/Android.bp @@ -1,4 +1,13 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_amrwbenc", defaults: ["libstagefright_softomx-defaults"], @@ -20,4 +29,3 @@ cc_library_shared { "libstagefright_enc_common", ], } - diff --git a/media/libstagefright/codecs/avcdec/Android.bp b/media/libstagefright/codecs/avcdec/Android.bp index 7ee3119315..1c2f9beb00 100644 --- a/media/libstagefright/codecs/avcdec/Android.bp +++ b/media/libstagefright/codecs/avcdec/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_avcdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/avcenc/Android.bp b/media/libstagefright/codecs/avcenc/Android.bp index 94f214dc66..586088c6f1 100644 --- a/media/libstagefright/codecs/avcenc/Android.bp +++ b/media/libstagefright/codecs/avcenc/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_avcenc", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/common/Android.bp b/media/libstagefright/codecs/common/Android.bp index 2290722119..08691e7d1b 100644 --- a/media/libstagefright/codecs/common/Android.bp +++ b/media/libstagefright/codecs/common/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_common_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_common_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libstagefright_enc_common", vendor_available: true, diff --git a/media/libstagefright/codecs/flac/dec/Android.bp b/media/libstagefright/codecs/flac/dec/Android.bp index 4064751b3d..d06e0b7623 100644 --- a/media/libstagefright/codecs/flac/dec/Android.bp +++ b/media/libstagefright/codecs/flac/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_flac_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_flac_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_flacdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/flac/enc/Android.bp b/media/libstagefright/codecs/flac/enc/Android.bp index f35bce18f4..59a4675c04 100644 --- a/media/libstagefright/codecs/flac/enc/Android.bp +++ b/media/libstagefright/codecs/flac/enc/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_flac_enc_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_flac_enc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_flacenc", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/g711/dec/Android.bp b/media/libstagefright/codecs/g711/dec/Android.bp index f5357f4781..1dc34c39a8 100644 --- a/media/libstagefright/codecs/g711/dec/Android.bp +++ b/media/libstagefright/codecs/g711/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_g711_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_g711_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_g711dec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/gsm/dec/Android.bp b/media/libstagefright/codecs/gsm/dec/Android.bp index 5672d89426..efa2f83f96 100644 --- a/media/libstagefright/codecs/gsm/dec/Android.bp +++ b/media/libstagefright/codecs/gsm/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_gsm_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_gsm_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_gsmdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/hevcdec/Android.bp b/media/libstagefright/codecs/hevcdec/Android.bp index ffad18c4a2..2c4091bcf3 100644 --- a/media/libstagefright/codecs/hevcdec/Android.bp +++ b/media/libstagefright/codecs/hevcdec/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_hevcdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/m4v_h263/dec/Android.bp b/media/libstagefright/codecs/m4v_h263/dec/Android.bp index e5cccd8cff..725c79cb0f 100644 --- a/media/libstagefright/codecs/m4v_h263/dec/Android.bp +++ b/media/libstagefright/codecs/m4v_h263/dec/Android.bp @@ -1,4 +1,13 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_mpeg4dec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/m4v_h263/enc/Android.bp b/media/libstagefright/codecs/m4v_h263/enc/Android.bp index 9e120d3cb5..d10e40d3f4 100644 --- a/media/libstagefright/codecs/m4v_h263/enc/Android.bp +++ b/media/libstagefright/codecs/m4v_h263/enc/Android.bp @@ -1,5 +1,14 @@ //############################################################################### +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_mpeg4enc", defaults: ["libstagefright_softomx-defaults"], @@ -19,4 +28,3 @@ cc_library_shared { cfi: true, }, } - diff --git a/media/libstagefright/codecs/mp3dec/Android.bp b/media/libstagefright/codecs/mp3dec/Android.bp index 61b248bb0a..b669c84a6f 100644 --- a/media/libstagefright/codecs/mp3dec/Android.bp +++ b/media/libstagefright/codecs/mp3dec/Android.bp @@ -1,4 +1,13 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_mp3dec", defaults: ["libstagefright_softomx-defaults"], @@ -16,4 +25,3 @@ cc_library_shared { static_libs: ["libstagefright_mp3dec"], } - diff --git a/media/libstagefright/codecs/mpeg2dec/Android.bp b/media/libstagefright/codecs/mpeg2dec/Android.bp index e849410b99..abd1379c9d 100644 --- a/media/libstagefright/codecs/mpeg2dec/Android.bp +++ b/media/libstagefright/codecs/mpeg2dec/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_mpeg2dec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/on2/dec/Android.bp b/media/libstagefright/codecs/on2/dec/Android.bp index 82bb8d1da4..ba6dc2a4cc 100644 --- a/media/libstagefright/codecs/on2/dec/Android.bp +++ b/media/libstagefright/codecs/on2/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_on2_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_on2_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_vpxdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/on2/enc/Android.bp b/media/libstagefright/codecs/on2/enc/Android.bp index 705e554de8..e85ff98975 100644 --- a/media/libstagefright/codecs/on2/enc/Android.bp +++ b/media/libstagefright/codecs/on2/enc/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_on2_enc_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_on2_enc_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_vpxenc", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/opus/dec/Android.bp b/media/libstagefright/codecs/opus/dec/Android.bp index 71a2a0d3cd..3d8af6950e 100644 --- a/media/libstagefright/codecs/opus/dec/Android.bp +++ b/media/libstagefright/codecs/opus/dec/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_opusdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/raw/Android.bp b/media/libstagefright/codecs/raw/Android.bp index fcc7a0a100..3673786c56 100644 --- a/media/libstagefright/codecs/raw/Android.bp +++ b/media/libstagefright/codecs/raw/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_raw_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_raw_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_rawdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/vorbis/dec/Android.bp b/media/libstagefright/codecs/vorbis/dec/Android.bp index 3efb952c73..7764294662 100644 --- a/media/libstagefright/codecs/vorbis/dec/Android.bp +++ b/media/libstagefright/codecs/vorbis/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_codecs_vorbis_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_codecs_vorbis_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_soft_vorbisdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/codecs/xaacdec/Android.bp b/media/libstagefright/codecs/xaacdec/Android.bp index 2706665230..1d03c16bbd 100644 --- a/media/libstagefright/codecs/xaacdec/Android.bp +++ b/media/libstagefright/codecs/xaacdec/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_soft_xaacdec", defaults: ["libstagefright_softomx-defaults"], diff --git a/media/libstagefright/colorconversion/Android.bp b/media/libstagefright/colorconversion/Android.bp index 6b08b08578..06cebd3c78 100644 --- a/media/libstagefright/colorconversion/Android.bp +++ b/media/libstagefright/colorconversion/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_colorconversion_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_colorconversion_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_color_conversion", diff --git a/media/libstagefright/data/Android.bp b/media/libstagefright/data/Android.bp index 616b4b3639..6da2ccbe7f 100644 --- a/media/libstagefright/data/Android.bp +++ b/media/libstagefright/data/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + prebuilt_etc { name: "mediaswcodec.xml", src: "media_codecs_sw.xml", diff --git a/media/libstagefright/filters/Android.bp b/media/libstagefright/filters/Android.bp index 88f30c47b3..acc9e8757e 100644 --- a/media/libstagefright/filters/Android.bp +++ b/media/libstagefright/filters/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_static { name: "libstagefright_mediafilter", diff --git a/media/libstagefright/flac/dec/Android.bp b/media/libstagefright/flac/dec/Android.bp index b63353c5eb..225c930dd1 100644 --- a/media/libstagefright/flac/dec/Android.bp +++ b/media/libstagefright/flac/dec/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_flac_dec_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_flac_dec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libstagefright_flacdec", vendor_available: true, diff --git a/media/libstagefright/flac/dec/test/Android.bp b/media/libstagefright/flac/dec/test/Android.bp index 70ca80a390..a4c2735a46 100644 --- a/media/libstagefright/flac/dec/test/Android.bp +++ b/media/libstagefright/flac/dec/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_flac_dec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_flac_dec_license", + ], +} + cc_test { name: "FlacDecoderTest", gtest: true, diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp index 39670a21e0..7655d90bc9 100644 --- a/media/libstagefright/foundation/Android.bp +++ b/media/libstagefright/foundation/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_foundation_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_foundation_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_headers { name: "libstagefright_foundation_headers", export_include_dirs: ["include"], diff --git a/media/libstagefright/foundation/tests/AVCUtils/Android.bp b/media/libstagefright/foundation/tests/AVCUtils/Android.bp index 5d0e48108d..594da56a46 100644 --- a/media/libstagefright/foundation/tests/AVCUtils/Android.bp +++ b/media/libstagefright/foundation/tests/AVCUtils/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_foundation_license", + ], +} + cc_test { name: "AVCUtilsUnitTest", gtest: true, diff --git a/media/libstagefright/foundation/tests/Android.bp b/media/libstagefright/foundation/tests/Android.bp index 9e6718940f..715b57a297 100644 --- a/media/libstagefright/foundation/tests/Android.bp +++ b/media/libstagefright/foundation/tests/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_foundation_license", + ], +} + cc_test { name: "sf_foundation_test", test_suites: ["device-tests"], diff --git a/media/libstagefright/foundation/tests/OpusHeader/Android.bp b/media/libstagefright/foundation/tests/OpusHeader/Android.bp index ed3298ccdc..fa2b40e7fc 100644 --- a/media/libstagefright/foundation/tests/OpusHeader/Android.bp +++ b/media/libstagefright/foundation/tests/OpusHeader/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_foundation_license", + ], +} + cc_test { name: "OpusHeaderTest", test_suites: ["device-tests"], diff --git a/media/libstagefright/foundation/tests/colorutils/Android.bp b/media/libstagefright/foundation/tests/colorutils/Android.bp index d77f40511c..5a17e4bbbb 100644 --- a/media/libstagefright/foundation/tests/colorutils/Android.bp +++ b/media/libstagefright/foundation/tests/colorutils/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_foundation_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_foundation_license", + ], +} + cc_test { name: "ColorUtilsTest", gtest: true, diff --git a/media/libstagefright/http/Android.bp b/media/libstagefright/http/Android.bp index 8655caf9a1..f4d6d99474 100644 --- a/media/libstagefright/http/Android.bp +++ b/media/libstagefright/http/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_shared { name: "libstagefright_http_support", diff --git a/media/libstagefright/httplive/Android.bp b/media/libstagefright/httplive/Android.bp index 12e7ca60d1..0b0acbf0ab 100644 --- a/media/libstagefright/httplive/Android.bp +++ b/media/libstagefright/httplive/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_httplive_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_httplive_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libstagefright_httplive", diff --git a/media/libstagefright/id3/Android.bp b/media/libstagefright/id3/Android.bp index e34504d9bb..3f5ba47e03 100644 --- a/media/libstagefright/id3/Android.bp +++ b/media/libstagefright/id3/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_id3_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_id3_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_id3", min_sdk_version: "29", diff --git a/media/libstagefright/id3/test/Android.bp b/media/libstagefright/id3/test/Android.bp index acf38e2b57..52cdfa5f41 100644 --- a/media/libstagefright/id3/test/Android.bp +++ b/media/libstagefright/id3/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_id3_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_id3_license", + ], +} + cc_test { name: "ID3Test", test_suites: ["device-tests"], diff --git a/media/libstagefright/mpeg2ts/Android.bp b/media/libstagefright/mpeg2ts/Android.bp index 5d697f7c51..a9702243e8 100644 --- a/media/libstagefright/mpeg2ts/Android.bp +++ b/media/libstagefright/mpeg2ts/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_mpeg2ts_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_mpeg2ts_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_defaults { name: "libstagefright_mpeg2support_defaults", diff --git a/media/libstagefright/mpeg2ts/test/Android.bp b/media/libstagefright/mpeg2ts/test/Android.bp index d8b030479c..464b039657 100644 --- a/media/libstagefright/mpeg2ts/test/Android.bp +++ b/media/libstagefright/mpeg2ts/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_mpeg2ts_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_mpeg2ts_license", + ], +} + cc_test{ name: "Mpeg2tsUnitTest", gtest: true, diff --git a/media/libstagefright/omx/Android.bp b/media/libstagefright/omx/Android.bp index 7c372cd762..54c5697c14 100644 --- a/media/libstagefright/omx/Android.bp +++ b/media/libstagefright/omx/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_omx_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_omx_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libstagefright_omx", vendor_available: true, @@ -227,4 +246,3 @@ cc_library_shared { }, cflags: ["-Wall", "-Werror"], } - diff --git a/media/libstagefright/omx/tests/Android.bp b/media/libstagefright/omx/tests/Android.bp index fefb3bb3f4..83cc80e037 100644 --- a/media/libstagefright/omx/tests/Android.bp +++ b/media/libstagefright/omx/tests/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_omx_tests_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_omx_tests_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_test { name: "omx_tests", gtest: false, diff --git a/media/libstagefright/renderfright/Android.bp b/media/libstagefright/renderfright/Android.bp index 7a71f52139..9a7bad98cc 100644 --- a/media/libstagefright/renderfright/Android.bp +++ b/media/libstagefright/renderfright/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_defaults { name: "renderfright_defaults", cflags: [ diff --git a/media/libstagefright/renderfright/tests/Android.bp b/media/libstagefright/renderfright/tests/Android.bp index 9fee646ea4..e4b13fbfaf 100644 --- a/media/libstagefright/renderfright/tests/Android.bp +++ b/media/libstagefright/renderfright/tests/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_test { name: "librenderfright_test", defaults: ["surfaceflinger_defaults"], diff --git a/media/libstagefright/rtsp/Android.bp b/media/libstagefright/rtsp/Android.bp index f990ecf7f9..dcadbaf6ed 100644 --- a/media/libstagefright/rtsp/Android.bp +++ b/media/libstagefright/rtsp/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_rtsp_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_rtsp_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_defaults { name: "libstagefright_rtsp_defaults", diff --git a/media/libstagefright/tests/Android.bp b/media/libstagefright/tests/Android.bp index 4a505d4caf..a799a138a0 100644 --- a/media/libstagefright/tests/Android.bp +++ b/media/libstagefright/tests/Android.bp @@ -1,5 +1,24 @@ // Build the unit tests. +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_tests_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_test { name: "MediaCodecListOverrides_test", diff --git a/media/libstagefright/tests/ESDS/Android.bp b/media/libstagefright/tests/ESDS/Android.bp index 1ad1a64096..04e9b294f0 100644 --- a/media/libstagefright/tests/ESDS/Android.bp +++ b/media/libstagefright/tests/ESDS/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "ESDSTest", gtest: true, diff --git a/media/libstagefright/tests/HEVC/Android.bp b/media/libstagefright/tests/HEVC/Android.bp index 3762553d9a..91bf385c36 100644 --- a/media/libstagefright/tests/HEVC/Android.bp +++ b/media/libstagefright/tests/HEVC/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "HEVCUtilsUnitTest", test_suites: ["device-tests"], diff --git a/media/libstagefright/tests/extractorFactory/Android.bp b/media/libstagefright/tests/extractorFactory/Android.bp index 26ec507c9e..13d5b89975 100644 --- a/media/libstagefright/tests/extractorFactory/Android.bp +++ b/media/libstagefright/tests/extractorFactory/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "ExtractorFactoryTest", gtest: true, diff --git a/media/libstagefright/tests/fuzzers/Android.bp b/media/libstagefright/tests/fuzzers/Android.bp index d39dd18595..65e74e6fb6 100644 --- a/media/libstagefright/tests/fuzzers/Android.bp +++ b/media/libstagefright/tests/fuzzers/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_defaults { name: "libstagefright_fuzzer_defaults", cflags: [ diff --git a/media/libstagefright/tests/mediacodec/Android.bp b/media/libstagefright/tests/mediacodec/Android.bp index 0bd0639092..9cdc6d42a2 100644 --- a/media/libstagefright/tests/mediacodec/Android.bp +++ b/media/libstagefright/tests/mediacodec/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "mediacodecTest", gtest: true, diff --git a/media/libstagefright/tests/metadatautils/Android.bp b/media/libstagefright/tests/metadatautils/Android.bp index 69830fcd9d..ecdf89be3c 100644 --- a/media/libstagefright/tests/metadatautils/Android.bp +++ b/media/libstagefright/tests/metadatautils/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "MetaDataUtilsTest", gtest: true, diff --git a/media/libstagefright/tests/writer/Android.bp b/media/libstagefright/tests/writer/Android.bp index b5d453ea22..38d5ecca11 100644 --- a/media/libstagefright/tests/writer/Android.bp +++ b/media/libstagefright/tests/writer/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_tests_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_tests_license", + ], +} + cc_test { name: "writerTest", gtest: true, diff --git a/media/libstagefright/timedtext/Android.bp b/media/libstagefright/timedtext/Android.bp index 4f4ceb1f58..6590ef761d 100644 --- a/media/libstagefright/timedtext/Android.bp +++ b/media/libstagefright/timedtext/Android.bp @@ -1,3 +1,22 @@ +package { + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_timedtext_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_libstagefright_timedtext_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libstagefright_timedtext", @@ -22,5 +41,3 @@ cc_library_static { shared_libs: ["libmedia"], } - - diff --git a/media/libstagefright/timedtext/test/Android.bp b/media/libstagefright/timedtext/test/Android.bp index 11e50771d7..0b632bf898 100644 --- a/media/libstagefright/timedtext/test/Android.bp +++ b/media/libstagefright/timedtext/test/Android.bp @@ -14,6 +14,17 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_timedtext_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_media_libstagefright_timedtext_license", + ], +} + cc_test { name: "TimedTextUnitTest", test_suites: ["device-tests"], diff --git a/media/libstagefright/webm/Android.bp b/media/libstagefright/webm/Android.bp index 2cebe8fcda..68752cd95c 100644 --- a/media/libstagefright/webm/Android.bp +++ b/media/libstagefright/webm/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_static { name: "libstagefright_webm", diff --git a/media/libstagefright/webm/tests/Android.bp b/media/libstagefright/webm/tests/Android.bp index 5183a49495..4443766869 100644 --- a/media/libstagefright/webm/tests/Android.bp +++ b/media/libstagefright/webm/tests/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_test { name: "WebmFrameThreadUnitTest", gtest: true, diff --git a/media/libstagefright/writer_fuzzers/Android.bp b/media/libstagefright/writer_fuzzers/Android.bp index f1e504d312..a33b888979 100644 --- a/media/libstagefright/writer_fuzzers/Android.bp +++ b/media/libstagefright/writer_fuzzers/Android.bp @@ -17,6 +17,15 @@ ***************************************************************************** * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_defaults { name: "writer-fuzzerbase-defaults", local_include_dirs: [ diff --git a/media/libstagefright/xmlparser/Android.bp b/media/libstagefright/xmlparser/Android.bp index 7ed0e88d15..055dd805ee 100644 --- a/media/libstagefright/xmlparser/Android.bp +++ b/media/libstagefright/xmlparser/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_library_headers { name: "libstagefright_xmlparser_headers", export_include_dirs: ["include"], @@ -49,4 +58,3 @@ xsd_config { srcs: ["media_codecs.xsd"], package_name: "media.codecs", } - diff --git a/media/libstagefright/xmlparser/test/Android.bp b/media/libstagefright/xmlparser/test/Android.bp index ba02f84347..06a52f1703 100644 --- a/media/libstagefright/xmlparser/test/Android.bp +++ b/media/libstagefright/xmlparser/test/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_test { name: "XMLParserTest", test_suites: ["device-tests"], diff --git a/media/libstagefright/xmlparser/vts/Android.bp b/media/libstagefright/xmlparser/vts/Android.bp index 132ce8203c..1e36c8fa8e 100644 --- a/media/libstagefright/xmlparser/vts/Android.bp +++ b/media/libstagefright/xmlparser/vts/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libstagefright_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libstagefright_license"], +} + cc_test { name: "vts_mediaCodecs_validate_test", srcs: [ diff --git a/media/libwatchdog/Android.bp b/media/libwatchdog/Android.bp index f7f0db77a2..411c206d47 100644 --- a/media/libwatchdog/Android.bp +++ b/media/libwatchdog/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libwatchdog", host_supported: true, diff --git a/media/mediaserver/Android.bp b/media/mediaserver/Android.bp index ee7285d056..a9617ec0c2 100644 --- a/media/mediaserver/Android.bp +++ b/media/mediaserver/Android.bp @@ -1,4 +1,21 @@ +package { + default_applicable_licenses: ["frameworks_av_media_mediaserver_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_mediaserver_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_static { name: "libregistermsext", srcs: ["register.cpp"], diff --git a/media/mtp/Android.bp b/media/mtp/Android.bp index e572249cc5..97e2a22dc9 100644 --- a/media/mtp/Android.bp +++ b/media/mtp/Android.bp @@ -14,6 +14,23 @@ // limitations under the License. // +package { + default_applicable_licenses: ["frameworks_av_media_mtp_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_mtp_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libmtp", srcs: [ @@ -54,4 +71,3 @@ cc_library_shared { ], header_libs: ["libcutils_headers"], } - diff --git a/media/mtp/tests/MtpFfsHandleTest/Android.bp b/media/mtp/tests/MtpFfsHandleTest/Android.bp index e3930674c1..ec9c7a44ae 100644 --- a/media/mtp/tests/MtpFfsHandleTest/Android.bp +++ b/media/mtp/tests/MtpFfsHandleTest/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_mtp_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_mtp_license"], +} + cc_test { name: "mtp_ffs_handle_test", test_suites: ["device-tests"], @@ -29,4 +38,3 @@ cc_test { "-Werror", ], } - diff --git a/media/mtp/tests/MtpFuzzer/Android.bp b/media/mtp/tests/MtpFuzzer/Android.bp index 9cd4669b2b..5365f4bd49 100644 --- a/media/mtp/tests/MtpFuzzer/Android.bp +++ b/media/mtp/tests/MtpFuzzer/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_mtp_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_mtp_license"], +} + cc_fuzz { name: "mtp_fuzzer", srcs: [ diff --git a/media/mtp/tests/PosixAsyncIOTest/Android.bp b/media/mtp/tests/PosixAsyncIOTest/Android.bp index 1d401b8231..09cf6b7fc8 100644 --- a/media/mtp/tests/PosixAsyncIOTest/Android.bp +++ b/media/mtp/tests/PosixAsyncIOTest/Android.bp @@ -14,6 +14,15 @@ // limitations under the License. // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_mtp_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_mtp_license"], +} + cc_test { name: "posix_async_io_test", test_suites: ["device-tests"], diff --git a/media/ndk/Android.bp b/media/ndk/Android.bp index 11f8f38f89..3007574e3e 100644 --- a/media/ndk/Android.bp +++ b/media/ndk/Android.bp @@ -16,6 +16,37 @@ // to refer to headers in parent directories and the headers live in // frameworks/av/include. +package { + default_applicable_licenses: ["frameworks_av_media_ndk_license"], +} + +// Added automatically by a large-scale-change that took the approach of +// 'apply every license found to every target'. While this makes sure we respect +// every license restriction, it may not be entirely correct. +// +// e.g. GPL in an MIT project might only apply to the contrib/ directory. +// +// Please consider splitting the single license below into multiple licenses, +// taking care not to lose any license_kind information, and overriding the +// default license using the 'licenses: [...]' property on targets as needed. +// +// For unused files, consider creating a 'fileGroup' with "//visibility:private" +// to attach the license to, and including a comment whether the files may be +// used in the current project. +// See: http://go/android-license-faq +license { + name: "frameworks_av_media_ndk_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + "SPDX-license-identifier-MIT", + "SPDX-license-identifier-Unicode-DFS", + ], + license_text: [ + "NOTICE", + ], +} + ndk_library { name: "libmediandk", symbol_file: "libmediandk.map.txt", diff --git a/media/tests/benchmark/Android.bp b/media/tests/benchmark/Android.bp index de408ddbca..8503a9c785 100644 --- a/media/tests/benchmark/Android.bp +++ b/media/tests/benchmark/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + subdirs = [ "src", "tests", diff --git a/media/tests/benchmark/MediaBenchmarkTest/Android.bp b/media/tests/benchmark/MediaBenchmarkTest/Android.bp index d80d9a54e6..2e06da54a1 100644 --- a/media/tests/benchmark/MediaBenchmarkTest/Android.bp +++ b/media/tests/benchmark/MediaBenchmarkTest/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + android_test { name: "MediaBenchmarkTest", diff --git a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp index 3e5e4c8744..af924246f5 100644 --- a/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp +++ b/media/tests/benchmark/MediaBenchmarkTest/src/main/cpp/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test_library { name: "libmediabenchmark_jni", sdk_version: "current", diff --git a/media/tests/benchmark/src/native/common/Android.bp b/media/tests/benchmark/src/native/common/Android.bp index d4389da244..6b54c6af86 100644 --- a/media/tests/benchmark/src/native/common/Android.bp +++ b/media/tests/benchmark/src/native/common/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libmediabenchmark_common", defaults: [ diff --git a/media/tests/benchmark/src/native/decoder/Android.bp b/media/tests/benchmark/src/native/decoder/Android.bp index 9791c11d60..601b2f601d 100644 --- a/media/tests/benchmark/src/native/decoder/Android.bp +++ b/media/tests/benchmark/src/native/decoder/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libmediabenchmark_decoder", defaults: [ diff --git a/media/tests/benchmark/src/native/encoder/Android.bp b/media/tests/benchmark/src/native/encoder/Android.bp index 8de782387a..a78706837e 100644 --- a/media/tests/benchmark/src/native/encoder/Android.bp +++ b/media/tests/benchmark/src/native/encoder/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libmediabenchmark_encoder", defaults: [ diff --git a/media/tests/benchmark/src/native/extractor/Android.bp b/media/tests/benchmark/src/native/extractor/Android.bp index 7ed94764c3..4946990b95 100644 --- a/media/tests/benchmark/src/native/extractor/Android.bp +++ b/media/tests/benchmark/src/native/extractor/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libmediabenchmark_extractor", defaults: [ diff --git a/media/tests/benchmark/src/native/muxer/Android.bp b/media/tests/benchmark/src/native/muxer/Android.bp index f669d4a516..84985e4266 100644 --- a/media/tests/benchmark/src/native/muxer/Android.bp +++ b/media/tests/benchmark/src/native/muxer/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libmediabenchmark_muxer", defaults: [ diff --git a/media/tests/benchmark/tests/Android.bp b/media/tests/benchmark/tests/Android.bp index f46fa4a99e..0fbd20d0c5 100644 --- a/media/tests/benchmark/tests/Android.bp +++ b/media/tests/benchmark/tests/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "extractorTest", gtest: true, diff --git a/media/utils/Android.bp b/media/utils/Android.bp index 952fe37352..ec77bd0582 100644 --- a/media/utils/Android.bp +++ b/media/utils/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libmediautils", diff --git a/media/utils/fuzzers/Android.bp b/media/utils/fuzzers/Android.bp index ca1123c2e6..80882b22a4 100644 --- a/media/utils/fuzzers/Android.bp +++ b/media/utils/fuzzers/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_defaults { name: "libmediautils_fuzzer_defaults", shared_libs: [ diff --git a/media/utils/tests/Android.bp b/media/utils/tests/Android.bp index bb413c339e..6593d56421 100644 --- a/media/utils/tests/Android.bp +++ b/media/utils/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "media_synchronization_tests", diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp index 09d3871656..518ef9afbf 100644 --- a/services/audioflinger/Android.bp +++ b/services/audioflinger/Android.bp @@ -1,5 +1,24 @@ +package { + default_applicable_licenses: [ + "frameworks_av_services_audioflinger_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_services_audioflinger_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libaudioflinger", diff --git a/services/audiopolicy/Android.bp b/services/audiopolicy/Android.bp index a42b89fcf6..e018dd3133 100644 --- a/services/audiopolicy/Android.bp +++ b/services/audiopolicy/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiopolicymanager_interface_headers", host_supported: true, diff --git a/services/audiopolicy/common/Android.bp b/services/audiopolicy/common/Android.bp index 6e0d2f6574..91701ad303 100644 --- a/services/audiopolicy/common/Android.bp +++ b/services/audiopolicy/common/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiopolicycommon", header_libs: [ diff --git a/services/audiopolicy/common/managerdefinitions/Android.bp b/services/audiopolicy/common/managerdefinitions/Android.bp index 57f0b5b6a5..227c2d8c4a 100644 --- a/services/audiopolicy/common/managerdefinitions/Android.bp +++ b/services/audiopolicy/common/managerdefinitions/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_static { name: "libaudiopolicycomponents", diff --git a/services/audiopolicy/config/Android.bp b/services/audiopolicy/config/Android.bp index f4610bb9bd..671b30a491 100644 --- a/services/audiopolicy/config/Android.bp +++ b/services/audiopolicy/config/Android.bp @@ -17,6 +17,15 @@ soong_namespace { } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "a2dp_in_audio_policy_configuration.xml", vendor: true, diff --git a/services/audiopolicy/engine/common/Android.bp b/services/audiopolicy/engine/common/Android.bp index a1c69f23a5..50c5eab236 100644 --- a/services/audiopolicy/engine/common/Android.bp +++ b/services/audiopolicy/engine/common/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiopolicyengine_common_headers", host_supported: true, diff --git a/services/audiopolicy/engine/config/Android.bp b/services/audiopolicy/engine/config/Android.bp index ff840f9893..459cc78b4a 100644 --- a/services/audiopolicy/engine/config/Android.bp +++ b/services/audiopolicy/engine/config/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libaudiopolicyengine_config", export_include_dirs: ["include"], diff --git a/services/audiopolicy/engine/config/tests/Android.bp b/services/audiopolicy/engine/config/tests/Android.bp index 6b0774fe82..5791f172e0 100644 --- a/services/audiopolicy/engine/config/tests/Android.bp +++ b/services/audiopolicy/engine/config/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "audiopolicy_engineconfig_tests", diff --git a/services/audiopolicy/engine/config/tests/resources/Android.bp b/services/audiopolicy/engine/config/tests/resources/Android.bp index 0aee0e98df..9cee978778 100644 --- a/services/audiopolicy/engine/config/tests/resources/Android.bp +++ b/services/audiopolicy/engine/config/tests/resources/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "audiopolicy_engineconfig_files", srcs: [ diff --git a/services/audiopolicy/engine/interface/Android.bp b/services/audiopolicy/engine/interface/Android.bp index 2ea42b698f..5dd5adb3f9 100644 --- a/services/audiopolicy/engine/interface/Android.bp +++ b/services/audiopolicy/engine/interface/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiopolicyengine_interface_headers", host_supported: true, diff --git a/services/audiopolicy/engineconfigurable/Android.bp b/services/audiopolicy/engineconfigurable/Android.bp index 8f522f0b5f..a747822903 100644 --- a/services/audiopolicy/engineconfigurable/Android.bp +++ b/services/audiopolicy/engineconfigurable/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_headers { name: "libaudiopolicyengineconfigurable_interface_headers", host_supported: true, diff --git a/services/audiopolicy/engineconfigurable/config/Android.bp b/services/audiopolicy/engineconfigurable/config/Android.bp index fe3eae0cb4..b3d1f9764d 100644 --- a/services/audiopolicy/engineconfigurable/config/Android.bp +++ b/services/audiopolicy/engineconfigurable/config/Android.bp @@ -16,6 +16,15 @@ // Root soong_namespace for common components +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "audio_policy_engine_criteria.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp index f913a14bde..e46b60f510 100644 --- a/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp +++ b/services/audiopolicy/engineconfigurable/config/example/automotive/Android.bp @@ -22,6 +22,15 @@ soong_namespace { ], } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "audio_policy_engine_configuration.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp index fae6b7bdfb..ad6eeb1ae3 100644 --- a/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp +++ b/services/audiopolicy/engineconfigurable/config/example/caremu/Android.bp @@ -23,6 +23,15 @@ soong_namespace { ], } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "audio_policy_engine_configuration.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp index 94d33bd5b6..773a99a44e 100644 --- a/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp +++ b/services/audiopolicy/engineconfigurable/config/example/phone/Android.bp @@ -22,6 +22,15 @@ soong_namespace { ], } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "audio_policy_engine_configuration.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp index 90ebffd7a8..ee62d5e135 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/Android.bp @@ -16,6 +16,15 @@ // Root soong_namespace for common components +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "PolicyClass.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp index 82b1b6dc23..bc72484d36 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Car/Android.bp @@ -26,6 +26,15 @@ soong_namespace { // // Generate Audio Policy Parameter Framework Product Strategies Structure file from template // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "ProductStrategies.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp index e4605b215f..11da8c7cb5 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/CarEmu/Android.bp @@ -27,6 +27,15 @@ soong_namespace { // // Generate Audio Policy Parameter Framework Product Strategies Structure file from template // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "ProductStrategies.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp index 61b54cf859..91ffeb5ff2 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/Phone/Android.bp @@ -26,6 +26,15 @@ soong_namespace { // // Generate Audio Policy Parameter Framework Product Strategies Structure file from template // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "ProductStrategies.xml", vendor: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp index 9abcb701d3..cac63fcd0d 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoInput/Android.bp @@ -23,6 +23,15 @@ soong_namespace { ], } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "parameter-framework.policy", filename_from_src: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp index 27172a4d68..337f358049 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/examples/SettingsNoOutput/Android.bp @@ -23,6 +23,15 @@ soong_namespace { ], } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "parameter-framework.policy", filename_from_src: true, diff --git a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp index 2685c6dc8c..0398fc79f2 100644 --- a/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp +++ b/services/audiopolicy/engineconfigurable/parameter-framework/plugin/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libpolicy-subsystem", srcs: [ diff --git a/services/audiopolicy/engineconfigurable/tools/Android.bp b/services/audiopolicy/engineconfigurable/tools/Android.bp index b51918a6f8..40efb3d8bd 100644 --- a/services/audiopolicy/engineconfigurable/tools/Android.bp +++ b/services/audiopolicy/engineconfigurable/tools/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + python_defaults { name: "tools_default", version: { diff --git a/services/audiopolicy/engineconfigurable/wrapper/Android.bp b/services/audiopolicy/engineconfigurable/wrapper/Android.bp index 301ecc0fb9..3e04b68e37 100644 --- a/services/audiopolicy/engineconfigurable/wrapper/Android.bp +++ b/services/audiopolicy/engineconfigurable/wrapper/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libaudiopolicyengineconfigurable_pfwwrapper", export_include_dirs: ["include"], diff --git a/services/audiopolicy/enginedefault/Android.bp b/services/audiopolicy/enginedefault/Android.bp index aaf4158baf..7f9c0acedd 100644 --- a/services/audiopolicy/enginedefault/Android.bp +++ b/services/audiopolicy/enginedefault/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libaudiopolicyenginedefault", srcs: [ diff --git a/services/audiopolicy/enginedefault/config/example/Android.bp b/services/audiopolicy/enginedefault/config/example/Android.bp index 0bfcaa1284..59a704b810 100644 --- a/services/audiopolicy/enginedefault/config/example/Android.bp +++ b/services/audiopolicy/enginedefault/config/example/Android.bp @@ -19,6 +19,15 @@ soong_namespace { } +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + prebuilt_etc { name: "audio_policy_engine_configuration.xml", vendor: true, diff --git a/services/audiopolicy/fuzzer/Android.bp b/services/audiopolicy/fuzzer/Android.bp index 21f651542f..5dbcebd8b1 100644 --- a/services/audiopolicy/fuzzer/Android.bp +++ b/services/audiopolicy/fuzzer/Android.bp @@ -16,6 +16,15 @@ * ******************************************************************************/ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "audiopolicy_fuzzer", srcs: [ diff --git a/services/audiopolicy/fuzzer/resources/Android.bp b/services/audiopolicy/fuzzer/resources/Android.bp index f1e3a5109e..22ee256781 100644 --- a/services/audiopolicy/fuzzer/resources/Android.bp +++ b/services/audiopolicy/fuzzer/resources/Android.bp @@ -16,6 +16,15 @@ * ******************************************************************************/ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "audiopolicyfuzzer_configuration_files", srcs: [ diff --git a/services/audiopolicy/managerdefault/Android.bp b/services/audiopolicy/managerdefault/Android.bp index 577b42fcd6..5572beb51f 100644 --- a/services/audiopolicy/managerdefault/Android.bp +++ b/services/audiopolicy/managerdefault/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libaudiopolicymanagerdefault", diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index d4f508899d..439f9f03fc 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library_shared { name: "libaudiopolicyservice", diff --git a/services/audiopolicy/tests/Android.bp b/services/audiopolicy/tests/Android.bp index daedf314dc..d10fcb9e19 100644 --- a/services/audiopolicy/tests/Android.bp +++ b/services/audiopolicy/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "audiopolicy_tests", diff --git a/services/audiopolicy/tests/resources/Android.bp b/services/audiopolicy/tests/resources/Android.bp index 2f6e92573c..ff4d568a1e 100644 --- a/services/audiopolicy/tests/resources/Android.bp +++ b/services/audiopolicy/tests/resources/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "audiopolicytest_configuration_files", srcs: [ diff --git a/services/camera/libcameraservice/Android.bp b/services/camera/libcameraservice/Android.bp index 8cb40e03e5..e9f95cb129 100644 --- a/services/camera/libcameraservice/Android.bp +++ b/services/camera/libcameraservice/Android.bp @@ -16,6 +16,25 @@ // libcameraservice // +package { + default_applicable_licenses: [ + "frameworks_av_services_camera_libcameraservice_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_services_camera_libcameraservice_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libcameraservice", @@ -160,4 +179,3 @@ cc_library_shared { ], } - diff --git a/services/camera/libcameraservice/fuzzer/Android.bp b/services/camera/libcameraservice/fuzzer/Android.bp index c5b7f00d14..9a9a03bba5 100644 --- a/services/camera/libcameraservice/fuzzer/Android.bp +++ b/services/camera/libcameraservice/fuzzer/Android.bp @@ -12,6 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_services_camera_libcameraservice_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_services_camera_libcameraservice_license", + ], +} + cc_defaults { name: "libcameraservice_fuzz_defaults", fuzz_config: { diff --git a/services/camera/libcameraservice/tests/Android.mk b/services/camera/libcameraservice/tests/Android.mk index 3ead71557f..b53034204a 100644 --- a/services/camera/libcameraservice/tests/Android.mk +++ b/services/camera/libcameraservice/tests/Android.mk @@ -51,6 +51,9 @@ LOCAL_CFLAGS += -Wall -Wextra -Werror LOCAL_SANITIZE := address LOCAL_MODULE:= cameraservice_test +LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0 +LOCAL_LICENSE_CONDITIONS:= notice +LOCAL_NOTICE_FILE:= $(LOCAL_PATH)/../NOTICE LOCAL_COMPATIBILITY_SUITE := device-tests LOCAL_MODULE_TAGS := tests diff --git a/services/mediacodec/Android.bp b/services/mediacodec/Android.bp index dc0773b732..bf4d524ec8 100644 --- a/services/mediacodec/Android.bp +++ b/services/mediacodec/Android.bp @@ -1,3 +1,20 @@ +package { + default_applicable_licenses: ["frameworks_av_services_mediacodec_license"], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_services_mediacodec_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_binary { name: "mediaswcodec", vendor_available: true, diff --git a/services/mediacodec/registrant/Android.bp b/services/mediacodec/registrant/Android.bp index 0441cfacd2..696b9679f3 100644 --- a/services/mediacodec/registrant/Android.bp +++ b/services/mediacodec/registrant/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_services_mediacodec_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_services_mediacodec_license"], +} + cc_library_shared { name: "libmedia_codecserviceregistrant", vendor_available: true, @@ -55,4 +64,3 @@ cc_library_shared { "libcodec2_soft_gsmdec", ], } - diff --git a/services/mediaextractor/Android.bp b/services/mediaextractor/Android.bp index 03e1e41797..85ce110559 100644 --- a/services/mediaextractor/Android.bp +++ b/services/mediaextractor/Android.bp @@ -1,4 +1,23 @@ // service library +package { + default_applicable_licenses: [ + "frameworks_av_services_mediaextractor_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_services_mediaextractor_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library_shared { name: "libmediaextractorservice", cflags: [ @@ -67,4 +86,3 @@ prebuilt_etc { "code_coverage.policy", ], } - diff --git a/services/medialog/Android.bp b/services/medialog/Android.bp index 3a27a43781..cfc4c40234 100644 --- a/services/medialog/Android.bp +++ b/services/medialog/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libmedialogservice", diff --git a/services/medialog/fuzzer/Android.bp b/services/medialog/fuzzer/Android.bp index 2afaaae9ac..9ff0ce4152 100644 --- a/services/medialog/fuzzer/Android.bp +++ b/services/medialog/fuzzer/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "media_log_fuzzer", static_libs: [ diff --git a/services/mediametrics/Android.bp b/services/mediametrics/Android.bp index 8e1a88b0d5..e40754e457 100644 --- a/services/mediametrics/Android.bp +++ b/services/mediametrics/Android.bp @@ -1,6 +1,15 @@ // Media Statistics service // +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + tidy_errors = [ // https://clang.llvm.org/extra/clang-tidy/checks/list.html // For many categories, the checks are too many to specify individually. diff --git a/services/mediametrics/benchmarks/Android.bp b/services/mediametrics/benchmarks/Android.bp index b61f44f030..68d414554d 100644 --- a/services/mediametrics/benchmarks/Android.bp +++ b/services/mediametrics/benchmarks/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "mediametrics_benchmarks", srcs: ["mediametrics_benchmarks.cpp"], diff --git a/services/mediametrics/fuzzer/Android.bp b/services/mediametrics/fuzzer/Android.bp index 19ed919915..d75ded24ca 100644 --- a/services/mediametrics/fuzzer/Android.bp +++ b/services/mediametrics/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "mediametrics_service_fuzzer", diff --git a/services/mediametrics/tests/Android.bp b/services/mediametrics/tests/Android.bp index e9d91c290c..71193a270c 100644 --- a/services/mediametrics/tests/Android.bp +++ b/services/mediametrics/tests/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "mediametrics_tests", test_suites: ["device-tests"], diff --git a/services/mediaresourcemanager/Android.bp b/services/mediaresourcemanager/Android.bp index cb69aa013d..926de3e879 100644 --- a/services/mediaresourcemanager/Android.bp +++ b/services/mediaresourcemanager/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "resourcemanager_aidl", srcs: [ diff --git a/services/mediaresourcemanager/fuzzer/Android.bp b/services/mediaresourcemanager/fuzzer/Android.bp index 324a9fedb1..81c85e56f2 100644 --- a/services/mediaresourcemanager/fuzzer/Android.bp +++ b/services/mediaresourcemanager/fuzzer/Android.bp @@ -18,6 +18,15 @@ * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_fuzz { name: "mediaresourcemanager_fuzzer", srcs: [ diff --git a/services/mediaresourcemanager/test/Android.bp b/services/mediaresourcemanager/test/Android.bp index ad70a3516e..ec4ba583c0 100644 --- a/services/mediaresourcemanager/test/Android.bp +++ b/services/mediaresourcemanager/test/Android.bp @@ -1,4 +1,13 @@ // Build the unit tests. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_test { name: "ResourceManagerService_test", srcs: ["ResourceManagerService_test.cpp"], diff --git a/services/mediatranscoding/Android.bp b/services/mediatranscoding/Android.bp index 532e1756a7..a9fd14f26e 100644 --- a/services/mediatranscoding/Android.bp +++ b/services/mediatranscoding/Android.bp @@ -1,4 +1,23 @@ // service library +package { + default_applicable_licenses: [ + "frameworks_av_services_mediatranscoding_license", + ], +} + +// Added automatically by a large-scale-change +// See: http://go/android-license-faq +license { + name: "frameworks_av_services_mediatranscoding_license", + visibility: [":__subpackages__"], + license_kinds: [ + "SPDX-license-identifier-Apache-2.0", + ], + license_text: [ + "NOTICE", + ], +} + cc_library { name: "libmediatranscodingservice", diff --git a/services/mediatranscoding/tests/Android.bp b/services/mediatranscoding/tests/Android.bp index 9d3e56c77b..4df5a9f9d4 100644 --- a/services/mediatranscoding/tests/Android.bp +++ b/services/mediatranscoding/tests/Android.bp @@ -1,5 +1,16 @@ // Build the unit tests for MediaTranscodingService +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_services_mediatranscoding_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_services_mediatranscoding_license", + ], +} + cc_defaults { name: "mediatranscodingservice_test_defaults", diff --git a/services/mediatranscoding/tests/TranscodingUidPolicyTestApp/Android.bp b/services/mediatranscoding/tests/TranscodingUidPolicyTestApp/Android.bp index 95a94fc993..df00aa1d73 100644 --- a/services/mediatranscoding/tests/TranscodingUidPolicyTestApp/Android.bp +++ b/services/mediatranscoding/tests/TranscodingUidPolicyTestApp/Android.bp @@ -1,3 +1,14 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_services_mediatranscoding_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: [ + "frameworks_av_services_mediatranscoding_license", + ], +} + android_test_helper_app { name: "TranscodingUidPolicy_TestAppA", manifest: "TestAppA.xml", @@ -20,4 +31,4 @@ android_test_helper_app { static_libs: ["androidx.test.rules"], sdk_version: "test_current", srcs: ["src/**/*.java"], -} \ No newline at end of file +} diff --git a/services/minijail/Android.bp b/services/minijail/Android.bp index b057968711..3a89e12393 100644 --- a/services/minijail/Android.bp +++ b/services/minijail/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + minijail_common_cflags = [ "-Wall", "-Werror", diff --git a/services/oboeservice/Android.bp b/services/oboeservice/Android.bp index 9da486790a..21f3247d24 100644 --- a/services/oboeservice/Android.bp +++ b/services/oboeservice/Android.bp @@ -12,6 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + cc_library { name: "libaaudioservice", diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp index caa34741dd..63120f88d5 100644 --- a/services/tuner/Android.bp +++ b/services/tuner/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + filegroup { name: "tv_tuner_aidl", srcs: [ -- GitLab From 037008bcb46928c9c99d46cdfecb52fabf52fc01 Mon Sep 17 00:00:00 2001 From: Bob Badour Date: Thu, 25 Feb 2021 17:01:42 -0800 Subject: [PATCH 020/694] Finish revert of LOCAL_LICENSE_KINDS. Change-Id: I361d6777596c7a55019d245972eb1a491ad400d1 --- media/libmedia/tests/mediaplayer/Android.bp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/media/libmedia/tests/mediaplayer/Android.bp b/media/libmedia/tests/mediaplayer/Android.bp index 0fff7b4cbc..5538ea0908 100644 --- a/media/libmedia/tests/mediaplayer/Android.bp +++ b/media/libmedia/tests/mediaplayer/Android.bp @@ -14,15 +14,6 @@ * limitations under the License. */ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_av_media_libmedia_license"], -} - cc_test { name: "IMediaPlayerTest", test_suites: ["device-tests", "mts"], -- GitLab From 6750b8951db9e58d6ca1f80547f55dd2290bc095 Mon Sep 17 00:00:00 2001 From: Linus Nilsson Date: Thu, 25 Feb 2021 15:49:43 -0800 Subject: [PATCH 021/694] Transcoding: Log transcoder level metrics. - Add transcoder-level metric logging through west world, to monitor performance and failures. - Add new unit tests for TranscodingLogger class. Bug: 179274112 Test: New and existing unit tests. Change-Id: Ie8d9bc589c714a7b8be8f4f298c4fa75a81a6e56 --- media/libmediatranscoding/Android.bp | 43 +++ .../libmediatranscoding/TranscoderWrapper.cpp | 87 ++++-- .../TranscodingClientManager.cpp | 4 +- .../libmediatranscoding/TranscodingLogger.cpp | 194 ++++++++++++ .../TranscodingSessionController.cpp | 45 +-- .../include/media/ControllerClientInterface.h | 4 +- .../include/media/TranscoderInterface.h | 4 +- .../include/media/TranscoderWrapper.h | 22 +- .../include/media/TranscodingLogger.h | 97 ++++++ .../media/TranscodingSessionController.h | 5 +- media/libmediatranscoding/tests/Android.bp | 12 + .../tests/TranscodingClientManager_tests.cpp | 2 +- .../tests/TranscodingLogger_tests.cpp | 286 ++++++++++++++++++ .../TranscodingSessionController_tests.cpp | 86 +++--- .../tests/build_and_run_all_unit_tests.sh | 4 + .../transcoder/NdkCommon.cpp | 27 +- .../transcoder/VideoTrackTranscoder.cpp | 28 +- .../transcoder/include/media/NdkCommon.h | 2 + .../MediaTranscodingService.cpp | 11 +- .../MediaTranscodingService.h | 2 + .../mediatranscoding/SimulatedTranscoder.cpp | 2 + .../mediatranscoding/SimulatedTranscoder.h | 4 +- 22 files changed, 837 insertions(+), 134 deletions(-) create mode 100644 media/libmediatranscoding/TranscodingLogger.cpp create mode 100644 media/libmediatranscoding/include/media/TranscodingLogger.h create mode 100644 media/libmediatranscoding/tests/TranscodingLogger_tests.cpp diff --git a/media/libmediatranscoding/Android.bp b/media/libmediatranscoding/Android.bp index 534fa91b27..042850cf62 100644 --- a/media/libmediatranscoding/Android.bp +++ b/media/libmediatranscoding/Android.bp @@ -82,6 +82,7 @@ cc_library { srcs: [ "TranscoderWrapper.cpp", "TranscodingClientManager.cpp", + "TranscodingLogger.cpp", "TranscodingResourcePolicy.cpp", "TranscodingSessionController.cpp", "TranscodingThermalPolicy.cpp", @@ -96,6 +97,7 @@ cc_library { "libutils", "libmediatranscoder", "libmediandk", + "libstatssocket#30", ], export_shared_lib_headers: [ "libmediandk", @@ -106,6 +108,7 @@ cc_library { static_libs: [ "mediatranscoding_aidl_interface-ndk_platform", "resourceobserver_aidl_interface-V1-ndk_platform", + "libstatslog_media", ], cflags: [ @@ -126,3 +129,43 @@ cc_library { cfi: true, }, } + +cc_library_static { + name: "libstatslog_media", + generated_sources: ["statslog_media.cpp"], + generated_headers: ["statslog_media.h"], + min_sdk_version: "29", + cflags: [ + "-Wall", + "-Werror", + ], + export_generated_headers: ["statslog_media.h"], + apex_available: [ + "com.android.media", + "test_com.android.media", + ], + shared_libs: [ + "libcutils", + "liblog", + "libstatssocket#30", + "libutils", + ], +} + +genrule { + name: "statslog_media.h", + tools: ["stats-log-api-gen"], + cmd: "$(location stats-log-api-gen) --header $(genDir)/statslog_media.h --module media --namespace android,media,stats", + out: [ + "statslog_media.h", + ], +} + +genrule { + name: "statslog_media.cpp", + tools: ["stats-log-api-gen"], + cmd: "$(location stats-log-api-gen) --cpp $(genDir)/statslog_media.cpp --module media --namespace android,media,stats --importHeader statslog_media.h", + out: [ + "statslog_media.cpp", + ], +} \ No newline at end of file diff --git a/media/libmediatranscoding/TranscoderWrapper.cpp b/media/libmediatranscoding/TranscoderWrapper.cpp index 4bd41052e0..d9c98c6f5e 100644 --- a/media/libmediatranscoding/TranscoderWrapper.cpp +++ b/media/libmediatranscoding/TranscoderWrapper.cpp @@ -56,34 +56,34 @@ static TranscodingErrorCode toTranscodingError(media_status_t status) { } } -static AMediaFormat* getVideoFormat( +static std::shared_ptr getVideoFormat( const char* originalMime, const std::optional& requestedFormat) { if (requestedFormat == std::nullopt) { return nullptr; } - AMediaFormat* format = AMediaFormat_new(); + std::shared_ptr format = + std::shared_ptr(AMediaFormat_new(), &AMediaFormat_delete); bool changed = false; if (requestedFormat->codecType == TranscodingVideoCodecType::kHevc && strcmp(originalMime, AMEDIA_MIMETYPE_VIDEO_HEVC)) { - AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, AMEDIA_MIMETYPE_VIDEO_HEVC); + AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, AMEDIA_MIMETYPE_VIDEO_HEVC); changed = true; } else if (requestedFormat->codecType == TranscodingVideoCodecType::kAvc && strcmp(originalMime, AMEDIA_MIMETYPE_VIDEO_AVC)) { - AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, AMEDIA_MIMETYPE_VIDEO_AVC); + AMediaFormat_setString(format.get(), AMEDIAFORMAT_KEY_MIME, AMEDIA_MIMETYPE_VIDEO_AVC); changed = true; } if (requestedFormat->bitrateBps > 0) { - AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, requestedFormat->bitrateBps); + AMediaFormat_setInt32(format.get(), AMEDIAFORMAT_KEY_BIT_RATE, requestedFormat->bitrateBps); changed = true; } // TODO: translate other fields from requestedFormat to the format for MediaTranscoder. // Also need to determine more settings to expose in TranscodingVideoTrackFormat. if (!changed) { - AMediaFormat_delete(format); // Use null format for passthru. - format = nullptr; + format.reset(); } return format; } @@ -180,8 +180,10 @@ private: }; TranscoderWrapper::TranscoderWrapper(const std::shared_ptr& cb, + const std::shared_ptr& logger, int64_t heartBeatIntervalUs) : mCallback(cb), + mLogger(logger), mHeartBeatIntervalUs(heartBeatIntervalUs), mCurrentClientId(0), mCurrentSessionId(-1), @@ -219,10 +221,10 @@ void TranscoderWrapper::reportError(ClientIdType clientId, SessionIdType session } void TranscoderWrapper::start(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCb) { queueEvent(Event::Start, clientId, sessionId, [=, &request] { - media_status_t err = handleStart(clientId, sessionId, request, clientCb); + media_status_t err = handleStart(clientId, sessionId, request, callingUid, clientCb); if (err != AMEDIA_OK) { cleanup(); reportError(clientId, sessionId, err); @@ -253,10 +255,10 @@ void TranscoderWrapper::pause(ClientIdType clientId, SessionIdType sessionId) { } void TranscoderWrapper::resume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCb) { queueEvent(Event::Resume, clientId, sessionId, [=, &request] { - media_status_t err = handleResume(clientId, sessionId, request, clientCb); + media_status_t err = handleResume(clientId, sessionId, request, callingUid, clientCb); if (err != AMEDIA_OK) { cleanup(); reportError(clientId, sessionId, err); @@ -280,6 +282,7 @@ void TranscoderWrapper::stop(ClientIdType clientId, SessionIdType sessionId, boo } else { ALOGI("transcoder stopped"); } + logSessionEnded(TranscodingLogger::SessionEndedReason::CANCELLED, err); cleanup(); } else { // For sessions that's not currently running, release any pausedState for the session. @@ -297,6 +300,7 @@ void TranscoderWrapper::onFinish(ClientIdType clientId, SessionIdType sessionId) queueEvent(Event::Finish, clientId, sessionId, [=] { if (mTranscoder != nullptr && clientId == mCurrentClientId && sessionId == mCurrentSessionId) { + logSessionEnded(TranscodingLogger::SessionEndedReason::FINISHED, AMEDIA_OK); cleanup(); } @@ -314,6 +318,7 @@ void TranscoderWrapper::onError(ClientIdType clientId, SessionIdType sessionId, [=] { if (mTranscoder != nullptr && clientId == mCurrentClientId && sessionId == mCurrentSessionId) { + logSessionEnded(TranscodingLogger::SessionEndedReason::ERROR, error); cleanup(); } reportError(clientId, sessionId, error); @@ -345,7 +350,8 @@ void TranscoderWrapper::onHeartBeat(ClientIdType clientId, SessionIdType session media_status_t TranscoderWrapper::setupTranscoder( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& request, - const std::shared_ptr& clientCb, + uid_t callingUid, const std::shared_ptr& clientCb, + TranscodingLogger::SessionEndedReason* failureReason, const std::shared_ptr& pausedState) { if (clientCb == nullptr) { ALOGE("client callback is null"); @@ -364,6 +370,7 @@ media_status_t TranscoderWrapper::setupTranscoder( status = clientCb->openFileDescriptor(request.sourceFilePath, "r", &srcFd); if (!status.isOk() || srcFd.get() < 0) { ALOGE("failed to open source"); + *failureReason = TranscodingLogger::SessionEndedReason::OPEN_SRC_FD_FAILED; return AMEDIA_ERROR_IO; } srcFdInt = srcFd.get(); @@ -377,6 +384,7 @@ media_status_t TranscoderWrapper::setupTranscoder( status = clientCb->openFileDescriptor(request.destinationFilePath, "rw", &dstFd); if (!status.isOk() || dstFd.get() < 0) { ALOGE("failed to open destination"); + *failureReason = TranscodingLogger::SessionEndedReason::OPEN_DST_FD_FAILED; return AMEDIA_ERROR_IO; } dstFdInt = dstFd.get(); @@ -384,41 +392,46 @@ media_status_t TranscoderWrapper::setupTranscoder( mCurrentClientId = clientId; mCurrentSessionId = sessionId; + mCurrentCallingUid = callingUid; mTranscoderCb = std::make_shared(shared_from_this(), clientId, sessionId); mTranscoder = MediaTranscoder::create(mTranscoderCb, mHeartBeatIntervalUs, request.clientPid, request.clientUid, pausedState); if (mTranscoder == nullptr) { ALOGE("failed to create transcoder"); + *failureReason = TranscodingLogger::SessionEndedReason::CREATE_FAILED; return AMEDIA_ERROR_UNKNOWN; } media_status_t err = mTranscoder->configureSource(srcFdInt); if (err != AMEDIA_OK) { ALOGE("failed to configure source: %d", err); + *failureReason = TranscodingLogger::SessionEndedReason::CONFIG_SRC_FAILED; return err; } std::vector> trackFormats = mTranscoder->getTrackFormats(); if (trackFormats.size() == 0) { ALOGE("failed to get track formats!"); + *failureReason = TranscodingLogger::SessionEndedReason::NO_TRACKS; return AMEDIA_ERROR_MALFORMED; } for (int i = 0; i < trackFormats.size(); ++i) { - AMediaFormat* format = nullptr; + std::shared_ptr format; const char* mime = nullptr; AMediaFormat_getString(trackFormats[i].get(), AMEDIAFORMAT_KEY_MIME, &mime); if (!strncmp(mime, "video/", 6)) { format = getVideoFormat(mime, request.requestedVideoTrackFormat); - } - err = mTranscoder->configureTrackFormat(i, format); - if (format != nullptr) { - AMediaFormat_delete(format); + mSrcFormat = trackFormats[i]; + mDstFormat = format; } + + err = mTranscoder->configureTrackFormat(i, format.get()); if (err != AMEDIA_OK) { ALOGE("failed to configure track format for track %d: %d", i, err); + *failureReason = TranscodingLogger::SessionEndedReason::CONFIG_TRACK_FAILED; return err; } } @@ -426,6 +439,7 @@ media_status_t TranscoderWrapper::setupTranscoder( err = mTranscoder->configureDestination(dstFdInt); if (err != AMEDIA_OK) { ALOGE("failed to configure dest: %d", err); + *failureReason = TranscodingLogger::SessionEndedReason::CONFIG_DST_FAILED; return err; } @@ -434,17 +448,23 @@ media_status_t TranscoderWrapper::setupTranscoder( media_status_t TranscoderWrapper::handleStart( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& request, - const std::shared_ptr& clientCb) { + uid_t callingUid, const std::shared_ptr& clientCb) { ALOGI("%s: setting up transcoder for start", __FUNCTION__); - media_status_t err = setupTranscoder(clientId, sessionId, request, clientCb); + TranscodingLogger::SessionEndedReason reason = TranscodingLogger::SessionEndedReason::UNKNOWN; + media_status_t err = + setupTranscoder(clientId, sessionId, request, callingUid, clientCb, &reason); if (err != AMEDIA_OK) { ALOGI("%s: failed to setup transcoder", __FUNCTION__); + logSessionEnded(reason, err); return err; } + mTranscodeStartTime = std::chrono::steady_clock::now(); + err = mTranscoder->start(); if (err != AMEDIA_OK) { ALOGE("%s: failed to start transcoder: %d", __FUNCTION__, err); + logSessionEnded(TranscodingLogger::SessionEndedReason::START_FAILED, err); return err; } @@ -467,6 +487,7 @@ media_status_t TranscoderWrapper::handlePause(ClientIdType clientId, SessionIdTy std::shared_ptr pauseStates; media_status_t err = mTranscoder->pause(&pauseStates); + logSessionEnded(TranscodingLogger::SessionEndedReason::PAUSED, err); if (err != AMEDIA_OK) { ALOGE("%s: failed to pause transcoder: %d", __FUNCTION__, err); return err; @@ -479,7 +500,7 @@ media_status_t TranscoderWrapper::handlePause(ClientIdType clientId, SessionIdTy media_status_t TranscoderWrapper::handleResume( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& request, - const std::shared_ptr& clientCb) { + uid_t callingUid, const std::shared_ptr& clientCb) { std::shared_ptr pausedState; auto it = mPausedStateMap.find(SessionKeyType(clientId, sessionId)); if (it != mPausedStateMap.end()) { @@ -491,15 +512,23 @@ media_status_t TranscoderWrapper::handleResume( } ALOGI("%s: setting up transcoder for resume", __FUNCTION__); - media_status_t err = setupTranscoder(clientId, sessionId, request, clientCb, pausedState); + TranscodingLogger::SessionEndedReason reason = TranscodingLogger::SessionEndedReason::UNKNOWN; + media_status_t err = setupTranscoder(clientId, sessionId, request, callingUid, clientCb, + &reason, pausedState); if (err != AMEDIA_OK) { ALOGE("%s: failed to setup transcoder: %d", __FUNCTION__, err); + logSessionEnded(reason, err); return err; } + // Note: For now resume() will just restart transcoding from the beginning, so there is no need + // to distinguish between resume and start from a performance perspective. + mTranscodeStartTime = std::chrono::steady_clock::now(); + err = mTranscoder->resume(); if (err != AMEDIA_OK) { ALOGE("%s: failed to resume transcoder: %d", __FUNCTION__, err); + logSessionEnded(TranscodingLogger::SessionEndedReason::RESUME_FAILED, err); return err; } @@ -510,8 +539,23 @@ media_status_t TranscoderWrapper::handleResume( void TranscoderWrapper::cleanup() { mCurrentClientId = 0; mCurrentSessionId = -1; + mCurrentCallingUid = -1; mTranscoderCb = nullptr; mTranscoder = nullptr; + mSrcFormat = nullptr; + mDstFormat = nullptr; +} + +void TranscoderWrapper::logSessionEnded(const TranscodingLogger::SessionEndedReason& reason, + int error) { + std::chrono::microseconds transcodeDuration(-1); + if (reason == TranscodingLogger::SessionEndedReason::FINISHED && error == AMEDIA_OK) { + transcodeDuration = std::chrono::duration_cast( + std::chrono::steady_clock::now() - mTranscodeStartTime); + } + + mLogger->logSessionEnded(reason, mCurrentCallingUid, error, transcodeDuration, mSrcFormat.get(), + mDstFormat.get()); } void TranscoderWrapper::queueEvent(Event::Type type, ClientIdType clientId, SessionIdType sessionId, @@ -555,5 +599,4 @@ void TranscoderWrapper::threadLoop() { lock.lock(); } } - } // namespace android diff --git a/media/libmediatranscoding/TranscodingClientManager.cpp b/media/libmediatranscoding/TranscodingClientManager.cpp index 76bb33eba7..06c542173b 100644 --- a/media/libmediatranscoding/TranscodingClientManager.cpp +++ b/media/libmediatranscoding/TranscodingClientManager.cpp @@ -162,8 +162,8 @@ Status TranscodingClientManager::ClientImpl::submitRequest( int32_t sessionId = mNextSessionId.fetch_add(1); - *_aidl_return = owner->mSessionController->submit(mClientId, sessionId, in_clientUid, - in_request, mClientCallback); + *_aidl_return = owner->mSessionController->submit(mClientId, sessionId, callingUid, + in_clientUid, in_request, mClientCallback); if (*_aidl_return) { out_session->sessionId = sessionId; diff --git a/media/libmediatranscoding/TranscodingLogger.cpp b/media/libmediatranscoding/TranscodingLogger.cpp new file mode 100644 index 0000000000..29a52b0902 --- /dev/null +++ b/media/libmediatranscoding/TranscodingLogger.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// #define LOG_NDEBUG 0 +#define LOG_TAG "TranscodingLogger" + +#include +#include +#include +#include + +#include +#include + +namespace android { + +static_assert(TranscodingLogger::UNKNOWN == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__UNKNOWN, + "Session event mismatch"); +static_assert(TranscodingLogger::FINISHED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__FINISHED, + "Session event mismatch"); +static_assert(TranscodingLogger::ERROR == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__ERROR, + "Session event mismatch"); +static_assert(TranscodingLogger::PAUSED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__PAUSED, + "Session event mismatch"); +static_assert(TranscodingLogger::CANCELLED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__CANCELLED, + "Session event mismatch"); +static_assert(TranscodingLogger::START_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__START_FAILED, + "Session event mismatch"); +static_assert(TranscodingLogger::RESUME_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__RESUME_FAILED, + "Session event mismatch"); +static_assert(TranscodingLogger::CREATE_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__CREATE_FAILED, + "Session event mismatch"); +static_assert( + TranscodingLogger::CONFIG_SRC_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__CONFIG_SRC_FAILED, + "Session event mismatch"); +static_assert( + TranscodingLogger::CONFIG_DST_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__CONFIG_DST_FAILED, + "Session event mismatch"); +static_assert( + TranscodingLogger::CONFIG_TRACK_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__CONFIG_TRACK_FAILED, + "Session event mismatch"); +static_assert( + TranscodingLogger::OPEN_SRC_FD_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__OPEN_SRC_FD_FAILED, + "Session event mismatch"); +static_assert( + TranscodingLogger::OPEN_DST_FD_FAILED == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__OPEN_DST_FD_FAILED, + "Session event mismatch"); +static_assert(TranscodingLogger::NO_TRACKS == + android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED__REASON__NO_TRACKS, + "Session event mismatch"); + +static inline int32_t getInt32(AMediaFormat* fmt, const char* key, int32_t defaultValue = -1) { + int32_t value; + if (fmt == nullptr || !AMediaFormat_getInt32(fmt, key, &value)) { + ALOGW("Unable to get %s", key); + value = defaultValue; + } + return value; +} + +// Note: returned string is owned by format and only valid until the next getString. +static inline const char* getString(AMediaFormat* fmt, const char* key, + const char* defaultValue = "(null)") { + const char* value; + if (fmt == nullptr || !AMediaFormat_getString(fmt, key, &value)) { + ALOGW("Unable to get %s", key); + value = defaultValue; + } + return value; +} + +TranscodingLogger::TranscodingLogger() + : mSessionEndedAtomWriter(&android::media::stats::stats_write) {} + +void TranscodingLogger::logSessionEnded(enum SessionEndedReason reason, uid_t callingUid, + int status, std::chrono::microseconds duration, + AMediaFormat* srcFormat, AMediaFormat* dstFormat) { + logSessionEnded(std::chrono::steady_clock::now(), reason, callingUid, status, duration, + srcFormat, dstFormat); +} + +void TranscodingLogger::logSessionEnded(const std::chrono::steady_clock::time_point& now, + enum SessionEndedReason reason, uid_t callingUid, + int status, std::chrono::microseconds duration, + AMediaFormat* srcFormat, AMediaFormat* dstFormat) { + if (srcFormat == nullptr) { + ALOGE("Source format is null. Dropping event."); + return; + } + + if (!shouldLogAtom(now, status)) { + ALOGD("Maximum logged event count reached. Dropping event."); + return; + } + + // Extract the pieces of information to log. + const int32_t srcWidth = getInt32(srcFormat, AMEDIAFORMAT_KEY_WIDTH); + const int32_t srcHeight = getInt32(srcFormat, AMEDIAFORMAT_KEY_HEIGHT); + const char* srcMime = getString(srcFormat, AMEDIAFORMAT_KEY_MIME); + const int32_t srcProfile = getInt32(srcFormat, AMEDIAFORMAT_KEY_PROFILE); + const int32_t srcLevel = getInt32(srcFormat, AMEDIAFORMAT_KEY_LEVEL); + const int32_t srcFrameRate = getInt32(srcFormat, AMEDIAFORMAT_KEY_FRAME_RATE); + const int32_t srcFrameCount = getInt32(srcFormat, AMEDIAFORMAT_KEY_FRAME_COUNT); + const bool srcIsHdr = AMediaFormatUtils::VideoIsHdr(srcFormat); + + int32_t dstWidth = getInt32(dstFormat, AMEDIAFORMAT_KEY_WIDTH, srcWidth); + int32_t dstHeight = getInt32(dstFormat, AMEDIAFORMAT_KEY_HEIGHT, srcHeight); + const char* dstMime = dstFormat == nullptr + ? "passthrough" + : getString(dstFormat, AMEDIAFORMAT_KEY_MIME, srcMime); + const bool dstIsHdr = false; // Transcoder always request SDR output. + + int64_t tmpDurationUs; + const int32_t srcDurationMs = + AMediaFormat_getInt64(srcFormat, AMEDIAFORMAT_KEY_DURATION, &tmpDurationUs) + ? static_cast(tmpDurationUs / 1000) + : -1; + + int32_t transcodeFrameRate = -1; + if (status == 0 && srcFrameCount > 0 && duration.count() > 0) { + std::chrono::duration seconds{duration}; + transcodeFrameRate = static_cast( + std::round(static_cast(srcFrameCount) / seconds.count())); + } + + // Write the atom. + mSessionEndedAtomWriter(android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED, + static_cast(reason), callingUid, status, transcodeFrameRate, + srcWidth, srcHeight, srcMime, srcProfile, srcLevel, srcFrameRate, + srcDurationMs, srcIsHdr, dstWidth, dstHeight, dstMime, dstIsHdr); +} + +bool TranscodingLogger::shouldLogAtom(const std::chrono::steady_clock::time_point& now, + int status) { + std::scoped_lock lock{mLock}; + static const std::chrono::hours oneDay(24); + + // Remove events older than one day. + while (mLastLoggedAtoms.size() > 0 && (now - mLastLoggedAtoms.front().first) >= oneDay) { + if (mLastLoggedAtoms.front().second == AMEDIA_OK) { + --mSuccessfulCount; + } + mLastLoggedAtoms.pop(); + } + + // Don't log if maximum number of events is reached. + if (mLastLoggedAtoms.size() >= kMaxAtomsPerDay) { + return false; + } + + // Don't log if the event is successful and the maximum number of successful events is reached. + if (status == AMEDIA_OK && mSuccessfulCount >= kMaxSuccessfulAtomsPerDay) { + return false; + } + + // Record the event. + if (status == AMEDIA_OK) { + ++mSuccessfulCount; + } + mLastLoggedAtoms.emplace(now, status); + return true; +} + +void TranscodingLogger::setSessionEndedAtomWriter(const SessionEndedAtomWriter& writer) { + mSessionEndedAtomWriter = writer; +} + +} // namespace android diff --git a/media/libmediatranscoding/TranscodingSessionController.cpp b/media/libmediatranscoding/TranscodingSessionController.cpp index d12af21814..54357bd1eb 100644 --- a/media/libmediatranscoding/TranscodingSessionController.cpp +++ b/media/libmediatranscoding/TranscodingSessionController.cpp @@ -372,10 +372,12 @@ void TranscodingSessionController::updateCurrentSession_l() { if (shouldBeRunning) { if (topSession->getState() == Session::NOT_STARTED) { mTranscoder->start(topSession->key.first, topSession->key.second, - topSession->request, topSession->callback.lock()); + topSession->request, topSession->callingUid, + topSession->callback.lock()); } else if (topSession->getState() == Session::PAUSED) { mTranscoder->resume(topSession->key.first, topSession->key.second, - topSession->request, topSession->callback.lock()); + topSession->request, topSession->callingUid, + topSession->callback.lock()); } setSessionState_l(topSession, Session::RUNNING); } @@ -393,7 +395,7 @@ void TranscodingSessionController::removeSession_l(const SessionKeyType& session } // Remove session from uid's queue. - const uid_t uid = mSessionMap[sessionKey].uid; + const uid_t uid = mSessionMap[sessionKey].clientUid; SessionQueueType& sessionQueue = mSessionQueues[uid]; auto it = std::find(sessionQueue.begin(), sessionQueue.end(), sessionKey); if (it == sessionQueue.end()) { @@ -482,13 +484,13 @@ void TranscodingSessionController::moveUidsToTop_l(const std::unordered_set& callback) { SessionKeyType sessionKey = std::make_pair(clientId, sessionId); ALOGV("%s: session %s, uid %d, prioirty %d", __FUNCTION__, sessionToString(sessionKey).c_str(), - uid, (int32_t)request.priority); + clientUid, (int32_t)request.priority); std::scoped_lock lock{mLock}; @@ -498,19 +500,20 @@ bool TranscodingSessionController::submit( } // Add the uid package name to the store of package names we already know. - if (mUidPackageNames.count(uid) == 0) { - mUidPackageNames.emplace(uid, request.clientPackageName); + if (mUidPackageNames.count(clientUid) == 0) { + mUidPackageNames.emplace(clientUid, request.clientPackageName); } // TODO(chz): only support offline vs real-time for now. All kUnspecified sessions // go to offline queue. if (request.priority == TranscodingSessionPriority::kUnspecified) { - uid = OFFLINE_UID; + clientUid = OFFLINE_UID; } // Add session to session map. mSessionMap[sessionKey].key = sessionKey; - mSessionMap[sessionKey].uid = uid; + mSessionMap[sessionKey].clientUid = clientUid; + mSessionMap[sessionKey].callingUid = callingUid; mSessionMap[sessionKey].lastProgress = 0; mSessionMap[sessionKey].pauseCount = 0; mSessionMap[sessionKey].request = request; @@ -520,25 +523,25 @@ bool TranscodingSessionController::submit( // If it's an offline session, the queue was already added in constructor. // If it's a real-time sessions, check if a queue is already present for the uid, // and add a new queue if needed. - if (uid != OFFLINE_UID) { - if (mSessionQueues.count(uid) == 0) { - mUidPolicy->registerMonitorUid(uid); - if (mUidPolicy->isUidOnTop(uid)) { - mUidSortedList.push_front(uid); + if (clientUid != OFFLINE_UID) { + if (mSessionQueues.count(clientUid) == 0) { + mUidPolicy->registerMonitorUid(clientUid); + if (mUidPolicy->isUidOnTop(clientUid)) { + mUidSortedList.push_front(clientUid); } else { // Shouldn't be submitting real-time requests from non-top app, // put it in front of the offline queue. - mUidSortedList.insert(mOfflineUidIterator, uid); + mUidSortedList.insert(mOfflineUidIterator, clientUid); } - } else if (uid != *mUidSortedList.begin()) { - if (mUidPolicy->isUidOnTop(uid)) { - mUidSortedList.remove(uid); - mUidSortedList.push_front(uid); + } else if (clientUid != *mUidSortedList.begin()) { + if (mUidPolicy->isUidOnTop(clientUid)) { + mUidSortedList.remove(clientUid); + mUidSortedList.push_front(clientUid); } } } // Append this session to the uid's queue. - mSessionQueues[uid].push_back(sessionKey); + mSessionQueues[clientUid].push_back(sessionKey); updateCurrentSession_l(); @@ -557,7 +560,7 @@ bool TranscodingSessionController::cancel(ClientIdType clientId, SessionIdType s if (sessionId < 0) { for (auto it = mSessionMap.begin(); it != mSessionMap.end(); ++it) { - if (it->first.first == clientId && it->second.uid != OFFLINE_UID) { + if (it->first.first == clientId && it->second.clientUid != OFFLINE_UID) { sessionsToRemove.push_back(it->first); } } diff --git a/media/libmediatranscoding/include/media/ControllerClientInterface.h b/media/libmediatranscoding/include/media/ControllerClientInterface.h index 3fd4f0c866..0d13607975 100644 --- a/media/libmediatranscoding/include/media/ControllerClientInterface.h +++ b/media/libmediatranscoding/include/media/ControllerClientInterface.h @@ -36,8 +36,8 @@ public: * Returns true on success and false on failure. This call will fail is a session identified * by already exists. */ - virtual bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t uid, - const TranscodingRequestParcel& request, + virtual bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t callingUid, + uid_t clientUid, const TranscodingRequestParcel& request, const std::weak_ptr& clientCallback) = 0; /** diff --git a/media/libmediatranscoding/include/media/TranscoderInterface.h b/media/libmediatranscoding/include/media/TranscoderInterface.h index 5f27d825a7..3b0bd3bc51 100644 --- a/media/libmediatranscoding/include/media/TranscoderInterface.h +++ b/media/libmediatranscoding/include/media/TranscoderInterface.h @@ -33,11 +33,11 @@ class TranscoderCallbackInterface; class TranscoderInterface { public: virtual void start(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) = 0; virtual void pause(ClientIdType clientId, SessionIdType sessionId) = 0; virtual void resume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) = 0; // Stop the specified session. If abandon is true, the transcoder wrapper will be discarded // after the session stops. diff --git a/media/libmediatranscoding/include/media/TranscoderWrapper.h b/media/libmediatranscoding/include/media/TranscoderWrapper.h index 7935bbe757..d3d4c86a00 100644 --- a/media/libmediatranscoding/include/media/TranscoderWrapper.h +++ b/media/libmediatranscoding/include/media/TranscoderWrapper.h @@ -18,8 +18,11 @@ #define ANDROID_TRANSCODER_WRAPPER_H #include +#include #include +#include +#include #include #include #include @@ -37,16 +40,17 @@ class TranscoderWrapper : public TranscoderInterface, public std::enable_shared_from_this { public: TranscoderWrapper(const std::shared_ptr& cb, + const std::shared_ptr& logger, int64_t heartBeatIntervalUs); ~TranscoderWrapper(); // TranscoderInterface void start(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) override; void pause(ClientIdType clientId, SessionIdType sessionId) override; void resume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) override; void stop(ClientIdType clientId, SessionIdType sessionId, bool abandon = false) override; // ~TranscoderInterface @@ -76,6 +80,9 @@ private: std::shared_ptr mTranscoderCb; std::shared_ptr mTranscoder; std::weak_ptr mCallback; + std::shared_ptr mLogger; + std::shared_ptr mSrcFormat; + std::shared_ptr mDstFormat; int64_t mHeartBeatIntervalUs; std::mutex mLock; std::condition_variable mCondition; @@ -83,6 +90,9 @@ private: std::map> mPausedStateMap; ClientIdType mCurrentClientId; SessionIdType mCurrentSessionId; + uid_t mCurrentCallingUid; + std::chrono::steady_clock::time_point mTranscodeStartTime; + // Whether the looper has been created. bool mLooperReady; @@ -93,18 +103,20 @@ private: void onHeartBeat(ClientIdType clientId, SessionIdType sessionId); media_status_t handleStart(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& callback); media_status_t handlePause(ClientIdType clientId, SessionIdType sessionId); media_status_t handleResume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& callback); media_status_t setupTranscoder( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& request, - const std::shared_ptr& callback, + uid_t callingUid, const std::shared_ptr& callback, + TranscodingLogger::SessionEndedReason* failureReason /* nonnull */, const std::shared_ptr& pausedState = nullptr); void cleanup(); + void logSessionEnded(const TranscodingLogger::SessionEndedReason& reason, int error); void reportError(ClientIdType clientId, SessionIdType sessionId, media_status_t err); void queueEvent(Event::Type type, ClientIdType clientId, SessionIdType sessionId, const std::function runnable, int32_t arg = 0); diff --git a/media/libmediatranscoding/include/media/TranscodingLogger.h b/media/libmediatranscoding/include/media/TranscodingLogger.h new file mode 100644 index 0000000000..dc245518e1 --- /dev/null +++ b/media/libmediatranscoding/include/media/TranscodingLogger.h @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TRANSCODING_LOGGER_H +#define ANDROID_MEDIA_TRANSCODING_LOGGER_H + +#include +#include + +#include +#include +#include +#include + +namespace android { + +/** Class for logging transcoding events. */ +class TranscodingLogger { +public: + /** The maximum number of atoms pushed to statsd per day. */ + static constexpr int kMaxAtomsPerDay = 50; + + /** The maximum number of successful transcoding atoms pushed to statsd per day. */ + static constexpr int kMaxSuccessfulAtomsPerDay = 35; + + /** Reason transcoding session ended. Maps to MediaTranscodingSessionEnded atom's Reason. */ + enum SessionEndedReason { + UNKNOWN = 0, + FINISHED, + ERROR, + PAUSED, + CANCELLED, + START_FAILED, + RESUME_FAILED, + CREATE_FAILED, + CONFIG_SRC_FAILED, + CONFIG_DST_FAILED, + CONFIG_TRACK_FAILED, + OPEN_SRC_FD_FAILED, + OPEN_DST_FD_FAILED, + NO_TRACKS, + }; + + TranscodingLogger(); + ~TranscodingLogger() = default; + + /** + * Logs a transcoding session ended event (MediaTranscodingSessionEnded atom). + * @param reason Reason for the transcoding session to end. + * @param callingUid UID of the caller connecting to the transcoding service. + * @param status Status (error code) of the transcoding session. + * @param duration Duration of the transcoding session. + * @param srcFormat The source video track format. + * @param dstFormat The destination video track format. + */ + void logSessionEnded(enum SessionEndedReason reason, uid_t callingUid, int status, + std::chrono::microseconds duration, AMediaFormat* srcFormat, + AMediaFormat* dstFormat); + +private: + friend class TranscodingLoggerTest; + + // Function prototype for writing out the session ended atom. + using SessionEndedAtomWriter = std::function; + + std::mutex mLock; + std::queue> mLastLoggedAtoms + GUARDED_BY(mLock); + uint32_t mSuccessfulCount = 0; + SessionEndedAtomWriter mSessionEndedAtomWriter; + + void logSessionEnded(const std::chrono::steady_clock::time_point& now, + enum SessionEndedReason reason, uid_t callingUid, int status, + std::chrono::microseconds duration, AMediaFormat* srcFormat, + AMediaFormat* dstFormat); + bool shouldLogAtom(const std::chrono::steady_clock::time_point& now, int status); + // Used for testing to validate what gets sent to statsd. + void setSessionEndedAtomWriter(const SessionEndedAtomWriter& writer); +}; + +} // namespace android +#endif // ANDROID_MEDIA_TRANSCODING_LOGGER_H diff --git a/media/libmediatranscoding/include/media/TranscodingSessionController.h b/media/libmediatranscoding/include/media/TranscodingSessionController.h index 34e9506e3f..cfa2f13181 100644 --- a/media/libmediatranscoding/include/media/TranscodingSessionController.h +++ b/media/libmediatranscoding/include/media/TranscodingSessionController.h @@ -48,7 +48,7 @@ public: virtual ~TranscodingSessionController(); // ControllerClientInterface - bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t uid, + bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t callingUid, uid_t clientUid, const TranscodingRequestParcel& request, const std::weak_ptr& clientCallback) override; bool cancel(ClientIdType clientId, SessionIdType sessionId) override; @@ -108,7 +108,8 @@ private: ERROR, }; SessionKeyType key; - uid_t uid; + uid_t clientUid; + uid_t callingUid; int32_t lastProgress; int32_t pauseCount; std::chrono::time_point stateEnterTime; diff --git a/media/libmediatranscoding/tests/Android.bp b/media/libmediatranscoding/tests/Android.bp index 06b9b1732c..603611af8b 100644 --- a/media/libmediatranscoding/tests/Android.bp +++ b/media/libmediatranscoding/tests/Android.bp @@ -72,3 +72,15 @@ cc_test { srcs: ["AdjustableMaxPriorityQueue_tests.cpp"], } + +// +// TranscodingLogger unit test +// +cc_test { + name: "TranscodingLogger_tests", + defaults: ["libmediatranscoding_test_defaults"], + shared_libs: ["libmediandk", "libstatssocket#30"], + static_libs: ["libmediatranscoder", "libstatslog_media"], + + srcs: ["TranscodingLogger_tests.cpp"], +} diff --git a/media/libmediatranscoding/tests/TranscodingClientManager_tests.cpp b/media/libmediatranscoding/tests/TranscodingClientManager_tests.cpp index 1a50923c3f..57a2e27185 100644 --- a/media/libmediatranscoding/tests/TranscodingClientManager_tests.cpp +++ b/media/libmediatranscoding/tests/TranscodingClientManager_tests.cpp @@ -135,7 +135,7 @@ struct TestController : public ControllerClientInterface { virtual ~TestController() { ALOGI("TestController Destroyed"); } - bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t /*uid*/, + bool submit(ClientIdType clientId, SessionIdType sessionId, uid_t /*callingUid*/, uid_t /*uid*/, const TranscodingRequestParcel& request, const std::weak_ptr& clientCallback) override { SessionKeyType sessionKey = std::make_pair(clientId, sessionId); diff --git a/media/libmediatranscoding/tests/TranscodingLogger_tests.cpp b/media/libmediatranscoding/tests/TranscodingLogger_tests.cpp new file mode 100644 index 0000000000..39e5cd4b62 --- /dev/null +++ b/media/libmediatranscoding/tests/TranscodingLogger_tests.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Unit Test for TranscodingLogger + +// #define LOG_NDEBUG 0 +#define LOG_TAG "TranscodingLoggerTest" + +#include +#include +#include +#include +#include +#include + +#include + +namespace android { + +using Reason = TranscodingLogger::SessionEndedReason; + +// Data structure corresponding to MediaTranscodingEnded atom. +struct SessionEndedAtom { + SessionEndedAtom(int32_t atomCode, int32_t reason, int32_t callingUid, int32_t status, + int32_t transcoderFps, int32_t srcWidth, int32_t srcHeight, + char const* srcMime, int32_t srcProfile, int32_t srcLevel, int32_t srcFps, + int32_t srcDurationMs, bool srcIsHdr, int32_t dstWidth, int32_t dstHeight, + char const* dstMime, bool dstIsHdr) + : atomCode(atomCode), + reason(reason), + callingUid(callingUid), + status(status), + transcoderFps(transcoderFps), + srcWidth(srcWidth), + srcHeight(srcHeight), + srcMime(srcMime), + srcProfile(srcProfile), + srcLevel(srcLevel), + srcFps(srcFps), + srcDurationMs(srcDurationMs), + srcIsHdr(srcIsHdr), + dstWidth(dstWidth), + dstHeight(dstHeight), + dstMime(dstMime), + dstIsHdr(dstIsHdr) {} + + int32_t atomCode; + int32_t reason; + int32_t callingUid; + int32_t status; + int32_t transcoderFps; + int32_t srcWidth; + int32_t srcHeight; + std::string srcMime; + int32_t srcProfile; + int32_t srcLevel; + int32_t srcFps; + int32_t srcDurationMs; + bool srcIsHdr; + int32_t dstWidth; + int32_t dstHeight; + std::string dstMime; + bool dstIsHdr; +}; + +// Default configuration values. +static constexpr int32_t kDefaultCallingUid = 1; +static constexpr std::chrono::microseconds kDefaultTranscodeDuration = std::chrono::seconds{2}; + +static constexpr int32_t kDefaultSrcWidth = 1920; +static constexpr int32_t kDefaultSrcHeight = 1080; +static const std::string kDefaultSrcMime{AMEDIA_MIMETYPE_VIDEO_HEVC}; +static constexpr int32_t kDefaultSrcProfile = 1; // HEVC Main +static constexpr int32_t kDefaultSrcLevel = 65536; // HEVCMainTierLevel51 +static constexpr int32_t kDefaultSrcFps = 30; +static constexpr int32_t kDefaultSrcFrameCount = 120; +static constexpr int64_t kDefaultSrcDurationUs = 1000000 * kDefaultSrcFrameCount / kDefaultSrcFps; + +static constexpr int32_t kDefaultDstWidth = 1280; +static constexpr int32_t kDefaultDstHeight = 720; +static const std::string kDefaultDstMime{AMEDIA_MIMETYPE_VIDEO_AVC}; + +// Util for creating a default source video format. +static AMediaFormat* CreateSrcFormat() { + AMediaFormat* fmt = AMediaFormat_new(); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_WIDTH, kDefaultSrcWidth); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_HEIGHT, kDefaultSrcHeight); + AMediaFormat_setString(fmt, AMEDIAFORMAT_KEY_MIME, kDefaultSrcMime.c_str()); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_PROFILE, kDefaultSrcProfile); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_LEVEL, kDefaultSrcLevel); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_FRAME_RATE, kDefaultSrcFps); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_FRAME_COUNT, kDefaultSrcFrameCount); + AMediaFormat_setInt64(fmt, AMEDIAFORMAT_KEY_DURATION, kDefaultSrcDurationUs); + return fmt; +} + +// Util for creating a default destination video format. +static AMediaFormat* CreateDstFormat() { + AMediaFormat* fmt = AMediaFormat_new(); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_WIDTH, kDefaultDstWidth); + AMediaFormat_setInt32(fmt, AMEDIAFORMAT_KEY_HEIGHT, kDefaultDstHeight); + AMediaFormat_setString(fmt, AMEDIAFORMAT_KEY_MIME, kDefaultDstMime.c_str()); + return fmt; +} + +class TranscodingLoggerTest : public ::testing::Test { +public: + TranscodingLoggerTest() { ALOGI("TranscodingLoggerTest created"); } + + void SetUp() override { + ALOGI("TranscodingLoggerTest set up"); + mLogger.reset(new TranscodingLogger()); + mLoggedAtoms.clear(); + mSrcFormat.reset(); + mDstFormat.reset(); + + // Set a custom atom writer that saves all data, so the test can validate it afterwards. + mLogger->setSessionEndedAtomWriter( + [=](int32_t atomCode, int32_t reason, int32_t callingUid, int32_t status, + int32_t transcoderFps, int32_t srcWidth, int32_t srcHeight, char const* srcMime, + int32_t srcProfile, int32_t srcLevel, int32_t srcFps, int32_t srcDurationMs, + bool srcIsHdr, int32_t dstWidth, int32_t dstHeight, char const* dstMime, + bool dstIsHdr) -> int { + mLoggedAtoms.emplace_back(atomCode, reason, callingUid, status, transcoderFps, + srcWidth, srcHeight, srcMime, srcProfile, srcLevel, + srcFps, srcDurationMs, srcIsHdr, dstWidth, dstHeight, + dstMime, dstIsHdr); + return 0; + }); + } + + void logSession(const std::chrono::steady_clock::time_point& time, Reason reason, int status, + AMediaFormat* srcFormat, AMediaFormat* dstFormat) { + mLogger->logSessionEnded(time, reason, kDefaultCallingUid, status, + kDefaultTranscodeDuration, srcFormat, dstFormat); + } + + void logSession(const std::chrono::steady_clock::time_point& time, Reason reason, int status) { + if (!mSrcFormat) { + mSrcFormat = std::shared_ptr(CreateSrcFormat(), &AMediaFormat_delete); + } + if (!mDstFormat) { + mDstFormat = std::shared_ptr(CreateDstFormat(), &AMediaFormat_delete); + } + logSession(time, reason, status, mSrcFormat.get(), mDstFormat.get()); + } + + void logSessionFinished(const std::chrono::steady_clock::time_point& time) { + logSession(time, Reason::FINISHED, 0); + } + + void logSessionFailed(const std::chrono::steady_clock::time_point& time) { + logSession(time, Reason::ERROR, AMEDIA_ERROR_UNKNOWN); + } + + int logCount() const { return mLoggedAtoms.size(); } + + void validateLatestAtom(Reason reason, int status, bool passthrough = false) { + const SessionEndedAtom& atom = mLoggedAtoms.back(); + + EXPECT_EQ(atom.atomCode, android::media::stats::MEDIA_TRANSCODING_SESSION_ENDED); + EXPECT_EQ(atom.reason, static_cast(reason)); + EXPECT_EQ(atom.callingUid, kDefaultCallingUid); + EXPECT_EQ(atom.status, status); + EXPECT_EQ(atom.srcWidth, kDefaultSrcWidth); + EXPECT_EQ(atom.srcHeight, kDefaultSrcHeight); + EXPECT_EQ(atom.srcMime, kDefaultSrcMime); + EXPECT_EQ(atom.srcProfile, kDefaultSrcProfile); + EXPECT_EQ(atom.srcLevel, kDefaultSrcLevel); + EXPECT_EQ(atom.srcFps, kDefaultSrcFps); + EXPECT_EQ(atom.srcDurationMs, kDefaultSrcDurationUs / 1000); + EXPECT_FALSE(atom.srcIsHdr); + EXPECT_EQ(atom.dstWidth, passthrough ? kDefaultSrcWidth : kDefaultDstWidth); + EXPECT_EQ(atom.dstHeight, passthrough ? kDefaultSrcHeight : kDefaultDstHeight); + EXPECT_EQ(atom.dstMime, passthrough ? "passthrough" : kDefaultDstMime); + EXPECT_FALSE(atom.dstIsHdr); + + // Transcoder frame rate is only present on successful sessions. + if (status == AMEDIA_OK) { + std::chrono::duration seconds{kDefaultTranscodeDuration}; + const int32_t transcoderFps = + static_cast(kDefaultSrcFrameCount / seconds.count()); + EXPECT_EQ(atom.transcoderFps, transcoderFps); + } else { + EXPECT_EQ(atom.transcoderFps, -1); + } + } + + void TearDown() override { ALOGI("TranscodingLoggerTest tear down"); } + ~TranscodingLoggerTest() { ALOGD("TranscodingLoggerTest destroyed"); } + + std::shared_ptr mLogger; + std::vector mLoggedAtoms; + + std::shared_ptr mSrcFormat; + std::shared_ptr mDstFormat; +}; + +TEST_F(TranscodingLoggerTest, TestDailyLogQuota) { + ALOGD("TestDailyLogQuota"); + auto start = std::chrono::steady_clock::now(); + + EXPECT_LT(TranscodingLogger::kMaxSuccessfulAtomsPerDay, TranscodingLogger::kMaxAtomsPerDay); + + // 1. Check that the first kMaxSuccessfulAtomsPerDay successful atoms are logged. + for (int i = 0; i < TranscodingLogger::kMaxSuccessfulAtomsPerDay; ++i) { + logSessionFinished(start + std::chrono::seconds{i}); + EXPECT_EQ(logCount(), i + 1); + } + + // 2. Check that subsequent successful atoms within the same 24h interval are not logged. + for (int i = 1; i < 24; ++i) { + logSessionFinished(start + std::chrono::hours{i}); + EXPECT_EQ(logCount(), TranscodingLogger::kMaxSuccessfulAtomsPerDay); + } + + // 3. Check that failed atoms are logged up to kMaxAtomsPerDay. + for (int i = TranscodingLogger::kMaxSuccessfulAtomsPerDay; + i < TranscodingLogger::kMaxAtomsPerDay; ++i) { + logSessionFailed(start + std::chrono::seconds{i}); + EXPECT_EQ(logCount(), i + 1); + } + + // 4. Check that subsequent failed atoms within the same 24h interval are not logged. + for (int i = 1; i < 24; ++i) { + logSessionFailed(start + std::chrono::hours{i}); + EXPECT_EQ(logCount(), TranscodingLogger::kMaxAtomsPerDay); + } + + // 5. Check that failed and successful atoms are logged again after 24h. + logSessionFinished(start + std::chrono::hours{24}); + EXPECT_EQ(logCount(), TranscodingLogger::kMaxAtomsPerDay + 1); + + logSessionFailed(start + std::chrono::hours{24} + std::chrono::seconds{1}); + EXPECT_EQ(logCount(), TranscodingLogger::kMaxAtomsPerDay + 2); +} + +TEST_F(TranscodingLoggerTest, TestNullFormats) { + ALOGD("TestNullFormats"); + auto srcFormat = std::shared_ptr(CreateSrcFormat(), &AMediaFormat_delete); + auto dstFormat = std::shared_ptr(CreateDstFormat(), &AMediaFormat_delete); + auto now = std::chrono::steady_clock::now(); + + // Source format null, should not log. + logSession(now, Reason::FINISHED, AMEDIA_OK, nullptr /*srcFormat*/, dstFormat.get()); + EXPECT_EQ(logCount(), 0); + + // Both formats null, should not log. + logSession(now, Reason::FINISHED, AMEDIA_OK, nullptr /*srcFormat*/, nullptr /*dstFormat*/); + EXPECT_EQ(logCount(), 0); + + // Destination format null (passthrough mode), should log. + logSession(now, Reason::FINISHED, AMEDIA_OK, srcFormat.get(), nullptr /*dstFormat*/); + EXPECT_EQ(logCount(), 1); + validateLatestAtom(Reason::FINISHED, AMEDIA_OK, true /*passthrough*/); +} + +TEST_F(TranscodingLoggerTest, TestAtomContentCorrectness) { + ALOGD("TestAtomContentCorrectness"); + auto now = std::chrono::steady_clock::now(); + + // Log and validate a failure. + logSession(now, Reason::ERROR, AMEDIA_ERROR_MALFORMED); + EXPECT_EQ(logCount(), 1); + validateLatestAtom(Reason::ERROR, AMEDIA_ERROR_MALFORMED); + + // Log and validate a success. + logSession(now, Reason::FINISHED, AMEDIA_OK); + EXPECT_EQ(logCount(), 2); + validateLatestAtom(Reason::FINISHED, AMEDIA_OK); +} + +} // namespace android diff --git a/media/libmediatranscoding/tests/TranscodingSessionController_tests.cpp b/media/libmediatranscoding/tests/TranscodingSessionController_tests.cpp index 2e9daee227..3cd9112a79 100644 --- a/media/libmediatranscoding/tests/TranscodingSessionController_tests.cpp +++ b/media/libmediatranscoding/tests/TranscodingSessionController_tests.cpp @@ -123,7 +123,7 @@ public: // TranscoderInterface void start(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& /*request*/, + const TranscodingRequestParcel& /*request*/, uid_t /*callingUid*/, const std::shared_ptr& /*clientCallback*/) override { append(Start(clientId, sessionId)); } @@ -131,7 +131,7 @@ public: append(Pause(clientId, sessionId)); } void resume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& /*request*/, + const TranscodingRequestParcel& /*request*/, uid_t /*callingUid*/, const std::shared_ptr& /*clientCallback*/) override { append(Resume(clientId, sessionId)); } @@ -349,32 +349,32 @@ TEST_F(TranscodingSessionControllerTest, TestSubmitSession) { // Submit offline session to CLIENT(0) in UID(0). // Should start immediately (because this is the only session). - mController->submit(CLIENT(0), SESSION(0), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), 0)); // Submit real-time session to CLIENT(0). // Should pause offline session and start new session, even if UID(0) is not on top. - mController->submit(CLIENT(0), SESSION(1), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(1), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(1))); // Submit real-time session to CLIENT(0), should be queued after the previous session. - mController->submit(CLIENT(0), SESSION(2), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(2), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Submit real-time session to CLIENT(1) in same uid, should be queued after the previous // session. - mController->submit(CLIENT(1), SESSION(0), UID(0), mRealtimeRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mRealtimeRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Submit real-time session to CLIENT(2) in UID(1). // Should pause previous session and start new session, because UID(1) is (has been) top. - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(1))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); // Submit offline session, shouldn't generate any event. - mController->submit(CLIENT(2), SESSION(1), UID(1), mOfflineRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(1), UID(2), UID(1), mOfflineRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Bring UID(0) to top. @@ -388,15 +388,15 @@ TEST_F(TranscodingSessionControllerTest, TestCancelSession) { ALOGD("TestCancelSession"); // Submit real-time session SESSION(0), should start immediately. - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit real-time session SESSION(1), should not start. - mController->submit(CLIENT(0), SESSION(1), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(1), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Submit offline session SESSION(2), should not start. - mController->submit(CLIENT(0), SESSION(2), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(2), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Cancel queued real-time session. @@ -408,7 +408,7 @@ TEST_F(TranscodingSessionControllerTest, TestCancelSession) { EXPECT_TRUE(mController->cancel(CLIENT(0), SESSION(2))); // Submit offline session SESSION(3), shouldn't cause any event. - mController->submit(CLIENT(0), SESSION(3), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(3), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Cancel running real-time session SESSION(0). @@ -420,7 +420,7 @@ TEST_F(TranscodingSessionControllerTest, TestCancelSession) { // Submit real-time session SESSION(4), offline SESSION(3) should pause and SESSION(4) // should start. - mController->submit(CLIENT(0), SESSION(4), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(4), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(3))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(4))); @@ -438,16 +438,16 @@ TEST_F(TranscodingSessionControllerTest, TestFinishSession) { EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Submit offline session SESSION(0), should start immediately. - mController->submit(CLIENT(0), SESSION(0), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit real-time session SESSION(1), should pause offline session and start immediately. - mController->submit(CLIENT(0), SESSION(1), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(1), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(1))); // Submit real-time session SESSION(2), should not start. - mController->submit(CLIENT(0), SESSION(2), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(2), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Finish when the session never started, should be ignored. @@ -458,7 +458,7 @@ TEST_F(TranscodingSessionControllerTest, TestFinishSession) { mUidPolicy->setTop(UID(1)); // Submit real-time session to CLIENT(1) in UID(1), should pause previous session and start // new session. - mController->submit(CLIENT(1), SESSION(0), UID(1), mRealtimeRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(1), mRealtimeRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(1))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(1), SESSION(0))); @@ -495,16 +495,16 @@ TEST_F(TranscodingSessionControllerTest, TestFailSession) { EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Submit offline session SESSION(0), should start immediately. - mController->submit(CLIENT(0), SESSION(0), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit real-time session SESSION(1), should pause offline session and start immediately. - mController->submit(CLIENT(0), SESSION(1), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(1), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(1))); // Submit real-time session SESSION(2), should not start. - mController->submit(CLIENT(0), SESSION(2), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(2), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Fail when the session never started, should be ignored. @@ -515,7 +515,7 @@ TEST_F(TranscodingSessionControllerTest, TestFailSession) { mUidPolicy->setTop(UID(1)); // Submit real-time session to CLIENT(1) in UID(1), should pause previous session and start // new session. - mController->submit(CLIENT(1), SESSION(0), UID(1), mRealtimeRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(1), mRealtimeRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(1))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(1), SESSION(0))); @@ -549,11 +549,11 @@ TEST_F(TranscodingSessionControllerTest, TestTopUidChanged) { // Start with unspecified top UID. // Submit real-time session to CLIENT(0), session should start immediately. - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit offline session to CLIENT(0), should not start. - mController->submit(CLIENT(1), SESSION(0), UID(0), mOfflineRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mOfflineRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Move UID(1) to top. @@ -562,7 +562,7 @@ TEST_F(TranscodingSessionControllerTest, TestTopUidChanged) { // Submit real-time session to CLIENT(2) in different uid UID(1). // Should pause previous session and start new session. - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); @@ -591,11 +591,11 @@ TEST_F(TranscodingSessionControllerTest, TestTopUidSetChanged) { // Start with unspecified top UID. // Submit real-time session to CLIENT(0), session should start immediately. - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit offline session to CLIENT(0), should not start. - mController->submit(CLIENT(1), SESSION(0), UID(0), mOfflineRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mOfflineRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Set UID(0), UID(1) to top set. @@ -605,7 +605,7 @@ TEST_F(TranscodingSessionControllerTest, TestTopUidSetChanged) { // Submit real-time session to CLIENT(2) in different uid UID(1). // UID(0) should pause and UID(1) should start. - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); @@ -647,12 +647,12 @@ TEST_F(TranscodingSessionControllerTest, TestResourceLost) { // Start with unspecified top UID. // Submit real-time session to CLIENT(0), session should start immediately. mRealtimeRequest.clientPid = PID(0); - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit offline session to CLIENT(0), should not start. mOfflineRequest.clientPid = PID(0); - mController->submit(CLIENT(1), SESSION(0), UID(0), mOfflineRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mOfflineRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Move UID(1) to top. @@ -662,7 +662,7 @@ TEST_F(TranscodingSessionControllerTest, TestResourceLost) { // Submit real-time session to CLIENT(2) in different uid UID(1). // Should pause previous session and start new session. mRealtimeRequest.clientPid = PID(1); - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); @@ -719,7 +719,7 @@ TEST_F(TranscodingSessionControllerTest, TestResourceLost) { // Submit real-time session to CLIENT(3) in UID(2), session shouldn't start due to no resource. mRealtimeRequest.clientPid = PID(2); - mController->submit(CLIENT(3), SESSION(0), UID(2), mRealtimeRequest, mClientCallback3); + mController->submit(CLIENT(3), SESSION(0), UID(3), UID(2), mRealtimeRequest, mClientCallback3); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Signal resource available, CLIENT(3)'s session should start. @@ -734,12 +734,12 @@ TEST_F(TranscodingSessionControllerTest, TestThermalCallback) { // Start with unspecified top UID. // Submit real-time session to CLIENT(0), session should start immediately. mRealtimeRequest.clientPid = PID(0); - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit offline session to CLIENT(0), should not start. mOfflineRequest.clientPid = PID(0); - mController->submit(CLIENT(1), SESSION(0), UID(0), mOfflineRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mOfflineRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Move UID(1) to top. @@ -749,7 +749,7 @@ TEST_F(TranscodingSessionControllerTest, TestThermalCallback) { // Submit real-time session to CLIENT(2) in different uid UID(1). // Should pause previous session and start new session. mRealtimeRequest.clientPid = PID(1); - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); @@ -788,7 +788,7 @@ TEST_F(TranscodingSessionControllerTest, TestThermalCallback) { mUidPolicy->setTop(UID(2)); // Submit real-time session to CLIENT(3) in UID(2), session shouldn't start during throttling. mRealtimeRequest.clientPid = PID(2); - mController->submit(CLIENT(3), SESSION(0), UID(2), mRealtimeRequest, mClientCallback3); + mController->submit(CLIENT(3), SESSION(0), UID(3), UID(2), mRealtimeRequest, mClientCallback3); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Throttling stops, CLIENT(3)'s session should start. mController->onThrottlingStopped(); @@ -802,12 +802,12 @@ TEST_F(TranscodingSessionControllerTest, TestResourceLostAndThermalCallback) { // Start with unspecified top UID. // Submit real-time session to CLIENT(0), session should start immediately. mRealtimeRequest.clientPid = PID(0); - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); // Submit offline session to CLIENT(0), should not start. mOfflineRequest.clientPid = PID(0); - mController->submit(CLIENT(1), SESSION(0), UID(0), mOfflineRequest, mClientCallback1); + mController->submit(CLIENT(1), SESSION(0), UID(1), UID(0), mOfflineRequest, mClientCallback1); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::NoEvent); // Move UID(1) to top. @@ -817,7 +817,7 @@ TEST_F(TranscodingSessionControllerTest, TestResourceLostAndThermalCallback) { // Submit real-time session to CLIENT(2) in different uid UID(1). // Should pause previous session and start new session. mRealtimeRequest.clientPid = PID(1); - mController->submit(CLIENT(2), SESSION(0), UID(1), mRealtimeRequest, mClientCallback2); + mController->submit(CLIENT(2), SESSION(0), UID(2), UID(1), mRealtimeRequest, mClientCallback2); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(0))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(2), SESSION(0))); @@ -859,7 +859,7 @@ TEST_F(TranscodingSessionControllerTest, TestTranscoderWatchdogTimeout) { // Submit session to CLIENT(0) in UID(0). // Should start immediately (because this is the only session). - mController->submit(CLIENT(0), SESSION(0), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(0), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(0))); int32_t expectedGen = 2; @@ -867,7 +867,7 @@ TEST_F(TranscodingSessionControllerTest, TestTranscoderWatchdogTimeout) { expectTimeout(CLIENT(0), SESSION(0), expectedGen++); // Test 2: No timeout as long as keep-alive coming; timeout after keep-alive stops. - mController->submit(CLIENT(0), SESSION(1), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(1), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(1))); for (int i = 0; i < 5; i++) { EXPECT_EQ(mTranscoder->popEvent(1000000), TestTranscoder::NoEvent); @@ -876,7 +876,7 @@ TEST_F(TranscodingSessionControllerTest, TestTranscoderWatchdogTimeout) { expectTimeout(CLIENT(0), SESSION(1), expectedGen++); // Test 3a: No timeout for paused session even if no keep-alive is sent. - mController->submit(CLIENT(0), SESSION(2), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(2), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(2))); // Trigger a pause by sending a resource lost. mController->onResourceLost(CLIENT(0), SESSION(2)); @@ -886,12 +886,12 @@ TEST_F(TranscodingSessionControllerTest, TestTranscoderWatchdogTimeout) { expectTimeout(CLIENT(0), SESSION(2), expectedGen++); // Test 3b: No timeout for paused session even if no keep-alive is sent. - mController->submit(CLIENT(0), SESSION(3), UID(0), mOfflineRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(3), UID(0), UID(0), mOfflineRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(3))); // Let the session run almost to timeout, to test timeout reset after pause. EXPECT_EQ(mTranscoder->popEvent(2900000), TestTranscoder::NoEvent); // Trigger a pause by submitting a higher-priority request. - mController->submit(CLIENT(0), SESSION(4), UID(0), mRealtimeRequest, mClientCallback0); + mController->submit(CLIENT(0), SESSION(4), UID(0), UID(0), mRealtimeRequest, mClientCallback0); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Pause(CLIENT(0), SESSION(3))); EXPECT_EQ(mTranscoder->popEvent(), TestTranscoder::Start(CLIENT(0), SESSION(4))); // Finish the higher-priority session, lower-priority session should resume, diff --git a/media/libmediatranscoding/tests/build_and_run_all_unit_tests.sh b/media/libmediatranscoding/tests/build_and_run_all_unit_tests.sh index 5db9258948..3cbf1dd302 100644 --- a/media/libmediatranscoding/tests/build_and_run_all_unit_tests.sh +++ b/media/libmediatranscoding/tests/build_and_run_all_unit_tests.sh @@ -32,3 +32,7 @@ adb shell /data/nativetest/AdjustableMaxPriorityQueue_tests/AdjustableMaxPriorit echo "testing TranscodingSessionController" #adb shell /data/nativetest64/TranscodingSessionController_tests/TranscodingSessionController_tests adb shell /data/nativetest/TranscodingSessionController_tests/TranscodingSessionController_tests + +echo "testing TranscodingLogger" +#adb shell /data/nativetest64/TranscodingLogger_tests/TranscodingLogger_tests +adb shell /data/nativetest/TranscodingLogger_tests/TranscodingLogger_tests diff --git a/media/libmediatranscoding/transcoder/NdkCommon.cpp b/media/libmediatranscoding/transcoder/NdkCommon.cpp index f5c9594432..fb909b2043 100644 --- a/media/libmediatranscoding/transcoder/NdkCommon.cpp +++ b/media/libmediatranscoding/transcoder/NdkCommon.cpp @@ -90,4 +90,29 @@ void CopyFormatEntries(AMediaFormat* from, AMediaFormat* to, const EntryCopier* DEFINE_SET_DEFAULT_FORMAT_VALUE_FUNC(float, Float); DEFINE_SET_DEFAULT_FORMAT_VALUE_FUNC(int32_t, Int32); -} // namespace AMediaFormatUtils \ No newline at end of file +// Determines whether a track format describes HDR video content or not. The +// logic is based on isHdr() in libstagefright/Utils.cpp. +bool VideoIsHdr(AMediaFormat* format) { + // If VUI signals HDR content, this internal flag is set by the extractor. + int32_t isHdr; + if (AMediaFormat_getInt32(format, "android._is-hdr", &isHdr)) { + return isHdr; + } + + // If container supplied HDR static info without transfer set, assume HDR. + const char* hdrInfo; + int32_t transfer; + if ((AMediaFormat_getString(format, AMEDIAFORMAT_KEY_HDR_STATIC_INFO, &hdrInfo) || + AMediaFormat_getString(format, "hdr10-plus-info", &hdrInfo)) && + !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_COLOR_TRANSFER, &transfer)) { + return true; + } + + // Otherwise, check if an HDR transfer function is set. + if (AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_COLOR_TRANSFER, &transfer)) { + return transfer == COLOR_TRANSFER_ST2084 || transfer == COLOR_TRANSFER_HLG; + } + + return false; +} +} // namespace AMediaFormatUtils diff --git a/media/libmediatranscoding/transcoder/VideoTrackTranscoder.cpp b/media/libmediatranscoding/transcoder/VideoTrackTranscoder.cpp index 04a513e974..acf5f6c071 100644 --- a/media/libmediatranscoding/transcoder/VideoTrackTranscoder.cpp +++ b/media/libmediatranscoding/transcoder/VideoTrackTranscoder.cpp @@ -51,32 +51,6 @@ static constexpr int32_t kDefaultBitrateMbps = 10 * 1000 * 1000; // Default frame rate. static constexpr int32_t kDefaultFrameRate = 30; -// Determines whether a track format describes HDR video content or not. The -// logic is based on isHdr() in libstagefright/Utils.cpp. -static bool isHdr(AMediaFormat* format) { - // If VUI signals HDR content, this internal flag is set by the extractor. - int32_t isHdr; - if (AMediaFormat_getInt32(format, "android._is-hdr", &isHdr)) { - return isHdr; - } - - // If container supplied HDR static info without transfer set, assume HDR. - const char* hdrInfo; - int32_t transfer; - if ((AMediaFormat_getString(format, AMEDIAFORMAT_KEY_HDR_STATIC_INFO, &hdrInfo) || - AMediaFormat_getString(format, "hdr10-plus-info", &hdrInfo)) && - !AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_COLOR_TRANSFER, &transfer)) { - return true; - } - - // Otherwise, check if an HDR transfer function is set. - if (AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_COLOR_TRANSFER, &transfer)) { - return transfer == COLOR_TRANSFER_ST2084 || transfer == COLOR_TRANSFER_HLG; - } - - return false; -} - template void VideoTrackTranscoder::BlockingQueue::push(T const& value, bool front) { { @@ -347,7 +321,7 @@ media_status_t VideoTrackTranscoder::configureDestinationFormat( } // Request decoder to convert HDR content to SDR. - const bool sourceIsHdr = isHdr(mSourceFormat.get()); + const bool sourceIsHdr = VideoIsHdr(mSourceFormat.get()); if (sourceIsHdr) { AMediaFormat_setInt32(decoderFormat.get(), TBD_AMEDIACODEC_PARAMETER_KEY_COLOR_TRANSFER_REQUEST, diff --git a/media/libmediatranscoding/transcoder/include/media/NdkCommon.h b/media/libmediatranscoding/transcoder/include/media/NdkCommon.h index cc3399a203..a7ed6a71ea 100644 --- a/media/libmediatranscoding/transcoder/include/media/NdkCommon.h +++ b/media/libmediatranscoding/transcoder/include/media/NdkCommon.h @@ -88,5 +88,7 @@ void CopyFormatEntries(AMediaFormat* from, AMediaFormat* to, const EntryCopier* bool SetDefaultFormatValueFloat(const char* key, AMediaFormat* format, float value); bool SetDefaultFormatValueInt32(const char* key, AMediaFormat* format, int32_t value); +bool VideoIsHdr(AMediaFormat* format); + } // namespace AMediaFormatUtils #endif // ANDROID_MEDIA_TRANSCODING_NDK_COMMON_H diff --git a/services/mediatranscoding/MediaTranscodingService.cpp b/services/mediatranscoding/MediaTranscodingService.cpp index cca36fb748..4433f330e0 100644 --- a/services/mediatranscoding/MediaTranscodingService.cpp +++ b/services/mediatranscoding/MediaTranscodingService.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -44,15 +45,17 @@ namespace android { MediaTranscodingService::MediaTranscodingService(bool simulated) : mUidPolicy(new TranscodingUidPolicy()), mResourcePolicy(new TranscodingResourcePolicy()), - mThermalPolicy(new TranscodingThermalPolicy()) { + mThermalPolicy(new TranscodingThermalPolicy()), + mLogger(new TranscodingLogger()) { ALOGV("MediaTranscodingService is created"); mSessionController.reset(new TranscodingSessionController( - [simulated](const std::shared_ptr& cb, - int64_t heartBeatUs) -> std::shared_ptr { + [simulated, logger = mLogger]( + const std::shared_ptr& cb, + int64_t heartBeatUs) -> std::shared_ptr { if (simulated) { return std::make_shared(cb, heartBeatUs); } - return std::make_shared(cb, heartBeatUs); + return std::make_shared(cb, logger, heartBeatUs); }, mUidPolicy, mResourcePolicy, mThermalPolicy)); mClientManager.reset(new TranscodingClientManager(mSessionController)); diff --git a/services/mediatranscoding/MediaTranscodingService.h b/services/mediatranscoding/MediaTranscodingService.h index d024c54b08..9384641f6d 100644 --- a/services/mediatranscoding/MediaTranscodingService.h +++ b/services/mediatranscoding/MediaTranscodingService.h @@ -29,6 +29,7 @@ using ::aidl::android::media::ITranscodingClientCallback; using ::aidl::android::media::TranscodingRequestParcel; using ::aidl::android::media::TranscodingSessionParcel; class TranscodingClientManager; +class TranscodingLogger; class TranscodingSessionController; class UidPolicyInterface; class ResourcePolicyInterface; @@ -62,6 +63,7 @@ private: std::shared_ptr mUidPolicy; std::shared_ptr mResourcePolicy; std::shared_ptr mThermalPolicy; + std::shared_ptr mLogger; std::shared_ptr mSessionController; std::shared_ptr mClientManager; }; diff --git a/services/mediatranscoding/SimulatedTranscoder.cpp b/services/mediatranscoding/SimulatedTranscoder.cpp index db83ccb52c..0151b3d770 100644 --- a/services/mediatranscoding/SimulatedTranscoder.cpp +++ b/services/mediatranscoding/SimulatedTranscoder.cpp @@ -59,6 +59,7 @@ SimulatedTranscoder::~SimulatedTranscoder() { void SimulatedTranscoder::start( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& request, + uid_t /*callingUid*/, const std::shared_ptr& /*clientCallback*/) { { auto lock = std::scoped_lock(mLock); @@ -91,6 +92,7 @@ void SimulatedTranscoder::pause(ClientIdType clientId, SessionIdType sessionId) void SimulatedTranscoder::resume( ClientIdType clientId, SessionIdType sessionId, const TranscodingRequestParcel& /*request*/, + uid_t /*callingUid*/, const std::shared_ptr& /*clientCallback*/) { queueEvent(Event::Resume, clientId, sessionId, [=] { auto callback = mCallback.lock(); diff --git a/services/mediatranscoding/SimulatedTranscoder.h b/services/mediatranscoding/SimulatedTranscoder.h index 010f0f0132..69905761f0 100644 --- a/services/mediatranscoding/SimulatedTranscoder.h +++ b/services/mediatranscoding/SimulatedTranscoder.h @@ -55,11 +55,11 @@ public: // TranscoderInterface void start(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) override; void pause(ClientIdType clientId, SessionIdType sessionId) override; void resume(ClientIdType clientId, SessionIdType sessionId, - const TranscodingRequestParcel& request, + const TranscodingRequestParcel& request, uid_t callingUid, const std::shared_ptr& clientCallback) override; void stop(ClientIdType clientId, SessionIdType sessionId, bool abandon = false) override; // ~TranscoderInterface -- GitLab From 685e4c409d6aa1b7e014fe035eca3e5640741881 Mon Sep 17 00:00:00 2001 From: Bob Badour Date: Fri, 12 Mar 2021 06:28:14 -0800 Subject: [PATCH 022/694] [LSC] Add LOCAL_LICENSE_KINDS to frameworks/av Added SPDX-license-identifier-Apache-2.0 to: media/tests/SampleVideoEncoder/app/Android.bp Bug: 68860345 Bug: 151177513 Bug: 151953481 Test: m all Exempt-From-Owner-Approval: janitorial work Change-Id: Ie0a1d4beef9738d7effa35f8225f30d6d3835494 --- media/tests/SampleVideoEncoder/app/Android.bp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/media/tests/SampleVideoEncoder/app/Android.bp b/media/tests/SampleVideoEncoder/app/Android.bp index 35fe0d88fb..3a66955942 100644 --- a/media/tests/SampleVideoEncoder/app/Android.bp +++ b/media/tests/SampleVideoEncoder/app/Android.bp @@ -14,6 +14,15 @@ * limitations under the License. */ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_license"], +} + android_app { name: "SampleVideoEncoder", -- GitLab From e7718810d0b3fa284729d3951a6489a8adc11eca Mon Sep 17 00:00:00 2001 From: Vignesh Venkatasubramanian Date: Thu, 4 Feb 2021 12:39:06 -0800 Subject: [PATCH 023/694] gav1: Support monochrome videos/images Support monochrome videos by filling U&V planes with neutral values. Since all our output is in 8bit, the neutral value would be 128. Bug: 141654151 Test: AV1 related CTS tests continue to pass Change-Id: I87eb5e11ab8bd88d4d3baf8d59c3bc53398b288d --- .../codec2/components/gav1/C2SoftGav1Dec.cpp | 62 ++++++++++++++----- 1 file changed, 48 insertions(+), 14 deletions(-) diff --git a/media/codec2/components/gav1/C2SoftGav1Dec.cpp b/media/codec2/components/gav1/C2SoftGav1Dec.cpp index 76345ae77e..eb222729b5 100644 --- a/media/codec2/components/gav1/C2SoftGav1Dec.cpp +++ b/media/codec2/components/gav1/C2SoftGav1Dec.cpp @@ -26,6 +26,11 @@ #include namespace android { +namespace { + +constexpr uint8_t NEUTRAL_UV_VALUE = 128; + +} // namespace // codecname set and passed in as a compile flag from Android.bp constexpr char COMPONENT_NAME[] = CODECNAME; @@ -462,7 +467,8 @@ static void copyOutputBufferToYV12Frame(uint8_t *dstY, uint8_t *dstU, uint8_t *d const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV, size_t srcYStride, size_t srcUStride, size_t srcVStride, size_t dstYStride, size_t dstUVStride, - uint32_t width, uint32_t height) { + uint32_t width, uint32_t height, + bool isMonochrome) { for (size_t i = 0; i < height; ++i) { memcpy(dstY, srcY, width); @@ -470,6 +476,17 @@ static void copyOutputBufferToYV12Frame(uint8_t *dstY, uint8_t *dstU, uint8_t *d dstY += dstYStride; } + if (isMonochrome) { + // Fill with neutral U/V values. + for (size_t i = 0; i < height / 2; ++i) { + memset(dstV, NEUTRAL_UV_VALUE, width / 2); + memset(dstU, NEUTRAL_UV_VALUE, width / 2); + dstV += dstUVStride; + dstU += dstUVStride; + } + return; + } + for (size_t i = 0; i < height / 2; ++i) { memcpy(dstV, srcV, width / 2); srcV += srcVStride; @@ -555,7 +572,7 @@ static void convertYUV420Planar16ToYUV420Planar( const uint16_t *srcY, const uint16_t *srcU, const uint16_t *srcV, size_t srcYStride, size_t srcUStride, size_t srcVStride, size_t dstYStride, size_t dstUVStride, - size_t width, size_t height) { + size_t width, size_t height, bool isMonochrome) { for (size_t y = 0; y < height; ++y) { for (size_t x = 0; x < width; ++x) { @@ -566,6 +583,17 @@ static void convertYUV420Planar16ToYUV420Planar( dstY += dstYStride; } + if (isMonochrome) { + // Fill with neutral U/V values. + for (size_t y = 0; y < (height + 1) / 2; ++y) { + memset(dstV, NEUTRAL_UV_VALUE, (width + 1) / 2); + memset(dstU, NEUTRAL_UV_VALUE, (width + 1) / 2); + dstV += dstUVStride; + dstU += dstUVStride; + } + return; + } + for (size_t y = 0; y < (height + 1) / 2; ++y) { for (size_t x = 0; x < (width + 1) / 2; ++x) { dstU[x] = (uint8_t)(srcU[x] >> 2); @@ -621,8 +649,10 @@ bool C2SoftGav1Dec::outputBuffer(const std::shared_ptr &pool, } } - // TODO(vigneshv): Add support for monochrome videos since AV1 supports it. - CHECK(buffer->image_format == libgav1::kImageFormatYuv420); + CHECK(buffer->image_format == libgav1::kImageFormatYuv420 || + buffer->image_format == libgav1::kImageFormatMonochrome400); + const bool isMonochrome = + buffer->image_format == libgav1::kImageFormatMonochrome400; std::shared_ptr block; uint32_t format = HAL_PIXEL_FORMAT_YV12; @@ -634,6 +664,13 @@ bool C2SoftGav1Dec::outputBuffer(const std::shared_ptr &pool, if (defaultColorAspects->primaries == C2Color::PRIMARIES_BT2020 && defaultColorAspects->matrix == C2Color::MATRIX_BT2020 && defaultColorAspects->transfer == C2Color::TRANSFER_ST2084) { + if (buffer->image_format != libgav1::kImageFormatYuv420) { + ALOGE("Only YUV420 output is supported when targeting RGBA_1010102"); + mSignalledError = true; + work->result = C2_OMITTED; + work->workletsProcessed = 1u; + return false; + } format = HAL_PIXEL_FORMAT_RGBA_1010102; } } @@ -680,21 +717,18 @@ bool C2SoftGav1Dec::outputBuffer(const std::shared_ptr &pool, (uint32_t *)dstY, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2, srcVStride / 2, dstYStride / sizeof(uint32_t), mWidth, mHeight); } else { - convertYUV420Planar16ToYUV420Planar(dstY, dstU, dstV, - srcY, srcU, srcV, - srcYStride / 2, srcUStride / 2, srcVStride / 2, - dstYStride, dstUVStride, - mWidth, mHeight); + convertYUV420Planar16ToYUV420Planar( + dstY, dstU, dstV, srcY, srcU, srcV, srcYStride / 2, srcUStride / 2, + srcVStride / 2, dstYStride, dstUVStride, mWidth, mHeight, + isMonochrome); } } else { const uint8_t *srcY = (const uint8_t *)buffer->plane[0]; const uint8_t *srcU = (const uint8_t *)buffer->plane[1]; const uint8_t *srcV = (const uint8_t *)buffer->plane[2]; - copyOutputBufferToYV12Frame(dstY, dstU, dstV, - srcY, srcU, srcV, - srcYStride, srcUStride, srcVStride, - dstYStride, dstUVStride, - mWidth, mHeight); + copyOutputBufferToYV12Frame( + dstY, dstU, dstV, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride, + dstYStride, dstUVStride, mWidth, mHeight, isMonochrome); } finishWork(buffer->user_private_data, work, std::move(block)); block = nullptr; -- GitLab From 67f3ee254971b299567c39b138ba6a99cb456a73 Mon Sep 17 00:00:00 2001 From: Gopalakrishnan Nallasamy Date: Wed, 13 Jan 2021 10:12:24 -0800 Subject: [PATCH 024/694] AppendData:MPEG4Writer&Extractor,MediaAppender Bug: 154734325 Append media data to an MPEG4File. Changes were made in MPEG4Extractor to pass sample offsets of existing data in file to the writer. MediaAppender class takes cares of parsing and preparing exisiting MPEG4 file to be added with new data. Data that is present in the file is not copied again, hence that pass happens fast. New data is appended at the end of the file. Test: atest android.mediav2.cts.MuxerTest Test: atest android.media.cts.MediaMuxerTest Test: atest android.media.cts.MediaRecorderTest Test: atest android.media.cts.MediaExtractorTest Change-Id: I72ef683ec0e5046ef0fcaa996bfba00fe3f596ba --- media/extractors/mp4/MPEG4Extractor.cpp | 23 +- media/libstagefright/Android.bp | 1 + media/libstagefright/MPEG4Writer.cpp | 72 ++- media/libstagefright/MediaAppender.cpp | 425 ++++++++++++++++++ media/libstagefright/MediaMuxer.cpp | 36 ++ media/libstagefright/MediaTrack.cpp | 8 + media/libstagefright/NuMediaExtractor.cpp | 5 + media/libstagefright/Utils.cpp | 21 +- .../include/media/stagefright/MPEG4Writer.h | 1 + .../include/media/stagefright/MediaAppender.h | 100 +++++ .../include/media/stagefright/MediaMuxer.h | 34 +- .../media/stagefright/MediaMuxerBase.h | 133 ++++++ .../include/media/stagefright/MetaDataBase.h | 5 + .../media/stagefright/NuMediaExtractor.h | 2 + media/ndk/NdkMediaExtractor.cpp | 17 + media/ndk/NdkMediaFormat.cpp | 3 + media/ndk/NdkMediaMuxer.cpp | 61 ++- media/ndk/include/media/NdkMediaFormat.h | 3 + media/ndk/include/media/NdkMediaMuxer.h | 46 ++ media/ndk/libmediandk.map.txt | 6 + 20 files changed, 955 insertions(+), 47 deletions(-) create mode 100644 media/libstagefright/MediaAppender.cpp create mode 100644 media/libstagefright/include/media/stagefright/MediaAppender.h create mode 100644 media/libstagefright/include/media/stagefright/MediaMuxerBase.h diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 314a822632..8d001e876a 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6258,7 +6258,18 @@ media_status_t MPEG4Source::read( if (isSyncSample) { AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } - + + AMediaFormat_setInt64( + meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, + offset); + + if (mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + AMediaFormat_setInt64( + meta, + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + mSampleTable->getLastSampleIndexInChunk()); + } + ++mCurrentSampleIndex; } } @@ -6408,6 +6419,16 @@ media_status_t MPEG4Source::read( AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } + AMediaFormat_setInt64( + meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, offset); + + if (mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + AMediaFormat_setInt64( + meta, + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + mSampleTable->getLastSampleIndexInChunk()); + } + ++mCurrentSampleIndex; *out = mBuffer; diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index 930bc0fd9f..1e7ea4a774 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -274,6 +274,7 @@ cc_library { "MPEG2TSWriter.cpp", "MPEG4Writer.cpp", "MediaAdapter.cpp", + "MediaAppender.cpp", "MediaClock.cpp", "MediaCodec.cpp", "MediaCodecList.cpp", diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp index 76a5cabde7..aef6d25689 100644 --- a/media/libstagefright/MPEG4Writer.cpp +++ b/media/libstagefright/MPEG4Writer.cpp @@ -519,12 +519,12 @@ void MPEG4Writer::initInternal(int fd, bool isFirstSession) { mSendNotify = false; mWriteSeekErr = false; mFallocateErr = false; - // Reset following variables for all the sessions and they will be // initialized in start(MetaData *param). mIsRealTimeRecording = true; mUse4ByteNalLength = true; mOffset = 0; + mMaxOffsetAppend = 0; mPreAllocateFileEndOffset = 0; mMdatOffset = 0; mMdatEndOffset = 0; @@ -992,6 +992,9 @@ status_t MPEG4Writer::start(MetaData *param) { seekOrPostError(mFd, mFreeBoxOffset, SEEK_SET); writeInt32(mInMemoryCacheSize); write("free", 4); + for (int i = 0; i < mInMemoryCacheSize - 8; ++i) { + writeOrPostError(mFd, "\x00", 1); + } mMdatOffset = mFreeBoxOffset + mInMemoryCacheSize; } else { mMdatOffset = mOffset; @@ -1541,6 +1544,26 @@ off64_t MPEG4Writer::addSample_l( MediaBuffer *buffer, bool usePrefix, uint32_t tiffHdrOffset, size_t *bytesWritten) { off64_t old_offset = mOffset; + int64_t offset; + ALOGV("buffer->range_length:%lld", (long long)buffer->range_length()); + if (buffer->meta_data().findInt64(kKeySampleFileOffset, &offset)) { + ALOGV("offset:%lld, old_offset:%lld", (long long)offset, (long long)old_offset); + if (old_offset == offset) { + mOffset += buffer->range_length(); + } else { + ALOGV("offset and old_offset are not equal! diff:%lld", (long long)offset - old_offset); + mOffset = offset + buffer->range_length(); + // mOffset += buffer->range_length() + offset - old_offset; + } + *bytesWritten = buffer->range_length(); + ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld, bytesWritten:%lld", (long long)mOffset, + (long long)mMaxOffsetAppend, (long long)*bytesWritten); + mMaxOffsetAppend = std::max(mOffset, mMaxOffsetAppend); + seekOrPostError(mFd, mMaxOffsetAppend, SEEK_SET); + return offset; + } + + ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, (long long)mMaxOffsetAppend); if (usePrefix) { addMultipleLengthPrefixedSamples_l(buffer); @@ -1557,6 +1580,10 @@ off64_t MPEG4Writer::addSample_l( mOffset += buffer->range_length(); } *bytesWritten = mOffset - old_offset; + + ALOGV("mOffset:%lld, old_offset:%lld, bytesWritten:%lld", (long long)mOffset, + (long long)old_offset, (long long)*bytesWritten); + return old_offset; } @@ -1569,6 +1596,7 @@ static void StripStartcode(MediaBuffer *buffer) { (const uint8_t *)buffer->data() + buffer->range_offset(); if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) { + ALOGV("stripping start code"); buffer->set_range( buffer->range_offset() + 4, buffer->range_length() - 4); } @@ -1599,8 +1627,10 @@ void MPEG4Writer::addMultipleLengthPrefixedSamples_l(MediaBuffer *buffer) { } void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { + ALOGV("alp:buffer->range_length:%lld", (long long)buffer->range_length()); size_t length = buffer->range_length(); if (mUse4ByteNalLength) { + ALOGV("mUse4ByteNalLength"); uint8_t x[4]; x[0] = length >> 24; x[1] = (length >> 16) & 0xff; @@ -1610,6 +1640,7 @@ void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { writeOrPostError(mFd, (const uint8_t*)buffer->data() + buffer->range_offset(), length); mOffset += length + 4; } else { + ALOGV("mUse2ByteNalLength"); CHECK_LT(length, 65536u); uint8_t x[2]; @@ -2762,6 +2793,9 @@ void MPEG4Writer::threadFunc() { } writeAllChunks(); + ALOGV("threadFunc mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, + (long long)mMaxOffsetAppend); + mOffset = std::max(mOffset, mMaxOffsetAppend); } status_t MPEG4Writer::startWriterThread() { @@ -3323,6 +3357,7 @@ status_t MPEG4Writer::Track::threadEntry() { uint32_t lastSamplesPerChunk = 0; int64_t lastSampleDurationUs = -1; // Duration calculated from EOS buffer and its timestamp int64_t lastSampleDurationTicks = -1; // Timescale based ticks + int64_t sampleFileOffset = -1; if (mIsAudio) { prctl(PR_SET_NAME, (unsigned long)"MP4WtrAudTrkThread", 0, 0, 0); @@ -3342,6 +3377,7 @@ status_t MPEG4Writer::Track::threadEntry() { MediaBufferBase *buffer; const char *trackName = getTrackType(); while (!mDone && (err = mSource->read(&buffer)) == OK) { + ALOGV("read:buffer->range_length:%lld", (long long)buffer->range_length()); int32_t isEOS = false; if (buffer->range_length() == 0) { if (buffer->meta_data().findInt32(kKeyIsEndOfStream, &isEOS) && isEOS) { @@ -3448,6 +3484,14 @@ status_t MPEG4Writer::Track::threadEntry() { continue; } } + if (!buffer->meta_data().findInt64(kKeySampleFileOffset, &sampleFileOffset)) { + sampleFileOffset = -1; + } + int64_t lastSample = -1; + if (!buffer->meta_data().findInt64(kKeyLastSampleIndexInChunk, &lastSample)) { + lastSample = -1; + } + ALOGV("sampleFileOffset:%lld", (long long)sampleFileOffset); /* * Reserve space in the file for the current sample + to be written MOOV box. If reservation @@ -3455,7 +3499,7 @@ status_t MPEG4Writer::Track::threadEntry() { * write MOOV box successfully as space for the same was reserved in the prior call. * Release the current buffer/sample here. */ - if (!mOwner->preAllocate(buffer->range_length())) { + if (sampleFileOffset == -1 && !mOwner->preAllocate(buffer->range_length())) { buffer->release(); buffer = nullptr; break; @@ -3466,9 +3510,14 @@ status_t MPEG4Writer::Track::threadEntry() { // Make a deep copy of the MediaBuffer and Metadata and release // the original as soon as we can MediaBuffer *copy = new MediaBuffer(buffer->range_length()); - memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(), - buffer->range_length()); + if (sampleFileOffset != -1) { + copy->meta_data().setInt64(kKeySampleFileOffset, sampleFileOffset); + } else { + memcpy(copy->data(), (uint8_t*)buffer->data() + buffer->range_offset(), + buffer->range_length()); + } copy->set_range(0, buffer->range_length()); + meta_data = new MetaData(buffer->meta_data()); buffer->release(); buffer = NULL; @@ -3476,14 +3525,16 @@ status_t MPEG4Writer::Track::threadEntry() { copy->meta_data().setInt32(kKeyExifTiffOffset, tiffHdrOffset); } bool usePrefix = this->usePrefix() && !isExif; - - if (usePrefix) StripStartcode(copy); - + if (sampleFileOffset == -1 && usePrefix) { + StripStartcode(copy); + } size_t sampleSize = copy->range_length(); - if (usePrefix) { + if (sampleFileOffset == -1 && usePrefix) { if (mOwner->useNalLengthFour()) { + ALOGV("nallength4"); sampleSize += 4; } else { + ALOGV("nallength2"); sampleSize += 2; } } @@ -3778,7 +3829,8 @@ status_t MPEG4Writer::Track::threadEntry() { chunkTimestampUs = timestampUs; } else { int64_t chunkDurationUs = timestampUs - chunkTimestampUs; - if (chunkDurationUs > interleaveDurationUs) { + if (chunkDurationUs > interleaveDurationUs || lastSample > 1) { + ALOGV("lastSample:%lld", (long long)lastSample); if (chunkDurationUs > mMaxChunkDurationUs) { mMaxChunkDurationUs = chunkDurationUs; } @@ -5331,4 +5383,4 @@ void MPEG4Writer::writeGeoDataBox() { endBox(); } -} // namespace android +} // namespace android \ No newline at end of file diff --git a/media/libstagefright/MediaAppender.cpp b/media/libstagefright/MediaAppender.cpp new file mode 100644 index 0000000000..5d80b304bc --- /dev/null +++ b/media/libstagefright/MediaAppender.cpp @@ -0,0 +1,425 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//#define LOG_NDEBUG 0 +#define LOG_TAG "MediaAppender" + +#include +#include +#include +#include +// TODO : check if this works for NDK apps without JVM +// #include + +namespace android { + +struct MediaAppender::sampleDataInfo { + size_t size; + int64_t time; + size_t exTrackIndex; + sp meta; +}; + +sp MediaAppender::create(int fd, AppendMode mode) { + if (fd < 0) { + ALOGE("invalid file descriptor"); + return nullptr; + } + if (!(mode >= APPEND_MODE_FIRST && mode <= APPEND_MODE_LAST)) { + ALOGE("invalid mode %d", mode); + return nullptr; + } + sp ma = new (std::nothrow) MediaAppender(fd, mode); + if (ma->init() != OK) { + return nullptr; + } + return ma; +} + +// TODO: inject mediamuxer and mediaextractor objects. +// TODO: @format is not required as an input if we can sniff the file and find the format of +// the existing content. +// TODO: Code it to the interface(MediaAppender), and have a separate MediaAppender NDK +MediaAppender::MediaAppender(int fd, AppendMode mode) + : mFd(fd), + mMode(mode), + // TODO : check if this works for NDK apps without JVM + // mExtractor(new NuMediaExtractor(NdkJavaVMHelper::getJNIEnv() != nullptr + // ? NuMediaExtractor::EntryPoint::NDK_WITH_JVM + // : NuMediaExtractor::EntryPoint::NDK_NO_JVM)), + mExtractor(new (std::nothrow) NuMediaExtractor(NuMediaExtractor::EntryPoint::NDK_WITH_JVM)), + mTrackCount(0), + mState(UNINITIALIZED) { + ALOGV("MediaAppender::MediaAppender mode:%d", mode); + } + +status_t MediaAppender::init() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::init"); + status_t status = mExtractor->setDataSource(mFd, 0, lseek(mFd, 0, SEEK_END)); + if (status != OK) { + ALOGE("extractor_setDataSource failed, status :%d", status); + return status; + } + + if (strcmp("MPEG4Extractor", mExtractor->getName()) == 0) { + mFormat = MediaMuxer::OUTPUT_FORMAT_MPEG_4; + } else { + ALOGE("Unsupported format, extractor name:%s", mExtractor->getName()); + return ERROR_UNSUPPORTED; + } + + mTrackCount = mExtractor->countTracks(); + ALOGV("mTrackCount:%zu", mTrackCount); + if (mTrackCount == 0) { + ALOGE("no tracks are present"); + return ERROR_MALFORMED; + } + size_t exTrackIndex = 0; + ssize_t audioTrackIndex = -1, videoTrackIndex = -1; + bool audioSyncSampleTimeSet = false; + + while (exTrackIndex < mTrackCount) { + sp fmt; + status = mExtractor->getTrackFormat(exTrackIndex, &fmt, 0); + if (status != OK) { + ALOGE("getTrackFormat failed for trackIndex:%zu, status:%d", exTrackIndex, status); + return status; + } + AString mime; + if (fmt->findString("mime", &mime)) { + if (!strncasecmp(mime.c_str(), "video/", 6)) { + ALOGV("VideoTrack"); + if (videoTrackIndex != -1) { + ALOGE("Not more than one video track is supported"); + return ERROR_UNSUPPORTED; + } + videoTrackIndex = exTrackIndex; + } else if (!strncasecmp(mime.c_str(), "audio/", 6)) { + ALOGV("AudioTrack"); + if (audioTrackIndex != -1) { + ALOGE("Not more than one audio track is supported"); + } + audioTrackIndex = exTrackIndex; + } else { + ALOGV("Neither Video nor Audio track"); + } + } + mFmtIndexMap.emplace(exTrackIndex, fmt); + mSampleCountVect.emplace_back(0); + mMaxTimestampVect.emplace_back(0); + mLastSyncSampleTimeVect.emplace_back(0); + status = mExtractor->selectTrack(exTrackIndex); + if (status != OK) { + ALOGE("selectTrack failed for trackIndex:%zu, status:%d", exTrackIndex, status); + return status; + } + ++exTrackIndex; + } + + ALOGV("AudioTrackIndex:%zu, VideoTrackIndex:%zu", audioTrackIndex, videoTrackIndex); + + do { + sampleDataInfo tmpSDI; + // TODO: read info into members of the struct sampleDataInfo directly + size_t sampleSize; + status = mExtractor->getSampleSize(&sampleSize); + if (status != OK) { + ALOGE("getSampleSize failed, status:%d", status); + return status; + } + mSampleSizeVect.emplace_back(sampleSize); + tmpSDI.size = sampleSize; + int64_t sampleTime = 0; + status = mExtractor->getSampleTime(&sampleTime); + if (status != OK) { + ALOGE("getSampleTime failed, status:%d", status); + return status; + } + mSampleTimeVect.emplace_back(sampleTime); + tmpSDI.time = sampleTime; + status = mExtractor->getSampleTrackIndex(&exTrackIndex); + if (status != OK) { + ALOGE("getSampleTrackIndex failed, status:%d", status); + return status; + } + mSampleIndexVect.emplace_back(exTrackIndex); + tmpSDI.exTrackIndex = exTrackIndex; + ++mSampleCountVect[exTrackIndex]; + mMaxTimestampVect[exTrackIndex] = std::max(mMaxTimestampVect[exTrackIndex], sampleTime); + sp sampleMeta; + status = mExtractor->getSampleMeta(&sampleMeta); + if (status != OK) { + ALOGE("getSampleMeta failed, status:%d", status); + return status; + } + mSampleMetaVect.emplace_back(sampleMeta); + int32_t val = 0; + if (sampleMeta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + mLastSyncSampleTimeVect[exTrackIndex] = sampleTime; + } + tmpSDI.meta = sampleMeta; + mSDI.emplace_back(tmpSDI); + } while (mExtractor->advance() == OK); + + mExtractor.clear(); + + std::sort(mSDI.begin(), mSDI.end(), [](sampleDataInfo& a, sampleDataInfo& b) { + int64_t aOffset, bOffset; + a.meta->findInt64(kKeySampleFileOffset, &aOffset); + b.meta->findInt64(kKeySampleFileOffset, &bOffset); + return aOffset < bOffset; + }); + for (int64_t syncSampleTime : mLastSyncSampleTimeVect) { + ALOGV("before ignoring frames, mLastSyncSampleTimeVect:%lld", (long long)syncSampleTime); + } + ALOGV("mMode:%u", mMode); + if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex != -1 ) { + ALOGV("Video track is present"); + bool lastVideoIframe = false; + size_t lastVideoIframeOffset = 0; + int64_t lastVideoSampleTime = -1; + for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { + if (rItr->exTrackIndex != videoTrackIndex) { + continue; + } + if (lastVideoSampleTime == -1) { + lastVideoSampleTime = rItr->time; + } + int64_t offset = 0; + if (!rItr->meta->findInt64(kKeySampleFileOffset, &offset) || offset == 0) { + ALOGE("Missing offset"); + return ERROR_MALFORMED; + } + ALOGV("offset:%lld", (long long)offset); + int32_t val = 0; + if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + ALOGV("sampleTime:%lld", (long long)rItr->time); + ALOGV("lastVideoSampleTime:%lld", (long long)lastVideoSampleTime); + if (lastVideoIframe == false && (lastVideoSampleTime - rItr->time) > + 1000000/* Track interleaving duration in MPEG4Writer*/) { + ALOGV("lastVideoIframe got chosen"); + lastVideoIframe = true; + mLastSyncSampleTimeVect[videoTrackIndex] = rItr->time; + lastVideoIframeOffset = offset; + ALOGV("lastVideoIframeOffset:%lld", (long long)offset); + break; + } + } + } + if (lastVideoIframe == false) { + ALOGV("Need to rewrite all samples"); + mLastSyncSampleTimeVect[videoTrackIndex] = 0; + lastVideoIframeOffset = 0; + } + unsigned int framesIgnoredCount = 0; + for (auto itr = mSDI.begin(); itr != mSDI.end();) { + int64_t offset = 0; + ALOGV("trackIndex:%zu, %" PRId64 "", itr->exTrackIndex, itr->time); + if (itr->meta->findInt64(kKeySampleFileOffset, &offset) && + offset >= lastVideoIframeOffset) { + ALOGV("offset:%lld", (long long)offset); + if (!audioSyncSampleTimeSet && audioTrackIndex != -1 && + audioTrackIndex == itr->exTrackIndex) { + mLastSyncSampleTimeVect[audioTrackIndex] = itr->time; + audioSyncSampleTimeSet = true; + } + itr = mSDI.erase(itr); + ++framesIgnoredCount; + } else { + ++itr; + } + } + ALOGV("framesIgnoredCount:%u", framesIgnoredCount); + } + + if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex == -1 && + audioTrackIndex != -1) { + ALOGV("Only AudioTrack is present"); + for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { + int32_t val = 0; + if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + mLastSyncSampleTimeVect[audioTrackIndex] = rItr->time; + break; + } + } + unsigned int framesIgnoredCount = 0; + for (auto itr = mSDI.begin(); itr != mSDI.end();) { + if (itr->time >= mLastSyncSampleTimeVect[audioTrackIndex]) { + itr = mSDI.erase(itr); + ++framesIgnoredCount; + } else { + ++itr; + } + } + ALOGV("framesIgnoredCount :%u", framesIgnoredCount); + } + + for (size_t i = 0; i < mLastSyncSampleTimeVect.size(); ++i) { + ALOGV("mLastSyncSampleTimeVect[%zu]:%lld", i, (long long)mLastSyncSampleTimeVect[i]); + mFmtIndexMap[i]->setInt64( + "sample-time-before-append" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, + mLastSyncSampleTimeVect[i]); + } + for (size_t i = 0; i < mMaxTimestampVect.size(); ++i) { + ALOGV("mMaxTimestamp[%zu]:%lld", i, (long long)mMaxTimestampVect[i]); + } + for (size_t i = 0; i < mSampleCountVect.size(); ++i) { + ALOGV("SampleCountVect[%zu]:%zu", i, mSampleCountVect[i]); + } + mState = INITIALIZED; + return OK; +} + +MediaAppender::~MediaAppender() { + ALOGV("MediaAppender::~MediaAppender"); + mMuxer.clear(); + mExtractor.clear(); +} + +status_t MediaAppender::start() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::start"); + if (mState != INITIALIZED) { + ALOGE("MediaAppender::start() is called in invalid state %d", mState); + return INVALID_OPERATION; + } + mMuxer = new (std::nothrow) MediaMuxer(mFd, mFormat); + for (const auto& n : mFmtIndexMap) { + ssize_t muxIndex = mMuxer->addTrack(n.second); + if (muxIndex < 0) { + ALOGE("addTrack failed"); + return UNKNOWN_ERROR; + } + mTrackIndexMap.emplace(n.first, muxIndex); + } + ALOGV("trackIndexmap size:%zu", mTrackIndexMap.size()); + + status_t status = mMuxer->start(); + if (status != OK) { + ALOGE("muxer start failed:%d", status); + return status; + } + + ALOGV("Sorting samples based on their offsets"); + for (int i = 0; i < mSDI.size(); ++i) { + ALOGV("i:%d", i + 1); + /* TODO : Allocate a single allocation of the max size, and reuse it across ABuffers if + * using new ABuffer(void *, size_t). + */ + sp data = new (std::nothrow) ABuffer(mSDI[i].size); + if (data == nullptr) { + ALOGE("memory allocation failed"); + return NO_MEMORY; + } + data->setRange(0, mSDI[i].size); + int32_t val = 0; + int sampleFlags = 0; + if (mSDI[i].meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + sampleFlags |= MediaCodec::BUFFER_FLAG_SYNCFRAME; + } + + int64_t val64; + if (mSDI[i].meta->findInt64(kKeySampleFileOffset, &val64)) { + ALOGV("SampleFileOffset Found :%zu:%lld:%lld", mSDI[i].exTrackIndex, + (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); + sp bufMeta = data->meta(); + bufMeta->setInt64("sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, + val64); + } + if (mSDI[i].meta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { + ALOGV("kKeyLastSampleIndexInChunk Found %lld:%lld", + (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); + sp bufMeta = data->meta(); + bufMeta->setInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + val64); + } + status = mMuxer->writeSampleData(data, mTrackIndexMap[mSDI[i].exTrackIndex], mSDI[i].time, + sampleFlags); + if (status != OK) { + ALOGE("muxer writeSampleData failed:%d", status); + return status; + } + } + mState = STARTED; + return OK; +} + +status_t MediaAppender::stop() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::stop"); + if (mState == STARTED) { + status_t status = mMuxer->stop(); + if (status != OK) { + mState = ERROR; + } else { + mState = STOPPED; + } + return status; + } else { + ALOGE("stop() is called in invalid state %d", mState); + return INVALID_OPERATION; + } +} + +ssize_t MediaAppender::getTrackCount() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::getTrackCount"); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackCount() is called in invalid state %d", mState); + return -1; + } + return mTrackCount; +} + +sp MediaAppender::getTrackFormat(size_t idx) { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::getTrackFormat"); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackFormat() is called in invalid state %d", mState); + return nullptr; + } + if (idx < 0 || idx >= mTrackCount) { + ALOGE("getTrackFormat() idx is out of range"); + return nullptr; + } + return mFmtIndexMap[idx]; +} + +status_t MediaAppender::writeSampleData(const sp& buffer, size_t trackIndex, + int64_t timeUs, uint32_t flags) { + std::scoped_lock lock(mMutex); + ALOGV("writeSampleData:trackIndex:%zu, time:%" PRId64 "", trackIndex, timeUs); + return mMuxer->writeSampleData(buffer, trackIndex, timeUs, flags); +} + +status_t MediaAppender::setOrientationHint([[maybe_unused]] int degrees) { + ALOGE("setOrientationHint not supported. Has to be called prior to start on initial muxer"); + return ERROR_UNSUPPORTED; +}; + +status_t MediaAppender::setLocation([[maybe_unused]] int latit, [[maybe_unused]] int longit) { + ALOGE("setLocation not supported. Has to be called prior to start on initial muxer"); + return ERROR_UNSUPPORTED; +} + +ssize_t MediaAppender::addTrack([[maybe_unused]] const sp &format) { + ALOGE("addTrack not supported"); + return ERROR_UNSUPPORTED; +} + +} // namespace android diff --git a/media/libstagefright/MediaMuxer.cpp b/media/libstagefright/MediaMuxer.cpp index c91386d489..a946f71e9b 100644 --- a/media/libstagefright/MediaMuxer.cpp +++ b/media/libstagefright/MediaMuxer.cpp @@ -76,6 +76,7 @@ MediaMuxer::~MediaMuxer() { mFileMeta.clear(); mWriter.clear(); mTrackList.clear(); + mFormatList.clear(); } ssize_t MediaMuxer::addTrack(const sp &format) { @@ -109,6 +110,8 @@ ssize_t MediaMuxer::addTrack(const sp &format) { ALOGW("addTrack() setCaptureRate failed :%d", result); } } + + mFormatList.add(format); return mTrackList.add(newTrack); } @@ -224,9 +227,42 @@ status_t MediaMuxer::writeSampleData(const sp &buffer, size_t trackInde ALOGV("BUFFER_FLAG_EOS"); } + sp bufMeta = buffer->meta(); + int64_t val64; + if (bufMeta->findInt64("sample-file-offset", &val64)) { + sampleMetaData.setInt64(kKeySampleFileOffset, val64); + } + if (bufMeta->findInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + &val64)) { + sampleMetaData.setInt64(kKeyLastSampleIndexInChunk, val64); + } + sp currentTrack = mTrackList[trackIndex]; // This pushBuffer will wait until the mediaBuffer is consumed. return currentTrack->pushBuffer(mediaBuffer); } +ssize_t MediaMuxer::getTrackCount() { + Mutex::Autolock autoLock(mMuxerLock); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackCount() must be called either in INITIALIZED or STARTED state"); + return -1; + } + return mTrackList.size(); +} + +sp MediaMuxer::getTrackFormat([[maybe_unused]] size_t idx) { + Mutex::Autolock autoLock(mMuxerLock); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackFormat() must be called either in INITIALIZED or STARTED state"); + return nullptr; + } + if (idx < 0 || idx >= mFormatList.size()) { + ALOGE("getTrackFormat() idx is out of range"); + return nullptr; + } + return mFormatList[idx]; +} + } // namespace android diff --git a/media/libstagefright/MediaTrack.cpp b/media/libstagefright/MediaTrack.cpp index 24ba38af87..2447f5e904 100644 --- a/media/libstagefright/MediaTrack.cpp +++ b/media/libstagefright/MediaTrack.cpp @@ -133,6 +133,14 @@ status_t MediaTrackCUnwrapper::read(MediaBufferBase **buffer, const ReadOptions if (format->mFormat->findInt64("target-time", &val64)) { meta.setInt64(kKeyTargetTime, val64); } + if (format->mFormat->findInt64("sample-file-offset", &val64)) { + meta.setInt64(kKeySampleFileOffset, val64); + } + if (format->mFormat->findInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + &val64)) { + meta.setInt64(kKeyLastSampleIndexInChunk, val64); + } int32_t val32; if (format->mFormat->findInt32("is-sync-frame", &val32)) { meta.setInt32(kKeyIsSyncFrame, val32); diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp index 3ee78d04f5..f54a56f5c2 100644 --- a/media/libstagefright/NuMediaExtractor.cpp +++ b/media/libstagefright/NuMediaExtractor.cpp @@ -189,6 +189,11 @@ status_t NuMediaExtractor::setDataSource(const sp &source) { return err; } +const char* NuMediaExtractor::getName() const { + Mutex::Autolock autoLock(mLock); + return mImpl == nullptr ? nullptr : mImpl->name().string(); +} + static String8 arrayToString(const std::vector &array) { String8 result; for (size_t i = 0; i < array.size(); i++) { diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp index 51d9730bba..6091cb8f7d 100644 --- a/media/libstagefright/Utils.cpp +++ b/media/libstagefright/Utils.cpp @@ -725,16 +725,19 @@ static std::vector> floatMappings { } }; -static std::vector> int64Mappings { +static std::vector> int64Mappings { { - { "exif-offset", kKeyExifOffset }, - { "exif-size", kKeyExifSize }, - { "xmp-offset", kKeyXmpOffset }, - { "xmp-size", kKeyXmpSize }, - { "target-time", kKeyTargetTime }, - { "thumbnail-time", kKeyThumbnailTime }, - { "timeUs", kKeyTime }, - { "durationUs", kKeyDuration }, + { "exif-offset", kKeyExifOffset}, + { "exif-size", kKeyExifSize}, + { "xmp-offset", kKeyXmpOffset}, + { "xmp-size", kKeyXmpSize}, + { "target-time", kKeyTargetTime}, + { "thumbnail-time", kKeyThumbnailTime}, + { "timeUs", kKeyTime}, + { "durationUs", kKeyDuration}, + { "sample-file-offset", kKeySampleFileOffset}, + { "last-sample-index-in-chunk", kKeyLastSampleIndexInChunk}, + { "sample-time-before-append", kKeySampleTimeBeforeAppend}, } }; diff --git a/media/libstagefright/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/media/stagefright/MPEG4Writer.h index 2582ed0815..7f2728ebd8 100644 --- a/media/libstagefright/include/media/stagefright/MPEG4Writer.h +++ b/media/libstagefright/include/media/stagefright/MPEG4Writer.h @@ -106,6 +106,7 @@ private: off64_t mOffset; off64_t mPreAllocateFileEndOffset; //End of file offset during preallocation. off64_t mMdatOffset; + off64_t mMaxOffsetAppend; // File offset written upto while appending. off64_t mMdatEndOffset; // End offset of mdat atom. uint8_t *mInMemoryCache; off64_t mInMemoryCacheOffset; diff --git a/media/libstagefright/include/media/stagefright/MediaAppender.h b/media/libstagefright/include/media/stagefright/MediaAppender.h new file mode 100644 index 0000000000..c2f6f1045b --- /dev/null +++ b/media/libstagefright/include/media/stagefright/MediaAppender.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_APPENDER_H +#define ANDROID_MEDIA_APPENDER_H + +#include +#include +#include + +namespace android { + +struct MediaAppender : public MediaMuxerBase { +public: + enum AppendMode { + APPEND_MODE_FIRST = 0, + APPEND_MODE_IGNORE_LAST_VIDEO_GOP = APPEND_MODE_FIRST, + APPEND_MODE_ADD_TO_EXISTING_DATA = 1, + APPEND_MODE_LAST = APPEND_MODE_ADD_TO_EXISTING_DATA, + }; + + static sp create(int fd, AppendMode mode); + + virtual ~MediaAppender(); + + status_t init(); + + status_t start(); + + status_t stop(); + + status_t writeSampleData(const sp& buffer, size_t trackIndex, int64_t timeUs, + uint32_t flags); + + status_t setOrientationHint(int degrees); + + status_t setLocation(int latitude, int longitude); + + ssize_t addTrack(const sp &format); + + ssize_t getTrackCount(); + + sp getTrackFormat(size_t idx); + +private: + MediaAppender(int fd, AppendMode mode); + + int mFd; + MediaMuxer::OutputFormat mFormat; + AppendMode mMode; + sp mExtractor; + sp mMuxer; + size_t mTrackCount; + // Map track index given by extractor to the ones received from muxer. + std::map mTrackIndexMap; + // Count of the samples in each track, indexed by extractor track ids. + std::vector mSampleCountVect; + // Extractor track index of samples. + std::vector mSampleIndexVect; + // Track format indexed by extractor track ids. + std::map> mFmtIndexMap; + // Size of samples. + std::vector mSampleSizeVect; + // Presentation time stamp of samples. + std::vector mSampleTimeVect; + // Timestamp of last sample of tracks. + std::vector mMaxTimestampVect; + // Metadata of samples. + std::vector> mSampleMetaVect; + std::mutex mMutex; + // Timestamp of the last sync sample of tracks. + std::vector mLastSyncSampleTimeVect; + + struct sampleDataInfo; + std::vector mSDI; + + enum : int { + UNINITIALIZED, + INITIALIZED, + STARTED, + STOPPED, + ERROR, + } mState GUARDED_BY(mMutex); +}; + +} // namespace android +#endif // ANDROID_MEDIA_APPENDER_H \ No newline at end of file diff --git a/media/libstagefright/include/media/stagefright/MediaMuxer.h b/media/libstagefright/include/media/stagefright/MediaMuxer.h index a1b9465d65..e97a65ee6b 100644 --- a/media/libstagefright/include/media/stagefright/MediaMuxer.h +++ b/media/libstagefright/include/media/stagefright/MediaMuxer.h @@ -22,7 +22,12 @@ #include #include +#include +#include +#include + #include "media/stagefright/foundation/ABase.h" +#include "MediaMuxerBase.h" namespace android { @@ -33,6 +38,7 @@ class MediaBuffer; struct MediaSource; class MetaData; struct MediaWriter; +struct NuMediaExtractor; // MediaMuxer is used to mux multiple tracks into a video. Currently, we only // support a mp4 file as the output. @@ -40,19 +46,8 @@ struct MediaWriter; // Constructor -> addTrack+ -> start -> writeSampleData+ -> stop // If muxing operation need to be cancelled, the app is responsible for // deleting the output file after stop. -struct MediaMuxer : public RefBase { +struct MediaMuxer : public MediaMuxerBase { public: - // Please update media/java/android/media/MediaMuxer.java if the - // OutputFormat is updated. - enum OutputFormat { - OUTPUT_FORMAT_MPEG_4 = 0, - OUTPUT_FORMAT_WEBM = 1, - OUTPUT_FORMAT_THREE_GPP = 2, - OUTPUT_FORMAT_HEIF = 3, - OUTPUT_FORMAT_OGG = 4, - OUTPUT_FORMAT_LIST_END // must be last - used to validate format type - }; - // Construct the muxer with the file descriptor. Note that the MediaMuxer // will close this file at stop(). MediaMuxer(int fd, OutputFormat format); @@ -117,10 +112,25 @@ public: status_t writeSampleData(const sp &buffer, size_t trackIndex, int64_t timeUs, uint32_t flags) ; + /** + * Gets the number of tracks added successfully. Should be called in + * INITIALIZED(after constructor) or STARTED(after start()) state. + * @return the number of tracks or -1 in wrong state. + */ + ssize_t getTrackCount(); + + /** + * Gets the format of the track by their index. + * @param idx : index of the track whose format is wanted. + * @return smart pointer to AMessage containing the format details. + */ + sp getTrackFormat(size_t idx); + private: const OutputFormat mFormat; sp mWriter; Vector< sp > mTrackList; // Each track has its MediaAdapter. + Vector< sp > mFormatList; // Format of each track. sp mFileMeta; // Metadata for the whole file. Mutex mMuxerLock; diff --git a/media/libstagefright/include/media/stagefright/MediaMuxerBase.h b/media/libstagefright/include/media/stagefright/MediaMuxerBase.h new file mode 100644 index 0000000000..f02d510835 --- /dev/null +++ b/media/libstagefright/include/media/stagefright/MediaMuxerBase.h @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEDIA_MUXER_BASE_H_ +#define MEDIA_MUXER_BASE_H_ + +#include +#include "media/stagefright/foundation/ABase.h" + +namespace android { + +struct ABuffer; +struct AMessage; + +// MediaMuxer is used to mux multiple tracks into a video. Currently, we only +// support a mp4 file as the output. +// The expected calling order of the functions is: +// Constructor -> addTrack+ -> start -> writeSampleData+ -> stop +// If muxing operation need to be cancelled, the app is responsible for +// deleting the output file after stop. +struct MediaMuxerBase : public RefBase { +public: + // Please update media/java/android/media/MediaMuxer.java if the + // OutputFormat is updated. + enum OutputFormat { + OUTPUT_FORMAT_MPEG_4 = 0, + OUTPUT_FORMAT_WEBM = 1, + OUTPUT_FORMAT_THREE_GPP = 2, + OUTPUT_FORMAT_HEIF = 3, + OUTPUT_FORMAT_OGG = 4, + OUTPUT_FORMAT_LIST_END // must be last - used to validate format type + }; + + // Construct the muxer with the file descriptor. Note that the MediaMuxer + // will close this file at stop(). + MediaMuxerBase() {}; + + virtual ~MediaMuxerBase() {}; + + /** + * Add a track with its format information. This should be + * called before start(). + * @param format the track's format. + * @return the track's index or negative number if error. + */ + virtual ssize_t addTrack(const sp &format) = 0; + + /** + * Start muxing. Make sure all the tracks have been added before + * calling this. + */ + virtual status_t start() = 0; + + /** + * Set the orientation hint. + * @param degrees The rotation degrees. It has to be either 0, + * 90, 180 or 270. + * @return OK if no error. + */ + virtual status_t setOrientationHint(int degrees) = 0; + + /** + * Set the location. + * @param latitude The latitude in degree x 1000. Its value must be in the range + * [-900000, 900000]. + * @param longitude The longitude in degree x 1000. Its value must be in the range + * [-1800000, 1800000]. + * @return OK if no error. + */ + virtual status_t setLocation(int latitude, int longitude) = 0; + + /** + * Stop muxing. + * This method is a blocking call. Depending on how + * much data is bufferred internally, the time needed for stopping + * the muxer may be time consuming. UI thread is + * not recommended for launching this call. + * @return OK if no error. + */ + virtual status_t stop() = 0; + + /** + * Send a sample buffer for muxing. + * The buffer can be reused once this method returns. Typically, + * this function won't be blocked for very long, and thus there + * is no need to use a separate thread calling this method to + * push a buffer. + * @param buffer the incoming sample buffer. + * @param trackIndex the buffer's track index number. + * @param timeUs the buffer's time stamp. + * @param flags the only supported flag for now is + * MediaCodec::BUFFER_FLAG_SYNCFRAME. + * @return OK if no error. + */ + virtual status_t writeSampleData(const sp &buffer, size_t trackIndex, + int64_t timeUs, uint32_t flags) = 0 ; + + /** + * Gets the number of tracks added successfully. Should be called in + * INITIALIZED(after constructor) or STARTED(after start()) state. + * @return the number of tracks or -1 in wrong state. + */ + virtual ssize_t getTrackCount() = 0; + + /** + * Gets the format of the track by their index. + * @param idx : index of the track whose format is wanted. + * @return smart pointer to AMessage containing the format details. + */ + virtual sp getTrackFormat(size_t idx) = 0; + +private: + + DISALLOW_EVIL_CONSTRUCTORS(MediaMuxerBase); +}; + +} // namespace android + +#endif // MEDIA_MUXER_BASE_H_ + diff --git a/media/libstagefright/include/media/stagefright/MetaDataBase.h b/media/libstagefright/include/media/stagefright/MetaDataBase.h index 940bd86848..408872fe26 100644 --- a/media/libstagefright/include/media/stagefright/MetaDataBase.h +++ b/media/libstagefright/include/media/stagefright/MetaDataBase.h @@ -264,6 +264,11 @@ enum { // Slow-motion markers kKeySlowMotionMarkers = 'slmo', // raw data, byte array following spec for // MediaFormat#KEY_SLOW_MOTION_MARKERS + + kKeySampleFileOffset = 'sfof', // int64_t, sample's offset in a media file. + kKeyLastSampleIndexInChunk = 'lsic', //int64_t, index of last sample in a chunk. + kKeySampleTimeBeforeAppend = 'lsba', // int64_t, timestamp of last sample of a track. + }; enum { diff --git a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h index 1cad140b03..6aa7c0fd46 100644 --- a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h @@ -102,6 +102,8 @@ struct NuMediaExtractor : public RefBase { status_t setPlaybackId(const String8& playbackId); + const char* getName() const; + protected: virtual ~NuMediaExtractor(); diff --git a/media/ndk/NdkMediaExtractor.cpp b/media/ndk/NdkMediaExtractor.cpp index 0c65e9e552..07fc5de09c 100644 --- a/media/ndk/NdkMediaExtractor.cpp +++ b/media/ndk/NdkMediaExtractor.cpp @@ -419,6 +419,7 @@ int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *ex) { EXPORT media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat *fmt) { + ALOGV("AMediaExtractor_getSampleFormat"); if (fmt == NULL) { return AMEDIA_ERROR_INVALID_PARAMETER; } @@ -428,6 +429,9 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat if (err != OK) { return translate_error(err); } +#ifdef LOG_NDEBUG + sampleMeta->dumpToLog(); +#endif sp meta; AMediaFormat_getFormat(fmt, &meta); @@ -483,6 +487,19 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat meta->setBuffer(AMEDIAFORMAT_KEY_AUDIO_PRESENTATION_INFO, audioPresentationsData); } + int64_t val64; + if (sampleMeta->findInt64(kKeySampleFileOffset, &val64)) { + meta->setInt64("sample-file-offset", val64); + ALOGV("SampleFileOffset Found"); + } + if (sampleMeta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { + meta->setInt64("last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + val64); + ALOGV("kKeyLastSampleIndexInChunk Found"); + } + + ALOGV("AMediaFormat_toString:%s", AMediaFormat_toString(fmt)); + return AMEDIA_OK; } diff --git a/media/ndk/NdkMediaFormat.cpp b/media/ndk/NdkMediaFormat.cpp index 1773023f37..c1793ce159 100644 --- a/media/ndk/NdkMediaFormat.cpp +++ b/media/ndk/NdkMediaFormat.cpp @@ -334,6 +334,7 @@ EXPORT const char* AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE = "is-forced-subtitle"; EXPORT const char* AMEDIAFORMAT_KEY_IS_SYNC_FRAME = "is-sync-frame"; EXPORT const char* AMEDIAFORMAT_KEY_I_FRAME_INTERVAL = "i-frame-interval"; EXPORT const char* AMEDIAFORMAT_KEY_LANGUAGE = "language"; +EXPORT const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK = "last-sample-index-in-chunk"; EXPORT const char* AMEDIAFORMAT_KEY_LATENCY = "latency"; EXPORT const char* AMEDIAFORMAT_KEY_LEVEL = "level"; EXPORT const char* AMEDIAFORMAT_KEY_LOCATION = "location"; @@ -359,7 +360,9 @@ EXPORT const char* AMEDIAFORMAT_KEY_PSSH = "pssh"; EXPORT const char* AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP = "push-blank-buffers-on-shutdown"; EXPORT const char* AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER = "repeat-previous-frame-after"; EXPORT const char* AMEDIAFORMAT_KEY_ROTATION = "rotation-degrees"; +EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET = "sample-file-offset"; EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_RATE = "sample-rate"; +EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND = "sample-time-before-append"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_HEIGHT = "sar-height"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_WIDTH = "sar-width"; EXPORT const char* AMEDIAFORMAT_KEY_SEI = "sei"; diff --git a/media/ndk/NdkMediaMuxer.cpp b/media/ndk/NdkMediaMuxer.cpp index d1992bf7ed..1965e62502 100644 --- a/media/ndk/NdkMediaMuxer.cpp +++ b/media/ndk/NdkMediaMuxer.cpp @@ -17,28 +17,24 @@ //#define LOG_NDEBUG 0 #define LOG_TAG "NdkMediaMuxer" - -#include +#include +#include +#include #include #include #include - - -#include -#include +#include +#include +#include #include #include -#include -#include -#include - -#include +#include +#include using namespace android; struct AMediaMuxer { - sp mImpl; - + sp mImpl; }; extern "C" { @@ -46,8 +42,15 @@ extern "C" { EXPORT AMediaMuxer* AMediaMuxer_new(int fd, OutputFormat format) { ALOGV("ctor"); - AMediaMuxer *mData = new AMediaMuxer(); - mData->mImpl = new MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); + AMediaMuxer *mData = new (std::nothrow) AMediaMuxer(); + if (mData == nullptr) { + return nullptr; + } + mData->mImpl = new (std::nothrow) MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); + if (mData->mImpl == nullptr) { + delete mData; + return nullptr; + } return mData; } @@ -94,6 +97,34 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, muxer->mImpl->writeSampleData(buf, trackIdx, info->presentationTimeUs, info->flags)); } +EXPORT +AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) { + ALOGV("append"); + AMediaMuxer* mData = new (std::nothrow) AMediaMuxer(); + if (mData == nullptr) { + return nullptr; + } + mData->mImpl = MediaAppender::create(fd, (android::MediaAppender::AppendMode)mode); + if (mData->mImpl == nullptr) { + delete mData; + return nullptr; + } + return mData; +} + +EXPORT +ssize_t AMediaMuxer_getTrackCount(AMediaMuxer* muxer) { + return muxer->mImpl->getTrackCount(); +} + +EXPORT +AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) { + sp format = muxer->mImpl->getTrackFormat(idx); + if (format != nullptr) { + return AMediaFormat_fromMsg(&format); + } + return nullptr; +} } // extern "C" diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h index 476bbd9d05..fbd855d66b 100644 --- a/media/ndk/include/media/NdkMediaFormat.h +++ b/media/ndk/include/media/NdkMediaFormat.h @@ -307,6 +307,9 @@ extern const char* AMEDIAFORMAT_KEY_SLOW_MOTION_MARKERS __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_THUMBNAIL_CSD_AV1C __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_OFFSET __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_SIZE __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MAX __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MIN __INTRODUCED_IN(31); diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h index 519e249503..866ebfd730 100644 --- a/media/ndk/include/media/NdkMediaMuxer.h +++ b/media/ndk/include/media/NdkMediaMuxer.h @@ -54,6 +54,17 @@ typedef enum { AMEDIAMUXER_OUTPUT_FORMAT_THREE_GPP = 2, } OutputFormat; +typedef enum { + /* Last group of pictures(GOP) of video track can be incomplete, so it would be safe to + * scrap that and rewrite. If both audio and video tracks are present in a file, then + * samples of audio track after last GOP of video would be scrapped too. + * If only audio track is present, then no sample would be discarded. + */ + AMEDIAMUXER_APPEND_IGNORE_LAST_VIDEO_GOP = 0, + // Keep all existing samples as it is and append new samples after that only. + AMEDIAMUXER_APPEND_TO_EXISTING_DATA = 1, +} AppendMode; + /** * Create new media muxer. * @@ -138,6 +149,41 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, size_t trackIdx, const uint8_t *data, const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21); +/** + * Creates a new media muxer for appending data to an existing MPEG4 file. + * This is a synchronous API call and could take a while to return if the existing file is large. + * Works for only MPEG4 files that contain a) a single audio track, b) a single video track, + * c) a single audio and a single video track. + * @param(fd): needs to be opened with read and write permission. Does not take ownership of + * this fd i.e., caller is responsible for closing fd. + * @param(mode): AppendMode is an enum that specifies one of the modes of appending data. + * @return : Pointer to AMediaMuxer if the file(fd) has tracks already, otherwise, nullptr. + * {@link AMediaMuxer_delete} should be used to free the returned pointer. + * + * Available since API level 31. + */ +AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) __INTRODUCED_IN(31); + +/** + * Returns the number of tracks added in the file passed to {@link AMediaMuxer_new} or + * the number of existing tracks in the file passed to {@link AMediaMuxer_append}. + * Should be called in INITIALIZED or STARTED state, otherwise returns -1. + * + * Available since API level 31. + */ +ssize_t AMediaMuxer_getTrackCount(AMediaMuxer*) __INTRODUCED_IN(31); + +/** + * Returns AMediaFormat of the added track with index idx in the file passed to + * {@link AMediaMuxer_new} or the AMediaFormat of the existing track with index idx + * in the file passed to {@link AMediaMuxer_append}. + * Should be called in INITIALIZED or STARTED state, otherwise returns nullptr. + * {@link AMediaFormat_delete} should be used to free the returned pointer. + * + * Available since API level 31. + */ +AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) __INTRODUCED_IN(31); + __END_DECLS #endif // _NDK_MEDIA_MUXER_H diff --git a/media/ndk/libmediandk.map.txt b/media/ndk/libmediandk.map.txt index eead681648..7e9e57ef8d 100644 --- a/media/ndk/libmediandk.map.txt +++ b/media/ndk/libmediandk.map.txt @@ -109,6 +109,7 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_IS_SYNC_FRAME; # var introduced=29 AMEDIAFORMAT_KEY_I_FRAME_INTERVAL; # var introduced=21 AMEDIAFORMAT_KEY_LANGUAGE; # var introduced=21 + AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK; # var introduced=31 AMEDIAFORMAT_KEY_LATENCY; # var introduced=28 AMEDIAFORMAT_KEY_LEVEL; # var introduced=28 AMEDIAFORMAT_KEY_LOCATION; # var introduced=29 @@ -134,6 +135,8 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP; # var introduced=21 AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER; # var introduced=21 AMEDIAFORMAT_KEY_ROTATION; # var introduced=28 + AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET; # var introduced=31 + AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND; # var introduced=31 AMEDIAFORMAT_KEY_SAMPLE_RATE; # var introduced=21 AMEDIAFORMAT_KEY_SAR_HEIGHT; # var introduced=29 AMEDIAFORMAT_KEY_SAR_WIDTH; # var introduced=29 @@ -286,7 +289,10 @@ LIBMEDIANDK { AMediaFormat_setString; AMediaFormat_toString; AMediaMuxer_addTrack; + AMediaMuxer_append; # introduced=31 AMediaMuxer_delete; + AMediaMuxer_getTrackCount; # introduced=31 + AMediaMuxer_getTrackFormat; # introduced=31 AMediaMuxer_new; AMediaMuxer_setLocation; AMediaMuxer_setOrientationHint; -- GitLab From e483398b90ff5599c8e8c9cbd9896926fbcce077 Mon Sep 17 00:00:00 2001 From: Gopalakrishnan Nallasamy Date: Thu, 18 Mar 2021 22:10:24 -0700 Subject: [PATCH 025/694] MPEG4Extractor:mSampleTable dereference Bug: 183163047 SampleTable won't be available while decoding images. Hence check whether mSampleTable is not nullptr before dereferencing. Test: atest android.graphics.cts.BitmapRegionDecoderTest#testHeif Change-Id: I304db46d7498964af6bbe8b17447d14ec23efe10 --- media/extractors/mp4/MPEG4Extractor.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 8d001e876a..159b3d2e2b 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6263,7 +6263,8 @@ media_status_t MPEG4Source::read( meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, offset); - if (mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + if (mSampleTable != nullptr && + mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { AMediaFormat_setInt64( meta, "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, @@ -6422,7 +6423,8 @@ media_status_t MPEG4Source::read( AMediaFormat_setInt64( meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, offset); - if (mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + if (mSampleTable != nullptr && + mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { AMediaFormat_setInt64( meta, "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, -- GitLab From 9ead0397408c140f6ed2d91b4444bdaa010fcc00 Mon Sep 17 00:00:00 2001 From: Gopalakrishnan Nallasamy Date: Wed, 24 Mar 2021 12:37:07 +0000 Subject: [PATCH 026/694] Revert "AppendData:MPEG4Writer&Extractor,MediaAppender" Revert "Updating references for libmediandk" Revert submission 13020888-PauseResume changes in Muxer and Extractor for Transcoding Reason for revert: Broken test: com.android.server.wm.flicker.monitor.ScreenRecorderTest#videoCanBeSaved Reverted Changes: I109cec9b3:Updating references for libmediandk I72ef683ec:AppendData:MPEG4Writer&Extractor,MediaAppender Change-Id: I99a3a8aec1c9c6f524a58a99563c882dd73b2ce2 --- media/extractors/mp4/MPEG4Extractor.cpp | 24 - media/libstagefright/Android.bp | 1 - media/libstagefright/MPEG4Writer.cpp | 72 +-- media/libstagefright/MediaAppender.cpp | 425 ------------------ media/libstagefright/MediaMuxer.cpp | 36 -- media/libstagefright/MediaTrack.cpp | 8 - media/libstagefright/NuMediaExtractor.cpp | 5 - media/libstagefright/Utils.cpp | 21 +- .../include/media/stagefright/MPEG4Writer.h | 1 - .../include/media/stagefright/MediaAppender.h | 100 ----- .../include/media/stagefright/MediaMuxer.h | 34 +- .../media/stagefright/MediaMuxerBase.h | 133 ------ .../include/media/stagefright/MetaDataBase.h | 5 - .../media/stagefright/NuMediaExtractor.h | 2 - media/ndk/NdkMediaExtractor.cpp | 17 - media/ndk/NdkMediaFormat.cpp | 3 - media/ndk/NdkMediaMuxer.cpp | 61 +-- media/ndk/include/media/NdkMediaFormat.h | 3 - media/ndk/include/media/NdkMediaMuxer.h | 46 -- media/ndk/libmediandk.map.txt | 6 - 20 files changed, 46 insertions(+), 957 deletions(-) delete mode 100644 media/libstagefright/MediaAppender.cpp delete mode 100644 media/libstagefright/include/media/stagefright/MediaAppender.h delete mode 100644 media/libstagefright/include/media/stagefright/MediaMuxerBase.h diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 159b3d2e2b..129c95558b 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6258,19 +6258,6 @@ media_status_t MPEG4Source::read( if (isSyncSample) { AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } - - AMediaFormat_setInt64( - meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, - offset); - - if (mSampleTable != nullptr && - mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { - AMediaFormat_setInt64( - meta, - "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - mSampleTable->getLastSampleIndexInChunk()); - } - ++mCurrentSampleIndex; } } @@ -6420,17 +6407,6 @@ media_status_t MPEG4Source::read( AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } - AMediaFormat_setInt64( - meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, offset); - - if (mSampleTable != nullptr && - mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { - AMediaFormat_setInt64( - meta, - "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - mSampleTable->getLastSampleIndexInChunk()); - } - ++mCurrentSampleIndex; *out = mBuffer; diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index d6e36b94c3..52434b3cf6 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -274,7 +274,6 @@ cc_library { "MPEG2TSWriter.cpp", "MPEG4Writer.cpp", "MediaAdapter.cpp", - "MediaAppender.cpp", "MediaClock.cpp", "MediaCodec.cpp", "MediaCodecList.cpp", diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp index aef6d25689..76a5cabde7 100644 --- a/media/libstagefright/MPEG4Writer.cpp +++ b/media/libstagefright/MPEG4Writer.cpp @@ -519,12 +519,12 @@ void MPEG4Writer::initInternal(int fd, bool isFirstSession) { mSendNotify = false; mWriteSeekErr = false; mFallocateErr = false; + // Reset following variables for all the sessions and they will be // initialized in start(MetaData *param). mIsRealTimeRecording = true; mUse4ByteNalLength = true; mOffset = 0; - mMaxOffsetAppend = 0; mPreAllocateFileEndOffset = 0; mMdatOffset = 0; mMdatEndOffset = 0; @@ -992,9 +992,6 @@ status_t MPEG4Writer::start(MetaData *param) { seekOrPostError(mFd, mFreeBoxOffset, SEEK_SET); writeInt32(mInMemoryCacheSize); write("free", 4); - for (int i = 0; i < mInMemoryCacheSize - 8; ++i) { - writeOrPostError(mFd, "\x00", 1); - } mMdatOffset = mFreeBoxOffset + mInMemoryCacheSize; } else { mMdatOffset = mOffset; @@ -1544,26 +1541,6 @@ off64_t MPEG4Writer::addSample_l( MediaBuffer *buffer, bool usePrefix, uint32_t tiffHdrOffset, size_t *bytesWritten) { off64_t old_offset = mOffset; - int64_t offset; - ALOGV("buffer->range_length:%lld", (long long)buffer->range_length()); - if (buffer->meta_data().findInt64(kKeySampleFileOffset, &offset)) { - ALOGV("offset:%lld, old_offset:%lld", (long long)offset, (long long)old_offset); - if (old_offset == offset) { - mOffset += buffer->range_length(); - } else { - ALOGV("offset and old_offset are not equal! diff:%lld", (long long)offset - old_offset); - mOffset = offset + buffer->range_length(); - // mOffset += buffer->range_length() + offset - old_offset; - } - *bytesWritten = buffer->range_length(); - ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld, bytesWritten:%lld", (long long)mOffset, - (long long)mMaxOffsetAppend, (long long)*bytesWritten); - mMaxOffsetAppend = std::max(mOffset, mMaxOffsetAppend); - seekOrPostError(mFd, mMaxOffsetAppend, SEEK_SET); - return offset; - } - - ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, (long long)mMaxOffsetAppend); if (usePrefix) { addMultipleLengthPrefixedSamples_l(buffer); @@ -1580,10 +1557,6 @@ off64_t MPEG4Writer::addSample_l( mOffset += buffer->range_length(); } *bytesWritten = mOffset - old_offset; - - ALOGV("mOffset:%lld, old_offset:%lld, bytesWritten:%lld", (long long)mOffset, - (long long)old_offset, (long long)*bytesWritten); - return old_offset; } @@ -1596,7 +1569,6 @@ static void StripStartcode(MediaBuffer *buffer) { (const uint8_t *)buffer->data() + buffer->range_offset(); if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) { - ALOGV("stripping start code"); buffer->set_range( buffer->range_offset() + 4, buffer->range_length() - 4); } @@ -1627,10 +1599,8 @@ void MPEG4Writer::addMultipleLengthPrefixedSamples_l(MediaBuffer *buffer) { } void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { - ALOGV("alp:buffer->range_length:%lld", (long long)buffer->range_length()); size_t length = buffer->range_length(); if (mUse4ByteNalLength) { - ALOGV("mUse4ByteNalLength"); uint8_t x[4]; x[0] = length >> 24; x[1] = (length >> 16) & 0xff; @@ -1640,7 +1610,6 @@ void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { writeOrPostError(mFd, (const uint8_t*)buffer->data() + buffer->range_offset(), length); mOffset += length + 4; } else { - ALOGV("mUse2ByteNalLength"); CHECK_LT(length, 65536u); uint8_t x[2]; @@ -2793,9 +2762,6 @@ void MPEG4Writer::threadFunc() { } writeAllChunks(); - ALOGV("threadFunc mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, - (long long)mMaxOffsetAppend); - mOffset = std::max(mOffset, mMaxOffsetAppend); } status_t MPEG4Writer::startWriterThread() { @@ -3357,7 +3323,6 @@ status_t MPEG4Writer::Track::threadEntry() { uint32_t lastSamplesPerChunk = 0; int64_t lastSampleDurationUs = -1; // Duration calculated from EOS buffer and its timestamp int64_t lastSampleDurationTicks = -1; // Timescale based ticks - int64_t sampleFileOffset = -1; if (mIsAudio) { prctl(PR_SET_NAME, (unsigned long)"MP4WtrAudTrkThread", 0, 0, 0); @@ -3377,7 +3342,6 @@ status_t MPEG4Writer::Track::threadEntry() { MediaBufferBase *buffer; const char *trackName = getTrackType(); while (!mDone && (err = mSource->read(&buffer)) == OK) { - ALOGV("read:buffer->range_length:%lld", (long long)buffer->range_length()); int32_t isEOS = false; if (buffer->range_length() == 0) { if (buffer->meta_data().findInt32(kKeyIsEndOfStream, &isEOS) && isEOS) { @@ -3484,14 +3448,6 @@ status_t MPEG4Writer::Track::threadEntry() { continue; } } - if (!buffer->meta_data().findInt64(kKeySampleFileOffset, &sampleFileOffset)) { - sampleFileOffset = -1; - } - int64_t lastSample = -1; - if (!buffer->meta_data().findInt64(kKeyLastSampleIndexInChunk, &lastSample)) { - lastSample = -1; - } - ALOGV("sampleFileOffset:%lld", (long long)sampleFileOffset); /* * Reserve space in the file for the current sample + to be written MOOV box. If reservation @@ -3499,7 +3455,7 @@ status_t MPEG4Writer::Track::threadEntry() { * write MOOV box successfully as space for the same was reserved in the prior call. * Release the current buffer/sample here. */ - if (sampleFileOffset == -1 && !mOwner->preAllocate(buffer->range_length())) { + if (!mOwner->preAllocate(buffer->range_length())) { buffer->release(); buffer = nullptr; break; @@ -3510,14 +3466,9 @@ status_t MPEG4Writer::Track::threadEntry() { // Make a deep copy of the MediaBuffer and Metadata and release // the original as soon as we can MediaBuffer *copy = new MediaBuffer(buffer->range_length()); - if (sampleFileOffset != -1) { - copy->meta_data().setInt64(kKeySampleFileOffset, sampleFileOffset); - } else { - memcpy(copy->data(), (uint8_t*)buffer->data() + buffer->range_offset(), - buffer->range_length()); - } + memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(), + buffer->range_length()); copy->set_range(0, buffer->range_length()); - meta_data = new MetaData(buffer->meta_data()); buffer->release(); buffer = NULL; @@ -3525,16 +3476,14 @@ status_t MPEG4Writer::Track::threadEntry() { copy->meta_data().setInt32(kKeyExifTiffOffset, tiffHdrOffset); } bool usePrefix = this->usePrefix() && !isExif; - if (sampleFileOffset == -1 && usePrefix) { - StripStartcode(copy); - } + + if (usePrefix) StripStartcode(copy); + size_t sampleSize = copy->range_length(); - if (sampleFileOffset == -1 && usePrefix) { + if (usePrefix) { if (mOwner->useNalLengthFour()) { - ALOGV("nallength4"); sampleSize += 4; } else { - ALOGV("nallength2"); sampleSize += 2; } } @@ -3829,8 +3778,7 @@ status_t MPEG4Writer::Track::threadEntry() { chunkTimestampUs = timestampUs; } else { int64_t chunkDurationUs = timestampUs - chunkTimestampUs; - if (chunkDurationUs > interleaveDurationUs || lastSample > 1) { - ALOGV("lastSample:%lld", (long long)lastSample); + if (chunkDurationUs > interleaveDurationUs) { if (chunkDurationUs > mMaxChunkDurationUs) { mMaxChunkDurationUs = chunkDurationUs; } @@ -5383,4 +5331,4 @@ void MPEG4Writer::writeGeoDataBox() { endBox(); } -} // namespace android \ No newline at end of file +} // namespace android diff --git a/media/libstagefright/MediaAppender.cpp b/media/libstagefright/MediaAppender.cpp deleted file mode 100644 index 5d80b304bc..0000000000 --- a/media/libstagefright/MediaAppender.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//#define LOG_NDEBUG 0 -#define LOG_TAG "MediaAppender" - -#include -#include -#include -#include -// TODO : check if this works for NDK apps without JVM -// #include - -namespace android { - -struct MediaAppender::sampleDataInfo { - size_t size; - int64_t time; - size_t exTrackIndex; - sp meta; -}; - -sp MediaAppender::create(int fd, AppendMode mode) { - if (fd < 0) { - ALOGE("invalid file descriptor"); - return nullptr; - } - if (!(mode >= APPEND_MODE_FIRST && mode <= APPEND_MODE_LAST)) { - ALOGE("invalid mode %d", mode); - return nullptr; - } - sp ma = new (std::nothrow) MediaAppender(fd, mode); - if (ma->init() != OK) { - return nullptr; - } - return ma; -} - -// TODO: inject mediamuxer and mediaextractor objects. -// TODO: @format is not required as an input if we can sniff the file and find the format of -// the existing content. -// TODO: Code it to the interface(MediaAppender), and have a separate MediaAppender NDK -MediaAppender::MediaAppender(int fd, AppendMode mode) - : mFd(fd), - mMode(mode), - // TODO : check if this works for NDK apps without JVM - // mExtractor(new NuMediaExtractor(NdkJavaVMHelper::getJNIEnv() != nullptr - // ? NuMediaExtractor::EntryPoint::NDK_WITH_JVM - // : NuMediaExtractor::EntryPoint::NDK_NO_JVM)), - mExtractor(new (std::nothrow) NuMediaExtractor(NuMediaExtractor::EntryPoint::NDK_WITH_JVM)), - mTrackCount(0), - mState(UNINITIALIZED) { - ALOGV("MediaAppender::MediaAppender mode:%d", mode); - } - -status_t MediaAppender::init() { - std::scoped_lock lock(mMutex); - ALOGV("MediaAppender::init"); - status_t status = mExtractor->setDataSource(mFd, 0, lseek(mFd, 0, SEEK_END)); - if (status != OK) { - ALOGE("extractor_setDataSource failed, status :%d", status); - return status; - } - - if (strcmp("MPEG4Extractor", mExtractor->getName()) == 0) { - mFormat = MediaMuxer::OUTPUT_FORMAT_MPEG_4; - } else { - ALOGE("Unsupported format, extractor name:%s", mExtractor->getName()); - return ERROR_UNSUPPORTED; - } - - mTrackCount = mExtractor->countTracks(); - ALOGV("mTrackCount:%zu", mTrackCount); - if (mTrackCount == 0) { - ALOGE("no tracks are present"); - return ERROR_MALFORMED; - } - size_t exTrackIndex = 0; - ssize_t audioTrackIndex = -1, videoTrackIndex = -1; - bool audioSyncSampleTimeSet = false; - - while (exTrackIndex < mTrackCount) { - sp fmt; - status = mExtractor->getTrackFormat(exTrackIndex, &fmt, 0); - if (status != OK) { - ALOGE("getTrackFormat failed for trackIndex:%zu, status:%d", exTrackIndex, status); - return status; - } - AString mime; - if (fmt->findString("mime", &mime)) { - if (!strncasecmp(mime.c_str(), "video/", 6)) { - ALOGV("VideoTrack"); - if (videoTrackIndex != -1) { - ALOGE("Not more than one video track is supported"); - return ERROR_UNSUPPORTED; - } - videoTrackIndex = exTrackIndex; - } else if (!strncasecmp(mime.c_str(), "audio/", 6)) { - ALOGV("AudioTrack"); - if (audioTrackIndex != -1) { - ALOGE("Not more than one audio track is supported"); - } - audioTrackIndex = exTrackIndex; - } else { - ALOGV("Neither Video nor Audio track"); - } - } - mFmtIndexMap.emplace(exTrackIndex, fmt); - mSampleCountVect.emplace_back(0); - mMaxTimestampVect.emplace_back(0); - mLastSyncSampleTimeVect.emplace_back(0); - status = mExtractor->selectTrack(exTrackIndex); - if (status != OK) { - ALOGE("selectTrack failed for trackIndex:%zu, status:%d", exTrackIndex, status); - return status; - } - ++exTrackIndex; - } - - ALOGV("AudioTrackIndex:%zu, VideoTrackIndex:%zu", audioTrackIndex, videoTrackIndex); - - do { - sampleDataInfo tmpSDI; - // TODO: read info into members of the struct sampleDataInfo directly - size_t sampleSize; - status = mExtractor->getSampleSize(&sampleSize); - if (status != OK) { - ALOGE("getSampleSize failed, status:%d", status); - return status; - } - mSampleSizeVect.emplace_back(sampleSize); - tmpSDI.size = sampleSize; - int64_t sampleTime = 0; - status = mExtractor->getSampleTime(&sampleTime); - if (status != OK) { - ALOGE("getSampleTime failed, status:%d", status); - return status; - } - mSampleTimeVect.emplace_back(sampleTime); - tmpSDI.time = sampleTime; - status = mExtractor->getSampleTrackIndex(&exTrackIndex); - if (status != OK) { - ALOGE("getSampleTrackIndex failed, status:%d", status); - return status; - } - mSampleIndexVect.emplace_back(exTrackIndex); - tmpSDI.exTrackIndex = exTrackIndex; - ++mSampleCountVect[exTrackIndex]; - mMaxTimestampVect[exTrackIndex] = std::max(mMaxTimestampVect[exTrackIndex], sampleTime); - sp sampleMeta; - status = mExtractor->getSampleMeta(&sampleMeta); - if (status != OK) { - ALOGE("getSampleMeta failed, status:%d", status); - return status; - } - mSampleMetaVect.emplace_back(sampleMeta); - int32_t val = 0; - if (sampleMeta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { - mLastSyncSampleTimeVect[exTrackIndex] = sampleTime; - } - tmpSDI.meta = sampleMeta; - mSDI.emplace_back(tmpSDI); - } while (mExtractor->advance() == OK); - - mExtractor.clear(); - - std::sort(mSDI.begin(), mSDI.end(), [](sampleDataInfo& a, sampleDataInfo& b) { - int64_t aOffset, bOffset; - a.meta->findInt64(kKeySampleFileOffset, &aOffset); - b.meta->findInt64(kKeySampleFileOffset, &bOffset); - return aOffset < bOffset; - }); - for (int64_t syncSampleTime : mLastSyncSampleTimeVect) { - ALOGV("before ignoring frames, mLastSyncSampleTimeVect:%lld", (long long)syncSampleTime); - } - ALOGV("mMode:%u", mMode); - if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex != -1 ) { - ALOGV("Video track is present"); - bool lastVideoIframe = false; - size_t lastVideoIframeOffset = 0; - int64_t lastVideoSampleTime = -1; - for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { - if (rItr->exTrackIndex != videoTrackIndex) { - continue; - } - if (lastVideoSampleTime == -1) { - lastVideoSampleTime = rItr->time; - } - int64_t offset = 0; - if (!rItr->meta->findInt64(kKeySampleFileOffset, &offset) || offset == 0) { - ALOGE("Missing offset"); - return ERROR_MALFORMED; - } - ALOGV("offset:%lld", (long long)offset); - int32_t val = 0; - if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { - ALOGV("sampleTime:%lld", (long long)rItr->time); - ALOGV("lastVideoSampleTime:%lld", (long long)lastVideoSampleTime); - if (lastVideoIframe == false && (lastVideoSampleTime - rItr->time) > - 1000000/* Track interleaving duration in MPEG4Writer*/) { - ALOGV("lastVideoIframe got chosen"); - lastVideoIframe = true; - mLastSyncSampleTimeVect[videoTrackIndex] = rItr->time; - lastVideoIframeOffset = offset; - ALOGV("lastVideoIframeOffset:%lld", (long long)offset); - break; - } - } - } - if (lastVideoIframe == false) { - ALOGV("Need to rewrite all samples"); - mLastSyncSampleTimeVect[videoTrackIndex] = 0; - lastVideoIframeOffset = 0; - } - unsigned int framesIgnoredCount = 0; - for (auto itr = mSDI.begin(); itr != mSDI.end();) { - int64_t offset = 0; - ALOGV("trackIndex:%zu, %" PRId64 "", itr->exTrackIndex, itr->time); - if (itr->meta->findInt64(kKeySampleFileOffset, &offset) && - offset >= lastVideoIframeOffset) { - ALOGV("offset:%lld", (long long)offset); - if (!audioSyncSampleTimeSet && audioTrackIndex != -1 && - audioTrackIndex == itr->exTrackIndex) { - mLastSyncSampleTimeVect[audioTrackIndex] = itr->time; - audioSyncSampleTimeSet = true; - } - itr = mSDI.erase(itr); - ++framesIgnoredCount; - } else { - ++itr; - } - } - ALOGV("framesIgnoredCount:%u", framesIgnoredCount); - } - - if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex == -1 && - audioTrackIndex != -1) { - ALOGV("Only AudioTrack is present"); - for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { - int32_t val = 0; - if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { - mLastSyncSampleTimeVect[audioTrackIndex] = rItr->time; - break; - } - } - unsigned int framesIgnoredCount = 0; - for (auto itr = mSDI.begin(); itr != mSDI.end();) { - if (itr->time >= mLastSyncSampleTimeVect[audioTrackIndex]) { - itr = mSDI.erase(itr); - ++framesIgnoredCount; - } else { - ++itr; - } - } - ALOGV("framesIgnoredCount :%u", framesIgnoredCount); - } - - for (size_t i = 0; i < mLastSyncSampleTimeVect.size(); ++i) { - ALOGV("mLastSyncSampleTimeVect[%zu]:%lld", i, (long long)mLastSyncSampleTimeVect[i]); - mFmtIndexMap[i]->setInt64( - "sample-time-before-append" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, - mLastSyncSampleTimeVect[i]); - } - for (size_t i = 0; i < mMaxTimestampVect.size(); ++i) { - ALOGV("mMaxTimestamp[%zu]:%lld", i, (long long)mMaxTimestampVect[i]); - } - for (size_t i = 0; i < mSampleCountVect.size(); ++i) { - ALOGV("SampleCountVect[%zu]:%zu", i, mSampleCountVect[i]); - } - mState = INITIALIZED; - return OK; -} - -MediaAppender::~MediaAppender() { - ALOGV("MediaAppender::~MediaAppender"); - mMuxer.clear(); - mExtractor.clear(); -} - -status_t MediaAppender::start() { - std::scoped_lock lock(mMutex); - ALOGV("MediaAppender::start"); - if (mState != INITIALIZED) { - ALOGE("MediaAppender::start() is called in invalid state %d", mState); - return INVALID_OPERATION; - } - mMuxer = new (std::nothrow) MediaMuxer(mFd, mFormat); - for (const auto& n : mFmtIndexMap) { - ssize_t muxIndex = mMuxer->addTrack(n.second); - if (muxIndex < 0) { - ALOGE("addTrack failed"); - return UNKNOWN_ERROR; - } - mTrackIndexMap.emplace(n.first, muxIndex); - } - ALOGV("trackIndexmap size:%zu", mTrackIndexMap.size()); - - status_t status = mMuxer->start(); - if (status != OK) { - ALOGE("muxer start failed:%d", status); - return status; - } - - ALOGV("Sorting samples based on their offsets"); - for (int i = 0; i < mSDI.size(); ++i) { - ALOGV("i:%d", i + 1); - /* TODO : Allocate a single allocation of the max size, and reuse it across ABuffers if - * using new ABuffer(void *, size_t). - */ - sp data = new (std::nothrow) ABuffer(mSDI[i].size); - if (data == nullptr) { - ALOGE("memory allocation failed"); - return NO_MEMORY; - } - data->setRange(0, mSDI[i].size); - int32_t val = 0; - int sampleFlags = 0; - if (mSDI[i].meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { - sampleFlags |= MediaCodec::BUFFER_FLAG_SYNCFRAME; - } - - int64_t val64; - if (mSDI[i].meta->findInt64(kKeySampleFileOffset, &val64)) { - ALOGV("SampleFileOffset Found :%zu:%lld:%lld", mSDI[i].exTrackIndex, - (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); - sp bufMeta = data->meta(); - bufMeta->setInt64("sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, - val64); - } - if (mSDI[i].meta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { - ALOGV("kKeyLastSampleIndexInChunk Found %lld:%lld", - (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); - sp bufMeta = data->meta(); - bufMeta->setInt64( - "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - val64); - } - status = mMuxer->writeSampleData(data, mTrackIndexMap[mSDI[i].exTrackIndex], mSDI[i].time, - sampleFlags); - if (status != OK) { - ALOGE("muxer writeSampleData failed:%d", status); - return status; - } - } - mState = STARTED; - return OK; -} - -status_t MediaAppender::stop() { - std::scoped_lock lock(mMutex); - ALOGV("MediaAppender::stop"); - if (mState == STARTED) { - status_t status = mMuxer->stop(); - if (status != OK) { - mState = ERROR; - } else { - mState = STOPPED; - } - return status; - } else { - ALOGE("stop() is called in invalid state %d", mState); - return INVALID_OPERATION; - } -} - -ssize_t MediaAppender::getTrackCount() { - std::scoped_lock lock(mMutex); - ALOGV("MediaAppender::getTrackCount"); - if (mState != INITIALIZED && mState != STARTED) { - ALOGE("getTrackCount() is called in invalid state %d", mState); - return -1; - } - return mTrackCount; -} - -sp MediaAppender::getTrackFormat(size_t idx) { - std::scoped_lock lock(mMutex); - ALOGV("MediaAppender::getTrackFormat"); - if (mState != INITIALIZED && mState != STARTED) { - ALOGE("getTrackFormat() is called in invalid state %d", mState); - return nullptr; - } - if (idx < 0 || idx >= mTrackCount) { - ALOGE("getTrackFormat() idx is out of range"); - return nullptr; - } - return mFmtIndexMap[idx]; -} - -status_t MediaAppender::writeSampleData(const sp& buffer, size_t trackIndex, - int64_t timeUs, uint32_t flags) { - std::scoped_lock lock(mMutex); - ALOGV("writeSampleData:trackIndex:%zu, time:%" PRId64 "", trackIndex, timeUs); - return mMuxer->writeSampleData(buffer, trackIndex, timeUs, flags); -} - -status_t MediaAppender::setOrientationHint([[maybe_unused]] int degrees) { - ALOGE("setOrientationHint not supported. Has to be called prior to start on initial muxer"); - return ERROR_UNSUPPORTED; -}; - -status_t MediaAppender::setLocation([[maybe_unused]] int latit, [[maybe_unused]] int longit) { - ALOGE("setLocation not supported. Has to be called prior to start on initial muxer"); - return ERROR_UNSUPPORTED; -} - -ssize_t MediaAppender::addTrack([[maybe_unused]] const sp &format) { - ALOGE("addTrack not supported"); - return ERROR_UNSUPPORTED; -} - -} // namespace android diff --git a/media/libstagefright/MediaMuxer.cpp b/media/libstagefright/MediaMuxer.cpp index a946f71e9b..c91386d489 100644 --- a/media/libstagefright/MediaMuxer.cpp +++ b/media/libstagefright/MediaMuxer.cpp @@ -76,7 +76,6 @@ MediaMuxer::~MediaMuxer() { mFileMeta.clear(); mWriter.clear(); mTrackList.clear(); - mFormatList.clear(); } ssize_t MediaMuxer::addTrack(const sp &format) { @@ -110,8 +109,6 @@ ssize_t MediaMuxer::addTrack(const sp &format) { ALOGW("addTrack() setCaptureRate failed :%d", result); } } - - mFormatList.add(format); return mTrackList.add(newTrack); } @@ -227,42 +224,9 @@ status_t MediaMuxer::writeSampleData(const sp &buffer, size_t trackInde ALOGV("BUFFER_FLAG_EOS"); } - sp bufMeta = buffer->meta(); - int64_t val64; - if (bufMeta->findInt64("sample-file-offset", &val64)) { - sampleMetaData.setInt64(kKeySampleFileOffset, val64); - } - if (bufMeta->findInt64( - "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - &val64)) { - sampleMetaData.setInt64(kKeyLastSampleIndexInChunk, val64); - } - sp currentTrack = mTrackList[trackIndex]; // This pushBuffer will wait until the mediaBuffer is consumed. return currentTrack->pushBuffer(mediaBuffer); } -ssize_t MediaMuxer::getTrackCount() { - Mutex::Autolock autoLock(mMuxerLock); - if (mState != INITIALIZED && mState != STARTED) { - ALOGE("getTrackCount() must be called either in INITIALIZED or STARTED state"); - return -1; - } - return mTrackList.size(); -} - -sp MediaMuxer::getTrackFormat([[maybe_unused]] size_t idx) { - Mutex::Autolock autoLock(mMuxerLock); - if (mState != INITIALIZED && mState != STARTED) { - ALOGE("getTrackFormat() must be called either in INITIALIZED or STARTED state"); - return nullptr; - } - if (idx < 0 || idx >= mFormatList.size()) { - ALOGE("getTrackFormat() idx is out of range"); - return nullptr; - } - return mFormatList[idx]; -} - } // namespace android diff --git a/media/libstagefright/MediaTrack.cpp b/media/libstagefright/MediaTrack.cpp index 2447f5e904..24ba38af87 100644 --- a/media/libstagefright/MediaTrack.cpp +++ b/media/libstagefright/MediaTrack.cpp @@ -133,14 +133,6 @@ status_t MediaTrackCUnwrapper::read(MediaBufferBase **buffer, const ReadOptions if (format->mFormat->findInt64("target-time", &val64)) { meta.setInt64(kKeyTargetTime, val64); } - if (format->mFormat->findInt64("sample-file-offset", &val64)) { - meta.setInt64(kKeySampleFileOffset, val64); - } - if (format->mFormat->findInt64( - "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - &val64)) { - meta.setInt64(kKeyLastSampleIndexInChunk, val64); - } int32_t val32; if (format->mFormat->findInt32("is-sync-frame", &val32)) { meta.setInt32(kKeyIsSyncFrame, val32); diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp index f54a56f5c2..3ee78d04f5 100644 --- a/media/libstagefright/NuMediaExtractor.cpp +++ b/media/libstagefright/NuMediaExtractor.cpp @@ -189,11 +189,6 @@ status_t NuMediaExtractor::setDataSource(const sp &source) { return err; } -const char* NuMediaExtractor::getName() const { - Mutex::Autolock autoLock(mLock); - return mImpl == nullptr ? nullptr : mImpl->name().string(); -} - static String8 arrayToString(const std::vector &array) { String8 result; for (size_t i = 0; i < array.size(); i++) { diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp index 6091cb8f7d..51d9730bba 100644 --- a/media/libstagefright/Utils.cpp +++ b/media/libstagefright/Utils.cpp @@ -725,19 +725,16 @@ static std::vector> floatMappings { } }; -static std::vector> int64Mappings { +static std::vector> int64Mappings { { - { "exif-offset", kKeyExifOffset}, - { "exif-size", kKeyExifSize}, - { "xmp-offset", kKeyXmpOffset}, - { "xmp-size", kKeyXmpSize}, - { "target-time", kKeyTargetTime}, - { "thumbnail-time", kKeyThumbnailTime}, - { "timeUs", kKeyTime}, - { "durationUs", kKeyDuration}, - { "sample-file-offset", kKeySampleFileOffset}, - { "last-sample-index-in-chunk", kKeyLastSampleIndexInChunk}, - { "sample-time-before-append", kKeySampleTimeBeforeAppend}, + { "exif-offset", kKeyExifOffset }, + { "exif-size", kKeyExifSize }, + { "xmp-offset", kKeyXmpOffset }, + { "xmp-size", kKeyXmpSize }, + { "target-time", kKeyTargetTime }, + { "thumbnail-time", kKeyThumbnailTime }, + { "timeUs", kKeyTime }, + { "durationUs", kKeyDuration }, } }; diff --git a/media/libstagefright/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/media/stagefright/MPEG4Writer.h index 7f2728ebd8..2582ed0815 100644 --- a/media/libstagefright/include/media/stagefright/MPEG4Writer.h +++ b/media/libstagefright/include/media/stagefright/MPEG4Writer.h @@ -106,7 +106,6 @@ private: off64_t mOffset; off64_t mPreAllocateFileEndOffset; //End of file offset during preallocation. off64_t mMdatOffset; - off64_t mMaxOffsetAppend; // File offset written upto while appending. off64_t mMdatEndOffset; // End offset of mdat atom. uint8_t *mInMemoryCache; off64_t mInMemoryCacheOffset; diff --git a/media/libstagefright/include/media/stagefright/MediaAppender.h b/media/libstagefright/include/media/stagefright/MediaAppender.h deleted file mode 100644 index c2f6f1045b..0000000000 --- a/media/libstagefright/include/media/stagefright/MediaAppender.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_MEDIA_APPENDER_H -#define ANDROID_MEDIA_APPENDER_H - -#include -#include -#include - -namespace android { - -struct MediaAppender : public MediaMuxerBase { -public: - enum AppendMode { - APPEND_MODE_FIRST = 0, - APPEND_MODE_IGNORE_LAST_VIDEO_GOP = APPEND_MODE_FIRST, - APPEND_MODE_ADD_TO_EXISTING_DATA = 1, - APPEND_MODE_LAST = APPEND_MODE_ADD_TO_EXISTING_DATA, - }; - - static sp create(int fd, AppendMode mode); - - virtual ~MediaAppender(); - - status_t init(); - - status_t start(); - - status_t stop(); - - status_t writeSampleData(const sp& buffer, size_t trackIndex, int64_t timeUs, - uint32_t flags); - - status_t setOrientationHint(int degrees); - - status_t setLocation(int latitude, int longitude); - - ssize_t addTrack(const sp &format); - - ssize_t getTrackCount(); - - sp getTrackFormat(size_t idx); - -private: - MediaAppender(int fd, AppendMode mode); - - int mFd; - MediaMuxer::OutputFormat mFormat; - AppendMode mMode; - sp mExtractor; - sp mMuxer; - size_t mTrackCount; - // Map track index given by extractor to the ones received from muxer. - std::map mTrackIndexMap; - // Count of the samples in each track, indexed by extractor track ids. - std::vector mSampleCountVect; - // Extractor track index of samples. - std::vector mSampleIndexVect; - // Track format indexed by extractor track ids. - std::map> mFmtIndexMap; - // Size of samples. - std::vector mSampleSizeVect; - // Presentation time stamp of samples. - std::vector mSampleTimeVect; - // Timestamp of last sample of tracks. - std::vector mMaxTimestampVect; - // Metadata of samples. - std::vector> mSampleMetaVect; - std::mutex mMutex; - // Timestamp of the last sync sample of tracks. - std::vector mLastSyncSampleTimeVect; - - struct sampleDataInfo; - std::vector mSDI; - - enum : int { - UNINITIALIZED, - INITIALIZED, - STARTED, - STOPPED, - ERROR, - } mState GUARDED_BY(mMutex); -}; - -} // namespace android -#endif // ANDROID_MEDIA_APPENDER_H \ No newline at end of file diff --git a/media/libstagefright/include/media/stagefright/MediaMuxer.h b/media/libstagefright/include/media/stagefright/MediaMuxer.h index e97a65ee6b..a1b9465d65 100644 --- a/media/libstagefright/include/media/stagefright/MediaMuxer.h +++ b/media/libstagefright/include/media/stagefright/MediaMuxer.h @@ -22,12 +22,7 @@ #include #include -#include -#include -#include - #include "media/stagefright/foundation/ABase.h" -#include "MediaMuxerBase.h" namespace android { @@ -38,7 +33,6 @@ class MediaBuffer; struct MediaSource; class MetaData; struct MediaWriter; -struct NuMediaExtractor; // MediaMuxer is used to mux multiple tracks into a video. Currently, we only // support a mp4 file as the output. @@ -46,8 +40,19 @@ struct NuMediaExtractor; // Constructor -> addTrack+ -> start -> writeSampleData+ -> stop // If muxing operation need to be cancelled, the app is responsible for // deleting the output file after stop. -struct MediaMuxer : public MediaMuxerBase { +struct MediaMuxer : public RefBase { public: + // Please update media/java/android/media/MediaMuxer.java if the + // OutputFormat is updated. + enum OutputFormat { + OUTPUT_FORMAT_MPEG_4 = 0, + OUTPUT_FORMAT_WEBM = 1, + OUTPUT_FORMAT_THREE_GPP = 2, + OUTPUT_FORMAT_HEIF = 3, + OUTPUT_FORMAT_OGG = 4, + OUTPUT_FORMAT_LIST_END // must be last - used to validate format type + }; + // Construct the muxer with the file descriptor. Note that the MediaMuxer // will close this file at stop(). MediaMuxer(int fd, OutputFormat format); @@ -112,25 +117,10 @@ public: status_t writeSampleData(const sp &buffer, size_t trackIndex, int64_t timeUs, uint32_t flags) ; - /** - * Gets the number of tracks added successfully. Should be called in - * INITIALIZED(after constructor) or STARTED(after start()) state. - * @return the number of tracks or -1 in wrong state. - */ - ssize_t getTrackCount(); - - /** - * Gets the format of the track by their index. - * @param idx : index of the track whose format is wanted. - * @return smart pointer to AMessage containing the format details. - */ - sp getTrackFormat(size_t idx); - private: const OutputFormat mFormat; sp mWriter; Vector< sp > mTrackList; // Each track has its MediaAdapter. - Vector< sp > mFormatList; // Format of each track. sp mFileMeta; // Metadata for the whole file. Mutex mMuxerLock; diff --git a/media/libstagefright/include/media/stagefright/MediaMuxerBase.h b/media/libstagefright/include/media/stagefright/MediaMuxerBase.h deleted file mode 100644 index f02d510835..0000000000 --- a/media/libstagefright/include/media/stagefright/MediaMuxerBase.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MEDIA_MUXER_BASE_H_ -#define MEDIA_MUXER_BASE_H_ - -#include -#include "media/stagefright/foundation/ABase.h" - -namespace android { - -struct ABuffer; -struct AMessage; - -// MediaMuxer is used to mux multiple tracks into a video. Currently, we only -// support a mp4 file as the output. -// The expected calling order of the functions is: -// Constructor -> addTrack+ -> start -> writeSampleData+ -> stop -// If muxing operation need to be cancelled, the app is responsible for -// deleting the output file after stop. -struct MediaMuxerBase : public RefBase { -public: - // Please update media/java/android/media/MediaMuxer.java if the - // OutputFormat is updated. - enum OutputFormat { - OUTPUT_FORMAT_MPEG_4 = 0, - OUTPUT_FORMAT_WEBM = 1, - OUTPUT_FORMAT_THREE_GPP = 2, - OUTPUT_FORMAT_HEIF = 3, - OUTPUT_FORMAT_OGG = 4, - OUTPUT_FORMAT_LIST_END // must be last - used to validate format type - }; - - // Construct the muxer with the file descriptor. Note that the MediaMuxer - // will close this file at stop(). - MediaMuxerBase() {}; - - virtual ~MediaMuxerBase() {}; - - /** - * Add a track with its format information. This should be - * called before start(). - * @param format the track's format. - * @return the track's index or negative number if error. - */ - virtual ssize_t addTrack(const sp &format) = 0; - - /** - * Start muxing. Make sure all the tracks have been added before - * calling this. - */ - virtual status_t start() = 0; - - /** - * Set the orientation hint. - * @param degrees The rotation degrees. It has to be either 0, - * 90, 180 or 270. - * @return OK if no error. - */ - virtual status_t setOrientationHint(int degrees) = 0; - - /** - * Set the location. - * @param latitude The latitude in degree x 1000. Its value must be in the range - * [-900000, 900000]. - * @param longitude The longitude in degree x 1000. Its value must be in the range - * [-1800000, 1800000]. - * @return OK if no error. - */ - virtual status_t setLocation(int latitude, int longitude) = 0; - - /** - * Stop muxing. - * This method is a blocking call. Depending on how - * much data is bufferred internally, the time needed for stopping - * the muxer may be time consuming. UI thread is - * not recommended for launching this call. - * @return OK if no error. - */ - virtual status_t stop() = 0; - - /** - * Send a sample buffer for muxing. - * The buffer can be reused once this method returns. Typically, - * this function won't be blocked for very long, and thus there - * is no need to use a separate thread calling this method to - * push a buffer. - * @param buffer the incoming sample buffer. - * @param trackIndex the buffer's track index number. - * @param timeUs the buffer's time stamp. - * @param flags the only supported flag for now is - * MediaCodec::BUFFER_FLAG_SYNCFRAME. - * @return OK if no error. - */ - virtual status_t writeSampleData(const sp &buffer, size_t trackIndex, - int64_t timeUs, uint32_t flags) = 0 ; - - /** - * Gets the number of tracks added successfully. Should be called in - * INITIALIZED(after constructor) or STARTED(after start()) state. - * @return the number of tracks or -1 in wrong state. - */ - virtual ssize_t getTrackCount() = 0; - - /** - * Gets the format of the track by their index. - * @param idx : index of the track whose format is wanted. - * @return smart pointer to AMessage containing the format details. - */ - virtual sp getTrackFormat(size_t idx) = 0; - -private: - - DISALLOW_EVIL_CONSTRUCTORS(MediaMuxerBase); -}; - -} // namespace android - -#endif // MEDIA_MUXER_BASE_H_ - diff --git a/media/libstagefright/include/media/stagefright/MetaDataBase.h b/media/libstagefright/include/media/stagefright/MetaDataBase.h index 408872fe26..940bd86848 100644 --- a/media/libstagefright/include/media/stagefright/MetaDataBase.h +++ b/media/libstagefright/include/media/stagefright/MetaDataBase.h @@ -264,11 +264,6 @@ enum { // Slow-motion markers kKeySlowMotionMarkers = 'slmo', // raw data, byte array following spec for // MediaFormat#KEY_SLOW_MOTION_MARKERS - - kKeySampleFileOffset = 'sfof', // int64_t, sample's offset in a media file. - kKeyLastSampleIndexInChunk = 'lsic', //int64_t, index of last sample in a chunk. - kKeySampleTimeBeforeAppend = 'lsba', // int64_t, timestamp of last sample of a track. - }; enum { diff --git a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h index 6aa7c0fd46..1cad140b03 100644 --- a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h @@ -102,8 +102,6 @@ struct NuMediaExtractor : public RefBase { status_t setPlaybackId(const String8& playbackId); - const char* getName() const; - protected: virtual ~NuMediaExtractor(); diff --git a/media/ndk/NdkMediaExtractor.cpp b/media/ndk/NdkMediaExtractor.cpp index 07fc5de09c..0c65e9e552 100644 --- a/media/ndk/NdkMediaExtractor.cpp +++ b/media/ndk/NdkMediaExtractor.cpp @@ -419,7 +419,6 @@ int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *ex) { EXPORT media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat *fmt) { - ALOGV("AMediaExtractor_getSampleFormat"); if (fmt == NULL) { return AMEDIA_ERROR_INVALID_PARAMETER; } @@ -429,9 +428,6 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat if (err != OK) { return translate_error(err); } -#ifdef LOG_NDEBUG - sampleMeta->dumpToLog(); -#endif sp meta; AMediaFormat_getFormat(fmt, &meta); @@ -487,19 +483,6 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat meta->setBuffer(AMEDIAFORMAT_KEY_AUDIO_PRESENTATION_INFO, audioPresentationsData); } - int64_t val64; - if (sampleMeta->findInt64(kKeySampleFileOffset, &val64)) { - meta->setInt64("sample-file-offset", val64); - ALOGV("SampleFileOffset Found"); - } - if (sampleMeta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { - meta->setInt64("last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, - val64); - ALOGV("kKeyLastSampleIndexInChunk Found"); - } - - ALOGV("AMediaFormat_toString:%s", AMediaFormat_toString(fmt)); - return AMEDIA_OK; } diff --git a/media/ndk/NdkMediaFormat.cpp b/media/ndk/NdkMediaFormat.cpp index c1793ce159..1773023f37 100644 --- a/media/ndk/NdkMediaFormat.cpp +++ b/media/ndk/NdkMediaFormat.cpp @@ -334,7 +334,6 @@ EXPORT const char* AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE = "is-forced-subtitle"; EXPORT const char* AMEDIAFORMAT_KEY_IS_SYNC_FRAME = "is-sync-frame"; EXPORT const char* AMEDIAFORMAT_KEY_I_FRAME_INTERVAL = "i-frame-interval"; EXPORT const char* AMEDIAFORMAT_KEY_LANGUAGE = "language"; -EXPORT const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK = "last-sample-index-in-chunk"; EXPORT const char* AMEDIAFORMAT_KEY_LATENCY = "latency"; EXPORT const char* AMEDIAFORMAT_KEY_LEVEL = "level"; EXPORT const char* AMEDIAFORMAT_KEY_LOCATION = "location"; @@ -360,9 +359,7 @@ EXPORT const char* AMEDIAFORMAT_KEY_PSSH = "pssh"; EXPORT const char* AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP = "push-blank-buffers-on-shutdown"; EXPORT const char* AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER = "repeat-previous-frame-after"; EXPORT const char* AMEDIAFORMAT_KEY_ROTATION = "rotation-degrees"; -EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET = "sample-file-offset"; EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_RATE = "sample-rate"; -EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND = "sample-time-before-append"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_HEIGHT = "sar-height"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_WIDTH = "sar-width"; EXPORT const char* AMEDIAFORMAT_KEY_SEI = "sei"; diff --git a/media/ndk/NdkMediaMuxer.cpp b/media/ndk/NdkMediaMuxer.cpp index 1965e62502..d1992bf7ed 100644 --- a/media/ndk/NdkMediaMuxer.cpp +++ b/media/ndk/NdkMediaMuxer.cpp @@ -17,24 +17,28 @@ //#define LOG_NDEBUG 0 #define LOG_TAG "NdkMediaMuxer" -#include -#include -#include + +#include #include #include #include -#include -#include -#include -#include -#include + + #include #include +#include +#include +#include +#include +#include + +#include using namespace android; struct AMediaMuxer { - sp mImpl; + sp mImpl; + }; extern "C" { @@ -42,15 +46,8 @@ extern "C" { EXPORT AMediaMuxer* AMediaMuxer_new(int fd, OutputFormat format) { ALOGV("ctor"); - AMediaMuxer *mData = new (std::nothrow) AMediaMuxer(); - if (mData == nullptr) { - return nullptr; - } - mData->mImpl = new (std::nothrow) MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); - if (mData->mImpl == nullptr) { - delete mData; - return nullptr; - } + AMediaMuxer *mData = new AMediaMuxer(); + mData->mImpl = new MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); return mData; } @@ -97,34 +94,6 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, muxer->mImpl->writeSampleData(buf, trackIdx, info->presentationTimeUs, info->flags)); } -EXPORT -AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) { - ALOGV("append"); - AMediaMuxer* mData = new (std::nothrow) AMediaMuxer(); - if (mData == nullptr) { - return nullptr; - } - mData->mImpl = MediaAppender::create(fd, (android::MediaAppender::AppendMode)mode); - if (mData->mImpl == nullptr) { - delete mData; - return nullptr; - } - return mData; -} - -EXPORT -ssize_t AMediaMuxer_getTrackCount(AMediaMuxer* muxer) { - return muxer->mImpl->getTrackCount(); -} - -EXPORT -AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) { - sp format = muxer->mImpl->getTrackFormat(idx); - if (format != nullptr) { - return AMediaFormat_fromMsg(&format); - } - return nullptr; -} } // extern "C" diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h index fbd855d66b..476bbd9d05 100644 --- a/media/ndk/include/media/NdkMediaFormat.h +++ b/media/ndk/include/media/NdkMediaFormat.h @@ -307,9 +307,6 @@ extern const char* AMEDIAFORMAT_KEY_SLOW_MOTION_MARKERS __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_THUMBNAIL_CSD_AV1C __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_OFFSET __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_SIZE __INTRODUCED_IN(31); -extern const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET __INTRODUCED_IN(31); -extern const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK __INTRODUCED_IN(31); -extern const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MAX __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MIN __INTRODUCED_IN(31); diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h index 866ebfd730..519e249503 100644 --- a/media/ndk/include/media/NdkMediaMuxer.h +++ b/media/ndk/include/media/NdkMediaMuxer.h @@ -54,17 +54,6 @@ typedef enum { AMEDIAMUXER_OUTPUT_FORMAT_THREE_GPP = 2, } OutputFormat; -typedef enum { - /* Last group of pictures(GOP) of video track can be incomplete, so it would be safe to - * scrap that and rewrite. If both audio and video tracks are present in a file, then - * samples of audio track after last GOP of video would be scrapped too. - * If only audio track is present, then no sample would be discarded. - */ - AMEDIAMUXER_APPEND_IGNORE_LAST_VIDEO_GOP = 0, - // Keep all existing samples as it is and append new samples after that only. - AMEDIAMUXER_APPEND_TO_EXISTING_DATA = 1, -} AppendMode; - /** * Create new media muxer. * @@ -149,41 +138,6 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, size_t trackIdx, const uint8_t *data, const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21); -/** - * Creates a new media muxer for appending data to an existing MPEG4 file. - * This is a synchronous API call and could take a while to return if the existing file is large. - * Works for only MPEG4 files that contain a) a single audio track, b) a single video track, - * c) a single audio and a single video track. - * @param(fd): needs to be opened with read and write permission. Does not take ownership of - * this fd i.e., caller is responsible for closing fd. - * @param(mode): AppendMode is an enum that specifies one of the modes of appending data. - * @return : Pointer to AMediaMuxer if the file(fd) has tracks already, otherwise, nullptr. - * {@link AMediaMuxer_delete} should be used to free the returned pointer. - * - * Available since API level 31. - */ -AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) __INTRODUCED_IN(31); - -/** - * Returns the number of tracks added in the file passed to {@link AMediaMuxer_new} or - * the number of existing tracks in the file passed to {@link AMediaMuxer_append}. - * Should be called in INITIALIZED or STARTED state, otherwise returns -1. - * - * Available since API level 31. - */ -ssize_t AMediaMuxer_getTrackCount(AMediaMuxer*) __INTRODUCED_IN(31); - -/** - * Returns AMediaFormat of the added track with index idx in the file passed to - * {@link AMediaMuxer_new} or the AMediaFormat of the existing track with index idx - * in the file passed to {@link AMediaMuxer_append}. - * Should be called in INITIALIZED or STARTED state, otherwise returns nullptr. - * {@link AMediaFormat_delete} should be used to free the returned pointer. - * - * Available since API level 31. - */ -AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) __INTRODUCED_IN(31); - __END_DECLS #endif // _NDK_MEDIA_MUXER_H diff --git a/media/ndk/libmediandk.map.txt b/media/ndk/libmediandk.map.txt index 7e9e57ef8d..eead681648 100644 --- a/media/ndk/libmediandk.map.txt +++ b/media/ndk/libmediandk.map.txt @@ -109,7 +109,6 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_IS_SYNC_FRAME; # var introduced=29 AMEDIAFORMAT_KEY_I_FRAME_INTERVAL; # var introduced=21 AMEDIAFORMAT_KEY_LANGUAGE; # var introduced=21 - AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK; # var introduced=31 AMEDIAFORMAT_KEY_LATENCY; # var introduced=28 AMEDIAFORMAT_KEY_LEVEL; # var introduced=28 AMEDIAFORMAT_KEY_LOCATION; # var introduced=29 @@ -135,8 +134,6 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP; # var introduced=21 AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER; # var introduced=21 AMEDIAFORMAT_KEY_ROTATION; # var introduced=28 - AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET; # var introduced=31 - AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND; # var introduced=31 AMEDIAFORMAT_KEY_SAMPLE_RATE; # var introduced=21 AMEDIAFORMAT_KEY_SAR_HEIGHT; # var introduced=29 AMEDIAFORMAT_KEY_SAR_WIDTH; # var introduced=29 @@ -289,10 +286,7 @@ LIBMEDIANDK { AMediaFormat_setString; AMediaFormat_toString; AMediaMuxer_addTrack; - AMediaMuxer_append; # introduced=31 AMediaMuxer_delete; - AMediaMuxer_getTrackCount; # introduced=31 - AMediaMuxer_getTrackFormat; # introduced=31 AMediaMuxer_new; AMediaMuxer_setLocation; AMediaMuxer_setOrientationHint; -- GitLab From 65f8d6159d6964d7cb373880de605247214da5aa Mon Sep 17 00:00:00 2001 From: Bob Badour Date: Fri, 26 Mar 2021 01:15:09 -0700 Subject: [PATCH 027/694] [LSC] Add LOCAL_LICENSE_KINDS to frameworks/av Added SPDX-license-identifier-Apache-2.0 to: media/libmedia/tests/fuzzer/Android.bp Bug: 68860345 Bug: 151177513 Bug: 151953481 Test: m all Exempt-From-Owner-Approval: janitorial work Change-Id: I92cb14a906e65f1c30e3c3218fc3c36bb89198b1 --- media/libmedia/tests/fuzzer/Android.bp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/media/libmedia/tests/fuzzer/Android.bp b/media/libmedia/tests/fuzzer/Android.bp index e58c396f65..c03b5b1706 100644 --- a/media/libmedia/tests/fuzzer/Android.bp +++ b/media/libmedia/tests/fuzzer/Android.bp @@ -1,3 +1,12 @@ +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "frameworks_av_media_libmedia_license" + // to get the below license kinds: + // SPDX-license-identifier-Apache-2.0 + default_applicable_licenses: ["frameworks_av_media_libmedia_license"], +} + cc_fuzz { name: "libmedia_metadata_fuzzer", srcs: [ @@ -7,4 +16,4 @@ cc_fuzz { "libmedia", "libbinder", ], -} \ No newline at end of file +} -- GitLab From 7115135df868e18866addd89cf26f9da3cb4dce9 Mon Sep 17 00:00:00 2001 From: Ytai Ben-Tsvi Date: Wed, 10 Mar 2021 16:29:01 -0800 Subject: [PATCH 028/694] Adapt to changes in AIDL interfaces There is no semantic change here. Just renaming and versioning of those modules. Test: m Change-Id: Ice10554b017463fc654c241324451de86c2f12fe --- media/libaaudio/src/Android.bp | 9 ++------- media/libaudioclient/Android.bp | 20 ++++++++++++++++---- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index fe2d98eeb0..9d137c857a 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -175,19 +175,14 @@ aidl_interface { "binding/aidl/aaudio/IAAudioService.aidl", ], imports: [ - "audio_common-aidl", + "android.media.audio.common.types", "shared-file-region-aidl", "media_permission-aidl", ], backend: { - cpp: { - enabled: true, - }, java: { - // TODO: need to have audio_common-aidl available in Java to enable - // this. - enabled: false, + sdk_version: "module_current", }, }, } diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 64a335ab63..0c84ccc19b 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -352,7 +352,7 @@ aidl_interface { "aidl/android/media/ExtraAudioDescriptor.aidl", ], imports: [ - "audio_common-aidl", + "android.media.audio.common.types", "media_permission-aidl", ], backend: { @@ -363,6 +363,9 @@ aidl_interface { "com.android.media", ], }, + java: { + sdk_version: "module_current", + }, }, } aidl_interface { @@ -390,7 +393,7 @@ aidl_interface { "aidl/android/media/SoundTriggerSession.aidl", ], imports: [ - "audio_common-aidl", + "android.media.audio.common.types", "audioclient-types-aidl", ], backend: { @@ -401,6 +404,9 @@ aidl_interface { "com.android.media", ], }, + java: { + sdk_version: "module_current", + }, }, } @@ -430,7 +436,7 @@ aidl_interface { "aidl/android/media/IAudioTrackCallback.aidl", ], imports: [ - "audio_common-aidl", + "android.media.audio.common.types", "audioclient-types-aidl", "av-types-aidl", "effect-aidl", @@ -446,6 +452,9 @@ aidl_interface { "com.android.media", ], }, + java: { + sdk_version: "module_current", + }, }, } @@ -465,7 +474,7 @@ aidl_interface { "aidl/android/media/IAudioPolicyServiceClient.aidl", ], imports: [ - "audio_common-aidl", + "android.media.audio.common.types", "audioclient-types-aidl", "audiopolicy-types-aidl", "capture_state_listener-aidl", @@ -480,5 +489,8 @@ aidl_interface { "com.android.media", ], }, + java: { + sdk_version: "module_current", + }, }, } -- GitLab From 13957711d419fa3b442844d28a5a43cc967c77d2 Mon Sep 17 00:00:00 2001 From: Gopalakrishnan Nallasamy Date: Mon, 29 Mar 2021 10:36:15 -0700 Subject: [PATCH 029/694] AppendData:MPEG4Writer&Extractor,MediaAppender Bug: 154734325 Append media data to an MPEG4File. Changes were made in MPEG4Extractor to pass sample offsets of existing data in file to the writer. MediaAppender class takes cares of parsing and preparing exisiting MPEG4 file to be added with new data. Data that is present in the file is not copied again, hence that pass happens fast. New data is appended at the end of the file. Test: atest android.mediav2.cts.MuxerTest Test: atest android.media.cts.MediaMuxerTest Test: atest android.media.cts.MediaRecorderTest Test: atest android.media.cts.MediaExtractorTest Change-Id: I3f2bfa6b92d85c3a87ac740b2d401dcb10d7976e --- media/extractors/mp4/MPEG4Extractor.cpp | 24 + media/libstagefright/Android.bp | 1 + media/libstagefright/MPEG4Writer.cpp | 82 +++- media/libstagefright/MediaAppender.cpp | 425 ++++++++++++++++++ media/libstagefright/MediaMuxer.cpp | 36 ++ media/libstagefright/MediaTrack.cpp | 8 + media/libstagefright/NuMediaExtractor.cpp | 5 + media/libstagefright/Utils.cpp | 21 +- .../include/media/stagefright/MPEG4Writer.h | 1 + .../include/media/stagefright/MediaAppender.h | 100 +++++ .../include/media/stagefright/MediaMuxer.h | 34 +- .../media/stagefright/MediaMuxerBase.h | 133 ++++++ .../include/media/stagefright/MetaDataBase.h | 5 + .../media/stagefright/NuMediaExtractor.h | 2 + media/ndk/NdkMediaExtractor.cpp | 17 + media/ndk/NdkMediaFormat.cpp | 3 + media/ndk/NdkMediaMuxer.cpp | 61 ++- media/ndk/include/media/NdkMediaFormat.h | 3 + media/ndk/include/media/NdkMediaMuxer.h | 46 ++ media/ndk/libmediandk.map.txt | 6 + 20 files changed, 967 insertions(+), 46 deletions(-) create mode 100644 media/libstagefright/MediaAppender.cpp create mode 100644 media/libstagefright/include/media/stagefright/MediaAppender.h create mode 100644 media/libstagefright/include/media/stagefright/MediaMuxerBase.h diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 129c95558b..159b3d2e2b 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6258,6 +6258,19 @@ media_status_t MPEG4Source::read( if (isSyncSample) { AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } + + AMediaFormat_setInt64( + meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, + offset); + + if (mSampleTable != nullptr && + mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + AMediaFormat_setInt64( + meta, + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + mSampleTable->getLastSampleIndexInChunk()); + } + ++mCurrentSampleIndex; } } @@ -6407,6 +6420,17 @@ media_status_t MPEG4Source::read( AMediaFormat_setInt32(meta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, 1); } + AMediaFormat_setInt64( + meta, "sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET*/, offset); + + if (mSampleTable != nullptr && + mCurrentSampleIndex == mSampleTable->getLastSampleIndexInChunk()) { + AMediaFormat_setInt64( + meta, + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + mSampleTable->getLastSampleIndexInChunk()); + } + ++mCurrentSampleIndex; *out = mBuffer; diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index 52434b3cf6..d6e36b94c3 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -274,6 +274,7 @@ cc_library { "MPEG2TSWriter.cpp", "MPEG4Writer.cpp", "MediaAdapter.cpp", + "MediaAppender.cpp", "MediaClock.cpp", "MediaCodec.cpp", "MediaCodecList.cpp", diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp index 76a5cabde7..5c3923966c 100644 --- a/media/libstagefright/MPEG4Writer.cpp +++ b/media/libstagefright/MPEG4Writer.cpp @@ -519,12 +519,12 @@ void MPEG4Writer::initInternal(int fd, bool isFirstSession) { mSendNotify = false; mWriteSeekErr = false; mFallocateErr = false; - // Reset following variables for all the sessions and they will be // initialized in start(MetaData *param). mIsRealTimeRecording = true; mUse4ByteNalLength = true; mOffset = 0; + mMaxOffsetAppend = 0; mPreAllocateFileEndOffset = 0; mMdatOffset = 0; mMdatEndOffset = 0; @@ -992,6 +992,19 @@ status_t MPEG4Writer::start(MetaData *param) { seekOrPostError(mFd, mFreeBoxOffset, SEEK_SET); writeInt32(mInMemoryCacheSize); write("free", 4); + if (mInMemoryCacheSize >= 8) { + off64_t bufSize = mInMemoryCacheSize - 8; + char* zeroBuffer = new (std::nothrow) char[bufSize]; + if (zeroBuffer) { + std::fill_n(zeroBuffer, bufSize, '0'); + writeOrPostError(mFd, zeroBuffer, bufSize); + delete [] zeroBuffer; + } else { + ALOGW("freebox in file isn't initialized to 0"); + } + } else { + ALOGW("freebox size is less than 8:%" PRId64, mInMemoryCacheSize); + } mMdatOffset = mFreeBoxOffset + mInMemoryCacheSize; } else { mMdatOffset = mOffset; @@ -1541,6 +1554,26 @@ off64_t MPEG4Writer::addSample_l( MediaBuffer *buffer, bool usePrefix, uint32_t tiffHdrOffset, size_t *bytesWritten) { off64_t old_offset = mOffset; + int64_t offset; + ALOGV("buffer->range_length:%lld", (long long)buffer->range_length()); + if (buffer->meta_data().findInt64(kKeySampleFileOffset, &offset)) { + ALOGV("offset:%lld, old_offset:%lld", (long long)offset, (long long)old_offset); + if (old_offset == offset) { + mOffset += buffer->range_length(); + } else { + ALOGV("offset and old_offset are not equal! diff:%lld", (long long)offset - old_offset); + mOffset = offset + buffer->range_length(); + // mOffset += buffer->range_length() + offset - old_offset; + } + *bytesWritten = buffer->range_length(); + ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld, bytesWritten:%lld", (long long)mOffset, + (long long)mMaxOffsetAppend, (long long)*bytesWritten); + mMaxOffsetAppend = std::max(mOffset, mMaxOffsetAppend); + seekOrPostError(mFd, mMaxOffsetAppend, SEEK_SET); + return offset; + } + + ALOGV("mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, (long long)mMaxOffsetAppend); if (usePrefix) { addMultipleLengthPrefixedSamples_l(buffer); @@ -1557,6 +1590,10 @@ off64_t MPEG4Writer::addSample_l( mOffset += buffer->range_length(); } *bytesWritten = mOffset - old_offset; + + ALOGV("mOffset:%lld, old_offset:%lld, bytesWritten:%lld", (long long)mOffset, + (long long)old_offset, (long long)*bytesWritten); + return old_offset; } @@ -1569,6 +1606,7 @@ static void StripStartcode(MediaBuffer *buffer) { (const uint8_t *)buffer->data() + buffer->range_offset(); if (!memcmp(ptr, "\x00\x00\x00\x01", 4)) { + ALOGV("stripping start code"); buffer->set_range( buffer->range_offset() + 4, buffer->range_length() - 4); } @@ -1599,8 +1637,10 @@ void MPEG4Writer::addMultipleLengthPrefixedSamples_l(MediaBuffer *buffer) { } void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { + ALOGV("alp:buffer->range_length:%lld", (long long)buffer->range_length()); size_t length = buffer->range_length(); if (mUse4ByteNalLength) { + ALOGV("mUse4ByteNalLength"); uint8_t x[4]; x[0] = length >> 24; x[1] = (length >> 16) & 0xff; @@ -1610,6 +1650,7 @@ void MPEG4Writer::addLengthPrefixedSample_l(MediaBuffer *buffer) { writeOrPostError(mFd, (const uint8_t*)buffer->data() + buffer->range_offset(), length); mOffset += length + 4; } else { + ALOGV("mUse2ByteNalLength"); CHECK_LT(length, 65536u); uint8_t x[2]; @@ -2762,6 +2803,9 @@ void MPEG4Writer::threadFunc() { } writeAllChunks(); + ALOGV("threadFunc mOffset:%lld, mMaxOffsetAppend:%lld", (long long)mOffset, + (long long)mMaxOffsetAppend); + mOffset = std::max(mOffset, mMaxOffsetAppend); } status_t MPEG4Writer::startWriterThread() { @@ -3323,6 +3367,7 @@ status_t MPEG4Writer::Track::threadEntry() { uint32_t lastSamplesPerChunk = 0; int64_t lastSampleDurationUs = -1; // Duration calculated from EOS buffer and its timestamp int64_t lastSampleDurationTicks = -1; // Timescale based ticks + int64_t sampleFileOffset = -1; if (mIsAudio) { prctl(PR_SET_NAME, (unsigned long)"MP4WtrAudTrkThread", 0, 0, 0); @@ -3342,6 +3387,7 @@ status_t MPEG4Writer::Track::threadEntry() { MediaBufferBase *buffer; const char *trackName = getTrackType(); while (!mDone && (err = mSource->read(&buffer)) == OK) { + ALOGV("read:buffer->range_length:%lld", (long long)buffer->range_length()); int32_t isEOS = false; if (buffer->range_length() == 0) { if (buffer->meta_data().findInt32(kKeyIsEndOfStream, &isEOS) && isEOS) { @@ -3448,6 +3494,14 @@ status_t MPEG4Writer::Track::threadEntry() { continue; } } + if (!buffer->meta_data().findInt64(kKeySampleFileOffset, &sampleFileOffset)) { + sampleFileOffset = -1; + } + int64_t lastSample = -1; + if (!buffer->meta_data().findInt64(kKeyLastSampleIndexInChunk, &lastSample)) { + lastSample = -1; + } + ALOGV("sampleFileOffset:%lld", (long long)sampleFileOffset); /* * Reserve space in the file for the current sample + to be written MOOV box. If reservation @@ -3455,7 +3509,7 @@ status_t MPEG4Writer::Track::threadEntry() { * write MOOV box successfully as space for the same was reserved in the prior call. * Release the current buffer/sample here. */ - if (!mOwner->preAllocate(buffer->range_length())) { + if (sampleFileOffset == -1 && !mOwner->preAllocate(buffer->range_length())) { buffer->release(); buffer = nullptr; break; @@ -3466,9 +3520,14 @@ status_t MPEG4Writer::Track::threadEntry() { // Make a deep copy of the MediaBuffer and Metadata and release // the original as soon as we can MediaBuffer *copy = new MediaBuffer(buffer->range_length()); - memcpy(copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(), - buffer->range_length()); + if (sampleFileOffset != -1) { + copy->meta_data().setInt64(kKeySampleFileOffset, sampleFileOffset); + } else { + memcpy(copy->data(), (uint8_t*)buffer->data() + buffer->range_offset(), + buffer->range_length()); + } copy->set_range(0, buffer->range_length()); + meta_data = new MetaData(buffer->meta_data()); buffer->release(); buffer = NULL; @@ -3476,14 +3535,16 @@ status_t MPEG4Writer::Track::threadEntry() { copy->meta_data().setInt32(kKeyExifTiffOffset, tiffHdrOffset); } bool usePrefix = this->usePrefix() && !isExif; - - if (usePrefix) StripStartcode(copy); - + if (sampleFileOffset == -1 && usePrefix) { + StripStartcode(copy); + } size_t sampleSize = copy->range_length(); - if (usePrefix) { + if (sampleFileOffset == -1 && usePrefix) { if (mOwner->useNalLengthFour()) { + ALOGV("nallength4"); sampleSize += 4; } else { + ALOGV("nallength2"); sampleSize += 2; } } @@ -3778,7 +3839,8 @@ status_t MPEG4Writer::Track::threadEntry() { chunkTimestampUs = timestampUs; } else { int64_t chunkDurationUs = timestampUs - chunkTimestampUs; - if (chunkDurationUs > interleaveDurationUs) { + if (chunkDurationUs > interleaveDurationUs || lastSample > 1) { + ALOGV("lastSample:%lld", (long long)lastSample); if (chunkDurationUs > mMaxChunkDurationUs) { mMaxChunkDurationUs = chunkDurationUs; } @@ -5331,4 +5393,4 @@ void MPEG4Writer::writeGeoDataBox() { endBox(); } -} // namespace android +} // namespace android \ No newline at end of file diff --git a/media/libstagefright/MediaAppender.cpp b/media/libstagefright/MediaAppender.cpp new file mode 100644 index 0000000000..5d80b304bc --- /dev/null +++ b/media/libstagefright/MediaAppender.cpp @@ -0,0 +1,425 @@ +/* + * Copyright (C) 2020 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//#define LOG_NDEBUG 0 +#define LOG_TAG "MediaAppender" + +#include +#include +#include +#include +// TODO : check if this works for NDK apps without JVM +// #include + +namespace android { + +struct MediaAppender::sampleDataInfo { + size_t size; + int64_t time; + size_t exTrackIndex; + sp meta; +}; + +sp MediaAppender::create(int fd, AppendMode mode) { + if (fd < 0) { + ALOGE("invalid file descriptor"); + return nullptr; + } + if (!(mode >= APPEND_MODE_FIRST && mode <= APPEND_MODE_LAST)) { + ALOGE("invalid mode %d", mode); + return nullptr; + } + sp ma = new (std::nothrow) MediaAppender(fd, mode); + if (ma->init() != OK) { + return nullptr; + } + return ma; +} + +// TODO: inject mediamuxer and mediaextractor objects. +// TODO: @format is not required as an input if we can sniff the file and find the format of +// the existing content. +// TODO: Code it to the interface(MediaAppender), and have a separate MediaAppender NDK +MediaAppender::MediaAppender(int fd, AppendMode mode) + : mFd(fd), + mMode(mode), + // TODO : check if this works for NDK apps without JVM + // mExtractor(new NuMediaExtractor(NdkJavaVMHelper::getJNIEnv() != nullptr + // ? NuMediaExtractor::EntryPoint::NDK_WITH_JVM + // : NuMediaExtractor::EntryPoint::NDK_NO_JVM)), + mExtractor(new (std::nothrow) NuMediaExtractor(NuMediaExtractor::EntryPoint::NDK_WITH_JVM)), + mTrackCount(0), + mState(UNINITIALIZED) { + ALOGV("MediaAppender::MediaAppender mode:%d", mode); + } + +status_t MediaAppender::init() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::init"); + status_t status = mExtractor->setDataSource(mFd, 0, lseek(mFd, 0, SEEK_END)); + if (status != OK) { + ALOGE("extractor_setDataSource failed, status :%d", status); + return status; + } + + if (strcmp("MPEG4Extractor", mExtractor->getName()) == 0) { + mFormat = MediaMuxer::OUTPUT_FORMAT_MPEG_4; + } else { + ALOGE("Unsupported format, extractor name:%s", mExtractor->getName()); + return ERROR_UNSUPPORTED; + } + + mTrackCount = mExtractor->countTracks(); + ALOGV("mTrackCount:%zu", mTrackCount); + if (mTrackCount == 0) { + ALOGE("no tracks are present"); + return ERROR_MALFORMED; + } + size_t exTrackIndex = 0; + ssize_t audioTrackIndex = -1, videoTrackIndex = -1; + bool audioSyncSampleTimeSet = false; + + while (exTrackIndex < mTrackCount) { + sp fmt; + status = mExtractor->getTrackFormat(exTrackIndex, &fmt, 0); + if (status != OK) { + ALOGE("getTrackFormat failed for trackIndex:%zu, status:%d", exTrackIndex, status); + return status; + } + AString mime; + if (fmt->findString("mime", &mime)) { + if (!strncasecmp(mime.c_str(), "video/", 6)) { + ALOGV("VideoTrack"); + if (videoTrackIndex != -1) { + ALOGE("Not more than one video track is supported"); + return ERROR_UNSUPPORTED; + } + videoTrackIndex = exTrackIndex; + } else if (!strncasecmp(mime.c_str(), "audio/", 6)) { + ALOGV("AudioTrack"); + if (audioTrackIndex != -1) { + ALOGE("Not more than one audio track is supported"); + } + audioTrackIndex = exTrackIndex; + } else { + ALOGV("Neither Video nor Audio track"); + } + } + mFmtIndexMap.emplace(exTrackIndex, fmt); + mSampleCountVect.emplace_back(0); + mMaxTimestampVect.emplace_back(0); + mLastSyncSampleTimeVect.emplace_back(0); + status = mExtractor->selectTrack(exTrackIndex); + if (status != OK) { + ALOGE("selectTrack failed for trackIndex:%zu, status:%d", exTrackIndex, status); + return status; + } + ++exTrackIndex; + } + + ALOGV("AudioTrackIndex:%zu, VideoTrackIndex:%zu", audioTrackIndex, videoTrackIndex); + + do { + sampleDataInfo tmpSDI; + // TODO: read info into members of the struct sampleDataInfo directly + size_t sampleSize; + status = mExtractor->getSampleSize(&sampleSize); + if (status != OK) { + ALOGE("getSampleSize failed, status:%d", status); + return status; + } + mSampleSizeVect.emplace_back(sampleSize); + tmpSDI.size = sampleSize; + int64_t sampleTime = 0; + status = mExtractor->getSampleTime(&sampleTime); + if (status != OK) { + ALOGE("getSampleTime failed, status:%d", status); + return status; + } + mSampleTimeVect.emplace_back(sampleTime); + tmpSDI.time = sampleTime; + status = mExtractor->getSampleTrackIndex(&exTrackIndex); + if (status != OK) { + ALOGE("getSampleTrackIndex failed, status:%d", status); + return status; + } + mSampleIndexVect.emplace_back(exTrackIndex); + tmpSDI.exTrackIndex = exTrackIndex; + ++mSampleCountVect[exTrackIndex]; + mMaxTimestampVect[exTrackIndex] = std::max(mMaxTimestampVect[exTrackIndex], sampleTime); + sp sampleMeta; + status = mExtractor->getSampleMeta(&sampleMeta); + if (status != OK) { + ALOGE("getSampleMeta failed, status:%d", status); + return status; + } + mSampleMetaVect.emplace_back(sampleMeta); + int32_t val = 0; + if (sampleMeta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + mLastSyncSampleTimeVect[exTrackIndex] = sampleTime; + } + tmpSDI.meta = sampleMeta; + mSDI.emplace_back(tmpSDI); + } while (mExtractor->advance() == OK); + + mExtractor.clear(); + + std::sort(mSDI.begin(), mSDI.end(), [](sampleDataInfo& a, sampleDataInfo& b) { + int64_t aOffset, bOffset; + a.meta->findInt64(kKeySampleFileOffset, &aOffset); + b.meta->findInt64(kKeySampleFileOffset, &bOffset); + return aOffset < bOffset; + }); + for (int64_t syncSampleTime : mLastSyncSampleTimeVect) { + ALOGV("before ignoring frames, mLastSyncSampleTimeVect:%lld", (long long)syncSampleTime); + } + ALOGV("mMode:%u", mMode); + if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex != -1 ) { + ALOGV("Video track is present"); + bool lastVideoIframe = false; + size_t lastVideoIframeOffset = 0; + int64_t lastVideoSampleTime = -1; + for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { + if (rItr->exTrackIndex != videoTrackIndex) { + continue; + } + if (lastVideoSampleTime == -1) { + lastVideoSampleTime = rItr->time; + } + int64_t offset = 0; + if (!rItr->meta->findInt64(kKeySampleFileOffset, &offset) || offset == 0) { + ALOGE("Missing offset"); + return ERROR_MALFORMED; + } + ALOGV("offset:%lld", (long long)offset); + int32_t val = 0; + if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + ALOGV("sampleTime:%lld", (long long)rItr->time); + ALOGV("lastVideoSampleTime:%lld", (long long)lastVideoSampleTime); + if (lastVideoIframe == false && (lastVideoSampleTime - rItr->time) > + 1000000/* Track interleaving duration in MPEG4Writer*/) { + ALOGV("lastVideoIframe got chosen"); + lastVideoIframe = true; + mLastSyncSampleTimeVect[videoTrackIndex] = rItr->time; + lastVideoIframeOffset = offset; + ALOGV("lastVideoIframeOffset:%lld", (long long)offset); + break; + } + } + } + if (lastVideoIframe == false) { + ALOGV("Need to rewrite all samples"); + mLastSyncSampleTimeVect[videoTrackIndex] = 0; + lastVideoIframeOffset = 0; + } + unsigned int framesIgnoredCount = 0; + for (auto itr = mSDI.begin(); itr != mSDI.end();) { + int64_t offset = 0; + ALOGV("trackIndex:%zu, %" PRId64 "", itr->exTrackIndex, itr->time); + if (itr->meta->findInt64(kKeySampleFileOffset, &offset) && + offset >= lastVideoIframeOffset) { + ALOGV("offset:%lld", (long long)offset); + if (!audioSyncSampleTimeSet && audioTrackIndex != -1 && + audioTrackIndex == itr->exTrackIndex) { + mLastSyncSampleTimeVect[audioTrackIndex] = itr->time; + audioSyncSampleTimeSet = true; + } + itr = mSDI.erase(itr); + ++framesIgnoredCount; + } else { + ++itr; + } + } + ALOGV("framesIgnoredCount:%u", framesIgnoredCount); + } + + if (mMode == APPEND_MODE_IGNORE_LAST_VIDEO_GOP && videoTrackIndex == -1 && + audioTrackIndex != -1) { + ALOGV("Only AudioTrack is present"); + for (auto rItr = mSDI.rbegin(); rItr != mSDI.rend(); ++rItr) { + int32_t val = 0; + if (rItr->meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + mLastSyncSampleTimeVect[audioTrackIndex] = rItr->time; + break; + } + } + unsigned int framesIgnoredCount = 0; + for (auto itr = mSDI.begin(); itr != mSDI.end();) { + if (itr->time >= mLastSyncSampleTimeVect[audioTrackIndex]) { + itr = mSDI.erase(itr); + ++framesIgnoredCount; + } else { + ++itr; + } + } + ALOGV("framesIgnoredCount :%u", framesIgnoredCount); + } + + for (size_t i = 0; i < mLastSyncSampleTimeVect.size(); ++i) { + ALOGV("mLastSyncSampleTimeVect[%zu]:%lld", i, (long long)mLastSyncSampleTimeVect[i]); + mFmtIndexMap[i]->setInt64( + "sample-time-before-append" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, + mLastSyncSampleTimeVect[i]); + } + for (size_t i = 0; i < mMaxTimestampVect.size(); ++i) { + ALOGV("mMaxTimestamp[%zu]:%lld", i, (long long)mMaxTimestampVect[i]); + } + for (size_t i = 0; i < mSampleCountVect.size(); ++i) { + ALOGV("SampleCountVect[%zu]:%zu", i, mSampleCountVect[i]); + } + mState = INITIALIZED; + return OK; +} + +MediaAppender::~MediaAppender() { + ALOGV("MediaAppender::~MediaAppender"); + mMuxer.clear(); + mExtractor.clear(); +} + +status_t MediaAppender::start() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::start"); + if (mState != INITIALIZED) { + ALOGE("MediaAppender::start() is called in invalid state %d", mState); + return INVALID_OPERATION; + } + mMuxer = new (std::nothrow) MediaMuxer(mFd, mFormat); + for (const auto& n : mFmtIndexMap) { + ssize_t muxIndex = mMuxer->addTrack(n.second); + if (muxIndex < 0) { + ALOGE("addTrack failed"); + return UNKNOWN_ERROR; + } + mTrackIndexMap.emplace(n.first, muxIndex); + } + ALOGV("trackIndexmap size:%zu", mTrackIndexMap.size()); + + status_t status = mMuxer->start(); + if (status != OK) { + ALOGE("muxer start failed:%d", status); + return status; + } + + ALOGV("Sorting samples based on their offsets"); + for (int i = 0; i < mSDI.size(); ++i) { + ALOGV("i:%d", i + 1); + /* TODO : Allocate a single allocation of the max size, and reuse it across ABuffers if + * using new ABuffer(void *, size_t). + */ + sp data = new (std::nothrow) ABuffer(mSDI[i].size); + if (data == nullptr) { + ALOGE("memory allocation failed"); + return NO_MEMORY; + } + data->setRange(0, mSDI[i].size); + int32_t val = 0; + int sampleFlags = 0; + if (mSDI[i].meta->findInt32(kKeyIsSyncFrame, &val) && val != 0) { + sampleFlags |= MediaCodec::BUFFER_FLAG_SYNCFRAME; + } + + int64_t val64; + if (mSDI[i].meta->findInt64(kKeySampleFileOffset, &val64)) { + ALOGV("SampleFileOffset Found :%zu:%lld:%lld", mSDI[i].exTrackIndex, + (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); + sp bufMeta = data->meta(); + bufMeta->setInt64("sample-file-offset" /*AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND*/, + val64); + } + if (mSDI[i].meta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { + ALOGV("kKeyLastSampleIndexInChunk Found %lld:%lld", + (long long)mSampleCountVect[mSDI[i].exTrackIndex], (long long)val64); + sp bufMeta = data->meta(); + bufMeta->setInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + val64); + } + status = mMuxer->writeSampleData(data, mTrackIndexMap[mSDI[i].exTrackIndex], mSDI[i].time, + sampleFlags); + if (status != OK) { + ALOGE("muxer writeSampleData failed:%d", status); + return status; + } + } + mState = STARTED; + return OK; +} + +status_t MediaAppender::stop() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::stop"); + if (mState == STARTED) { + status_t status = mMuxer->stop(); + if (status != OK) { + mState = ERROR; + } else { + mState = STOPPED; + } + return status; + } else { + ALOGE("stop() is called in invalid state %d", mState); + return INVALID_OPERATION; + } +} + +ssize_t MediaAppender::getTrackCount() { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::getTrackCount"); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackCount() is called in invalid state %d", mState); + return -1; + } + return mTrackCount; +} + +sp MediaAppender::getTrackFormat(size_t idx) { + std::scoped_lock lock(mMutex); + ALOGV("MediaAppender::getTrackFormat"); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackFormat() is called in invalid state %d", mState); + return nullptr; + } + if (idx < 0 || idx >= mTrackCount) { + ALOGE("getTrackFormat() idx is out of range"); + return nullptr; + } + return mFmtIndexMap[idx]; +} + +status_t MediaAppender::writeSampleData(const sp& buffer, size_t trackIndex, + int64_t timeUs, uint32_t flags) { + std::scoped_lock lock(mMutex); + ALOGV("writeSampleData:trackIndex:%zu, time:%" PRId64 "", trackIndex, timeUs); + return mMuxer->writeSampleData(buffer, trackIndex, timeUs, flags); +} + +status_t MediaAppender::setOrientationHint([[maybe_unused]] int degrees) { + ALOGE("setOrientationHint not supported. Has to be called prior to start on initial muxer"); + return ERROR_UNSUPPORTED; +}; + +status_t MediaAppender::setLocation([[maybe_unused]] int latit, [[maybe_unused]] int longit) { + ALOGE("setLocation not supported. Has to be called prior to start on initial muxer"); + return ERROR_UNSUPPORTED; +} + +ssize_t MediaAppender::addTrack([[maybe_unused]] const sp &format) { + ALOGE("addTrack not supported"); + return ERROR_UNSUPPORTED; +} + +} // namespace android diff --git a/media/libstagefright/MediaMuxer.cpp b/media/libstagefright/MediaMuxer.cpp index c91386d489..a946f71e9b 100644 --- a/media/libstagefright/MediaMuxer.cpp +++ b/media/libstagefright/MediaMuxer.cpp @@ -76,6 +76,7 @@ MediaMuxer::~MediaMuxer() { mFileMeta.clear(); mWriter.clear(); mTrackList.clear(); + mFormatList.clear(); } ssize_t MediaMuxer::addTrack(const sp &format) { @@ -109,6 +110,8 @@ ssize_t MediaMuxer::addTrack(const sp &format) { ALOGW("addTrack() setCaptureRate failed :%d", result); } } + + mFormatList.add(format); return mTrackList.add(newTrack); } @@ -224,9 +227,42 @@ status_t MediaMuxer::writeSampleData(const sp &buffer, size_t trackInde ALOGV("BUFFER_FLAG_EOS"); } + sp bufMeta = buffer->meta(); + int64_t val64; + if (bufMeta->findInt64("sample-file-offset", &val64)) { + sampleMetaData.setInt64(kKeySampleFileOffset, val64); + } + if (bufMeta->findInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + &val64)) { + sampleMetaData.setInt64(kKeyLastSampleIndexInChunk, val64); + } + sp currentTrack = mTrackList[trackIndex]; // This pushBuffer will wait until the mediaBuffer is consumed. return currentTrack->pushBuffer(mediaBuffer); } +ssize_t MediaMuxer::getTrackCount() { + Mutex::Autolock autoLock(mMuxerLock); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackCount() must be called either in INITIALIZED or STARTED state"); + return -1; + } + return mTrackList.size(); +} + +sp MediaMuxer::getTrackFormat([[maybe_unused]] size_t idx) { + Mutex::Autolock autoLock(mMuxerLock); + if (mState != INITIALIZED && mState != STARTED) { + ALOGE("getTrackFormat() must be called either in INITIALIZED or STARTED state"); + return nullptr; + } + if (idx < 0 || idx >= mFormatList.size()) { + ALOGE("getTrackFormat() idx is out of range"); + return nullptr; + } + return mFormatList[idx]; +} + } // namespace android diff --git a/media/libstagefright/MediaTrack.cpp b/media/libstagefright/MediaTrack.cpp index 24ba38af87..2447f5e904 100644 --- a/media/libstagefright/MediaTrack.cpp +++ b/media/libstagefright/MediaTrack.cpp @@ -133,6 +133,14 @@ status_t MediaTrackCUnwrapper::read(MediaBufferBase **buffer, const ReadOptions if (format->mFormat->findInt64("target-time", &val64)) { meta.setInt64(kKeyTargetTime, val64); } + if (format->mFormat->findInt64("sample-file-offset", &val64)) { + meta.setInt64(kKeySampleFileOffset, val64); + } + if (format->mFormat->findInt64( + "last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + &val64)) { + meta.setInt64(kKeyLastSampleIndexInChunk, val64); + } int32_t val32; if (format->mFormat->findInt32("is-sync-frame", &val32)) { meta.setInt32(kKeyIsSyncFrame, val32); diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp index 3ee78d04f5..f54a56f5c2 100644 --- a/media/libstagefright/NuMediaExtractor.cpp +++ b/media/libstagefright/NuMediaExtractor.cpp @@ -189,6 +189,11 @@ status_t NuMediaExtractor::setDataSource(const sp &source) { return err; } +const char* NuMediaExtractor::getName() const { + Mutex::Autolock autoLock(mLock); + return mImpl == nullptr ? nullptr : mImpl->name().string(); +} + static String8 arrayToString(const std::vector &array) { String8 result; for (size_t i = 0; i < array.size(); i++) { diff --git a/media/libstagefright/Utils.cpp b/media/libstagefright/Utils.cpp index 5ede871284..04a9b17906 100644 --- a/media/libstagefright/Utils.cpp +++ b/media/libstagefright/Utils.cpp @@ -725,16 +725,19 @@ static std::vector> floatMappings { } }; -static std::vector> int64Mappings { +static std::vector> int64Mappings { { - { "exif-offset", kKeyExifOffset }, - { "exif-size", kKeyExifSize }, - { "xmp-offset", kKeyXmpOffset }, - { "xmp-size", kKeyXmpSize }, - { "target-time", kKeyTargetTime }, - { "thumbnail-time", kKeyThumbnailTime }, - { "timeUs", kKeyTime }, - { "durationUs", kKeyDuration }, + { "exif-offset", kKeyExifOffset}, + { "exif-size", kKeyExifSize}, + { "xmp-offset", kKeyXmpOffset}, + { "xmp-size", kKeyXmpSize}, + { "target-time", kKeyTargetTime}, + { "thumbnail-time", kKeyThumbnailTime}, + { "timeUs", kKeyTime}, + { "durationUs", kKeyDuration}, + { "sample-file-offset", kKeySampleFileOffset}, + { "last-sample-index-in-chunk", kKeyLastSampleIndexInChunk}, + { "sample-time-before-append", kKeySampleTimeBeforeAppend}, } }; diff --git a/media/libstagefright/include/media/stagefright/MPEG4Writer.h b/media/libstagefright/include/media/stagefright/MPEG4Writer.h index 2582ed0815..7f2728ebd8 100644 --- a/media/libstagefright/include/media/stagefright/MPEG4Writer.h +++ b/media/libstagefright/include/media/stagefright/MPEG4Writer.h @@ -106,6 +106,7 @@ private: off64_t mOffset; off64_t mPreAllocateFileEndOffset; //End of file offset during preallocation. off64_t mMdatOffset; + off64_t mMaxOffsetAppend; // File offset written upto while appending. off64_t mMdatEndOffset; // End offset of mdat atom. uint8_t *mInMemoryCache; off64_t mInMemoryCacheOffset; diff --git a/media/libstagefright/include/media/stagefright/MediaAppender.h b/media/libstagefright/include/media/stagefright/MediaAppender.h new file mode 100644 index 0000000000..c2f6f1045b --- /dev/null +++ b/media/libstagefright/include/media/stagefright/MediaAppender.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_APPENDER_H +#define ANDROID_MEDIA_APPENDER_H + +#include +#include +#include + +namespace android { + +struct MediaAppender : public MediaMuxerBase { +public: + enum AppendMode { + APPEND_MODE_FIRST = 0, + APPEND_MODE_IGNORE_LAST_VIDEO_GOP = APPEND_MODE_FIRST, + APPEND_MODE_ADD_TO_EXISTING_DATA = 1, + APPEND_MODE_LAST = APPEND_MODE_ADD_TO_EXISTING_DATA, + }; + + static sp create(int fd, AppendMode mode); + + virtual ~MediaAppender(); + + status_t init(); + + status_t start(); + + status_t stop(); + + status_t writeSampleData(const sp& buffer, size_t trackIndex, int64_t timeUs, + uint32_t flags); + + status_t setOrientationHint(int degrees); + + status_t setLocation(int latitude, int longitude); + + ssize_t addTrack(const sp &format); + + ssize_t getTrackCount(); + + sp getTrackFormat(size_t idx); + +private: + MediaAppender(int fd, AppendMode mode); + + int mFd; + MediaMuxer::OutputFormat mFormat; + AppendMode mMode; + sp mExtractor; + sp mMuxer; + size_t mTrackCount; + // Map track index given by extractor to the ones received from muxer. + std::map mTrackIndexMap; + // Count of the samples in each track, indexed by extractor track ids. + std::vector mSampleCountVect; + // Extractor track index of samples. + std::vector mSampleIndexVect; + // Track format indexed by extractor track ids. + std::map> mFmtIndexMap; + // Size of samples. + std::vector mSampleSizeVect; + // Presentation time stamp of samples. + std::vector mSampleTimeVect; + // Timestamp of last sample of tracks. + std::vector mMaxTimestampVect; + // Metadata of samples. + std::vector> mSampleMetaVect; + std::mutex mMutex; + // Timestamp of the last sync sample of tracks. + std::vector mLastSyncSampleTimeVect; + + struct sampleDataInfo; + std::vector mSDI; + + enum : int { + UNINITIALIZED, + INITIALIZED, + STARTED, + STOPPED, + ERROR, + } mState GUARDED_BY(mMutex); +}; + +} // namespace android +#endif // ANDROID_MEDIA_APPENDER_H \ No newline at end of file diff --git a/media/libstagefright/include/media/stagefright/MediaMuxer.h b/media/libstagefright/include/media/stagefright/MediaMuxer.h index a1b9465d65..e97a65ee6b 100644 --- a/media/libstagefright/include/media/stagefright/MediaMuxer.h +++ b/media/libstagefright/include/media/stagefright/MediaMuxer.h @@ -22,7 +22,12 @@ #include #include +#include +#include +#include + #include "media/stagefright/foundation/ABase.h" +#include "MediaMuxerBase.h" namespace android { @@ -33,6 +38,7 @@ class MediaBuffer; struct MediaSource; class MetaData; struct MediaWriter; +struct NuMediaExtractor; // MediaMuxer is used to mux multiple tracks into a video. Currently, we only // support a mp4 file as the output. @@ -40,19 +46,8 @@ struct MediaWriter; // Constructor -> addTrack+ -> start -> writeSampleData+ -> stop // If muxing operation need to be cancelled, the app is responsible for // deleting the output file after stop. -struct MediaMuxer : public RefBase { +struct MediaMuxer : public MediaMuxerBase { public: - // Please update media/java/android/media/MediaMuxer.java if the - // OutputFormat is updated. - enum OutputFormat { - OUTPUT_FORMAT_MPEG_4 = 0, - OUTPUT_FORMAT_WEBM = 1, - OUTPUT_FORMAT_THREE_GPP = 2, - OUTPUT_FORMAT_HEIF = 3, - OUTPUT_FORMAT_OGG = 4, - OUTPUT_FORMAT_LIST_END // must be last - used to validate format type - }; - // Construct the muxer with the file descriptor. Note that the MediaMuxer // will close this file at stop(). MediaMuxer(int fd, OutputFormat format); @@ -117,10 +112,25 @@ public: status_t writeSampleData(const sp &buffer, size_t trackIndex, int64_t timeUs, uint32_t flags) ; + /** + * Gets the number of tracks added successfully. Should be called in + * INITIALIZED(after constructor) or STARTED(after start()) state. + * @return the number of tracks or -1 in wrong state. + */ + ssize_t getTrackCount(); + + /** + * Gets the format of the track by their index. + * @param idx : index of the track whose format is wanted. + * @return smart pointer to AMessage containing the format details. + */ + sp getTrackFormat(size_t idx); + private: const OutputFormat mFormat; sp mWriter; Vector< sp > mTrackList; // Each track has its MediaAdapter. + Vector< sp > mFormatList; // Format of each track. sp mFileMeta; // Metadata for the whole file. Mutex mMuxerLock; diff --git a/media/libstagefright/include/media/stagefright/MediaMuxerBase.h b/media/libstagefright/include/media/stagefright/MediaMuxerBase.h new file mode 100644 index 0000000000..f02d510835 --- /dev/null +++ b/media/libstagefright/include/media/stagefright/MediaMuxerBase.h @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEDIA_MUXER_BASE_H_ +#define MEDIA_MUXER_BASE_H_ + +#include +#include "media/stagefright/foundation/ABase.h" + +namespace android { + +struct ABuffer; +struct AMessage; + +// MediaMuxer is used to mux multiple tracks into a video. Currently, we only +// support a mp4 file as the output. +// The expected calling order of the functions is: +// Constructor -> addTrack+ -> start -> writeSampleData+ -> stop +// If muxing operation need to be cancelled, the app is responsible for +// deleting the output file after stop. +struct MediaMuxerBase : public RefBase { +public: + // Please update media/java/android/media/MediaMuxer.java if the + // OutputFormat is updated. + enum OutputFormat { + OUTPUT_FORMAT_MPEG_4 = 0, + OUTPUT_FORMAT_WEBM = 1, + OUTPUT_FORMAT_THREE_GPP = 2, + OUTPUT_FORMAT_HEIF = 3, + OUTPUT_FORMAT_OGG = 4, + OUTPUT_FORMAT_LIST_END // must be last - used to validate format type + }; + + // Construct the muxer with the file descriptor. Note that the MediaMuxer + // will close this file at stop(). + MediaMuxerBase() {}; + + virtual ~MediaMuxerBase() {}; + + /** + * Add a track with its format information. This should be + * called before start(). + * @param format the track's format. + * @return the track's index or negative number if error. + */ + virtual ssize_t addTrack(const sp &format) = 0; + + /** + * Start muxing. Make sure all the tracks have been added before + * calling this. + */ + virtual status_t start() = 0; + + /** + * Set the orientation hint. + * @param degrees The rotation degrees. It has to be either 0, + * 90, 180 or 270. + * @return OK if no error. + */ + virtual status_t setOrientationHint(int degrees) = 0; + + /** + * Set the location. + * @param latitude The latitude in degree x 1000. Its value must be in the range + * [-900000, 900000]. + * @param longitude The longitude in degree x 1000. Its value must be in the range + * [-1800000, 1800000]. + * @return OK if no error. + */ + virtual status_t setLocation(int latitude, int longitude) = 0; + + /** + * Stop muxing. + * This method is a blocking call. Depending on how + * much data is bufferred internally, the time needed for stopping + * the muxer may be time consuming. UI thread is + * not recommended for launching this call. + * @return OK if no error. + */ + virtual status_t stop() = 0; + + /** + * Send a sample buffer for muxing. + * The buffer can be reused once this method returns. Typically, + * this function won't be blocked for very long, and thus there + * is no need to use a separate thread calling this method to + * push a buffer. + * @param buffer the incoming sample buffer. + * @param trackIndex the buffer's track index number. + * @param timeUs the buffer's time stamp. + * @param flags the only supported flag for now is + * MediaCodec::BUFFER_FLAG_SYNCFRAME. + * @return OK if no error. + */ + virtual status_t writeSampleData(const sp &buffer, size_t trackIndex, + int64_t timeUs, uint32_t flags) = 0 ; + + /** + * Gets the number of tracks added successfully. Should be called in + * INITIALIZED(after constructor) or STARTED(after start()) state. + * @return the number of tracks or -1 in wrong state. + */ + virtual ssize_t getTrackCount() = 0; + + /** + * Gets the format of the track by their index. + * @param idx : index of the track whose format is wanted. + * @return smart pointer to AMessage containing the format details. + */ + virtual sp getTrackFormat(size_t idx) = 0; + +private: + + DISALLOW_EVIL_CONSTRUCTORS(MediaMuxerBase); +}; + +} // namespace android + +#endif // MEDIA_MUXER_BASE_H_ + diff --git a/media/libstagefright/include/media/stagefright/MetaDataBase.h b/media/libstagefright/include/media/stagefright/MetaDataBase.h index 940bd86848..408872fe26 100644 --- a/media/libstagefright/include/media/stagefright/MetaDataBase.h +++ b/media/libstagefright/include/media/stagefright/MetaDataBase.h @@ -264,6 +264,11 @@ enum { // Slow-motion markers kKeySlowMotionMarkers = 'slmo', // raw data, byte array following spec for // MediaFormat#KEY_SLOW_MOTION_MARKERS + + kKeySampleFileOffset = 'sfof', // int64_t, sample's offset in a media file. + kKeyLastSampleIndexInChunk = 'lsic', //int64_t, index of last sample in a chunk. + kKeySampleTimeBeforeAppend = 'lsba', // int64_t, timestamp of last sample of a track. + }; enum { diff --git a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h index 1cad140b03..6aa7c0fd46 100644 --- a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h @@ -102,6 +102,8 @@ struct NuMediaExtractor : public RefBase { status_t setPlaybackId(const String8& playbackId); + const char* getName() const; + protected: virtual ~NuMediaExtractor(); diff --git a/media/ndk/NdkMediaExtractor.cpp b/media/ndk/NdkMediaExtractor.cpp index 0c65e9e552..07fc5de09c 100644 --- a/media/ndk/NdkMediaExtractor.cpp +++ b/media/ndk/NdkMediaExtractor.cpp @@ -419,6 +419,7 @@ int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *ex) { EXPORT media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat *fmt) { + ALOGV("AMediaExtractor_getSampleFormat"); if (fmt == NULL) { return AMEDIA_ERROR_INVALID_PARAMETER; } @@ -428,6 +429,9 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat if (err != OK) { return translate_error(err); } +#ifdef LOG_NDEBUG + sampleMeta->dumpToLog(); +#endif sp meta; AMediaFormat_getFormat(fmt, &meta); @@ -483,6 +487,19 @@ media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat meta->setBuffer(AMEDIAFORMAT_KEY_AUDIO_PRESENTATION_INFO, audioPresentationsData); } + int64_t val64; + if (sampleMeta->findInt64(kKeySampleFileOffset, &val64)) { + meta->setInt64("sample-file-offset", val64); + ALOGV("SampleFileOffset Found"); + } + if (sampleMeta->findInt64(kKeyLastSampleIndexInChunk, &val64)) { + meta->setInt64("last-sample-index-in-chunk" /*AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK*/, + val64); + ALOGV("kKeyLastSampleIndexInChunk Found"); + } + + ALOGV("AMediaFormat_toString:%s", AMediaFormat_toString(fmt)); + return AMEDIA_OK; } diff --git a/media/ndk/NdkMediaFormat.cpp b/media/ndk/NdkMediaFormat.cpp index 1773023f37..c1793ce159 100644 --- a/media/ndk/NdkMediaFormat.cpp +++ b/media/ndk/NdkMediaFormat.cpp @@ -334,6 +334,7 @@ EXPORT const char* AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE = "is-forced-subtitle"; EXPORT const char* AMEDIAFORMAT_KEY_IS_SYNC_FRAME = "is-sync-frame"; EXPORT const char* AMEDIAFORMAT_KEY_I_FRAME_INTERVAL = "i-frame-interval"; EXPORT const char* AMEDIAFORMAT_KEY_LANGUAGE = "language"; +EXPORT const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK = "last-sample-index-in-chunk"; EXPORT const char* AMEDIAFORMAT_KEY_LATENCY = "latency"; EXPORT const char* AMEDIAFORMAT_KEY_LEVEL = "level"; EXPORT const char* AMEDIAFORMAT_KEY_LOCATION = "location"; @@ -359,7 +360,9 @@ EXPORT const char* AMEDIAFORMAT_KEY_PSSH = "pssh"; EXPORT const char* AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP = "push-blank-buffers-on-shutdown"; EXPORT const char* AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER = "repeat-previous-frame-after"; EXPORT const char* AMEDIAFORMAT_KEY_ROTATION = "rotation-degrees"; +EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET = "sample-file-offset"; EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_RATE = "sample-rate"; +EXPORT const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND = "sample-time-before-append"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_HEIGHT = "sar-height"; EXPORT const char* AMEDIAFORMAT_KEY_SAR_WIDTH = "sar-width"; EXPORT const char* AMEDIAFORMAT_KEY_SEI = "sei"; diff --git a/media/ndk/NdkMediaMuxer.cpp b/media/ndk/NdkMediaMuxer.cpp index d1992bf7ed..1965e62502 100644 --- a/media/ndk/NdkMediaMuxer.cpp +++ b/media/ndk/NdkMediaMuxer.cpp @@ -17,28 +17,24 @@ //#define LOG_NDEBUG 0 #define LOG_TAG "NdkMediaMuxer" - -#include +#include +#include +#include #include #include #include - - -#include -#include +#include +#include +#include #include #include -#include -#include -#include - -#include +#include +#include using namespace android; struct AMediaMuxer { - sp mImpl; - + sp mImpl; }; extern "C" { @@ -46,8 +42,15 @@ extern "C" { EXPORT AMediaMuxer* AMediaMuxer_new(int fd, OutputFormat format) { ALOGV("ctor"); - AMediaMuxer *mData = new AMediaMuxer(); - mData->mImpl = new MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); + AMediaMuxer *mData = new (std::nothrow) AMediaMuxer(); + if (mData == nullptr) { + return nullptr; + } + mData->mImpl = new (std::nothrow) MediaMuxer(fd, (android::MediaMuxer::OutputFormat)format); + if (mData->mImpl == nullptr) { + delete mData; + return nullptr; + } return mData; } @@ -94,6 +97,34 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, muxer->mImpl->writeSampleData(buf, trackIdx, info->presentationTimeUs, info->flags)); } +EXPORT +AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) { + ALOGV("append"); + AMediaMuxer* mData = new (std::nothrow) AMediaMuxer(); + if (mData == nullptr) { + return nullptr; + } + mData->mImpl = MediaAppender::create(fd, (android::MediaAppender::AppendMode)mode); + if (mData->mImpl == nullptr) { + delete mData; + return nullptr; + } + return mData; +} + +EXPORT +ssize_t AMediaMuxer_getTrackCount(AMediaMuxer* muxer) { + return muxer->mImpl->getTrackCount(); +} + +EXPORT +AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) { + sp format = muxer->mImpl->getTrackFormat(idx); + if (format != nullptr) { + return AMediaFormat_fromMsg(&format); + } + return nullptr; +} } // extern "C" diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h index 476bbd9d05..fbd855d66b 100644 --- a/media/ndk/include/media/NdkMediaFormat.h +++ b/media/ndk/include/media/NdkMediaFormat.h @@ -307,6 +307,9 @@ extern const char* AMEDIAFORMAT_KEY_SLOW_MOTION_MARKERS __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_THUMBNAIL_CSD_AV1C __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_OFFSET __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_KEY_XMP_SIZE __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK __INTRODUCED_IN(31); +extern const char* AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MAX __INTRODUCED_IN(31); extern const char* AMEDIAFORMAT_VIDEO_QP_B_MIN __INTRODUCED_IN(31); diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h index 519e249503..866ebfd730 100644 --- a/media/ndk/include/media/NdkMediaMuxer.h +++ b/media/ndk/include/media/NdkMediaMuxer.h @@ -54,6 +54,17 @@ typedef enum { AMEDIAMUXER_OUTPUT_FORMAT_THREE_GPP = 2, } OutputFormat; +typedef enum { + /* Last group of pictures(GOP) of video track can be incomplete, so it would be safe to + * scrap that and rewrite. If both audio and video tracks are present in a file, then + * samples of audio track after last GOP of video would be scrapped too. + * If only audio track is present, then no sample would be discarded. + */ + AMEDIAMUXER_APPEND_IGNORE_LAST_VIDEO_GOP = 0, + // Keep all existing samples as it is and append new samples after that only. + AMEDIAMUXER_APPEND_TO_EXISTING_DATA = 1, +} AppendMode; + /** * Create new media muxer. * @@ -138,6 +149,41 @@ media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer, size_t trackIdx, const uint8_t *data, const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21); +/** + * Creates a new media muxer for appending data to an existing MPEG4 file. + * This is a synchronous API call and could take a while to return if the existing file is large. + * Works for only MPEG4 files that contain a) a single audio track, b) a single video track, + * c) a single audio and a single video track. + * @param(fd): needs to be opened with read and write permission. Does not take ownership of + * this fd i.e., caller is responsible for closing fd. + * @param(mode): AppendMode is an enum that specifies one of the modes of appending data. + * @return : Pointer to AMediaMuxer if the file(fd) has tracks already, otherwise, nullptr. + * {@link AMediaMuxer_delete} should be used to free the returned pointer. + * + * Available since API level 31. + */ +AMediaMuxer* AMediaMuxer_append(int fd, AppendMode mode) __INTRODUCED_IN(31); + +/** + * Returns the number of tracks added in the file passed to {@link AMediaMuxer_new} or + * the number of existing tracks in the file passed to {@link AMediaMuxer_append}. + * Should be called in INITIALIZED or STARTED state, otherwise returns -1. + * + * Available since API level 31. + */ +ssize_t AMediaMuxer_getTrackCount(AMediaMuxer*) __INTRODUCED_IN(31); + +/** + * Returns AMediaFormat of the added track with index idx in the file passed to + * {@link AMediaMuxer_new} or the AMediaFormat of the existing track with index idx + * in the file passed to {@link AMediaMuxer_append}. + * Should be called in INITIALIZED or STARTED state, otherwise returns nullptr. + * {@link AMediaFormat_delete} should be used to free the returned pointer. + * + * Available since API level 31. + */ +AMediaFormat* AMediaMuxer_getTrackFormat(AMediaMuxer* muxer, size_t idx) __INTRODUCED_IN(31); + __END_DECLS #endif // _NDK_MEDIA_MUXER_H diff --git a/media/ndk/libmediandk.map.txt b/media/ndk/libmediandk.map.txt index eead681648..7e9e57ef8d 100644 --- a/media/ndk/libmediandk.map.txt +++ b/media/ndk/libmediandk.map.txt @@ -109,6 +109,7 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_IS_SYNC_FRAME; # var introduced=29 AMEDIAFORMAT_KEY_I_FRAME_INTERVAL; # var introduced=21 AMEDIAFORMAT_KEY_LANGUAGE; # var introduced=21 + AMEDIAFORMAT_KEY_LAST_SAMPLE_INDEX_IN_CHUNK; # var introduced=31 AMEDIAFORMAT_KEY_LATENCY; # var introduced=28 AMEDIAFORMAT_KEY_LEVEL; # var introduced=28 AMEDIAFORMAT_KEY_LOCATION; # var introduced=29 @@ -134,6 +135,8 @@ LIBMEDIANDK { AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP; # var introduced=21 AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER; # var introduced=21 AMEDIAFORMAT_KEY_ROTATION; # var introduced=28 + AMEDIAFORMAT_KEY_SAMPLE_FILE_OFFSET; # var introduced=31 + AMEDIAFORMAT_KEY_SAMPLE_TIME_BEFORE_APPEND; # var introduced=31 AMEDIAFORMAT_KEY_SAMPLE_RATE; # var introduced=21 AMEDIAFORMAT_KEY_SAR_HEIGHT; # var introduced=29 AMEDIAFORMAT_KEY_SAR_WIDTH; # var introduced=29 @@ -286,7 +289,10 @@ LIBMEDIANDK { AMediaFormat_setString; AMediaFormat_toString; AMediaMuxer_addTrack; + AMediaMuxer_append; # introduced=31 AMediaMuxer_delete; + AMediaMuxer_getTrackCount; # introduced=31 + AMediaMuxer_getTrackFormat; # introduced=31 AMediaMuxer_new; AMediaMuxer_setLocation; AMediaMuxer_setOrientationHint; -- GitLab From 5db9b8a570dd8d03d15edfc8d37f22c84a4320cb Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Fri, 22 Jan 2021 20:38:33 -0800 Subject: [PATCH 030/694] Fix CryptoPlugin use after free vulnerability. The shared memory buffer used by srcPtr can be freed by another thread because it is not protected by a mutex. Subsequently, a use after free AIGABRT can occur in a race condition. SafetyNet logging is not added to avoid log spamming. The mutex lock is called to setup for decryption, which is called frequently. The crash was reproduced on the device before the fix. Verified the test passes after the fix. Test: sts sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176495665#testPocBug_176495665 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-176495665_sts64 Bug: 176495665 Bug: 176444161 Change-Id: I3bfe5c34acb41608d1250a075984ab7860076331 --- drm/mediadrm/plugins/clearkey/hidl/Android.bp | 6 +++++- drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp | 6 ++++++ drm/mediadrm/plugins/clearkey/hidl/include/CryptoPlugin.h | 7 +++++-- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/drm/mediadrm/plugins/clearkey/hidl/Android.bp b/drm/mediadrm/plugins/clearkey/hidl/Android.bp index e6e1f8009f..d4b160af38 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/Android.bp +++ b/drm/mediadrm/plugins/clearkey/hidl/Android.bp @@ -50,7 +50,11 @@ cc_defaults { relative_install_path: "hw", - cflags: ["-Wall", "-Werror"], + cflags: [ + "-Wall", + "-Werror", + "-Wthread-safety", + ], shared_libs: [ "android.hardware.drm@1.0", diff --git a/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp b/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp index 005e551383..302dd39ddc 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp +++ b/drm/mediadrm/plugins/clearkey/hidl/CryptoPlugin.cpp @@ -37,6 +37,8 @@ Return CryptoPlugin::setSharedBufferBase( sp hidlMemory = mapMemory(base); ALOGE_IF(hidlMemory == nullptr, "mapMemory returns nullptr"); + std::lock_guard shared_buffer_lock(mSharedBufferLock); + // allow mapMemory to return nullptr mSharedBufferMap[bufferId] = hidlMemory; return Void(); @@ -94,6 +96,7 @@ Return CryptoPlugin::decrypt_1_2( return Void(); } + std::unique_lock shared_buffer_lock(mSharedBufferLock); if (mSharedBufferMap.find(source.bufferId) == mSharedBufferMap.end()) { _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0, "source decrypt buffer base not set"); @@ -151,6 +154,9 @@ Return CryptoPlugin::decrypt_1_2( } destPtr = static_cast(base + destination.nonsecureMemory.offset); + // release mSharedBufferLock + shared_buffer_lock.unlock(); + // Calculate the output buffer size and determine if any subsamples are // encrypted. size_t destSize = 0; diff --git a/drm/mediadrm/plugins/clearkey/hidl/include/CryptoPlugin.h b/drm/mediadrm/plugins/clearkey/hidl/include/CryptoPlugin.h index 8680f0ca54..23a64fac50 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/include/CryptoPlugin.h +++ b/drm/mediadrm/plugins/clearkey/hidl/include/CryptoPlugin.h @@ -20,6 +20,8 @@ #include #include +#include + #include "ClearKeyTypes.h" #include "Session.h" #include "Utils.h" @@ -93,7 +95,7 @@ struct CryptoPlugin : public drm::V1_2::ICryptoPlugin { const SharedBuffer& source, uint64_t offset, const DestinationBuffer& destination, - decrypt_1_2_cb _hidl_cb); + decrypt_1_2_cb _hidl_cb) NO_THREAD_SAFETY_ANALYSIS; // use unique_lock Return setSharedBufferBase(const hidl_memory& base, uint32_t bufferId); @@ -105,7 +107,8 @@ struct CryptoPlugin : public drm::V1_2::ICryptoPlugin { private: CLEARKEY_DISALLOW_COPY_AND_ASSIGN(CryptoPlugin); - std::map > mSharedBufferMap; + std::mutex mSharedBufferLock; + std::map> mSharedBufferMap GUARDED_BY(mSharedBufferLock); sp mSession; Status mInitStatus; }; -- GitLab From d8529a4cd59cabace373afff92341844b85f3aad Mon Sep 17 00:00:00 2001 From: George Burgess IV Date: Fri, 2 Apr 2021 11:47:47 -0700 Subject: [PATCH 031/694] mediacodec: hoist NULL assignments to variable initialization There're paths through this function where we end up using `key` (and presumably `iv`) without setting them. These paths _might_ be dynamically unreachable (I'm unfamiliar with this codebase), but it's locally unclear that that's the case. As a security mitigation, our compiler will zero-initialize these in all cases anyway. That said, it's probably best to make it more obvious to the reader that these are intended to be NULL on all paths except the `else if (!c2Buffer)` one Bug: None Test: TreeHugger Change-Id: Ib3c8e7d6b7cc8b794118c8784419458191d0cb56 --- media/libstagefright/MediaCodec.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp index 5675055e58..2cf96a2b43 100644 --- a/media/libstagefright/MediaCodec.cpp +++ b/media/libstagefright/MediaCodec.cpp @@ -4506,8 +4506,8 @@ status_t MediaCodec::onQueueInputBuffer(const sp &msg) { } const CryptoPlugin::SubSample *subSamples; size_t numSubSamples; - const uint8_t *key; - const uint8_t *iv; + const uint8_t *key = NULL; + const uint8_t *iv = NULL; CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted; // We allow the simpler queueInputBuffer API to be used even in @@ -4522,8 +4522,6 @@ status_t MediaCodec::onQueueInputBuffer(const sp &msg) { subSamples = &ss; numSubSamples = 1; - key = NULL; - iv = NULL; pattern.mEncryptBlocks = 0; pattern.mSkipBlocks = 0; } -- GitLab From 6c791fffdaef97d419b8e7f611520673e3156b0e Mon Sep 17 00:00:00 2001 From: Edwin Wong Date: Fri, 2 Apr 2021 18:35:58 -0700 Subject: [PATCH 032/694] bpfmt on Android.bp Try to avoid merge conflict in the future. Test: sts sts-tradefed run sts-engbuild-no-spl-lock -m StsHostTestCases --test android.security.sts.Bug_176495665#testPocBug_176495665 Test: push to device with target_hwasan-userdebug build adb shell /data/local/tmp/Bug-176495665_sts64 Bug: 176495665 Bug: 176444161 Change-Id: Ib8ccb49c37c570c7073d69ff0c6335377f6c4535 --- drm/mediadrm/plugins/clearkey/hidl/Android.bp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/drm/mediadrm/plugins/clearkey/hidl/Android.bp b/drm/mediadrm/plugins/clearkey/hidl/Android.bp index d4b160af38..c49d5fece0 100644 --- a/drm/mediadrm/plugins/clearkey/hidl/Android.bp +++ b/drm/mediadrm/plugins/clearkey/hidl/Android.bp @@ -50,11 +50,7 @@ cc_defaults { relative_install_path: "hw", - cflags: [ - "-Wall", - "-Werror", - "-Wthread-safety", - ], + cflags: ["-Wall", "-Werror", "-Wthread-safety"], shared_libs: [ "android.hardware.drm@1.0", -- GitLab From 373ddd7455d76e75bc1786d2213c31ac1abf7513 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Tue, 6 Apr 2021 23:12:18 +0100 Subject: [PATCH 033/694] Prevent overflow and out-of-bounds access Bug: 177617358 Test: atest CtsMediaTestCases:MediaExtractorTest Test: atest CtsMediaTestCases:MediaPlayerTest Change-Id: I18b7461aae1ea61348670bc8f71a5a4995c92e67 --- media/extractors/mp4/MPEG4Extractor.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 129c95558b..e2dce3bb12 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -2345,7 +2345,7 @@ status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { if (mLastTrack == NULL) return ERROR_MALFORMED; - AMediaFormat_setBuffer(mLastTrack->meta, + AMediaFormat_setBuffer(mLastTrack->meta, AMEDIAFORMAT_KEY_ESDS, &buffer[4], chunk_data_size - 4); if (mPath.size() >= 2 @@ -2427,7 +2427,7 @@ status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { if (mLastTrack == NULL) return ERROR_MALFORMED; - AMediaFormat_setBuffer(mLastTrack->meta, + AMediaFormat_setBuffer(mLastTrack->meta, AMEDIAFORMAT_KEY_CSD_AVC, buffer.get(), chunk_data_size); break; @@ -2449,7 +2449,7 @@ status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { if (mLastTrack == NULL) return ERROR_MALFORMED; - AMediaFormat_setBuffer(mLastTrack->meta, + AMediaFormat_setBuffer(mLastTrack->meta, AMEDIAFORMAT_KEY_CSD_HEVC, buffer.get(), chunk_data_size); *offset += chunk_size; @@ -4021,13 +4021,13 @@ status_t MPEG4Extractor::parseITunesMetaData(off64_t offset, size_t size) { // custom genre string buffer[size] = '\0'; - AMediaFormat_setString(mFileMetaData, + AMediaFormat_setString(mFileMetaData, metadataKey, (const char *)buffer + 8); } } else { buffer[size] = '\0'; - AMediaFormat_setString(mFileMetaData, + AMediaFormat_setString(mFileMetaData, metadataKey, (const char *)buffer + 8); } } @@ -6187,9 +6187,11 @@ media_status_t MPEG4Source::read( if (newBuffer) { if (mIsPcm) { // The twos' PCM block reader assumes that all samples has the same size. - - uint32_t samplesToRead = mSampleTable->getLastSampleIndexInChunk() - - mCurrentSampleIndex + 1; + uint32_t lastSampleIndexInChunk = mSampleTable->getLastSampleIndexInChunk(); + if (lastSampleIndexInChunk < mCurrentSampleIndex) { + return AMEDIA_ERROR_UNKNOWN; + } + uint32_t samplesToRead = lastSampleIndexInChunk - mCurrentSampleIndex + 1; if (samplesToRead > kMaxPcmFrameSize) { samplesToRead = kMaxPcmFrameSize; } @@ -6198,7 +6200,12 @@ media_status_t MPEG4Source::read( samplesToRead, size, mCurrentSampleIndex, mSampleTable->getLastSampleIndexInChunk()); - size_t totalSize = samplesToRead * size; + size_t totalSize = samplesToRead * size; + if (mBuffer->size() < totalSize) { + mBuffer->release(); + mBuffer = nullptr; + return AMEDIA_ERROR_UNKNOWN; + } uint8_t* buf = (uint8_t *)mBuffer->data(); ssize_t bytesRead = mDataSource->readAt(offset, buf, totalSize); if (bytesRead < (ssize_t)totalSize) { -- GitLab From 4c602f36b945198879aee9985144c1f3400bf019 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Thu, 8 Apr 2021 13:06:29 +0000 Subject: [PATCH 034/694] Release buffer upon parsing error Bug: 177617358 Change-Id: I06200fca390ec69e2957decbba52ee8a3a578a95 Test: atest CtsMediaTestCases:MediaExtractorTest Test: atest CtsMediaTestCases:MediaPlayerTest --- media/extractors/mp4/MPEG4Extractor.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 29c5d8e297..b1d72e8aef 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6196,6 +6196,8 @@ media_status_t MPEG4Source::read( // The twos' PCM block reader assumes that all samples has the same size. uint32_t lastSampleIndexInChunk = mSampleTable->getLastSampleIndexInChunk(); if (lastSampleIndexInChunk < mCurrentSampleIndex) { + mBuffer->release(); + mBuffer = nullptr; return AMEDIA_ERROR_UNKNOWN; } uint32_t samplesToRead = lastSampleIndexInChunk - mCurrentSampleIndex + 1; @@ -6218,7 +6220,6 @@ media_status_t MPEG4Source::read( if (bytesRead < (ssize_t)totalSize) { mBuffer->release(); mBuffer = NULL; - return AMEDIA_ERROR_IO; } -- GitLab From 7d323f1d1f2229b46511d59a0d6413a963987d51 Mon Sep 17 00:00:00 2001 From: Paul McLean Date: Mon, 12 Apr 2021 10:21:42 -0600 Subject: [PATCH 035/694] Add state testing to RecordThread "Microphone" methods RecordThread::getActiveMicrophones() RecordThread::setPreferredMicrophoneDirection() RecordThread::setPreferredMicrophoneFieldDimension() Bug: 184367936 Test: build, install... Change-Id: I0adc00b56270bc0b53c79640f6149b83172d188d --- services/audioflinger/Threads.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 90f7a6152b..b20e2ab156 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -8083,6 +8083,9 @@ status_t AudioFlinger::RecordThread::getActiveMicrophones( { ALOGV("RecordThread::getActiveMicrophones"); AutoMutex _l(mLock); + if (mInput == nullptr || mInput->stream == nullptr) { + return NO_INIT; + } status_t status = mInput->stream->getActiveMicrophones(activeMicrophones); return status; } @@ -8092,6 +8095,9 @@ status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection( { ALOGV("setPreferredMicrophoneDirection(%d)", direction); AutoMutex _l(mLock); + if (mInput == nullptr || mInput->stream == nullptr) { + return NO_INIT; + } return mInput->stream->setPreferredMicrophoneDirection(direction); } @@ -8099,6 +8105,9 @@ status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float { ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom); AutoMutex _l(mLock); + if (mInput == nullptr || mInput->stream == nullptr) { + return NO_INIT; + } return mInput->stream->setPreferredMicrophoneFieldDimension(zoom); } -- GitLab From 3f2116b3d95003a1ca862f487a141f157f57bad9 Mon Sep 17 00:00:00 2001 From: Dichen Zhang Date: Mon, 22 Mar 2021 00:56:29 -0700 Subject: [PATCH 036/694] enum migration Move proto messages out of enum/ directory. Test: make Bug: b/184754707 Change-Id: Ia65cfb5efbc5cee357453bbe7584b6113c402f43 --- services/mediametrics/statsd_codec.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/mediametrics/statsd_codec.cpp b/services/mediametrics/statsd_codec.cpp index 2746dfa973..33b472b7ec 100644 --- a/services/mediametrics/statsd_codec.cpp +++ b/services/mediametrics/statsd_codec.cpp @@ -33,7 +33,7 @@ #include "cleaner.h" #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -51,7 +51,7 @@ bool statsd_codec(const mediametrics::Item *item) // the rest into our own proto // - ::android::stats::mediametrics::CodecData metrics_proto; + ::android::stats::mediametrics_message::CodecData metrics_proto; // flesh out the protobuf we'll hand off with our data // -- GitLab From 31cce4f48b93ba339eaf9832410d858761c4b69c Mon Sep 17 00:00:00 2001 From: Dominik Laskowski Date: Wed, 14 Apr 2021 14:03:24 -0700 Subject: [PATCH 037/694] screenrecord: Use DisplayId::fromValue Bug: 182939859 Test: screenrecord -d Change-Id: I905348bd2fe31a505cf0ec84001ea8979874590a --- cmds/screenrecord/screenrecord.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/cmds/screenrecord/screenrecord.cpp b/cmds/screenrecord/screenrecord.cpp index e6e347321d..cd8fe970e8 100644 --- a/cmds/screenrecord/screenrecord.cpp +++ b/cmds/screenrecord/screenrecord.cpp @@ -1067,7 +1067,7 @@ int main(int argc, char* const argv[]) { std::optional displayId = SurfaceComposerClient::getInternalDisplayId(); if (!displayId) { - fprintf(stderr, "Failed to get token for internal display\n"); + fprintf(stderr, "Failed to get ID for internal display\n"); return 1; } @@ -1168,17 +1168,14 @@ int main(int argc, char* const argv[]) { } break; case 'd': - gPhysicalDisplayId = PhysicalDisplayId(atoll(optarg)); - if (gPhysicalDisplayId.value == 0) { - fprintf(stderr, "Please specify a valid physical display id\n"); - return 2; - } else if (SurfaceComposerClient:: - getPhysicalDisplayToken(gPhysicalDisplayId) == nullptr) { - fprintf(stderr, "Invalid physical display id: %s\n", - to_string(gPhysicalDisplayId).c_str()); - return 2; + if (const auto id = android::DisplayId::fromValue(atoll(optarg)); + id && SurfaceComposerClient::getPhysicalDisplayToken(*id)) { + gPhysicalDisplayId = *id; + break; } - break; + + fprintf(stderr, "Invalid physical display ID\n"); + return 2; default: if (ic != '?') { fprintf(stderr, "getopt_long returned unexpected value 0x%x\n", ic); -- GitLab From 4780e88a6949dda66b7c717917042d1d779fa61b Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Wed, 21 Apr 2021 13:51:38 +0100 Subject: [PATCH 038/694] Add log session id to MediaParser Bug: 167036690 Test: atest CtsMediaParserHostTestCases Change-Id: Idee9c7248ee6107379c8e58410346b8c92d3c250 --- services/mediametrics/statsd_mediaparser.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/services/mediametrics/statsd_mediaparser.cpp b/services/mediametrics/statsd_mediaparser.cpp index f917ead405..6cceb065e6 100644 --- a/services/mediametrics/statsd_mediaparser.cpp +++ b/services/mediametrics/statsd_mediaparser.cpp @@ -79,8 +79,8 @@ bool statsd_mediaparser(const std::shared_ptr& item, int32_t videoHeight = -1; item->getInt32("android.media.mediaparser.videoHeight", &videoHeight); - std::string playbackSessionId; - item->getString("android.media.mediaparser.playbackId", &playbackSessionId); + std::string logSessionId; + item->getString("android.media.mediaparser.logSessionId", &logSessionId); if (enabled_statsd) { (void) android::util::stats_write(android::util::MEDIAMETRICS_MEDIAPARSER_REPORTED, @@ -98,11 +98,10 @@ bool statsd_mediaparser(const std::shared_ptr& item, alteredParameters.c_str(), videoWidth, videoHeight, - playbackSessionId.c_str()); + logSessionId.c_str()); } else { ALOGV("NOT sending MediaParser media metrics."); } - // TODO: Cleanup after playback_id is merged. std::stringstream log; log << "result:" << "(result)" << " {" << " mediametrics_mediaparser_reported:" @@ -121,8 +120,7 @@ bool statsd_mediaparser(const std::shared_ptr& item, << " altered_parameters:" << alteredParameters << " video_width:" << videoWidth << " video_height:" << videoHeight - // TODO: Add MediaParser playback_id - // << " playback_id:" << playbackId + << " log_session_id:" << logSessionId << " }"; statsdLog->log(android::util::MEDIAMETRICS_MEDIAPARSER_REPORTED, log.str()); return true; -- GitLab From 922a8000f3058da1acb5b981611f90e5d4dc80a6 Mon Sep 17 00:00:00 2001 From: Dichen Zhang Date: Tue, 27 Apr 2021 18:22:48 -0700 Subject: [PATCH 039/694] Enum migration for MediaRecorder Test: make Change-Id: I2846f2de178c4a216069ffb47b6dc0886e389d04 --- services/mediametrics/statsd_recorder.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/mediametrics/statsd_recorder.cpp b/services/mediametrics/statsd_recorder.cpp index 902a52ac57..6edad7cbaa 100644 --- a/services/mediametrics/statsd_recorder.cpp +++ b/services/mediametrics/statsd_recorder.cpp @@ -32,7 +32,7 @@ #include #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -50,7 +50,7 @@ bool statsd_recorder(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::RecorderData metrics_proto; + ::android::stats::mediametrics_message::RecorderData metrics_proto; // flesh out the protobuf we'll hand off with our data // -- GitLab From d5bd06a5cd0db4a74c2277c3067ec36d5425d2d6 Mon Sep 17 00:00:00 2001 From: jiabin Date: Tue, 27 Apr 2021 22:04:08 +0000 Subject: [PATCH 040/694] Enable clang-tidy in libaaudio. Enabling clang-tidy could help find programming errors at compile time. Bug: 186572209 Test: make, atest AAudioTests Change-Id: If48282d10701df87b80a99e2a3d2199437189d70 --- media/libaaudio/src/Android.bp | 73 +++++++++++++++++++ .../src/binding/AAudioBinderClient.cpp | 5 +- .../src/binding/AAudioBinderClient.h | 8 +- .../src/binding/AAudioServiceInterface.h | 2 +- .../src/binding/AAudioStreamRequest.cpp | 4 +- .../src/binding/AudioEndpointParcelable.cpp | 18 ++--- .../src/binding/AudioEndpointParcelable.h | 2 +- .../src/binding/RingBufferParcelable.cpp | 12 +-- .../src/binding/SharedMemoryParcelable.cpp | 3 +- .../src/binding/SharedRegionParcelable.cpp | 3 - media/libaaudio/src/client/AudioEndpoint.cpp | 7 -- media/libaaudio/src/client/AudioEndpoint.h | 8 +- .../src/client/AudioStreamInternal.cpp | 10 +-- .../src/client/AudioStreamInternal.h | 2 +- .../src/client/AudioStreamInternalCapture.cpp | 8 +- .../src/client/AudioStreamInternalCapture.h | 7 +- .../src/client/AudioStreamInternalPlay.cpp | 8 +- .../src/client/AudioStreamInternalPlay.h | 7 +- .../src/client/IsochronousClockModel.cpp | 9 +-- .../src/client/IsochronousClockModel.h | 14 ++-- .../src/core/AAudioStreamParameters.cpp | 3 - .../src/core/AAudioStreamParameters.h | 8 +- media/libaaudio/src/core/AudioGlobal.h | 3 +- media/libaaudio/src/core/AudioStream.h | 4 +- .../libaaudio/src/core/AudioStreamBuilder.cpp | 12 +-- media/libaaudio/src/core/AudioStreamBuilder.h | 4 +- media/libaaudio/src/fifo/FifoBuffer.h | 4 +- media/libaaudio/src/fifo/FifoController.h | 4 +- .../libaaudio/src/fifo/FifoControllerBase.cpp | 3 - media/libaaudio/src/fifo/FifoControllerBase.h | 4 +- .../src/fifo/FifoControllerIndirect.h | 4 +- .../src/flowgraph/AudioProcessorBase.cpp | 7 +- .../src/flowgraph/MonoToMultiConverter.cpp | 2 - .../src/flowgraph/MonoToMultiConverter.h | 2 +- media/libaaudio/src/flowgraph/SourceFloat.cpp | 2 +- media/libaaudio/src/flowgraph/SourceI16.cpp | 2 +- media/libaaudio/src/flowgraph/SourceI24.cpp | 2 +- media/libaaudio/src/flowgraph/SourceI32.cpp | 2 +- .../src/legacy/AudioStreamLegacy.cpp | 3 - .../libaaudio/src/legacy/AudioStreamLegacy.h | 2 +- .../src/legacy/AudioStreamRecord.cpp | 2 +- .../libaaudio/src/legacy/AudioStreamTrack.cpp | 4 +- media/libaaudio/src/utility/AAudioUtilities.h | 10 +-- .../libaaudio/src/utility/FixedBlockAdapter.h | 2 +- .../libaaudio/src/utility/FixedBlockReader.h | 2 +- .../libaaudio/src/utility/FixedBlockWriter.h | 2 +- .../libaaudio/src/utility/MonotonicCounter.h | 4 +- 47 files changed, 170 insertions(+), 143 deletions(-) diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index 9d137c857a..7cadacdb2b 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -7,6 +7,65 @@ package { default_applicable_licenses: ["frameworks_av_license"], } +tidy_errors = [ + // https://clang.llvm.org/extra/clang-tidy/checks/list.html + // For many categories, the checks are too many to specify individually. + // Feel free to disable as needed - as warnings are generally ignored, + // we treat warnings as errors. + "android-*", + "bugprone-*", + "cert-*", + "clang-analyzer-security*", + "google-*", + "misc-*", + //"modernize-*", // explicitly list the modernize as they can be subjective. + "modernize-avoid-bind", + //"modernize-avoid-c-arrays", // std::array<> can be verbose + "modernize-concat-nested-namespaces", + //"modernize-deprecated-headers", // C headers still ok even if there is C++ equivalent. + "modernize-deprecated-ios-base-aliases", + "modernize-loop-convert", + "modernize-make-shared", + "modernize-make-unique", + "modernize-pass-by-value", + "modernize-raw-string-literal", + "modernize-redundant-void-arg", + "modernize-replace-auto-ptr", + "modernize-replace-random-shuffle", + "modernize-return-braced-init-list", + "modernize-shrink-to-fit", + "modernize-unary-static-assert", + // "modernize-use-auto", // found in AAudioAudio.cpp + "modernize-use-bool-literals", + "modernize-use-default-member-init", + "modernize-use-emplace", + "modernize-use-equals-default", + "modernize-use-equals-delete", + // "modernize-use-nodiscard", // found in aidl generated files + "modernize-use-noexcept", + "modernize-use-nullptr", + // "modernize-use-override", // found in aidl generated files + // "modernize-use-trailing-return-type", // not necessarily more readable + "modernize-use-transparent-functors", + "modernize-use-uncaught-exceptions", + // "modernize-use-using", // found typedef in several files + "performance-*", + + // Remove some pedantic stylistic requirements. + "-android-cloexec-dup", // found in SharedMemoryParcelable.cpp + "-bugprone-macro-parentheses", // found in SharedMemoryParcelable.h + "-bugprone-narrowing-conversions", // found in several interface from size_t to int32_t + + "-google-readability-casting", // C++ casts not always necessary and may be verbose + "-google-readability-todo", // do not require TODO(info) + "-google-build-using-namespace", // Reenable and fix later. + "-google-global-names-in-headers", // found in several files + + "-misc-non-private-member-variables-in-classes", // found in aidl generated files + + "-performance-no-int-to-ptr", // found in SharedMemoryParcelable.h +] + cc_library { name: "libaaudio", @@ -63,6 +122,13 @@ cc_library { symbol_file: "libaaudio.map.txt", versions: ["28"], }, + + tidy: true, + tidy_checks: tidy_errors, + tidy_checks_as_errors: tidy_errors, + tidy_flags: [ + "-format-style=file", + ] } cc_library { @@ -159,6 +225,13 @@ cc_library { integer_overflow: true, misc_undefined: ["bounds"], }, + + tidy: true, + tidy_checks: tidy_errors, + tidy_checks_as_errors: tidy_errors, + tidy_flags: [ + "-format-style=file", + ] } aidl_interface { diff --git a/media/libaaudio/src/binding/AAudioBinderClient.cpp b/media/libaaudio/src/binding/AAudioBinderClient.cpp index fa5a2da4f8..135bac37ba 100644 --- a/media/libaaudio/src/binding/AAudioBinderClient.cpp +++ b/media/libaaudio/src/binding/AAudioBinderClient.cpp @@ -36,13 +36,10 @@ using android::String16; using android::IServiceManager; using android::defaultServiceManager; using android::interface_cast; -using android::IInterface; using android::Mutex; using android::ProcessState; using android::sp; using android::status_t; -using android::wp; -using android::binder::Status; using namespace aaudio; @@ -93,7 +90,7 @@ std::shared_ptr AAudioBinderClient::getAAudioService() { ALOGE("%s() - linkToDeath() returned %d", __func__, status); } aaudioService = interface_cast(binder); - mAdapter.reset(new Adapter(aaudioService, mAAudioClient)); + mAdapter = std::make_shared(aaudioService, mAAudioClient); needToRegister = true; // Make sure callbacks can be received by mAAudioClient ProcessState::self()->startThreadPool(); diff --git a/media/libaaudio/src/binding/AAudioBinderClient.h b/media/libaaudio/src/binding/AAudioBinderClient.h index 6a7b639568..557ced5bb2 100644 --- a/media/libaaudio/src/binding/AAudioBinderClient.h +++ b/media/libaaudio/src/binding/AAudioBinderClient.h @@ -108,7 +108,7 @@ public: return AAUDIO_ERROR_UNAVAILABLE; } - void onStreamChange(aaudio_handle_t handle, int32_t opcode, int32_t value) { + void onStreamChange(aaudio_handle_t /*handle*/, int32_t /*opcode*/, int32_t /*value*/) { // TODO This is just a stub so we can have a client Binder to pass to the service. // TODO Implemented in a later CL. ALOGW("onStreamChange called!"); @@ -116,7 +116,7 @@ public: class AAudioClient : public android::IBinder::DeathRecipient, public BnAAudioClient { public: - AAudioClient(android::wp aaudioBinderClient) + explicit AAudioClient(const android::wp& aaudioBinderClient) : mBinderClient(aaudioBinderClient) { } @@ -150,10 +150,10 @@ public: class Adapter : public AAudioBinderAdapter { public: Adapter(const android::sp& delegate, - const android::sp& aaudioClient) + android::sp aaudioClient) : AAudioBinderAdapter(delegate.get()), mDelegate(delegate), - mAAudioClient(aaudioClient) {} + mAAudioClient(std::move(aaudioClient)) {} virtual ~Adapter() { if (mDelegate != nullptr) { diff --git a/media/libaaudio/src/binding/AAudioServiceInterface.h b/media/libaaudio/src/binding/AAudioServiceInterface.h index 5d11512e03..bf9477451e 100644 --- a/media/libaaudio/src/binding/AAudioServiceInterface.h +++ b/media/libaaudio/src/binding/AAudioServiceInterface.h @@ -37,7 +37,7 @@ namespace aaudio { class AAudioServiceInterface { public: - AAudioServiceInterface() {}; + AAudioServiceInterface() = default; virtual ~AAudioServiceInterface() = default; virtual void registerClient(const android::sp& client) = 0; diff --git a/media/libaaudio/src/binding/AAudioStreamRequest.cpp b/media/libaaudio/src/binding/AAudioStreamRequest.cpp index 5e0a4bb804..09f7a1c01e 100644 --- a/media/libaaudio/src/binding/AAudioStreamRequest.cpp +++ b/media/libaaudio/src/binding/AAudioStreamRequest.cpp @@ -30,7 +30,7 @@ using namespace aaudio; AAudioStreamRequest::AAudioStreamRequest(const StreamRequest& parcelable) : - mConfiguration(std::move(parcelable.params)), + mConfiguration(parcelable.params), mIdentity(parcelable.identity), mSharingModeMatchRequired(parcelable.sharingModeMatchRequired), mInService(parcelable.inService) { @@ -38,7 +38,7 @@ AAudioStreamRequest::AAudioStreamRequest(const StreamRequest& parcelable) : StreamRequest AAudioStreamRequest::parcelable() const { StreamRequest result; - result.params = std::move(mConfiguration).parcelable(); + result.params = mConfiguration.parcelable(); result.identity = mIdentity; result.sharingModeMatchRequired = mSharingModeMatchRequired; result.inService = mInService; diff --git a/media/libaaudio/src/binding/AudioEndpointParcelable.cpp b/media/libaaudio/src/binding/AudioEndpointParcelable.cpp index aa4ac273fc..dea3e4a6b7 100644 --- a/media/libaaudio/src/binding/AudioEndpointParcelable.cpp +++ b/media/libaaudio/src/binding/AudioEndpointParcelable.cpp @@ -29,17 +29,15 @@ #include "binding/AudioEndpointParcelable.h" using android::base::unique_fd; -using android::media::SharedFileRegion; -using android::NO_ERROR; using android::status_t; using namespace aaudio; AudioEndpointParcelable::AudioEndpointParcelable(Endpoint&& parcelable) - : mUpMessageQueueParcelable(std::move(parcelable.upMessageQueueParcelable)), - mDownMessageQueueParcelable(std::move(parcelable.downMessageQueueParcelable)), - mUpDataQueueParcelable(std::move(parcelable.upDataQueueParcelable)), - mDownDataQueueParcelable(std::move(parcelable.downDataQueueParcelable)), + : mUpMessageQueueParcelable(parcelable.upMessageQueueParcelable), + mDownMessageQueueParcelable(parcelable.downMessageQueueParcelable), + mUpDataQueueParcelable(parcelable.upDataQueueParcelable), + mDownDataQueueParcelable(parcelable.downDataQueueParcelable), mNumSharedMemories(parcelable.sharedMemories.size()) { for (size_t i = 0; i < parcelable.sharedMemories.size() && i < MAX_SHARED_MEMORIES; ++i) { // Re-construct. @@ -56,10 +54,10 @@ AudioEndpointParcelable& AudioEndpointParcelable::operator=(Endpoint&& parcelabl Endpoint AudioEndpointParcelable::parcelable()&& { Endpoint result; - result.upMessageQueueParcelable = std::move(mUpMessageQueueParcelable).parcelable(); - result.downMessageQueueParcelable = std::move(mDownMessageQueueParcelable).parcelable(); - result.upDataQueueParcelable = std::move(mUpDataQueueParcelable).parcelable(); - result.downDataQueueParcelable = std::move(mDownDataQueueParcelable).parcelable(); + result.upMessageQueueParcelable = mUpMessageQueueParcelable.parcelable(); + result.downMessageQueueParcelable = mDownMessageQueueParcelable.parcelable(); + result.upDataQueueParcelable = mUpDataQueueParcelable.parcelable(); + result.downDataQueueParcelable = mDownDataQueueParcelable.parcelable(); result.sharedMemories.reserve(std::min(mNumSharedMemories, MAX_SHARED_MEMORIES)); for (size_t i = 0; i < mNumSharedMemories && i < MAX_SHARED_MEMORIES; ++i) { result.sharedMemories.emplace_back(std::move(mSharedMemories[i]).parcelable()); diff --git a/media/libaaudio/src/binding/AudioEndpointParcelable.h b/media/libaaudio/src/binding/AudioEndpointParcelable.h index 5237a1ab64..544aa928b4 100644 --- a/media/libaaudio/src/binding/AudioEndpointParcelable.h +++ b/media/libaaudio/src/binding/AudioEndpointParcelable.h @@ -43,7 +43,7 @@ public: // Ctor/assignment from a parcelable representation. // Since the parcelable object owns unique FDs (for shared memory blocks), move semantics are // provided to avoid the need to dupe. - AudioEndpointParcelable(Endpoint&& parcelable); + explicit AudioEndpointParcelable(Endpoint&& parcelable); AudioEndpointParcelable& operator=(Endpoint&& parcelable); /** diff --git a/media/libaaudio/src/binding/RingBufferParcelable.cpp b/media/libaaudio/src/binding/RingBufferParcelable.cpp index a4b3cecc27..fa7ca72b12 100644 --- a/media/libaaudio/src/binding/RingBufferParcelable.cpp +++ b/media/libaaudio/src/binding/RingBufferParcelable.cpp @@ -30,9 +30,9 @@ using namespace aaudio; RingBufferParcelable::RingBufferParcelable(const RingBuffer& parcelable) - : mReadCounterParcelable(std::move(parcelable.readCounterParcelable)), - mWriteCounterParcelable(std::move(parcelable.writeCounterParcelable)), - mDataParcelable(std::move(parcelable.dataParcelable)), + : mReadCounterParcelable(parcelable.readCounterParcelable), + mWriteCounterParcelable(parcelable.writeCounterParcelable), + mDataParcelable(parcelable.dataParcelable), mBytesPerFrame(parcelable.bytesPerFrame), mFramesPerBurst(parcelable.framesPerBurst), mCapacityInFrames(parcelable.capacityInFrames), @@ -42,9 +42,9 @@ RingBufferParcelable::RingBufferParcelable(const RingBuffer& parcelable) RingBuffer RingBufferParcelable::parcelable() const { RingBuffer result; - result.readCounterParcelable = std::move(mReadCounterParcelable).parcelable(); - result.writeCounterParcelable = std::move(mWriteCounterParcelable).parcelable(); - result.dataParcelable = std::move(mDataParcelable).parcelable(); + result.readCounterParcelable = mReadCounterParcelable.parcelable(); + result.writeCounterParcelable = mWriteCounterParcelable.parcelable(); + result.dataParcelable = mDataParcelable.parcelable(); result.bytesPerFrame = mBytesPerFrame; result.framesPerBurst = mFramesPerBurst; result.capacityInFrames = mCapacityInFrames; diff --git a/media/libaaudio/src/binding/SharedMemoryParcelable.cpp b/media/libaaudio/src/binding/SharedMemoryParcelable.cpp index 685b779242..60a3bd5f6d 100644 --- a/media/libaaudio/src/binding/SharedMemoryParcelable.cpp +++ b/media/libaaudio/src/binding/SharedMemoryParcelable.cpp @@ -32,7 +32,6 @@ #include "binding/SharedMemoryParcelable.h" using android::base::unique_fd; -using android::NO_ERROR; using android::status_t; using android::media::SharedFileRegion; @@ -77,7 +76,7 @@ aaudio_result_t SharedMemoryParcelable::close() { } aaudio_result_t SharedMemoryParcelable::resolveSharedMemory(const unique_fd& fd) { - mResolvedAddress = (uint8_t *) mmap(0, mSizeInBytes, PROT_READ | PROT_WRITE, + mResolvedAddress = (uint8_t *) mmap(nullptr, mSizeInBytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0); if (mResolvedAddress == MMAP_UNRESOLVED_ADDRESS) { ALOGE("mmap() failed for fd = %d, nBytes = %" PRId64 ", errno = %s", diff --git a/media/libaaudio/src/binding/SharedRegionParcelable.cpp b/media/libaaudio/src/binding/SharedRegionParcelable.cpp index 56b99c0787..6fa109b33d 100644 --- a/media/libaaudio/src/binding/SharedRegionParcelable.cpp +++ b/media/libaaudio/src/binding/SharedRegionParcelable.cpp @@ -29,10 +29,7 @@ #include "binding/SharedMemoryParcelable.h" #include "binding/SharedRegionParcelable.h" -using android::NO_ERROR; using android::status_t; -using android::Parcel; -using android::Parcelable; using namespace aaudio; diff --git a/media/libaaudio/src/client/AudioEndpoint.cpp b/media/libaaudio/src/client/AudioEndpoint.cpp index 0a19d17b93..7427a8ed07 100644 --- a/media/libaaudio/src/client/AudioEndpoint.cpp +++ b/media/libaaudio/src/client/AudioEndpoint.cpp @@ -31,13 +31,6 @@ using namespace aaudio; #define RIDICULOUSLY_LARGE_BUFFER_CAPACITY (256 * 1024) #define RIDICULOUSLY_LARGE_FRAME_SIZE 4096 -AudioEndpoint::AudioEndpoint() - : mFreeRunning(false) - , mDataReadCounter(0) - , mDataWriteCounter(0) -{ -} - // TODO Consider moving to a method in RingBufferDescriptor static aaudio_result_t AudioEndpoint_validateQueueDescriptor(const char *type, const RingBufferDescriptor *descriptor) { diff --git a/media/libaaudio/src/client/AudioEndpoint.h b/media/libaaudio/src/client/AudioEndpoint.h index 4c8d60f28d..b3dbc20c25 100644 --- a/media/libaaudio/src/client/AudioEndpoint.h +++ b/media/libaaudio/src/client/AudioEndpoint.h @@ -34,7 +34,7 @@ namespace aaudio { class AudioEndpoint { public: - AudioEndpoint(); + AudioEndpoint() = default; /** * Configure based on the EndPointDescriptor_t. @@ -95,9 +95,9 @@ public: private: std::unique_ptr mUpCommandQueue; std::unique_ptr mDataQueue; - bool mFreeRunning; - android::fifo_counter_t mDataReadCounter; // only used if free-running - android::fifo_counter_t mDataWriteCounter; // only used if free-running + bool mFreeRunning{false}; + android::fifo_counter_t mDataReadCounter{0}; // only used if free-running + android::fifo_counter_t mDataWriteCounter{0}; // only used if free-running }; } // namespace aaudio diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp index dc961ad0e3..2992e67093 100644 --- a/media/libaaudio/src/client/AudioStreamInternal.cpp +++ b/media/libaaudio/src/client/AudioStreamInternal.cpp @@ -49,8 +49,6 @@ // This is needed to make sense of the logs more easily. #define LOG_TAG (mInService ? "AudioStreamInternal_Service" : "AudioStreamInternal_Client") -using android::Mutex; -using android::WrappingBuffer; using android::media::permission::Identity; using namespace aaudio; @@ -319,10 +317,10 @@ static void *aaudio_callback_thread_proc(void *context) { AudioStreamInternal *stream = (AudioStreamInternal *)context; //LOGD("oboe_callback_thread, stream = %p", stream); - if (stream != NULL) { + if (stream != nullptr) { return stream->callbackLoop(); } else { - return NULL; + return nullptr; } } @@ -411,7 +409,7 @@ aaudio_result_t AudioStreamInternal::stopCallback_l() if (isDataCallbackSet() && (isActive() || getState() == AAUDIO_STREAM_STATE_DISCONNECTED)) { mCallbackEnabled.store(false); - aaudio_result_t result = joinThread_l(NULL); // may temporarily unlock mStreamLock + aaudio_result_t result = joinThread_l(nullptr); // may temporarily unlock mStreamLock if (result == AAUDIO_ERROR_INVALID_HANDLE) { ALOGD("%s() INVALID_HANDLE, stream was probably stolen", __func__); result = AAUDIO_OK; @@ -498,7 +496,7 @@ aaudio_result_t AudioStreamInternal::stopClient(audio_port_handle_t portHandle) return result; } -aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t clockId, +aaudio_result_t AudioStreamInternal::getTimestamp(clockid_t /*clockId*/, int64_t *framePosition, int64_t *timeNanoseconds) { // Generated in server and passed to client. Return latest. diff --git a/media/libaaudio/src/client/AudioStreamInternal.h b/media/libaaudio/src/client/AudioStreamInternal.h index fbe4c13efd..eab1382df2 100644 --- a/media/libaaudio/src/client/AudioStreamInternal.h +++ b/media/libaaudio/src/client/AudioStreamInternal.h @@ -116,7 +116,7 @@ protected: virtual void prepareBuffersForStart() {} - virtual void advanceClientToMatchServerPosition(int32_t serverMargin = 0) = 0; + virtual void advanceClientToMatchServerPosition(int32_t serverMargin) = 0; virtual void onFlushFromServer() {} diff --git a/media/libaaudio/src/client/AudioStreamInternalCapture.cpp b/media/libaaudio/src/client/AudioStreamInternalCapture.cpp index f4a40a8423..5c8bdfcc12 100644 --- a/media/libaaudio/src/client/AudioStreamInternalCapture.cpp +++ b/media/libaaudio/src/client/AudioStreamInternalCapture.cpp @@ -46,8 +46,6 @@ AudioStreamInternalCapture::AudioStreamInternalCapture(AAudioServiceInterface & } -AudioStreamInternalCapture::~AudioStreamInternalCapture() {} - void AudioStreamInternalCapture::advanceClientToMatchServerPosition(int32_t serverMargin) { int64_t readCounter = mAudioEndpoint->getDataReadCounter(); int64_t writeCounter = mAudioEndpoint->getDataWriteCounter() + serverMargin; @@ -109,7 +107,7 @@ aaudio_result_t AudioStreamInternalCapture::processDataNow(void *buffer, int32_t if (mNeedCatchUp.isRequested()) { // Catch an MMAP pointer that is already advancing. // This will avoid initial underruns caused by a slow cold start. - advanceClientToMatchServerPosition(); + advanceClientToMatchServerPosition(0 /*serverMargin*/); mNeedCatchUp.acknowledge(); } @@ -244,7 +242,7 @@ int64_t AudioStreamInternalCapture::getFramesRead() { void *AudioStreamInternalCapture::callbackLoop() { aaudio_result_t result = AAUDIO_OK; aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE; - if (!isDataCallbackSet()) return NULL; + if (!isDataCallbackSet()) return nullptr; // result might be a frame count while (mCallbackEnabled.load() && isActive() && (result >= 0)) { @@ -276,5 +274,5 @@ void *AudioStreamInternalCapture::callbackLoop() { ALOGD("callbackLoop() exiting, result = %d, isActive() = %d", result, (int) isActive()); - return NULL; + return nullptr; } diff --git a/media/libaaudio/src/client/AudioStreamInternalCapture.h b/media/libaaudio/src/client/AudioStreamInternalCapture.h index 251a7f2b11..87017deb6f 100644 --- a/media/libaaudio/src/client/AudioStreamInternalCapture.h +++ b/media/libaaudio/src/client/AudioStreamInternalCapture.h @@ -28,8 +28,9 @@ namespace aaudio { class AudioStreamInternalCapture : public AudioStreamInternal { public: - AudioStreamInternalCapture(AAudioServiceInterface &serviceInterface, bool inService = false); - virtual ~AudioStreamInternalCapture(); + explicit AudioStreamInternalCapture(AAudioServiceInterface &serviceInterface, + bool inService = false); + virtual ~AudioStreamInternalCapture() = default; aaudio_result_t read(void *buffer, int32_t numFrames, @@ -45,7 +46,7 @@ public: } protected: - void advanceClientToMatchServerPosition(int32_t serverOffset = 0) override; + void advanceClientToMatchServerPosition(int32_t serverOffset) override; /** * Low level data processing that will not block. It will just read or write as much as it can. diff --git a/media/libaaudio/src/client/AudioStreamInternalPlay.cpp b/media/libaaudio/src/client/AudioStreamInternalPlay.cpp index 71bde9068f..59217997d5 100644 --- a/media/libaaudio/src/client/AudioStreamInternalPlay.cpp +++ b/media/libaaudio/src/client/AudioStreamInternalPlay.cpp @@ -44,8 +44,6 @@ AudioStreamInternalPlay::AudioStreamInternalPlay(AAudioServiceInterface &servic } -AudioStreamInternalPlay::~AudioStreamInternalPlay() {} - constexpr int kRampMSec = 10; // time to apply a change in volume aaudio_result_t AudioStreamInternalPlay::open(const AudioStreamBuilder &builder) { @@ -115,7 +113,7 @@ void AudioStreamInternalPlay::advanceClientToMatchServerPosition(int32_t serverM } void AudioStreamInternalPlay::onFlushFromServer() { - advanceClientToMatchServerPosition(); + advanceClientToMatchServerPosition(0 /*serverMargin*/); } // Write the data, block if needed and timeoutMillis > 0 @@ -281,7 +279,7 @@ void *AudioStreamInternalPlay::callbackLoop() { ALOGD("%s() entering >>>>>>>>>>>>>>>", __func__); aaudio_result_t result = AAUDIO_OK; aaudio_data_callback_result_t callbackResult = AAUDIO_CALLBACK_RESULT_CONTINUE; - if (!isDataCallbackSet()) return NULL; + if (!isDataCallbackSet()) return nullptr; int64_t timeoutNanos = calculateReasonableTimeout(mCallbackFrames); // result might be a frame count @@ -309,7 +307,7 @@ void *AudioStreamInternalPlay::callbackLoop() { ALOGD("%s() exiting, result = %d, isActive() = %d <<<<<<<<<<<<<<", __func__, result, (int) isActive()); - return NULL; + return nullptr; } //------------------------------------------------------------------------------ diff --git a/media/libaaudio/src/client/AudioStreamInternalPlay.h b/media/libaaudio/src/client/AudioStreamInternalPlay.h index 03c957d363..e7618079bb 100644 --- a/media/libaaudio/src/client/AudioStreamInternalPlay.h +++ b/media/libaaudio/src/client/AudioStreamInternalPlay.h @@ -30,8 +30,9 @@ namespace aaudio { class AudioStreamInternalPlay : public AudioStreamInternal { public: - AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface, bool inService = false); - virtual ~AudioStreamInternalPlay(); + explicit AudioStreamInternalPlay(AAudioServiceInterface &serviceInterface, + bool inService = false); + virtual ~AudioStreamInternalPlay() = default; aaudio_result_t open(const AudioStreamBuilder &builder) override; @@ -66,7 +67,7 @@ protected: void prepareBuffersForStart() override; - void advanceClientToMatchServerPosition(int32_t serverMargin = 0) override; + void advanceClientToMatchServerPosition(int32_t serverMargin) override; void onFlushFromServer() override; diff --git a/media/libaaudio/src/client/IsochronousClockModel.cpp b/media/libaaudio/src/client/IsochronousClockModel.cpp index f0dcd44859..692127118c 100644 --- a/media/libaaudio/src/client/IsochronousClockModel.cpp +++ b/media/libaaudio/src/client/IsochronousClockModel.cpp @@ -43,14 +43,7 @@ using namespace android::audio_utils; // and dumped to the log when the stream is stopped. IsochronousClockModel::IsochronousClockModel() - : mMarkerFramePosition(0) - , mMarkerNanoTime(0) - , mSampleRate(48000) - , mFramesPerBurst(48) - , mBurstPeriodNanos(0) // this will be updated before use - , mMaxMeasuredLatenessNanos(0) - , mLatenessForDriftNanos(kInitialLatenessForDriftNanos) - , mState(STATE_STOPPED) + : mLatenessForDriftNanos(kInitialLatenessForDriftNanos) { if ((AAudioProperty_getLogMask() & AAUDIO_LOG_CLOCK_MODEL_HISTOGRAM) != 0) { mHistogramMicros = std::make_unique(kHistogramBinCount, diff --git a/media/libaaudio/src/client/IsochronousClockModel.h b/media/libaaudio/src/client/IsochronousClockModel.h index 6280013587..3007237866 100644 --- a/media/libaaudio/src/client/IsochronousClockModel.h +++ b/media/libaaudio/src/client/IsochronousClockModel.h @@ -149,16 +149,16 @@ private: static constexpr int32_t kHistogramBinWidthMicros = 50; static constexpr int32_t kHistogramBinCount = 128; - int64_t mMarkerFramePosition; // Estimated HW position. - int64_t mMarkerNanoTime; // Estimated HW time. - int32_t mSampleRate; - int32_t mFramesPerBurst; // number of frames transferred at one time. - int32_t mBurstPeriodNanos; // Time between HW bursts. + int64_t mMarkerFramePosition{0}; // Estimated HW position. + int64_t mMarkerNanoTime{0}; // Estimated HW time. + int32_t mSampleRate{48000}; + int32_t mFramesPerBurst{48}; // number of frames transferred at one time. + int32_t mBurstPeriodNanos{0}; // Time between HW bursts. // Includes mBurstPeriodNanos because we sample randomly over time. - int32_t mMaxMeasuredLatenessNanos; + int32_t mMaxMeasuredLatenessNanos{0}; // Threshold for lateness that triggers a drift later in time. int32_t mLatenessForDriftNanos; - clock_model_state_t mState; // State machine handles startup sequence. + clock_model_state_t mState{STATE_STOPPED}; // State machine handles startup sequence. int32_t mTimestampCount = 0; // For logging. diff --git a/media/libaaudio/src/core/AAudioStreamParameters.cpp b/media/libaaudio/src/core/AAudioStreamParameters.cpp index 0d60120a9d..2694f41ed5 100644 --- a/media/libaaudio/src/core/AAudioStreamParameters.cpp +++ b/media/libaaudio/src/core/AAudioStreamParameters.cpp @@ -31,9 +31,6 @@ using namespace aaudio; // HDMI supports up to 32 channels at 1536000 Hz. #define SAMPLE_RATE_HZ_MAX 1600000 -AAudioStreamParameters::AAudioStreamParameters() {} -AAudioStreamParameters::~AAudioStreamParameters() {} - void AAudioStreamParameters::copyFrom(const AAudioStreamParameters &other) { mSamplesPerFrame = other.mSamplesPerFrame; mSampleRate = other.mSampleRate; diff --git a/media/libaaudio/src/core/AAudioStreamParameters.h b/media/libaaudio/src/core/AAudioStreamParameters.h index 5737052326..0349ffc117 100644 --- a/media/libaaudio/src/core/AAudioStreamParameters.h +++ b/media/libaaudio/src/core/AAudioStreamParameters.h @@ -26,8 +26,8 @@ namespace aaudio { class AAudioStreamParameters { public: - AAudioStreamParameters(); - virtual ~AAudioStreamParameters(); + AAudioStreamParameters() = default; + virtual ~AAudioStreamParameters() = default; int32_t getDeviceId() const { return mDeviceId; @@ -141,7 +141,7 @@ public: } // TODO b/182392769: reexamine if Identity can be used - void setOpPackageName(const std::optional opPackageName) { + void setOpPackageName(const std::optional& opPackageName) { mOpPackageName = opPackageName; } @@ -149,7 +149,7 @@ public: return mAttributionTag; } - void setAttributionTag(const std::optional attributionTag) { + void setAttributionTag(const std::optional& attributionTag) { mAttributionTag = attributionTag; } diff --git a/media/libaaudio/src/core/AudioGlobal.h b/media/libaaudio/src/core/AudioGlobal.h index 1e88d15df7..6c22744bb7 100644 --- a/media/libaaudio/src/core/AudioGlobal.h +++ b/media/libaaudio/src/core/AudioGlobal.h @@ -31,7 +31,8 @@ const char* AudioGlobal_convertPerformanceModeToText(aaudio_performance_mode_t m const char* AudioGlobal_convertResultToText(aaudio_result_t returnCode); const char* AudioGlobal_convertSharingModeToText(aaudio_sharing_mode_t mode); const char* AudioGlobal_convertStreamStateToText(aaudio_stream_state_t state); -} + +} // namespace aaudio #endif // AAUDIO_AUDIOGLOBAL_H diff --git a/media/libaaudio/src/core/AudioStream.h b/media/libaaudio/src/core/AudioStream.h index 3930964cdd..6ee8c54897 100644 --- a/media/libaaudio/src/core/AudioStream.h +++ b/media/libaaudio/src/core/AudioStream.h @@ -425,7 +425,7 @@ protected: // PlayerBase allows the system to control the stream volume. class MyPlayerBase : public android::PlayerBase { public: - MyPlayerBase() {}; + MyPlayerBase() = default; virtual ~MyPlayerBase() = default; @@ -554,7 +554,7 @@ protected: * @param numFrames * @return original pointer or the conversion buffer */ - virtual const void * maybeConvertDeviceData(const void *audioData, int32_t numFrames) { + virtual const void * maybeConvertDeviceData(const void *audioData, int32_t /*numFrames*/) { return audioData; } diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp index 207a8e38fd..494c22fb95 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.cpp +++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp @@ -54,16 +54,10 @@ using namespace aaudio; /* * AudioStreamBuilder */ -AudioStreamBuilder::AudioStreamBuilder() { -} - -AudioStreamBuilder::~AudioStreamBuilder() { -} - static aaudio_result_t builder_createStream(aaudio_direction_t direction, - aaudio_sharing_mode_t sharingMode, - bool tryMMap, - android::sp &stream) { + aaudio_sharing_mode_t /*sharingMode*/, + bool tryMMap, + android::sp &stream) { aaudio_result_t result = AAUDIO_OK; switch (direction) { diff --git a/media/libaaudio/src/core/AudioStreamBuilder.h b/media/libaaudio/src/core/AudioStreamBuilder.h index 9f93341ea4..f91c25a183 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.h +++ b/media/libaaudio/src/core/AudioStreamBuilder.h @@ -31,9 +31,9 @@ namespace aaudio { */ class AudioStreamBuilder : public AAudioStreamParameters { public: - AudioStreamBuilder(); + AudioStreamBuilder() = default; - ~AudioStreamBuilder(); + ~AudioStreamBuilder() = default; bool isSharingModeMatchRequired() const { return mSharingModeMatchRequired; diff --git a/media/libaaudio/src/fifo/FifoBuffer.h b/media/libaaudio/src/fifo/FifoBuffer.h index 37548f0cfb..7b0aca1f82 100644 --- a/media/libaaudio/src/fifo/FifoBuffer.h +++ b/media/libaaudio/src/fifo/FifoBuffer.h @@ -38,7 +38,7 @@ struct WrappingBuffer { class FifoBuffer { public: - FifoBuffer(int32_t bytesPerFrame); + explicit FifoBuffer(int32_t bytesPerFrame); virtual ~FifoBuffer() = default; @@ -162,6 +162,6 @@ private: uint8_t *mExternalStorage = nullptr; }; -} // android +} // namespace android #endif //FIFO_FIFO_BUFFER_H diff --git a/media/libaaudio/src/fifo/FifoController.h b/media/libaaudio/src/fifo/FifoController.h index 057a94e699..e15d444f2d 100644 --- a/media/libaaudio/src/fifo/FifoController.h +++ b/media/libaaudio/src/fifo/FifoController.h @@ -36,7 +36,7 @@ public: , mWriteCounter(0) {} - virtual ~FifoController() {} + virtual ~FifoController() = default; // TODO review use of memory barriers, probably incorrect virtual fifo_counter_t getReadCounter() override { @@ -57,6 +57,6 @@ private: std::atomic mWriteCounter; }; -} // android +} // namespace android #endif //FIFO_FIFO_CONTROLLER_H diff --git a/media/libaaudio/src/fifo/FifoControllerBase.cpp b/media/libaaudio/src/fifo/FifoControllerBase.cpp index 1dece0eb97..ad6d0415fe 100644 --- a/media/libaaudio/src/fifo/FifoControllerBase.cpp +++ b/media/libaaudio/src/fifo/FifoControllerBase.cpp @@ -29,9 +29,6 @@ FifoControllerBase::FifoControllerBase(fifo_frames_t capacity, fifo_frames_t thr { } -FifoControllerBase::~FifoControllerBase() { -} - fifo_frames_t FifoControllerBase::getFullFramesAvailable() { fifo_frames_t temp = 0; __builtin_sub_overflow(getWriteCounter(), getReadCounter(), &temp); diff --git a/media/libaaudio/src/fifo/FifoControllerBase.h b/media/libaaudio/src/fifo/FifoControllerBase.h index 1edb8a3cb5..2a6173b0ff 100644 --- a/media/libaaudio/src/fifo/FifoControllerBase.h +++ b/media/libaaudio/src/fifo/FifoControllerBase.h @@ -43,7 +43,7 @@ public: */ FifoControllerBase(fifo_frames_t capacity, fifo_frames_t threshold); - virtual ~FifoControllerBase(); + virtual ~FifoControllerBase() = default; // Abstract methods to be implemented in subclasses. /** @@ -123,6 +123,6 @@ private: fifo_frames_t mThreshold; }; -} // android +} // namespace android #endif // FIFO_FIFO_CONTROLLER_BASE_H diff --git a/media/libaaudio/src/fifo/FifoControllerIndirect.h b/media/libaaudio/src/fifo/FifoControllerIndirect.h index ec48e5778d..a59225adf0 100644 --- a/media/libaaudio/src/fifo/FifoControllerIndirect.h +++ b/media/libaaudio/src/fifo/FifoControllerIndirect.h @@ -44,7 +44,7 @@ public: setReadCounter(0); setWriteCounter(0); } - virtual ~FifoControllerIndirect() {}; + virtual ~FifoControllerIndirect() = default; // TODO review use of memory barriers, probably incorrect virtual fifo_counter_t getReadCounter() override { @@ -68,6 +68,6 @@ private: std::atomic * mWriteCounterAddress; }; -} // android +} // namespace android #endif //FIFO_FIFO_CONTROLLER_INDIRECT_H diff --git a/media/libaaudio/src/flowgraph/AudioProcessorBase.cpp b/media/libaaudio/src/flowgraph/AudioProcessorBase.cpp index 5667fdbc7b..d8ffd005b8 100644 --- a/media/libaaudio/src/flowgraph/AudioProcessorBase.cpp +++ b/media/libaaudio/src/flowgraph/AudioProcessorBase.cpp @@ -34,8 +34,7 @@ AudioFloatBlockPort::AudioFloatBlockPort(AudioProcessorBase &parent, int32_t samplesPerFrame, int32_t framesPerBlock) : AudioPort(parent, samplesPerFrame) - , mFramesPerBlock(framesPerBlock) - , mSampleBlock(NULL) { + , mFramesPerBlock(framesPerBlock) { int32_t numFloats = framesPerBlock * getSamplesPerFrame(); mSampleBlock = new float[numFloats]{0.0f}; } @@ -61,13 +60,13 @@ void AudioFloatOutputPort::disconnect(AudioFloatInputPort *port) { /***************************************************************************/ int32_t AudioFloatInputPort::pullData(int64_t framePosition, int32_t numFrames) { - return (mConnected == NULL) + return (mConnected == nullptr) ? std::min(getFramesPerBlock(), numFrames) : mConnected->pullData(framePosition, numFrames); } float *AudioFloatInputPort::getBlock() { - if (mConnected == NULL) { + if (mConnected == nullptr) { return AudioFloatBlockPort::getBlock(); // loaded using setValue() } else { return mConnected->getBlock(); diff --git a/media/libaaudio/src/flowgraph/MonoToMultiConverter.cpp b/media/libaaudio/src/flowgraph/MonoToMultiConverter.cpp index 78aad52fa2..c6fcac614a 100644 --- a/media/libaaudio/src/flowgraph/MonoToMultiConverter.cpp +++ b/media/libaaudio/src/flowgraph/MonoToMultiConverter.cpp @@ -26,8 +26,6 @@ MonoToMultiConverter::MonoToMultiConverter(int32_t channelCount) , output(*this, channelCount) { } -MonoToMultiConverter::~MonoToMultiConverter() { } - int32_t MonoToMultiConverter::onProcess(int64_t framePosition, int32_t numFrames) { int32_t framesToProcess = input.pullData(framePosition, numFrames); diff --git a/media/libaaudio/src/flowgraph/MonoToMultiConverter.h b/media/libaaudio/src/flowgraph/MonoToMultiConverter.h index 34d53c713a..5058ae0060 100644 --- a/media/libaaudio/src/flowgraph/MonoToMultiConverter.h +++ b/media/libaaudio/src/flowgraph/MonoToMultiConverter.h @@ -29,7 +29,7 @@ class MonoToMultiConverter : public AudioProcessorBase { public: explicit MonoToMultiConverter(int32_t channelCount); - virtual ~MonoToMultiConverter(); + virtual ~MonoToMultiConverter() = default; int32_t onProcess(int64_t framePosition, int32_t numFrames) override; diff --git a/media/libaaudio/src/flowgraph/SourceFloat.cpp b/media/libaaudio/src/flowgraph/SourceFloat.cpp index 4bb674fdfc..5b3a51eb08 100644 --- a/media/libaaudio/src/flowgraph/SourceFloat.cpp +++ b/media/libaaudio/src/flowgraph/SourceFloat.cpp @@ -25,7 +25,7 @@ SourceFloat::SourceFloat(int32_t channelCount) : AudioSource(channelCount) { } -int32_t SourceFloat::onProcess(int64_t framePosition, int32_t numFrames) { +int32_t SourceFloat::onProcess(int64_t /*framePosition*/, int32_t numFrames) { float *outputBuffer = output.getBlock(); int32_t channelCount = output.getSamplesPerFrame(); diff --git a/media/libaaudio/src/flowgraph/SourceI16.cpp b/media/libaaudio/src/flowgraph/SourceI16.cpp index c3fcec28e2..a645cc2668 100644 --- a/media/libaaudio/src/flowgraph/SourceI16.cpp +++ b/media/libaaudio/src/flowgraph/SourceI16.cpp @@ -30,7 +30,7 @@ SourceI16::SourceI16(int32_t channelCount) : AudioSource(channelCount) { } -int32_t SourceI16::onProcess(int64_t framePosition, int32_t numFrames) { +int32_t SourceI16::onProcess(int64_t /*framePosition*/, int32_t numFrames) { float *floatData = output.getBlock(); int32_t channelCount = output.getSamplesPerFrame(); diff --git a/media/libaaudio/src/flowgraph/SourceI24.cpp b/media/libaaudio/src/flowgraph/SourceI24.cpp index 097954ec8a..50fb98e000 100644 --- a/media/libaaudio/src/flowgraph/SourceI24.cpp +++ b/media/libaaudio/src/flowgraph/SourceI24.cpp @@ -32,7 +32,7 @@ SourceI24::SourceI24(int32_t channelCount) : AudioSource(channelCount) { } -int32_t SourceI24::onProcess(int64_t framePosition, int32_t numFrames) { +int32_t SourceI24::onProcess(int64_t /*framePosition*/, int32_t numFrames) { float *floatData = output.getBlock(); int32_t channelCount = output.getSamplesPerFrame(); diff --git a/media/libaaudio/src/flowgraph/SourceI32.cpp b/media/libaaudio/src/flowgraph/SourceI32.cpp index e8177ad20c..95bfd8f98d 100644 --- a/media/libaaudio/src/flowgraph/SourceI32.cpp +++ b/media/libaaudio/src/flowgraph/SourceI32.cpp @@ -30,7 +30,7 @@ SourceI32::SourceI32(int32_t channelCount) : AudioSource(channelCount) { } -int32_t SourceI32::onProcess(int64_t framePosition, int32_t numFrames) { +int32_t SourceI32::onProcess(int64_t /*framePosition*/, int32_t numFrames) { float *floatData = output.getBlock(); int32_t channelCount = output.getSamplesPerFrame(); diff --git a/media/libaaudio/src/legacy/AudioStreamLegacy.cpp b/media/libaaudio/src/legacy/AudioStreamLegacy.cpp index 60eb73a660..b6bd0e1e39 100644 --- a/media/libaaudio/src/legacy/AudioStreamLegacy.cpp +++ b/media/libaaudio/src/legacy/AudioStreamLegacy.cpp @@ -37,9 +37,6 @@ AudioStreamLegacy::AudioStreamLegacy() : AudioStream() { } -AudioStreamLegacy::~AudioStreamLegacy() { -} - // Called from AudioTrack.cpp or AudioRecord.cpp static void AudioStreamLegacy_callback(int event, void* userData, void *info) { AudioStreamLegacy *streamLegacy = (AudioStreamLegacy *) userData; diff --git a/media/libaaudio/src/legacy/AudioStreamLegacy.h b/media/libaaudio/src/legacy/AudioStreamLegacy.h index 88ef27070b..d9ba990e22 100644 --- a/media/libaaudio/src/legacy/AudioStreamLegacy.h +++ b/media/libaaudio/src/legacy/AudioStreamLegacy.h @@ -60,7 +60,7 @@ class AudioStreamLegacy : public AudioStream, public FixedBlockProcessor { public: AudioStreamLegacy(); - virtual ~AudioStreamLegacy(); + virtual ~AudioStreamLegacy() = default; aaudio_legacy_callback_t getLegacyCallback(); diff --git a/media/libaaudio/src/legacy/AudioStreamRecord.cpp b/media/libaaudio/src/legacy/AudioStreamRecord.cpp index e3ac6ffbb0..f907074856 100644 --- a/media/libaaudio/src/legacy/AudioStreamRecord.cpp +++ b/media/libaaudio/src/legacy/AudioStreamRecord.cpp @@ -496,7 +496,7 @@ aaudio_result_t AudioStreamRecord::read(void *buffer, return (aaudio_result_t) framesRead; } -aaudio_result_t AudioStreamRecord::setBufferSize(int32_t requestedFrames) +aaudio_result_t AudioStreamRecord::setBufferSize(int32_t /*requestedFrames*/) { return getBufferSize(); } diff --git a/media/libaaudio/src/legacy/AudioStreamTrack.cpp b/media/libaaudio/src/legacy/AudioStreamTrack.cpp index df97658e35..65d9382774 100644 --- a/media/libaaudio/src/legacy/AudioStreamTrack.cpp +++ b/media/libaaudio/src/legacy/AudioStreamTrack.cpp @@ -160,11 +160,11 @@ aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder) callback, callbackData, notificationFrames, - 0, // DEFAULT sharedBuffer*/, + nullptr, // DEFAULT sharedBuffer*/, false, // DEFAULT threadCanCallJava sessionId, streamTransferType, - NULL, // DEFAULT audio_offload_info_t + nullptr, // DEFAULT audio_offload_info_t Identity(), // DEFAULT uid and pid &attributes, // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging diff --git a/media/libaaudio/src/utility/AAudioUtilities.h b/media/libaaudio/src/utility/AAudioUtilities.h index 82eb77dd19..ee8cfd2fa3 100644 --- a/media/libaaudio/src/utility/AAudioUtilities.h +++ b/media/libaaudio/src/utility/AAudioUtilities.h @@ -198,7 +198,7 @@ aaudio_result_t AAudio_isFlushAllowed(aaudio_stream_state_t state); * @return true if f() eventually returns true. */ static inline bool AAudio_tryUntilTrue( - std::function f, int times, int sleepMs) { + const std::function& f, int times, int sleepMs) { static const useconds_t US_PER_MS = 1000; sleepMs = std::max(sleepMs, 0); @@ -270,9 +270,7 @@ private: class Timestamp { public: - Timestamp() - : mPosition(0) - , mNanoseconds(0) {} + Timestamp() = default; Timestamp(int64_t position, int64_t nanoseconds) : mPosition(position) , mNanoseconds(nanoseconds) {} @@ -283,8 +281,8 @@ public: private: // These cannot be const because we need to implement the copy assignment operator. - int64_t mPosition; - int64_t mNanoseconds; + int64_t mPosition{0}; + int64_t mNanoseconds{0}; }; diff --git a/media/libaaudio/src/utility/FixedBlockAdapter.h b/media/libaaudio/src/utility/FixedBlockAdapter.h index 4dc7e68959..290e47360f 100644 --- a/media/libaaudio/src/utility/FixedBlockAdapter.h +++ b/media/libaaudio/src/utility/FixedBlockAdapter.h @@ -35,7 +35,7 @@ public: class FixedBlockAdapter { public: - FixedBlockAdapter(FixedBlockProcessor &fixedBlockProcessor) + explicit FixedBlockAdapter(FixedBlockProcessor &fixedBlockProcessor) : mFixedBlockProcessor(fixedBlockProcessor) {} virtual ~FixedBlockAdapter() = default; diff --git a/media/libaaudio/src/utility/FixedBlockReader.h b/media/libaaudio/src/utility/FixedBlockReader.h index 128dd52fdd..dc824167f8 100644 --- a/media/libaaudio/src/utility/FixedBlockReader.h +++ b/media/libaaudio/src/utility/FixedBlockReader.h @@ -30,7 +30,7 @@ class FixedBlockReader : public FixedBlockAdapter { public: - FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor); + explicit FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor); virtual ~FixedBlockReader() = default; diff --git a/media/libaaudio/src/utility/FixedBlockWriter.h b/media/libaaudio/src/utility/FixedBlockWriter.h index f1d917ca08..3e89b5d0c6 100644 --- a/media/libaaudio/src/utility/FixedBlockWriter.h +++ b/media/libaaudio/src/utility/FixedBlockWriter.h @@ -28,7 +28,7 @@ class FixedBlockWriter : public FixedBlockAdapter { public: - FixedBlockWriter(FixedBlockProcessor &fixedBlockProcessor); + explicit FixedBlockWriter(FixedBlockProcessor &fixedBlockProcessor); virtual ~FixedBlockWriter() = default; diff --git a/media/libaaudio/src/utility/MonotonicCounter.h b/media/libaaudio/src/utility/MonotonicCounter.h index 63add4e8dd..313ccbdcca 100644 --- a/media/libaaudio/src/utility/MonotonicCounter.h +++ b/media/libaaudio/src/utility/MonotonicCounter.h @@ -30,8 +30,8 @@ class MonotonicCounter { public: - MonotonicCounter() {}; - virtual ~MonotonicCounter() {}; + MonotonicCounter() = default; + virtual ~MonotonicCounter() = default; /** * @return current value of the counter -- GitLab From 89b52c7b76c18b58f06487d45bc61a9792b4e1eb Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Wed, 28 Apr 2021 23:38:51 +0100 Subject: [PATCH 041/694] Rename extractor symbols to log session id Test: atest CtsMediaHostTestCases Bug: 167036690 Change-Id: Idfa64caade07760a0193bb9036115f8b6cf71049 --- media/libmedia/IMediaExtractor.cpp | 18 +++++++++--------- .../libmedia/include/android/IMediaExtractor.h | 2 +- media/libstagefright/NuMediaExtractor.cpp | 6 +++--- media/libstagefright/RemoteMediaExtractor.cpp | 9 ++++++--- .../media/stagefright/NuMediaExtractor.h | 2 +- .../media/stagefright/RemoteMediaExtractor.h | 2 +- services/mediametrics/statsd_extractor.cpp | 13 +++++-------- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/media/libmedia/IMediaExtractor.cpp b/media/libmedia/IMediaExtractor.cpp index 5999e516cb..eb436d1b7b 100644 --- a/media/libmedia/IMediaExtractor.cpp +++ b/media/libmedia/IMediaExtractor.cpp @@ -40,7 +40,7 @@ enum { NAME, GETMETRICS, SETENTRYPOINT, - SETPLAYBACKID + SETLOGSESSIONID }; class BpMediaExtractor : public BpInterface { @@ -152,11 +152,11 @@ public: return remote()->transact(SETENTRYPOINT, data, &reply); } - virtual status_t setPlaybackId(const String8& playbackId) { + virtual status_t setLogSessionId(const String8& logSessionId) { Parcel data, reply; data.writeInterfaceToken(BpMediaExtractor::getInterfaceDescriptor()); - data.writeString8(playbackId); - return remote()->transact(SETPLAYBACKID, data, &reply); + data.writeString8(logSessionId); + return remote()->transact(SETLOGSESSIONID, data, &reply); } }; @@ -258,13 +258,13 @@ status_t BnMediaExtractor::onTransact( } return err; } - case SETPLAYBACKID: { - ALOGV("setPlaybackId"); + case SETLOGSESSIONID: { + ALOGV("setLogSessionId"); CHECK_INTERFACE(IMediaExtractor, data, reply); - String8 playbackId; - status_t status = data.readString8(&playbackId); + String8 logSessionId; + status_t status = data.readString8(&logSessionId); if (status == OK) { - setPlaybackId(playbackId); + setLogSessionId(logSessionId); } return status; } diff --git a/media/libmedia/include/android/IMediaExtractor.h b/media/libmedia/include/android/IMediaExtractor.h index 8a5d24dad5..bb1eb99240 100644 --- a/media/libmedia/include/android/IMediaExtractor.h +++ b/media/libmedia/include/android/IMediaExtractor.h @@ -73,7 +73,7 @@ public: virtual status_t setEntryPoint(EntryPoint entryPoint) = 0; - virtual status_t setPlaybackId(const String8& playbackId) = 0; + virtual status_t setLogSessionId(const String8& logSessionId) = 0; }; diff --git a/media/libstagefright/NuMediaExtractor.cpp b/media/libstagefright/NuMediaExtractor.cpp index f54a56f5c2..a5c3ba608e 100644 --- a/media/libstagefright/NuMediaExtractor.cpp +++ b/media/libstagefright/NuMediaExtractor.cpp @@ -885,13 +885,13 @@ status_t NuMediaExtractor::getAudioPresentations( return ERROR_UNSUPPORTED; } -status_t NuMediaExtractor::setPlaybackId(const String8& playbackId) { +status_t NuMediaExtractor::setLogSessionId(const String8& logSessionId) { if (mImpl == nullptr) { return ERROR_UNSUPPORTED; } - status_t status = mImpl->setPlaybackId(playbackId); + status_t status = mImpl->setLogSessionId(logSessionId); if (status != OK) { - ALOGW("Failed to set playback session id: %d.", status); + ALOGW("Failed to set log session id: %d.", status); } return status; } diff --git a/media/libstagefright/RemoteMediaExtractor.cpp b/media/libstagefright/RemoteMediaExtractor.cpp index c4bde7e021..baa2ca1208 100644 --- a/media/libstagefright/RemoteMediaExtractor.cpp +++ b/media/libstagefright/RemoteMediaExtractor.cpp @@ -39,8 +39,11 @@ static const char *kKeyExtractor = "extractor"; static const char *kExtractorFormat = "android.media.mediaextractor.fmt"; static const char *kExtractorMime = "android.media.mediaextractor.mime"; static const char *kExtractorTracks = "android.media.mediaextractor.ntrk"; + +// The following are not available in frameworks/base/media/java/android/media/MediaExtractor.java +// because they are not applicable or useful to that API. static const char *kExtractorEntryPoint = "android.media.mediaextractor.entry"; -static const char *kExtractorPlaybackId = "android.media.mediaextractor.playbackId"; +static const char *kExtractorLogSessionId = "android.media.mediaextractor.logSessionId"; static const char *kEntryPointSdk = "sdk"; static const char *kEntryPointWithJvm = "ndk-with-jvm"; @@ -175,8 +178,8 @@ status_t RemoteMediaExtractor::setEntryPoint(EntryPoint entryPoint) { return OK; } -status_t RemoteMediaExtractor::setPlaybackId(const String8& playbackId) { - mMetricsItem->setCString(kExtractorPlaybackId, playbackId.c_str()); +status_t RemoteMediaExtractor::setLogSessionId(const String8& logSessionId) { + mMetricsItem->setCString(kExtractorLogSessionId, logSessionId.c_str()); return OK; } diff --git a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h index 6aa7c0fd46..d17a480bb8 100644 --- a/media/libstagefright/include/media/stagefright/NuMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/NuMediaExtractor.h @@ -100,7 +100,7 @@ struct NuMediaExtractor : public RefBase { status_t getAudioPresentations(size_t trackIdx, AudioPresentationCollection *presentations); - status_t setPlaybackId(const String8& playbackId); + status_t setLogSessionId(const String8& logSessionId); const char* getName() const; diff --git a/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h index 9b2841f0d4..9ad90d792b 100644 --- a/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h +++ b/media/libstagefright/include/media/stagefright/RemoteMediaExtractor.h @@ -43,7 +43,7 @@ public: virtual status_t setMediaCas(const HInterfaceToken &casToken); virtual String8 name(); virtual status_t setEntryPoint(EntryPoint entryPoint); - virtual status_t setPlaybackId(const String8& playbackId); + virtual status_t setLogSessionId(const String8& logSessionId); private: MediaExtractor *mExtractor; diff --git a/services/mediametrics/statsd_extractor.cpp b/services/mediametrics/statsd_extractor.cpp index a45f39974b..281a4ce394 100644 --- a/services/mediametrics/statsd_extractor.cpp +++ b/services/mediametrics/statsd_extractor.cpp @@ -86,10 +86,10 @@ bool statsd_extractor(const std::shared_ptr& item, metrics_proto.set_entry_point(entry_point); } - // android.media.mediaextractor.playbackId string - std::string playback_id; - if (item->getString("android.media.mediaextractor.playbackId", &playback_id)) { - metrics_proto.set_playback_id(std::move(playback_id)); + // android.media.mediaextractor.logSessionId string + std::string log_session_id; + if (item->getString("android.media.mediaextractor.logSessionId", &log_session_id)) { + metrics_proto.set_log_session_id(log_session_id); } std::string serialized; @@ -116,10 +116,7 @@ bool statsd_extractor(const std::shared_ptr& item, << " mime:" << mime << " tracks:" << tracks << " entry_point:" << entry_point_string << "(" << entry_point << ")" - - // TODO: Add MediaExtractor log_session_id - // << " log_session_id:" << log_session_id - + << " log_session_id:" << log_session_id << " }"; statsdLog->log(android::util::MEDIAMETRICS_EXTRACTOR_REPORTED, log.str()); return true; -- GitLab From 722c4d202d455231b6ecfe826d9590d527f3422e Mon Sep 17 00:00:00 2001 From: Jasmine Cha Date: Tue, 11 May 2021 10:11:14 +0800 Subject: [PATCH 042/694] audio: refactor update metadata process The meta data isn't updated when stream volume was changed on MMAP playback thread. - Move readAndClearHasChanged() and setMetadataHasChanged() from Track to TrackBase and changes of meta data is able to be noticed for all types of track. - Added the flow to check every track's status on ActiveTracks::readAndClearHasChanged(). - Added isStreamInitialized() in ThreadBase to simplify the processed flow for each thread. Bug: 187769565 Test: mmap playback/deep-buffer/offload/low-latency Signed-off-by: Jasmine Cha Change-Id: I949772cf38c77de4e41d4d699231c1edecf70f76 --- services/audioflinger/PlaybackTracks.h | 12 ------- services/audioflinger/Threads.cpp | 47 ++++++++++++-------------- services/audioflinger/Threads.h | 24 ++++++++++++- services/audioflinger/TrackBase.h | 14 ++++++++ 4 files changed, 59 insertions(+), 38 deletions(-) diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h index 24362488f5..0af4c7b553 100644 --- a/services/audioflinger/PlaybackTracks.h +++ b/services/audioflinger/PlaybackTracks.h @@ -148,14 +148,6 @@ public: void setFinalVolume(float volume); float getFinalVolume() const { return mFinalVolume; } - /** @return true if the track has changed (metadata or volume) since - * the last time this function was called, - * true if this function was never called since the track creation, - * false otherwise. - * Thread safe. - */ - bool readAndClearHasChanged() { return !mChangeNotified.test_and_set(); } - using SourceMetadatas = std::vector; using MetadataInserter = std::back_insert_iterator; /** Copy the track metadata in the provided iterator. Thread safe. */ @@ -234,8 +226,6 @@ protected: bool presentationComplete(int64_t framesWritten, size_t audioHalFrames); void signalClientFlag(int32_t flag); - /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */ - void setMetadataHasChanged() { mChangeNotified.clear(); } public: void triggerEvents(AudioSystem::sync_event_t type); virtual void invalidate(); @@ -320,8 +310,6 @@ private: bool mFlushHwPending; // track requests for thread flush bool mPauseHwPending = false; // direct/offload track request for thread pause audio_output_flags_t mFlags; - // If the last track change was notified to the client with readAndClearHasChanged - std::atomic_flag mChangeNotified = ATOMIC_FLAG_INIT; TeePatches mTeePatches; }; // end of Track diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 4fc60a4688..656cc88fe9 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -1798,8 +1798,14 @@ void AudioFlinger::ThreadBase::ActiveTracks::updatePowerState( template bool AudioFlinger::ThreadBase::ActiveTracks::readAndClearHasChanged() { - const bool hasChanged = mHasChanged; + bool hasChanged = mHasChanged; mHasChanged = false; + + for (const sp &track : mActiveTracks) { + // Do not short-circuit as all hasChanged states must be reset + // as all the metadata are going to be sent + hasChanged |= track->readAndClearHasChanged(); + } return hasChanged; } @@ -1986,7 +1992,7 @@ AudioFlinger::PlaybackThread::~PlaybackThread() void AudioFlinger::PlaybackThread::onFirstRef() { - if (mOutput == nullptr || mOutput->stream == nullptr) { + if (!isStreamInitialized()) { ALOGE("The stream is not open yet"); // This should not happen. } else { // setEventCallback will need a strong pointer as a parameter. Calling it @@ -2695,7 +2701,7 @@ String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys) status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) { Mutex::Autolock _l(mLock); - if (mOutput == nullptr || mOutput->stream == nullptr) { + if (!isStreamInitialized()) { return NO_INIT; } return mOutput->stream->selectPresentation(presentationId, programId); @@ -2992,16 +2998,7 @@ void AudioFlinger::PlaybackThread::readOutputParameters_l() void AudioFlinger::PlaybackThread::updateMetadata_l() { - if (mOutput == nullptr || mOutput->stream == nullptr ) { - return; // That should not happen - } - bool hasChanged = mActiveTracks.readAndClearHasChanged(); - for (const sp &track : mActiveTracks) { - // Do not short-circuit as all hasChanged states must be reset - // as all the metadata are going to be sent - hasChanged |= track->readAndClearHasChanged(); - } - if (!hasChanged) { + if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) { return; // nothing to do } StreamOutHalInterface::SourceMetadata metadata; @@ -8186,7 +8183,7 @@ status_t AudioFlinger::RecordThread::getActiveMicrophones( { ALOGV("RecordThread::getActiveMicrophones"); AutoMutex _l(mLock); - if (mInput == nullptr || mInput->stream == nullptr) { + if (!isStreamInitialized()) { return NO_INIT; } status_t status = mInput->stream->getActiveMicrophones(activeMicrophones); @@ -8198,7 +8195,7 @@ status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection( { ALOGV("setPreferredMicrophoneDirection(%d)", direction); AutoMutex _l(mLock); - if (mInput == nullptr || mInput->stream == nullptr) { + if (!isStreamInitialized()) { return NO_INIT; } return mInput->stream->setPreferredMicrophoneDirection(direction); @@ -8208,7 +8205,7 @@ status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float { ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom); AutoMutex _l(mLock); - if (mInput == nullptr || mInput->stream == nullptr) { + if (!isStreamInitialized()) { return NO_INIT; } return mInput->stream->setPreferredMicrophoneFieldDimension(zoom); @@ -8259,9 +8256,8 @@ status_t AudioFlinger::RecordThread::shareAudioHistory_l( void AudioFlinger::RecordThread::updateMetadata_l() { - if (mInput == nullptr || mInput->stream == nullptr || - !mActiveTracks.readAndClearHasChanged()) { - return; + if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) { + return; // nothing to do } StreamInHalInterface::SinkMetadata metadata; for (const sp &track : mActiveTracks) { @@ -9959,14 +9955,16 @@ void AudioFlinger::MmapPlaybackThread::processVolume_l() } } } + for (const sp &track : mActiveTracks) { + track->setMetadataHasChanged(); + } } } void AudioFlinger::MmapPlaybackThread::updateMetadata_l() { - if (mOutput == nullptr || mOutput->stream == nullptr || - !mActiveTracks.readAndClearHasChanged()) { - return; + if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) { + return; // nothing to do } StreamOutHalInterface::SourceMetadata metadata; for (const sp &track : mActiveTracks) { @@ -10093,9 +10091,8 @@ void AudioFlinger::MmapCaptureThread::processVolume_l() void AudioFlinger::MmapCaptureThread::updateMetadata_l() { - if (mInput == nullptr || mInput->stream == nullptr || - !mActiveTracks.readAndClearHasChanged()) { - return; + if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) { + return; // nothing to do } StreamInHalInterface::SinkMetadata metadata; for (const sp &track : mActiveTracks) { diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h index 65db986cf6..17acb16fcc 100644 --- a/services/audioflinger/Threads.h +++ b/services/audioflinger/Threads.h @@ -527,6 +527,8 @@ public: } } + virtual bool isStreamInitialized() = 0; + protected: // entry describing an effect being suspended in mSuspendedSessions keyed vector @@ -741,7 +743,9 @@ protected: void updatePowerState(sp thread, bool force = false); /** @return true if one or move active tracks was added or removed since the - * last time this function was called or the vector was created. */ + * last time this function was called or the vector was created. + * true if volume of one of active tracks was changed. + */ bool readAndClearHasChanged(); private: @@ -993,6 +997,10 @@ public: && outDeviceTypes().count(mTimestampCorrectedDevice) != 0; } + virtual bool isStreamInitialized() { + return !(mOutput == nullptr || mOutput->stream == nullptr); + } + audio_channel_mask_t hapticChannelMask() const override { return mHapticChannelMask; } @@ -1780,6 +1788,10 @@ public: audio_session_t sharedSessionId = AUDIO_SESSION_NONE, int64_t sharedAudioStartMs = -1); + virtual bool isStreamInitialized() { + return !(mInput == nullptr || mInput->stream == nullptr); + } + protected: void dumpInternals_l(int fd, const Vector& args) override; void dumpTracks_l(int fd, const Vector& args) override; @@ -1949,6 +1961,8 @@ class MmapThread : public ThreadBase virtual void setRecordSilenced(audio_port_handle_t portId __unused, bool silenced __unused) {} + virtual bool isStreamInitialized() { return false; } + protected: void dumpInternals_l(int fd, const Vector& args) override; void dumpTracks_l(int fd, const Vector& args) override; @@ -2011,6 +2025,10 @@ public: status_t getExternalPosition(uint64_t *position, int64_t *timeNanos) override; + virtual bool isStreamInitialized() { + return !(mOutput == nullptr || mOutput->stream == nullptr); + } + protected: void dumpInternals_l(int fd, const Vector& args) override; @@ -2043,6 +2061,10 @@ public: status_t getExternalPosition(uint64_t *position, int64_t *timeNanos) override; + virtual bool isStreamInitialized() { + return !(mInput == nullptr || mInput->stream == nullptr); + } + protected: AudioStreamIn* mInput; diff --git a/services/audioflinger/TrackBase.h b/services/audioflinger/TrackBase.h index 38dab5ba11..92f129cfa1 100644 --- a/services/audioflinger/TrackBase.h +++ b/services/audioflinger/TrackBase.h @@ -255,6 +255,17 @@ public: audio_channel_mask_t channelMask() const { return mChannelMask; } + /** @return true if the track has changed (metadata or volume) since + * the last time this function was called, + * true if this function was never called since the track creation, + * false otherwise. + * Thread safe. + */ + bool readAndClearHasChanged() { return !mChangeNotified.test_and_set(); } + + /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */ + void setMetadataHasChanged() { mChangeNotified.clear(); } + protected: DISALLOW_COPY_AND_ASSIGN(TrackBase); @@ -391,6 +402,9 @@ protected: std::atomic mKernelFrameTime{}; // last frame time on kernel side. const pid_t mCreatorPid; // can be different from mclient->pid() for instance // when created by NuPlayer on behalf of a client + + // If the last track change was notified to the client with readAndClearHasChanged + std::atomic_flag mChangeNotified = ATOMIC_FLAG_INIT; }; // PatchProxyBufferProvider interface is implemented by PatchTrack and PatchRecord. -- GitLab From 10a03f1713e29eadfa862087e504f9e14964387e Mon Sep 17 00:00:00 2001 From: jiabin Date: Fri, 7 May 2021 23:46:28 +0000 Subject: [PATCH 043/694] Do not invalidate stream when the secondary outputs are changed. When a dynamic policy is registered, the secondary outputs may be changed. Instead of tearing down the tracks, only tracks whose secondary outputs are changed will be updated with the new secondary outputs. Bug: 181582467 Test: atest AudioPlaybackCaptureTest audiopolicy_tests Test: repo steps in the bug Change-Id: I9a47a0a4b37ad3f4a1d554dd726ebffb27325141 --- media/libaudioclient/AidlConversion.cpp | 24 +++ media/libaudioclient/Android.bp | 1 + media/libaudioclient/IAudioFlinger.cpp | 19 ++ .../android/media/IAudioFlingerService.aidl | 6 + .../media/TrackSecondaryOutputInfo.aidl | 27 +++ .../include/media/AidlConversion.h | 8 + .../include/media/AudioCommonTypes.h | 2 + .../include/media/IAudioFlinger.h | 11 + services/audioflinger/AudioFlinger.cpp | 195 ++++++++++-------- services/audioflinger/AudioFlinger.h | 8 + services/audioflinger/PlaybackTracks.h | 7 +- services/audioflinger/Threads.cpp | 13 +- services/audioflinger/Threads.h | 2 + services/audioflinger/Tracks.cpp | 10 +- services/audiopolicy/AudioPolicyInterface.h | 4 + .../include/ClientDescriptor.h | 5 +- .../managerdefault/AudioPolicyManager.cpp | 24 ++- .../service/AudioPolicyClientImpl.cpp | 10 + .../audiopolicy/service/AudioPolicyService.h | 3 + .../tests/AudioPolicyManagerTestClient.h | 5 + .../audiopolicy/tests/AudioPolicyTestClient.h | 4 + 21 files changed, 295 insertions(+), 93 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/TrackSecondaryOutputInfo.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index c77aeeb795..946ec171de 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -2323,4 +2323,28 @@ legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( return unexpected(BAD_VALUE); } +ConversionResult +aidl2legacy_TrackSecondaryOutputInfo_TrackSecondaryOutputInfoPair( + const media::TrackSecondaryOutputInfo& aidl) { + TrackSecondaryOutputInfoPair trackSecondaryOutputInfoPair; + trackSecondaryOutputInfoPair.first = + VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.portId)); + trackSecondaryOutputInfoPair.second = + VALUE_OR_RETURN(convertContainer>( + aidl.secondaryOutputIds, aidl2legacy_int32_t_audio_io_handle_t)); + return trackSecondaryOutputInfoPair; +} + +ConversionResult +legacy2aidl_TrackSecondaryOutputInfoPair_TrackSecondaryOutputInfo( + const TrackSecondaryOutputInfoPair& legacy) { + media::TrackSecondaryOutputInfo trackSecondaryOutputInfo; + trackSecondaryOutputInfo.portId = + VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.first)); + trackSecondaryOutputInfo.secondaryOutputIds = + VALUE_OR_RETURN(convertContainer>( + legacy.second, legacy2aidl_audio_io_handle_t_int32_t)); + return trackSecondaryOutputInfo; +} + } // namespace android diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 6f39a0dd6f..c7f23e3f26 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -351,6 +351,7 @@ aidl_interface { "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", "aidl/android/media/ExtraAudioDescriptor.aidl", + "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ "android.media.audio.common.types", diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 389b73f3cd..0564cdfa3e 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -743,6 +743,16 @@ status_t AudioFlingerClientAdapter::setVibratorInfos( return statusTFromBinderStatus(mDelegate->setVibratorInfos(vibratorInfos)); } +status_t AudioFlingerClientAdapter::updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) { + std::vector trackSecondaryOutputInfos = + VALUE_OR_RETURN_STATUS( + convertContainer>( + trackSecondaryOutputs, + legacy2aidl_TrackSecondaryOutputInfoPair_TrackSecondaryOutputInfo)); + return statusTFromBinderStatus(mDelegate->updateSecondaryOutputs(trackSecondaryOutputInfos)); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // AudioFlingerServerAdapter @@ -1199,4 +1209,13 @@ Status AudioFlingerServerAdapter::setVibratorInfos( return Status::fromStatusT(mDelegate->setVibratorInfos(vibratorInfos)); } +Status AudioFlingerServerAdapter::updateSecondaryOutputs( + const std::vector& trackSecondaryOutputInfos) { + TrackSecondaryOutputsMap trackSecondaryOutputs = + VALUE_OR_RETURN_BINDER(convertContainer( + trackSecondaryOutputInfos, + aidl2legacy_TrackSecondaryOutputInfo_TrackSecondaryOutputInfoPair)); + return Status::fromStatusT(mDelegate->updateSecondaryOutputs(trackSecondaryOutputs)); +} + } // namespace android diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index abbced5876..d2cae6dd27 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -40,6 +40,7 @@ import android.media.IAudioRecord; import android.media.IAudioTrack; import android.media.MicrophoneInfoData; import android.media.RenderPosition; +import android.media.TrackSecondaryOutputInfo; import android.media.audio.common.AudioFormat; /** @@ -207,4 +208,9 @@ interface IAudioFlingerService { // Set vibrators' information. // The value will be used to initialize HapticGenerator. void setVibratorInfos(in AudioVibratorInfo[] vibratorInfos); + + // Update secondary outputs. + // This usually happens when there is a dynamic policy registered. + void updateSecondaryOutputs( + in TrackSecondaryOutputInfo[] trackSecondaryOutputInfos); } diff --git a/media/libaudioclient/aidl/android/media/TrackSecondaryOutputInfo.aidl b/media/libaudioclient/aidl/android/media/TrackSecondaryOutputInfo.aidl new file mode 100644 index 0000000000..113328ea8e --- /dev/null +++ b/media/libaudioclient/aidl/android/media/TrackSecondaryOutputInfo.aidl @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * This is a class that contains port handle for a track and handles for all secondary + * outputs of the track. + * @hide + */ +parcelable TrackSecondaryOutputInfo { + int portId; // audio_port_handle_t + int[] secondaryOutputIds; // audio_io_handle_t[] +} \ No newline at end of file diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 1dd9d60690..4ec69c71ae 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -50,6 +50,7 @@ #include #include #include +#include #include #include @@ -407,6 +408,13 @@ ConversionResult legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( const audio_encapsulation_type_t & legacy); +using TrackSecondaryOutputInfoPair = std::pair>; +ConversionResult +aidl2legacy_TrackSecondaryOutputInfo_TrackSecondaryOutputInfoPair( + const media::TrackSecondaryOutputInfo& aidl); +ConversionResult +legacy2aidl_TrackSecondaryOutputInfoPair_TrackSecondaryOutputInfo( + const TrackSecondaryOutputInfoPair& legacy); } // namespace android diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index 8e446ea48c..5dfe5fc9c3 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -29,6 +29,8 @@ const product_strategy_t PRODUCT_STRATEGY_NONE = static_cast using AttributesVector = std::vector; using StreamTypeVector = std::vector; +using TrackSecondaryOutputsMap = std::map>; + constexpr bool operator==(const audio_attributes_t &lhs, const audio_attributes_t &rhs) { return lhs.usage == rhs.usage && lhs.content_type == rhs.content_type && diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 3a04569596..3a4868ea8c 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -26,12 +26,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -55,6 +57,7 @@ #include "android/media/OpenInputResponse.h" #include "android/media/OpenOutputRequest.h" #include "android/media/OpenOutputResponse.h" +#include "android/media/TrackSecondaryOutputInfo.h" namespace android { @@ -338,6 +341,9 @@ public: // The values will be used to initialize HapticGenerator. virtual status_t setVibratorInfos( const std::vector& vibratorInfos) = 0; + + virtual status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; }; /** @@ -430,6 +436,8 @@ public: status_t getMicrophones(std::vector* microphones) override; status_t setAudioHalPids(const std::vector& pids) override; status_t setVibratorInfos(const std::vector& vibratorInfos) override; + status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; private: const sp mDelegate; @@ -513,6 +521,7 @@ public: SET_EFFECT_SUSPENDED = media::BnAudioFlingerService::TRANSACTION_setEffectSuspended, SET_AUDIO_HAL_PIDS = media::BnAudioFlingerService::TRANSACTION_setAudioHalPids, SET_VIBRATOR_INFOS = media::BnAudioFlingerService::TRANSACTION_setVibratorInfos, + UPDATE_SECONDARY_OUTPUTS = media::BnAudioFlingerService::TRANSACTION_updateSecondaryOutputs, }; /** @@ -619,6 +628,8 @@ public: Status getMicrophones(std::vector* _aidl_return) override; Status setAudioHalPids(const std::vector& pids) override; Status setVibratorInfos(const std::vector& vibratorInfos) override; + Status updateSecondaryOutputs( + const std::vector& trackSecondaryOutputInfos) override; private: const sp mDelegate; diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 3562b00a76..00f423c7bb 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -312,6 +312,27 @@ status_t AudioFlinger::setVibratorInfos( return NO_ERROR; } +status_t AudioFlinger::updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) { + Mutex::Autolock _l(mLock); + for (const auto& [trackId, secondaryOutputs] : trackSecondaryOutputs) { + size_t i = 0; + for (; i < mPlaybackThreads.size(); ++i) { + PlaybackThread *thread = mPlaybackThreads.valueAt(i).get(); + Mutex::Autolock _tl(thread->mLock); + sp track = thread->getTrackById_l(trackId); + if (track != nullptr) { + ALOGD("%s trackId: %u", __func__, trackId); + updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs); + break; + } + } + ALOGW_IF(i >= mPlaybackThreads.size(), + "%s cannot find track with id %u", __func__, trackId); + } + return NO_ERROR; +} + // getDefaultVibratorInfo_l must be called with AudioFlinger lock held. const media::AudioVibratorInfo* AudioFlinger::getDefaultVibratorInfo_l() { if (mAudioVibratorInfos.empty()) { @@ -944,88 +965,7 @@ status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input, // Connect secondary outputs. Failure on a secondary output must not imped the primary // Any secondary output setup failure will lead to a desync between the AP and AF until // the track is destroyed. - TeePatches teePatches; - for (audio_io_handle_t secondaryOutput : secondaryOutputs) { - PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput); - if (secondaryThread == NULL) { - ALOGE("no playback thread found for secondary output %d", output.outputId); - continue; - } - - size_t sourceFrameCount = thread->frameCount() * output.sampleRate - / thread->sampleRate(); - size_t sinkFrameCount = secondaryThread->frameCount() * output.sampleRate - / secondaryThread->sampleRate(); - // If the secondary output has just been opened, the first secondaryThread write - // will not block as it will fill the empty startup buffer of the HAL, - // so a second sink buffer needs to be ready for the immediate next blocking write. - // Additionally, have a margin of one main thread buffer as the scheduling jitter - // can reorder the writes (eg if thread A&B have the same write intervale, - // the scheduler could schedule AB...BA) - size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount; - // Total secondary output buffer must be at least as the read frames plus - // the margin of a few buffers on both sides in case the - // threads scheduling has some jitter. - // That value should not impact latency as the secondary track is started before - // its buffer is full, see frameCountToBeReady. - size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount); - // The frameCount should also not be smaller than the secondary thread min frame - // count - size_t minFrameCount = AudioSystem::calculateMinFrameCount( - [&] { Mutex::Autolock _l(secondaryThread->mLock); - return secondaryThread->latency_l(); }(), - secondaryThread->mNormalFrameCount, - secondaryThread->mSampleRate, - output.sampleRate, - input.speed); - frameCount = std::max(frameCount, minFrameCount); - - using namespace std::chrono_literals; - auto inChannelMask = audio_channel_mask_out_to_in(input.config.channel_mask); - sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */, - output.sampleRate, - inChannelMask, - input.config.format, - frameCount, - NULL /* buffer */, - (size_t)0 /* bufferSize */, - AUDIO_INPUT_FLAG_DIRECT, - 0ns /* timeout */); - status_t status = patchRecord->initCheck(); - if (status != NO_ERROR) { - ALOGE("Secondary output patchRecord init failed: %d", status); - continue; - } - - // TODO: We could check compatibility of the secondaryThread with the PatchTrack - // for fast usage: thread has fast mixer, sample rate matches, etc.; - // for now, we exclude fast tracks by removing the Fast flag. - const audio_output_flags_t outputFlags = - (audio_output_flags_t)(output.flags & ~AUDIO_OUTPUT_FLAG_FAST); - sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread, - streamType, - output.sampleRate, - input.config.channel_mask, - input.config.format, - frameCount, - patchRecord->buffer(), - patchRecord->bufferSize(), - outputFlags, - 0ns /* timeout */, - frameCountToBeReady); - status = patchTrack->initCheck(); - if (status != NO_ERROR) { - ALOGE("Secondary output patchTrack init failed: %d", status); - continue; - } - teePatches.push_back({patchRecord, patchTrack}); - secondaryThread->addPatchTrack(patchTrack); - // In case the downstream patchTrack on the secondaryThread temporarily outlives - // our created track, ensure the corresponding patchRecord is still alive. - patchTrack->setPeerProxy(patchRecord, true /* holdReference */); - patchRecord->setPeerProxy(patchTrack, false /* holdReference */); - } - track->setTeePatches(std::move(teePatches)); + updateSecondaryOutputsForTrack_l(track.get(), thread, secondaryOutputs); } // move effect chain to this output thread if an effect on same session was waiting @@ -3441,6 +3381,94 @@ AudioFlinger::ThreadBase *AudioFlinger::hapticPlaybackThread_l() const { return nullptr; } +void AudioFlinger::updateSecondaryOutputsForTrack_l( + PlaybackThread::Track* track, + PlaybackThread* thread, + const std::vector &secondaryOutputs) const { + TeePatches teePatches; + for (audio_io_handle_t secondaryOutput : secondaryOutputs) { + PlaybackThread *secondaryThread = checkPlaybackThread_l(secondaryOutput); + if (secondaryThread == nullptr) { + ALOGE("no playback thread found for secondary output %d", thread->id()); + continue; + } + + size_t sourceFrameCount = thread->frameCount() * track->sampleRate() + / thread->sampleRate(); + size_t sinkFrameCount = secondaryThread->frameCount() * track->sampleRate() + / secondaryThread->sampleRate(); + // If the secondary output has just been opened, the first secondaryThread write + // will not block as it will fill the empty startup buffer of the HAL, + // so a second sink buffer needs to be ready for the immediate next blocking write. + // Additionally, have a margin of one main thread buffer as the scheduling jitter + // can reorder the writes (eg if thread A&B have the same write intervale, + // the scheduler could schedule AB...BA) + size_t frameCountToBeReady = 2 * sinkFrameCount + sourceFrameCount; + // Total secondary output buffer must be at least as the read frames plus + // the margin of a few buffers on both sides in case the + // threads scheduling has some jitter. + // That value should not impact latency as the secondary track is started before + // its buffer is full, see frameCountToBeReady. + size_t frameCount = frameCountToBeReady + 2 * (sourceFrameCount + sinkFrameCount); + // The frameCount should also not be smaller than the secondary thread min frame + // count + size_t minFrameCount = AudioSystem::calculateMinFrameCount( + [&] { Mutex::Autolock _l(secondaryThread->mLock); + return secondaryThread->latency_l(); }(), + secondaryThread->mNormalFrameCount, + secondaryThread->mSampleRate, + track->sampleRate(), + track->getSpeed()); + frameCount = std::max(frameCount, minFrameCount); + + using namespace std::chrono_literals; + auto inChannelMask = audio_channel_mask_out_to_in(track->channelMask()); + sp patchRecord = new RecordThread::PatchRecord(nullptr /* thread */, + track->sampleRate(), + inChannelMask, + track->format(), + frameCount, + nullptr /* buffer */, + (size_t)0 /* bufferSize */, + AUDIO_INPUT_FLAG_DIRECT, + 0ns /* timeout */); + status_t status = patchRecord->initCheck(); + if (status != NO_ERROR) { + ALOGE("Secondary output patchRecord init failed: %d", status); + continue; + } + + // TODO: We could check compatibility of the secondaryThread with the PatchTrack + // for fast usage: thread has fast mixer, sample rate matches, etc.; + // for now, we exclude fast tracks by removing the Fast flag. + const audio_output_flags_t outputFlags = + (audio_output_flags_t)(track->getOutputFlags() & ~AUDIO_OUTPUT_FLAG_FAST); + sp patchTrack = new PlaybackThread::PatchTrack(secondaryThread, + track->streamType(), + track->sampleRate(), + track->channelMask(), + track->format(), + frameCount, + patchRecord->buffer(), + patchRecord->bufferSize(), + outputFlags, + 0ns /* timeout */, + frameCountToBeReady); + status = patchTrack->initCheck(); + if (status != NO_ERROR) { + ALOGE("Secondary output patchTrack init failed: %d", status); + continue; + } + teePatches.push_back({patchRecord, patchTrack}); + secondaryThread->addPatchTrack(patchTrack); + // In case the downstream patchTrack on the secondaryThread temporarily outlives + // our created track, ensure the corresponding patchRecord is still alive. + patchTrack->setPeerProxy(patchRecord, true /* holdReference */); + patchRecord->setPeerProxy(patchTrack, false /* holdReference */); + } + track->setTeePatches(std::move(teePatches)); +} + sp AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type, audio_session_t triggerSession, audio_session_t listenerSession, @@ -4170,7 +4198,8 @@ status_t AudioFlinger::onTransactWrapper(TransactionCode code, case TransactionCode::SET_LOW_RAM_DEVICE: case TransactionCode::SYSTEM_READY: case TransactionCode::SET_AUDIO_HAL_PIDS: - case TransactionCode::SET_VIBRATOR_INFOS: { + case TransactionCode::SET_VIBRATOR_INFOS: + case TransactionCode::UPDATE_SECONDARY_OUTPUTS: { if (!isServiceUid(IPCThreadState::self()->getCallingUid())) { ALOGW("%s: transaction %d received from PID %d unauthorized UID %d", __func__, code, IPCThreadState::self()->getCallingPid(), diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index 4b03d10c1c..b12f52e8a1 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -272,6 +272,9 @@ public: virtual status_t setVibratorInfos(const std::vector& vibratorInfos); + virtual status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs); + status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -775,6 +778,11 @@ using effect_buffer_t = int16_t; ThreadBase *hapticPlaybackThread_l() const; + void updateSecondaryOutputsForTrack_l( + PlaybackThread::Track* track, + PlaybackThread* thread, + const std::vector& secondaryOutputs) const; + void removeClient_l(pid_t pid); void removeNotificationClient(pid_t pid); diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h index 0af4c7b553..30a24327f0 100644 --- a/services/audioflinger/PlaybackTracks.h +++ b/services/audioflinger/PlaybackTracks.h @@ -81,7 +81,8 @@ public: audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE, /** default behaviour is to start when there are as many frames * ready as possible (aka. Buffer is full). */ - size_t frameCountToBeReady = SIZE_MAX); + size_t frameCountToBeReady = SIZE_MAX, + float speed = 1.0f); virtual ~Track(); virtual status_t initCheck() const; @@ -183,6 +184,9 @@ public: mAudioTrackServerProxy->getUnderrunFrames()); } } + + audio_output_flags_t getOutputFlags() const { return mFlags; } + float getSpeed() const { return mSpeed; } protected: // for numerous friend class PlaybackThread; @@ -311,6 +315,7 @@ private: bool mPauseHwPending = false; // direct/offload track request for thread pause audio_output_flags_t mFlags; TeePatches mTeePatches; + const float mSpeed; }; // end of Track diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index d8786118ee..25a19a2409 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -2425,7 +2425,7 @@ sp AudioFlinger::PlaybackThread::createTrac channelMask, frameCount, nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer, sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT, - portId, SIZE_MAX /*frameCountToBeReady*/); + portId, SIZE_MAX /*frameCountToBeReady*/, speed); lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; if (lStatus != NO_ERROR) { @@ -3321,6 +3321,17 @@ void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamTy invalidateTracks_l(streamType); } +// getTrackById_l must be called with holding thread lock +AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l( + audio_port_handle_t trackPortId) { + for (size_t i = 0; i < mTracks.size(); i++) { + if (mTracks[i]->portId() == trackPortId) { + return mTracks[i].get(); + } + } + return nullptr; +} + status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp& chain) { audio_session_t session = chain->sessionId(); diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h index 17acb16fcc..d4fb995f41 100644 --- a/services/audioflinger/Threads.h +++ b/services/audioflinger/Threads.h @@ -1013,6 +1013,8 @@ public: mDownStreamPatch = *patch; } + PlaybackThread::Track* getTrackById_l(audio_port_handle_t trackId); + protected: // updated by readOutputParameters_l() size_t mNormalFrameCount; // normal mixer and effects diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp index 3e048040af..a6dfe1ec2d 100644 --- a/services/audioflinger/Tracks.cpp +++ b/services/audioflinger/Tracks.cpp @@ -624,7 +624,8 @@ AudioFlinger::PlaybackThread::Track::Track( audio_output_flags_t flags, track_type type, audio_port_handle_t portId, - size_t frameCountToBeReady) + size_t frameCountToBeReady, + float speed) : TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount, // TODO: Using unsecurePointer() has some associated security pitfalls // (see declaration for details). @@ -658,7 +659,8 @@ AudioFlinger::PlaybackThread::Track::Track( mFinalVolume(0.f), mResumeToStopping(false), mFlushHwPending(false), - mFlags(flags) + mFlags(flags), + mSpeed(speed) { // client == 0 implies sharedBuffer == 0 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0)); @@ -1402,6 +1404,10 @@ void AudioFlinger::PlaybackThread::Track::copyMetadataTo(MetadataInserter& backI void AudioFlinger::PlaybackThread::Track::setTeePatches(TeePatches teePatches) { forEachTeePatchTrack([](auto patchTrack) { patchTrack->destroy(); }); mTeePatches = std::move(teePatches); + if (mState == TrackBase::ACTIVE || mState == TrackBase::RESUMING || + mState == TrackBase::STOPPING_1) { + forEachTeePatchTrack([](auto patchTrack) { patchTrack->start(); }); + } } status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp) diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h index 5f052a59e5..a904321116 100644 --- a/services/audiopolicy/AudioPolicyInterface.h +++ b/services/audiopolicy/AudioPolicyInterface.h @@ -17,6 +17,7 @@ #ifndef ANDROID_AUDIOPOLICY_INTERFACE_H #define ANDROID_AUDIOPOLICY_INTERFACE_H +#include #include #include #include @@ -453,6 +454,9 @@ public: virtual void setSoundTriggerCaptureState(bool active) = 0; virtual status_t getAudioPort(struct audio_port_v7 *port) = 0; + + virtual status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; }; // These are the signatures of createAudioPolicyManager/destroyAudioPolicyManager diff --git a/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h index 59876c626a..74b3405020 100644 --- a/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h +++ b/services/audiopolicy/common/managerdefinitions/include/ClientDescriptor.h @@ -109,6 +109,9 @@ public: const std::vector>& getSecondaryOutputs() const { return mSecondaryOutputs; }; + void setSecondaryOutputs(std::vector>&& secondaryOutputs) { + mSecondaryOutputs = std::move(secondaryOutputs); + } VolumeSource volumeSource() const { return mVolumeSource; } const sp getPrimaryMix() const { return mPrimaryMix.promote(); @@ -143,7 +146,7 @@ private: const product_strategy_t mStrategy; const VolumeSource mVolumeSource; const audio_output_flags_t mFlags; - const std::vector> mSecondaryOutputs; + std::vector> mSecondaryOutputs; const wp mPrimaryMix; /** * required for duplicating thread, prevent from removing active client from an output diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp index 7185435475..c8ddbc6e56 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -5694,6 +5695,7 @@ void AudioPolicyManager::checkOutputForAllStrategies() void AudioPolicyManager::checkSecondaryOutputs() { std::set streamsToInvalidate; + TrackSecondaryOutputsMap trackSecondaryOutputs; for (size_t i = 0; i < mOutputs.size(); i++) { const sp& outputDescriptor = mOutputs[i]; for (const sp& client : outputDescriptor->getClientIterable()) { @@ -5710,16 +5712,28 @@ void AudioPolicyManager::checkSecondaryOutputs() { } } - if (status != OK || - !std::equal(client->getSecondaryOutputs().begin(), - client->getSecondaryOutputs().end(), - secondaryDescs.begin(), secondaryDescs.end())) { + if (status != OK) { streamsToInvalidate.insert(client->stream()); + } else if (!std::equal( + client->getSecondaryOutputs().begin(), + client->getSecondaryOutputs().end(), + secondaryDescs.begin(), secondaryDescs.end())) { + std::vector> weakSecondaryDescs; + std::vector secondaryOutputIds; + for (const auto& secondaryDesc : secondaryDescs) { + secondaryOutputIds.push_back(secondaryDesc->mIoHandle); + weakSecondaryDescs.push_back(secondaryDesc); + } + trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds); + client->setSecondaryOutputs(std::move(weakSecondaryDescs)); } } } + if (!trackSecondaryOutputs.empty()) { + mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs); + } for (audio_stream_type_t stream : streamsToInvalidate) { - ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream); + ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream); mpClientInterface->invalidateStream(stream); } } diff --git a/services/audiopolicy/service/AudioPolicyClientImpl.cpp b/services/audiopolicy/service/AudioPolicyClientImpl.cpp index 77b5200134..cd5307384e 100644 --- a/services/audiopolicy/service/AudioPolicyClientImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyClientImpl.cpp @@ -291,4 +291,14 @@ status_t AudioPolicyService::AudioPolicyClient::getAudioPort(struct audio_port_v return af->getAudioPort(port); } +status_t AudioPolicyService::AudioPolicyClient::updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) { + sp af = AudioSystem::get_audio_flinger(); + if (af == nullptr) { + ALOGW("%s: could not get AudioFlinger", __func__); + return PERMISSION_DENIED; + } + return af->updateSecondaryOutputs(trackSecondaryOutputs); +} + } // namespace android diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 00d9670d8d..6eb33f60dc 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -735,6 +735,9 @@ private: status_t getAudioPort(struct audio_port_v7 *port) override; + status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; + private: AudioPolicyService *mAudioPolicyService; }; diff --git a/services/audiopolicy/tests/AudioPolicyManagerTestClient.h b/services/audiopolicy/tests/AudioPolicyManagerTestClient.h index e2d7d179e3..f7b0565a65 100644 --- a/services/audiopolicy/tests/AudioPolicyManagerTestClient.h +++ b/services/audiopolicy/tests/AudioPolicyManagerTestClient.h @@ -134,6 +134,11 @@ public: size_t getRoutingUpdatedCounter() const { return mRoutingUpdatedUpdateCount; } + status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs __unused) override { + return NO_ERROR; + } + private: audio_module_handle_t mNextModuleHandle = AUDIO_MODULE_HANDLE_NONE + 1; audio_io_handle_t mNextIoHandle = AUDIO_IO_HANDLE_NONE + 1; diff --git a/services/audiopolicy/tests/AudioPolicyTestClient.h b/services/audiopolicy/tests/AudioPolicyTestClient.h index d289e15dbd..138486417a 100644 --- a/services/audiopolicy/tests/AudioPolicyTestClient.h +++ b/services/audiopolicy/tests/AudioPolicyTestClient.h @@ -91,6 +91,10 @@ public: status_t getAudioPort(struct audio_port_v7 *port __unused) override { return INVALID_OPERATION; }; + status_t updateSecondaryOutputs( + const TrackSecondaryOutputsMap& trackSecondaryOutputs __unused) override { + return NO_INIT; + } }; } // namespace android -- GitLab From d3a05316fcacaf256ca81d7e22217f22dd0f39ce Mon Sep 17 00:00:00 2001 From: Cliff Wu Date: Mon, 26 Apr 2021 23:07:31 +0800 Subject: [PATCH 044/694] DynamicCamera: Inject the camera from CameraService to Camera3Device - Inject the injection camera from the camera service to the camera device via the camera client. Bug: 181735245 Test: Manual Change-Id: I53f076c24b932050e9c8af5acc10af73bcbe0e17 --- .../camera/libcameraservice/CameraService.cpp | 126 +++++++++++++++--- .../camera/libcameraservice/CameraService.h | 20 ++- .../api2/CameraOfflineSessionClient.cpp | 14 ++ .../api2/CameraOfflineSessionClient.h | 3 + .../common/Camera2ClientBase.cpp | 11 ++ .../common/Camera2ClientBase.h | 4 + .../common/CameraDeviceBase.h | 12 ++ 7 files changed, 171 insertions(+), 19 deletions(-) diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp index a0448b4299..0f2085d41c 100644 --- a/services/camera/libcameraservice/CameraService.cpp +++ b/services/camera/libcameraservice/CameraService.cpp @@ -1755,6 +1755,27 @@ Status CameraService::connectHelper(const sp& cameraCb, const String8& CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName, effectiveApiLevel, isNdk, openLatencyMs); + { + Mutex::Autolock lock(mInjectionParametersLock); + if (cameraId == mInjectionInternalCamId && mInjectionInitPending) { + mInjectionInitPending = false; + status_t res = NO_ERROR; + auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId); + if (clientDescriptor != nullptr) { + BasicClient* baseClientPtr = clientDescriptor->getValue().get(); + res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager); + if (res != OK) { + mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res); + } + } else { + ALOGE("%s: Internal camera ID = %s 's client does not exist!", + __FUNCTION__, mInjectionInternalCamId.string()); + res = NO_INIT; + mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res); + } + } + } + return ret; } @@ -2413,7 +2434,7 @@ Status CameraService::injectCamera( const String16& externalCamId, const sp& callback, /*out*/ - sp* cameraInjectionSession) { + sp* cameraInjectionSession) { ATRACE_CALL(); if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) { @@ -2430,18 +2451,30 @@ Status CameraService::injectCamera( __FUNCTION__, String8(packageName).string(), String8(internalCamId).string(), String8(externalCamId).string()); - binder::Status ret = binder::Status::ok(); - // TODO: Implement the injection camera function. - // ret = internalInjectCamera(...); - // if(!ret.isOk()) { - // mInjectionStatusListener->notifyInjectionError(...); - // return ret; - // } - + { + Mutex::Autolock lock(mInjectionParametersLock); + mInjectionInternalCamId = String8(internalCamId); + mInjectionExternalCamId = String8(externalCamId); + status_t res = NO_ERROR; + auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId); + // If the client already exists, we can directly connect to the camera device through the + // client's injectCamera(), otherwise we need to wait until the client is established + // (execute connectHelper()) before injecting the camera to the camera device. + if (clientDescriptor != nullptr) { + mInjectionInitPending = false; + BasicClient* baseClientPtr = clientDescriptor->getValue().get(); + res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager); + if(res != OK) { + mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res); + } + } else { + mInjectionInitPending = true; + } + } mInjectionStatusListener->addListener(callback); *cameraInjectionSession = new CameraInjectionSession(this); - return ret; + return binder::Status::ok(); } void CameraService::removeByClient(const BasicClient* client) { @@ -3704,13 +3737,50 @@ void CameraService::InjectionStatusListener::removeListener() { } void CameraService::InjectionStatusListener::notifyInjectionError( - int errorCode) { + String8 injectedCamId, status_t err) { Mutex::Autolock lock(mListenerLock); if (mCameraInjectionCallback == nullptr) { ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr"); return; } - mCameraInjectionCallback->onInjectionError(errorCode); + + switch (err) { + case -ENODEV: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_SESSION); + ALOGE("No camera device with ID \"%s\" currently available!", + injectedCamId.string()); + break; + case -EBUSY: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_SESSION); + ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!", + injectedCamId.string()); + break; + case DEAD_OBJECT: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_SESSION); + ALOGE("Camera ID \"%s\" object is dead!", + injectedCamId.string()); + break; + case INVALID_OPERATION: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_SESSION); + ALOGE("Camera ID \"%s\" encountered an operating or internal error!", + injectedCamId.string()); + break; + case UNKNOWN_TRANSACTION: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED); + ALOGE("Camera ID \"%s\" method doesn't support!", + injectedCamId.string()); + break; + default: + mCameraInjectionCallback->onInjectionError( + ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR); + ALOGE("Unexpected error %s (%d) opening camera \"%s\"!", + strerror(-err), err, injectedCamId.string()); + } } void CameraService::InjectionStatusListener::binderDied( @@ -3719,7 +3789,12 @@ void CameraService::InjectionStatusListener::binderDied( ALOGV("InjectionStatusListener: ICameraInjectionCallback has died"); auto parent = mParent.promote(); if (parent != nullptr) { - parent->stopInjectionImpl(); + parent->clearInjectionParameters(); + auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId); + if (clientDescriptor != nullptr) { + BasicClient* baseClientPtr = clientDescriptor->getValue().get(); + baseClientPtr->stopInjection(); + } } } @@ -3735,7 +3810,20 @@ binder::Status CameraService::CameraInjectionSession::stopInjection() { return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE, "Camera service encountered error"); } - parent->stopInjectionImpl(); + + status_t res = NO_ERROR; + parent->clearInjectionParameters(); + auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId); + if (clientDescriptor != nullptr) { + BasicClient* baseClientPtr = clientDescriptor->getValue().get(); + res = baseClientPtr->stopInjection(); + if (res != OK) { + ALOGE("CameraInjectionSession: Failed to stop the injection camera!" + " ret != NO_ERROR: %d", res); + return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION, + "Camera session encountered error"); + } + } return binder::Status::ok(); } @@ -4399,10 +4487,14 @@ int32_t CameraService::updateAudioRestrictionLocked() { return mode; } -void CameraService::stopInjectionImpl() { +void CameraService::clearInjectionParameters() { + { + Mutex::Autolock lock(mInjectionParametersLock); + mInjectionInitPending = true; + mInjectionInternalCamId = ""; + } + mInjectionExternalCamId = ""; mInjectionStatusListener->removeListener(); - - // TODO: Implement the stop injection function. } }; // namespace android diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h index 10e17489a2..2d5f113e79 100644 --- a/services/camera/libcameraservice/CameraService.h +++ b/services/camera/libcameraservice/CameraService.h @@ -317,6 +317,14 @@ public: // Set/reset camera mute virtual status_t setCameraMute(bool enabled) = 0; + // The injection camera session to replace the internal camera + // session. + virtual status_t injectCamera(const String8& injectedCamId, + sp manager) = 0; + + // Stop the injection camera and restore to internal camera session. + virtual status_t stopInjection() = 0; + protected: BasicClient(const sp& cameraService, const sp& remoteCallback, @@ -1168,7 +1176,7 @@ private: void addListener(const sp& callback); void removeListener(); - void notifyInjectionError(int errorCode); + void notifyInjectionError(String8 injectedCamId, status_t err); // IBinder::DeathRecipient implementation virtual void binderDied(const wp& who); @@ -1195,7 +1203,15 @@ private: wp mParent; }; - void stopInjectionImpl(); + void clearInjectionParameters(); + + // This is the existing camera id being replaced. + String8 mInjectionInternalCamId; + // This is the external camera Id replacing the internalId. + String8 mInjectionExternalCamId; + bool mInjectionInitPending = true; + // Guard mInjectionInternalCamId and mInjectionInitPending. + Mutex mInjectionParametersLock; }; } // namespace android diff --git a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp index ef15f2da5b..652842b1d3 100644 --- a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp +++ b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.cpp @@ -330,5 +330,19 @@ void CameraOfflineSessionClient::notifyRepeatingRequestError(long /*lastFrameNum CaptureResultExtras()); } +status_t CameraOfflineSessionClient::injectCamera(const String8& injectedCamId, + sp manager) { + ALOGV("%s: This client doesn't support the injection camera. injectedCamId: %s providerPtr: %p", + __FUNCTION__, injectedCamId.string(), manager.get()); + + return OK; +} + +status_t CameraOfflineSessionClient::stopInjection() { + ALOGV("%s: This client doesn't support the injection camera.", __FUNCTION__); + + return OK; +} + // ---------------------------------------------------------------------------- }; // namespace android diff --git a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h index b219a4c820..b5238b818d 100644 --- a/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h +++ b/services/camera/libcameraservice/api2/CameraOfflineSessionClient.h @@ -98,6 +98,9 @@ public: void notifyPrepared(int streamId) override; void notifyRequestQueueEmpty() override; void notifyRepeatingRequestError(long lastFrameNumber) override; + status_t injectCamera(const String8& injectedCamId, + sp manager) override; + status_t stopInjection() override; private: mutable Mutex mBinderSerializationLock; diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.cpp b/services/camera/libcameraservice/common/Camera2ClientBase.cpp index ce479a1364..12c50fb7aa 100644 --- a/services/camera/libcameraservice/common/Camera2ClientBase.cpp +++ b/services/camera/libcameraservice/common/Camera2ClientBase.cpp @@ -405,6 +405,17 @@ void Camera2ClientBase::SharedCameraCallbacks::clear() { mRemoteCallback.clear(); } +template +status_t Camera2ClientBase::injectCamera(const String8& injectedCamId, + sp manager) { + return mDevice->injectCamera(injectedCamId, manager); +} + +template +status_t Camera2ClientBase::stopInjection() { + return mDevice->stopInjection(); +} + template class Camera2ClientBase; template class Camera2ClientBase; diff --git a/services/camera/libcameraservice/common/Camera2ClientBase.h b/services/camera/libcameraservice/common/Camera2ClientBase.h index b3a38a2597..2d2a273032 100644 --- a/services/camera/libcameraservice/common/Camera2ClientBase.h +++ b/services/camera/libcameraservice/common/Camera2ClientBase.h @@ -113,6 +113,10 @@ public: mutable Mutex mRemoteCallbackLock; } mSharedCameraCallbacks; + status_t injectCamera(const String8& injectedCamId, + sp manager) override; + status_t stopInjection() override; + protected: // The PID provided in the constructor call diff --git a/services/camera/libcameraservice/common/CameraDeviceBase.h b/services/camera/libcameraservice/common/CameraDeviceBase.h index 85b0cc2d6f..3c95ed364f 100644 --- a/services/camera/libcameraservice/common/CameraDeviceBase.h +++ b/services/camera/libcameraservice/common/CameraDeviceBase.h @@ -427,6 +427,18 @@ class CameraDeviceBase : public virtual FrameProducer { */ void setImageDumpMask(int mask) { mImageDumpMask = mask; } + /** + * The injection camera session to replace the internal camera + * session. + */ + virtual status_t injectCamera(const String8& injectedCamId, + sp manager) = 0; + + /** + * Stop the injection camera and restore to internal camera session. + */ + virtual status_t stopInjection() = 0; + protected: bool mImageDumpMask = 0; }; -- GitLab From c10572eff23c10893efb5d6e3a07f48527cfc1f2 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 21 May 2021 17:42:02 -0700 Subject: [PATCH 045/694] Remove dependency on android.media.audio.common.AudioFormat In a preparation to converting audio HAL to SAIDL, ensure that Framework SAIDL is self-contained and has all the necessary types. This creates a temporary duplication of types with android.media.audio.common which will be fixed once we stabilize the common types between the framework and HALs. Bug: 188932434 Test: m Change-Id: Ib632c0ae5d2d1562266c87480b585b1b7f6e5ac6 --- media/libaaudio/src/Android.bp | 2 +- .../src/binding/AAudioStreamConfiguration.cpp | 4 +- .../binding/aidl/aaudio/StreamParameters.aidl | 4 +- media/libaudioclient/AidlConversion.cpp | 14 +- media/libaudioclient/Android.bp | 5 +- media/libaudioclient/AudioSystem.cpp | 8 +- media/libaudioclient/IAudioFlinger.cpp | 8 +- .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioFormatSys.aidl | 161 ++++++++++++++++++ .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioOffloadInfo.aidl | 2 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 6 +- .../android/media/IAudioPolicyService.aidl | 14 +- .../include/media/AidlConversion.h | 4 +- .../include/media/IAudioFlinger.h | 4 +- .../service/AudioPolicyInterfaceImpl.cpp | 14 +- .../audiopolicy/service/AudioPolicyService.h | 12 +- 20 files changed, 220 insertions(+), 62 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioFormatSys.aidl diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index 7cadacdb2b..5e054c5106 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -248,7 +248,7 @@ aidl_interface { "binding/aidl/aaudio/IAAudioService.aidl", ], imports: [ - "android.media.audio.common.types", + "audioclient-types-aidl", "shared-file-region-aidl", "media_permission-aidl", ], diff --git a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp index 2d501efaeb..f28e0d6bad 100644 --- a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp +++ b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp @@ -27,7 +27,7 @@ using namespace aaudio; -using android::media::audio::common::AudioFormat; +using android::media::AudioFormatSys; AAudioStreamConfiguration::AAudioStreamConfiguration(const StreamParameters& parcelable) { setSamplesPerFrame(parcelable.samplesPerFrame); @@ -69,7 +69,7 @@ StreamParameters AAudioStreamConfiguration::parcelable() const { static_assert(sizeof(aaudio_sharing_mode_t) == sizeof(result.sharingMode)); result.sharingMode = getSharingMode(); static_assert(sizeof(audio_format_t) == sizeof(result.audioFormat)); - result.audioFormat = static_cast(getFormat()); + result.audioFormat = static_cast(getFormat()); static_assert(sizeof(aaudio_direction_t) == sizeof(result.direction)); result.direction = getDirection(); static_assert(sizeof(audio_usage_t) == sizeof(result.usage)); diff --git a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl index b7c4f70557..d1ba9b302e 100644 --- a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl +++ b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl @@ -16,14 +16,14 @@ package aaudio; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; parcelable StreamParameters { int samplesPerFrame; // = AAUDIO_UNSPECIFIED; int sampleRate; // = AAUDIO_UNSPECIFIED; int deviceId; // = AAUDIO_UNSPECIFIED; int /* aaudio_sharing_mode_t */ sharingMode; // = AAUDIO_SHARING_MODE_SHARED; - AudioFormat audioFormat; // = AUDIO_FORMAT_DEFAULT; + AudioFormatSys audioFormat; // = AUDIO_FORMAT_DEFAULT; int /* aaudio_direction_t */ direction; // = AAUDIO_DIRECTION_OUTPUT; int /* aaudio_usage_t */ usage; // = AAUDIO_UNSPECIFIED; int /* aaudio_content_type_t */ contentType; // = AAUDIO_UNSPECIFIED; diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 946ec171de..d250440665 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -394,17 +394,17 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy } ConversionResult aidl2legacy_AudioFormat_audio_format_t( - media::audio::common::AudioFormat aidl) { - // This relies on AudioFormat being kept in sync with audio_format_t. - static_assert(sizeof(media::audio::common::AudioFormat) == sizeof(audio_format_t)); + media::AudioFormatSys aidl) { + // This relies on AudioFormatSys being kept in sync with audio_format_t. + static_assert(sizeof(media::AudioFormatSys) == sizeof(audio_format_t)); return static_cast(aidl); } -ConversionResult legacy2aidl_audio_format_t_AudioFormat( +ConversionResult legacy2aidl_audio_format_t_AudioFormat( audio_format_t legacy) { - // This relies on AudioFormat being kept in sync with audio_format_t. - static_assert(sizeof(media::audio::common::AudioFormat) == sizeof(audio_format_t)); - return static_cast(legacy); + // This relies on AudioFormatSys being kept in sync with audio_format_t. + static_assert(sizeof(media::AudioFormatSys) == sizeof(audio_format_t)); + return static_cast(legacy); } ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl) { diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index c7f23e3f26..85c33a0ecf 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -312,6 +312,7 @@ aidl_interface { "aidl/android/media/AudioEncapsulationMode.aidl", "aidl/android/media/AudioEncapsulationMetadataType.aidl", "aidl/android/media/AudioEncapsulationType.aidl", + "aidl/android/media/AudioFormatSys.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", "aidl/android/media/AudioGainConfig.aidl", @@ -354,7 +355,6 @@ aidl_interface { "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ - "android.media.audio.common.types", "media_permission-aidl", ], backend: { @@ -395,7 +395,6 @@ aidl_interface { "aidl/android/media/SoundTriggerSession.aidl", ], imports: [ - "android.media.audio.common.types", "audioclient-types-aidl", ], backend: { @@ -438,7 +437,6 @@ aidl_interface { "aidl/android/media/IAudioTrackCallback.aidl", ], imports: [ - "android.media.audio.common.types", "audioclient-types-aidl", "av-types-aidl", "effect-aidl", @@ -476,7 +474,6 @@ aidl_interface { "aidl/android/media/IAudioPolicyServiceClient.aidl", ], imports: [ - "android.media.audio.common.types", "audioclient-types-aidl", "audiopolicy-types-aidl", "capture_state_listener-aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 0bc592d108..48b74f1158 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -1842,7 +1842,7 @@ status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats, media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; std::vector surroundFormatsEnabledAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl, @@ -1869,7 +1869,7 @@ status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormat media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getReportedSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl))); @@ -1885,7 +1885,7 @@ status_t AudioSystem::setSurroundFormatEnabled(audio_format_t audioFormat, bool const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::audio::common::AudioFormat audioFormatAidl = VALUE_OR_RETURN_STATUS( + media::AudioFormatSys audioFormatAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormat(audioFormat)); return statusTFromBinderStatus( aps->setSurroundFormatEnabled(audioFormatAidl, enabled)); @@ -1939,7 +1939,7 @@ status_t AudioSystem::getHwOffloadEncodingFormatsSupportedForA2DP( & aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - std::vector formatsAidl; + std::vector formatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getHwOffloadEncodingFormatsSupportedForA2DP(&formatsAidl))); *formats = VALUE_OR_RETURN_STATUS( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 0564cdfa3e..b5175883ff 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -238,7 +238,7 @@ uint32_t AudioFlingerClientAdapter::sampleRate(audio_io_handle_t ioHandle) const audio_format_t AudioFlingerClientAdapter::format(audio_io_handle_t output) const { auto result = [&]() -> ConversionResult { int32_t outputAidl = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(output)); - media::audio::common::AudioFormat aidlRet; + media::AudioFormatSys aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus(mDelegate->format(outputAidl, &aidlRet))); return aidl2legacy_AudioFormat_audio_format_t(aidlRet); }(); @@ -406,7 +406,7 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ audio_channel_mask_t channelMask) const { auto result = [&]() -> ConversionResult { int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); - media::audio::common::AudioFormat formatAidl = VALUE_OR_RETURN( + media::AudioFormatSys formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormat(format)); int32_t channelMaskAidl = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_int32_t(channelMask)); @@ -798,7 +798,7 @@ Status AudioFlingerServerAdapter::sampleRate(int32_t ioHandle, int32_t* _aidl_re } Status AudioFlingerServerAdapter::format(int32_t output, - media::audio::common::AudioFormat* _aidl_return) { + media::AudioFormatSys* _aidl_return) { audio_io_handle_t outputLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_int32_t_audio_io_handle_t(output)); *_aidl_return = VALUE_OR_RETURN_BINDER( @@ -926,7 +926,7 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 8dc97d3260..907fa83c2c 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioOffloadInfo; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -29,7 +29,7 @@ parcelable AudioConfig { * TODO(ytai): Create a designated type. */ int channelMask; - AudioFormat format; + AudioFormatSys format; AudioOffloadInfo offloadInfo; long frameCount; } diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index 8353c0d0c5..306af1791e 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -25,5 +25,5 @@ parcelable AudioConfigBase { int sampleRate; /** Interpreted as audio_channel_mask_t. */ int channelMask; - AudioFormat format; + AudioFormatSys format; } diff --git a/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl b/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl new file mode 100644 index 0000000000..95a37537be --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * Audio format is a 32-bit word that consists of: + * main format field (upper 8 bits) + * sub format field (lower 24 bits). + * + * The main format indicates the main codec type. The sub format field indicates + * options and parameters for each format. The sub format is mainly used for + * record to indicate for instance the requested bitrate or profile. It can + * also be used for certain formats to give informations not present in the + * encoded audio stream (e.g. octet alignement for AMR). + * + * This type corresponds to enums in system/audio.h, whereas 'AudioFormat.aidl' + * located in frameworks/base/media/java/android/media is the type used by SDK. + * Both types are in the 'android.media' package. + * + * {@hide} + */ +@Backing(type="int") +enum AudioFormatSys { + /** + * Framework use only, do not constitute valid formats. + */ + MAIN_MASK = 0xFF000000, + SUB_MASK = 0x00FFFFFF, + INVALID = 0xFFFFFFFF, + PCM = 0x00000000, + + DEFAULT = 0, + + PCM_16_BIT = 0x1, + PCM_8_BIT = 0x2, + PCM_32_BIT = 0x3, + PCM_8_24_BIT = 0x4, + PCM_FLOAT = 0x5, + PCM_24_BIT_PACKED = 0x6, + MP3 = 0x01000000, + AMR_NB = 0x02000000, + AMR_WB = 0x03000000, + AAC = 0x04000000, + AAC_MAIN = 0x04000001, + AAC_LC = 0x04000002, + AAC_SSR = 0x04000004, + AAC_LTP = 0x04000008, + AAC_HE_V1 = 0x04000010, + AAC_SCALABLE = 0x04000020, + AAC_ERLC = 0x04000040, + AAC_LD = 0x04000080, + AAC_HE_V2 = 0x040000100, + AAC_ELD = 0x040000200, + AAC_XHE = 0x040000300, + /** + * Deprecated, Use AAC_HE_V1. + */ + HE_AAC_V1 = 0x05000000, + /** + * Deprecated, Use AAC_HE_V2. + */ + HE_AAC_V2 = 0x06000000, + VORBIS = 0x07000000, + OPUS = 0x08000000, + AC3 = 0x09000000, + E_AC3 = 0x0A000000, + E_AC3_JOC = 0x0A000001, + DTS = 0x0B000000, + DTS_HD = 0x0C000000, + IEC61937 = 0x0D000000, + DOLBY_TRUEHD = 0x0E000000, + EVRC = 0x10000000, + EVRCB = 0x11000000, + EVRCWB = 0x12000000, + EVRCNW = 0x13000000, + AAC_ADIF = 0x14000000, + WMA = 0x15000000, + WMA_PRO = 0x16000000, + AMR_WB_PLUS = 0x17000000, + MP2 = 0x18000000, + QCELP = 0x19000000, + DSD = 0x1A000000, + FLAC = 0x1B000000, + ALAC = 0x1C000000, + APE = 0x1D000000, + AAC_ADTS = 0x1E000000, + AAC_ADTS_MAIN = 0x1E000001, + AAC_ADTS_LC = 0x1E000002, + AAC_ADTS_SSR = 0x1E000004, + AAC_ADTS_LTP = 0x1E000008, + AAC_ADTS_HE_V1 = 0x1E000010, + AAC_ADTS_SCALABLE = 0x1E000020, + AAC_ADTS_ERLC = 0x1E000040, + AAC_ADTS_LD = 0x1E000080, + AAC_ADTS_HE_V2 = 0x1E000100, + AAC_ADTS_ELD = 0x1E000200, + AAC_ADTS_XHE = 0x1E000300, + SBC = 0x1F000000, + APTX = 0x20000000, + APTX_HD = 0x21000000, + AC4 = 0x22000000, + LDAC = 0x23000000, + MAT = 0x24000000, + MAT_1_0 = 0x24000001, + MAT_2_0 = 0x24000002, + MAT_2_1 = 0x24000003, + AAC_LATM = 0x25000000, + AAC_LATM_LC = 0x25000002, + AAC_LATM_HE_V1 = 0x25000010, + AAC_LATM_HE_V2 = 0x25000100, + CELT = 0x26000000, + APTX_ADAPTIVE = 0x27000000, + LHDC = 0x28000000, + LHDC_LL = 0x29000000, + APTX_TWSP = 0x2A000000, + LC3 = 0x2B000000, + MPEGH = 0x2C000000, + MPEGH_BL_L3 = 0x2C000013, + MPEGH_BL_L4 = 0x2C000014, + MPEGH_LC_L3 = 0x2C000023, + MPEGH_LC_L4 = 0x2C000024, + IEC60958 = 0x2D000000, + DTS_UHD = 0x2E000000, + DRA = 0x2F000000, + /** + * Subformats. + */ + AAC_SUB_MAIN = 0x1, + AAC_SUB_LC = 0x2, + AAC_SUB_SSR = 0x4, + AAC_SUB_LTP = 0x8, + AAC_SUB_HE_V1 = 0x10, + AAC_SUB_SCALABLE = 0x20, + AAC_SUB_ERLC = 0x40, + AAC_SUB_LD = 0x80, + AAC_SUB_HE_V2 = 0x100, + AAC_SUB_ELD = 0x200, + AAC_SUB_XHE = 0x300, + E_AC3_SUB_JOC = 0x1, + MAT_SUB_1_0 = 0x1, + MAT_SUB_2_0 = 0x2, + MAT_SUB_2_1 = 0x3, + MPEGH_SUB_BL_L3 = 0x13, + MPEGH_SUB_BL_L4 = 0x14, + MPEGH_SUB_LC_L3 = 0x23, + MPEGH_SUB_LC_L4 = 0x24, +} diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index 876ef9b43c..7d845d41d4 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioPatch; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -27,7 +27,7 @@ parcelable AudioIoDescriptor { int ioHandle; AudioPatch patch; int samplingRate; - AudioFormat format; + AudioFormatSys format; /** Interpreted as audio_channel_mask_t. */ int channelMask; long frameCount; diff --git a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl b/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl index c86b3f04b3..693c818e65 100644 --- a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl +++ b/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl @@ -20,7 +20,7 @@ import android.media.AudioConfigBase; import android.media.AudioEncapsulationMode; import android.media.AudioStreamType; import android.media.AudioUsage; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index 2dd30a4505..f1f338eb25 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -22,7 +22,7 @@ import android.media.AudioPortConfigExt; import android.media.AudioPortConfigType; import android.media.AudioPortRole; import android.media.AudioPortType; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -50,7 +50,7 @@ parcelable AudioPortConfig { /** * Format, if applicable. */ - AudioFormat format; + AudioFormatSys format; /** Gain to apply, if applicable. */ AudioGainConfig gain; /** Framework only: HW_AV_SYNC, DIRECT, ... */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index afb288f095..e73bb9e82c 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioEncapsulationType; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -25,7 +25,7 @@ import android.media.audio.common.AudioFormat; parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ - AudioFormat format; + AudioFormatSys format; /** Interpreted as audio_channel_mask_t. */ int[] channelMasks; int[] samplingRates; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index d2cae6dd27..df747d15b2 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -41,7 +41,7 @@ import android.media.IAudioTrack; import android.media.MicrophoneInfoData; import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; /** * {@hide} @@ -62,7 +62,7 @@ interface IAudioFlingerService { */ int sampleRate(int /* audio_io_handle_t */ ioHandle); - AudioFormat format(int /* audio_io_handle_t */ output); + AudioFormatSys format(int /* audio_io_handle_t */ output); long frameCount(int /* audio_io_handle_t */ ioHandle); @@ -115,7 +115,7 @@ interface IAudioFlingerService { // Retrieve the audio recording buffer size in bytes. // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, - AudioFormat format, + AudioFormatSys format, int /* audio_channel_mask_t */ channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index f8924f33ed..d90b9323e0 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.audio.common.AudioFormat; +import android.media.AudioFormatSys; import android.media.AudioAttributesEx; import android.media.AudioAttributesInternal; @@ -62,13 +62,13 @@ interface IAudioPolicyService { void setDeviceConnectionState(in AudioDevice device, in AudioPolicyDeviceState state, @utf8InCpp String deviceName, - in AudioFormat encodedFormat); + in AudioFormatSys encodedFormat); AudioPolicyDeviceState getDeviceConnectionState(in AudioDevice device); void handleDeviceConfigChange(in AudioDevice device, @utf8InCpp String deviceName, - in AudioFormat encodedFormat); + in AudioFormatSys encodedFormat); void setPhoneState(AudioMode state, int /* uid_t */ uid); @@ -278,7 +278,7 @@ interface IAudioPolicyService { * number of elements without actually retrieving them. */ void getSurroundFormats(inout Int count, - out AudioFormat[] formats, + out AudioFormatSys[] formats, out boolean[] formatsEnabled); /** @@ -290,11 +290,11 @@ interface IAudioPolicyService { * number of elements without actually retrieving them. */ void getReportedSurroundFormats(inout Int count, - out AudioFormat[] formats); + out AudioFormatSys[] formats); - AudioFormat[] getHwOffloadEncodingFormatsSupportedForA2DP(); + AudioFormatSys[] getHwOffloadEncodingFormatsSupportedForA2DP(); - void setSurroundFormatEnabled(AudioFormat audioFormat, boolean enabled); + void setSurroundFormatEnabled(AudioFormatSys audioFormat, boolean enabled); void setAssistantUid(int /* uid_t */ uid); diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 4ec69c71ae..b00ef37dd9 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -132,8 +132,8 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioFormat_audio_format_t( - media::audio::common::AudioFormat aidl); -ConversionResult legacy2aidl_audio_format_t_AudioFormat( + media::AudioFormatSys aidl); +ConversionResult legacy2aidl_audio_format_t_AudioFormat( audio_format_t legacy); ConversionResult diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 3a4868ea8c..a21fb5128a 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -563,7 +563,7 @@ public: Status createRecord(const media::CreateRecordRequest& request, media::CreateRecordResponse* _aidl_return) override; Status sampleRate(int32_t ioHandle, int32_t* _aidl_return) override; - Status format(int32_t output, media::audio::common::AudioFormat* _aidl_return) override; + Status format(int32_t output, media::AudioFormatSys* _aidl_return) override; Status frameCount(int32_t ioHandle, int64_t* _aidl_return) override; Status latency(int32_t output, int32_t* _aidl_return) override; Status setMasterVolume(float value) override; @@ -585,7 +585,7 @@ public: Status getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; - Status getInputBufferSize(int32_t sampleRate, media::audio::common::AudioFormat format, + Status getInputBufferSize(int32_t sampleRate, media::AudioFormatSys format, int32_t channelMask, int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 551013fa18..ff67a11fdf 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -98,7 +98,7 @@ Status AudioPolicyService::setDeviceConnectionState( const media::AudioDevice& deviceAidl, media::AudioPolicyDeviceState stateAidl, const std::string& deviceNameAidl, - media::audio::common::AudioFormat encodedFormatAidl) { + media::AudioFormatSys encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_devices_t(deviceAidl.type)); audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS( @@ -148,7 +148,7 @@ Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& de Status AudioPolicyService::handleDeviceConfigChange( const media::AudioDevice& deviceAidl, const std::string& deviceNameAidl, - media::audio::common::AudioFormat encodedFormatAidl) { + media::AudioFormatSys encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_devices_t(deviceAidl.type)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( @@ -1814,7 +1814,7 @@ Status AudioPolicyService::getStreamVolumeDB(media::AudioStreamType streamAidl, } Status AudioPolicyService::getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); @@ -1846,7 +1846,7 @@ Status AudioPolicyService::getSurroundFormats(media::Int* count, } Status AudioPolicyService::getReportedSurroundFormats( - media::Int* count, std::vector* formats) { + media::Int* count, std::vector* formats) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); if (numSurroundFormats > MAX_ITEMS_PER_LIST) { @@ -1872,7 +1872,7 @@ Status AudioPolicyService::getReportedSurroundFormats( } Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) { + std::vector* _aidl_return) { std::vector formats; if (mAudioPolicyManager == NULL) { @@ -1883,14 +1883,14 @@ Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getHwOffloadEncodingFormatsSupportedForA2DP(&formats))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>( + convertContainer>( formats, legacy2aidl_audio_format_t_AudioFormat)); return Status::ok(); } Status AudioPolicyService::setSurroundFormatEnabled( - media::audio::common::AudioFormat audioFormatAidl, bool enabled) { + media::AudioFormatSys audioFormatAidl, bool enabled) { audio_format_t audioFormat = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioFormat_audio_format_t(audioFormatAidl)); if (mAudioPolicyManager == NULL) { diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 6eb33f60dc..40192b89da 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -67,13 +67,13 @@ public: const media::AudioDevice& device, media::AudioPolicyDeviceState state, const std::string& deviceName, - media::audio::common::AudioFormat encodedFormat) override; + media::AudioFormatSys encodedFormat) override; binder::Status getDeviceConnectionState(const media::AudioDevice& device, media::AudioPolicyDeviceState* _aidl_return) override; binder::Status handleDeviceConfigChange( const media::AudioDevice& device, const std::string& deviceName, - media::audio::common::AudioFormat encodedFormat) override; + media::AudioFormatSys encodedFormat) override; binder::Status setPhoneState(media::AudioMode state, int32_t uid) override; binder::Status setForceUse(media::AudioPolicyForceUse usage, media::AudioPolicyForcedConfig config) override; @@ -186,13 +186,13 @@ public: binder::Status getStreamVolumeDB(media::AudioStreamType stream, int32_t index, int32_t device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) override; binder::Status getReportedSurroundFormats( - media::Int* count, std::vector* formats) override; + media::Int* count, std::vector* formats) override; binder::Status getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) override; - binder::Status setSurroundFormatEnabled(media::audio::common::AudioFormat audioFormat, + std::vector* _aidl_return) override; + binder::Status setSurroundFormatEnabled(media::AudioFormatSys audioFormat, bool enabled) override; binder::Status setAssistantUid(int32_t uid) override; binder::Status setA11yServicesUids(const std::vector& uids) override; -- GitLab From 6bc11fb56bd7e9a0729fa123c7e510026b1ca460 Mon Sep 17 00:00:00 2001 From: shubang Date: Thu, 6 May 2021 09:26:16 -0700 Subject: [PATCH 046/694] Move proto messages from enums/ to message/ Bug: 184754707 Test: make Change-Id: I21acc5ff1296d5ed6f5fcbea67a82d11bb037337 --- services/mediametrics/statsd_audiopolicy.cpp | 4 ++-- services/mediametrics/statsd_audiorecord.cpp | 4 ++-- services/mediametrics/statsd_audiothread.cpp | 4 ++-- services/mediametrics/statsd_audiotrack.cpp | 4 ++-- services/mediametrics/statsd_extractor.cpp | 16 ++++++++-------- services/mediametrics/statsd_nuplayer.cpp | 4 ++-- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/services/mediametrics/statsd_audiopolicy.cpp b/services/mediametrics/statsd_audiopolicy.cpp index f44b7c4689..3d9376e018 100644 --- a/services/mediametrics/statsd_audiopolicy.cpp +++ b/services/mediametrics/statsd_audiopolicy.cpp @@ -32,7 +32,7 @@ #include #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -50,7 +50,7 @@ bool statsd_audiopolicy(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::AudioPolicyData metrics_proto; + ::android::stats::mediametrics_message::AudioPolicyData metrics_proto; // flesh out the protobuf we'll hand off with our data // diff --git a/services/mediametrics/statsd_audiorecord.cpp b/services/mediametrics/statsd_audiorecord.cpp index 70a67aec5e..41efcaa809 100644 --- a/services/mediametrics/statsd_audiorecord.cpp +++ b/services/mediametrics/statsd_audiorecord.cpp @@ -33,7 +33,7 @@ #include "MediaMetricsService.h" #include "StringUtils.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -50,7 +50,7 @@ bool statsd_audiorecord(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::AudioRecordData metrics_proto; + ::android::stats::mediametrics_message::AudioRecordData metrics_proto; // flesh out the protobuf we'll hand off with our data // diff --git a/services/mediametrics/statsd_audiothread.cpp b/services/mediametrics/statsd_audiothread.cpp index 34cc923c52..e9b6dd673e 100644 --- a/services/mediametrics/statsd_audiothread.cpp +++ b/services/mediametrics/statsd_audiothread.cpp @@ -32,7 +32,7 @@ #include #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -50,7 +50,7 @@ bool statsd_audiothread(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::AudioThreadData metrics_proto; + ::android::stats::mediametrics_message::AudioThreadData metrics_proto; #define MM_PREFIX "android.media.audiothread." diff --git a/services/mediametrics/statsd_audiotrack.cpp b/services/mediametrics/statsd_audiotrack.cpp index fe269a1eef..59627ae3df 100644 --- a/services/mediametrics/statsd_audiotrack.cpp +++ b/services/mediametrics/statsd_audiotrack.cpp @@ -33,7 +33,7 @@ #include "MediaMetricsService.h" #include "StringUtils.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -51,7 +51,7 @@ bool statsd_audiotrack(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::AudioTrackData metrics_proto; + ::android::stats::mediametrics_message::AudioTrackData metrics_proto; // flesh out the protobuf we'll hand off with our data // diff --git a/services/mediametrics/statsd_extractor.cpp b/services/mediametrics/statsd_extractor.cpp index 2378f33786..4ac5621276 100644 --- a/services/mediametrics/statsd_extractor.cpp +++ b/services/mediametrics/statsd_extractor.cpp @@ -32,7 +32,7 @@ #include #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -50,7 +50,7 @@ bool statsd_extractor(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::ExtractorData metrics_proto; + ::android::stats::mediametrics_message::ExtractorData metrics_proto; std::string format; if (item->getString("android.media.mediaextractor.fmt", &format)) { @@ -68,17 +68,17 @@ bool statsd_extractor(const std::shared_ptr& item, } std::string entry_point_string; - stats::mediametrics::ExtractorData::EntryPoint entry_point = - stats::mediametrics::ExtractorData_EntryPoint_OTHER; + stats::mediametrics_message::ExtractorData::EntryPoint entry_point = + stats::mediametrics_message::ExtractorData_EntryPoint_OTHER; if (item->getString("android.media.mediaextractor.entry", &entry_point_string)) { if (entry_point_string == "sdk") { - entry_point = stats::mediametrics::ExtractorData_EntryPoint_SDK; + entry_point = stats::mediametrics_message::ExtractorData_EntryPoint_SDK; } else if (entry_point_string == "ndk-with-jvm") { - entry_point = stats::mediametrics::ExtractorData_EntryPoint_NDK_WITH_JVM; + entry_point = stats::mediametrics_message::ExtractorData_EntryPoint_NDK_WITH_JVM; } else if (entry_point_string == "ndk-no-jvm") { - entry_point = stats::mediametrics::ExtractorData_EntryPoint_NDK_NO_JVM; + entry_point = stats::mediametrics_message::ExtractorData_EntryPoint_NDK_NO_JVM; } else { - entry_point = stats::mediametrics::ExtractorData_EntryPoint_OTHER; + entry_point = stats::mediametrics_message::ExtractorData_EntryPoint_OTHER; } metrics_proto.set_entry_point(entry_point); } diff --git a/services/mediametrics/statsd_nuplayer.cpp b/services/mediametrics/statsd_nuplayer.cpp index 33da81e5ff..bdee1f2c32 100644 --- a/services/mediametrics/statsd_nuplayer.cpp +++ b/services/mediametrics/statsd_nuplayer.cpp @@ -32,7 +32,7 @@ #include #include "MediaMetricsService.h" -#include "frameworks/proto_logging/stats/enums/stats/mediametrics/mediametrics.pb.h" +#include "frameworks/proto_logging/stats/message/mediametrics_message.pb.h" #include "iface_statsd.h" namespace android { @@ -54,7 +54,7 @@ bool statsd_nuplayer(const std::shared_ptr& item, // the rest into our own proto // - ::android::stats::mediametrics::NuPlayerData metrics_proto; + ::android::stats::mediametrics_message::NuPlayerData metrics_proto; // flesh out the protobuf we'll hand off with our data // -- GitLab From 030067f8796038424df0ffa897000699711a4fc8 Mon Sep 17 00:00:00 2001 From: Dichen Zhang Date: Mon, 24 May 2021 18:05:39 -0700 Subject: [PATCH 047/694] Fixes for MediaCodec metrics 1. Fixed a typo 2. Removed "std::move()" for log-session-id Test: dumpsys Change-Id: I8eb5ade7f51be67faa224cd8ac681be2d9c440ca --- services/mediametrics/statsd_codec.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/mediametrics/statsd_codec.cpp b/services/mediametrics/statsd_codec.cpp index bcd5f9090f..e5ee2a3d20 100644 --- a/services/mediametrics/statsd_codec.cpp +++ b/services/mediametrics/statsd_codec.cpp @@ -55,10 +55,10 @@ bool statsd_codec(const std::shared_ptr& item, // flesh out the protobuf we'll hand off with our data // - //android.media.mediacodec.videoSessionId string + //android.media.mediacodec.log-session-id string std::string sessionId; - if (item->getString("android.media.mediacodec.log-session_id", &sessionId)) { - metrics_proto.set_log_session_id(std::move(sessionId)); + if (item->getString("android.media.mediacodec.log-session-id", &sessionId)) { + metrics_proto.set_log_session_id(sessionId); } // android.media.mediacodec.codec string std::string codec; -- GitLab From 3e5f14f71bfecd8e6834e55c5ea68d510f27c9d1 Mon Sep 17 00:00:00 2001 From: Svet Ganov Date: Thu, 13 May 2021 22:51:08 +0000 Subject: [PATCH 048/694] Switch media fw permissions checks to AttributionSource (av) Attribution source is the abstraction to capture the data flows for private data across apps. Checking permissions for an attribution source does this for all apps in the chain that would receive the data as well as the relevant app ops are checked/noted/started as needed. bug: 158792096 Test: atest CtsMediaTestCases atest CtsPermissionTestCases atest CtsPermission2TestCases atest CtsPermission3TestCases atest CtsPermission4TestCases atest CtsPermission5TestCases atest CtsAppOpsTestCases atest CtsAppOps2TestCases Change-Id: I1c5a4321dd3b2d458372058c99604a6ec208717c --- cmds/stagefright/Android.mk | 10 +- cmds/stagefright/audioloop.cpp | 8 +- media/libaaudio/src/Android.bp | 11 +- .../src/binding/AAudioStreamRequest.cpp | 6 +- .../src/binding/AAudioStreamRequest.h | 14 +- .../binding/aidl/aaudio/StreamRequest.aidl | 10 +- .../src/client/AudioStreamInternal.cpp | 17 +- .../src/legacy/AudioStreamRecord.cpp | 17 +- .../libaaudio/src/legacy/AudioStreamRecord.h | 4 +- .../libaaudio/src/legacy/AudioStreamTrack.cpp | 6 +- media/libaudioclient/AidlConversion.cpp | 4 +- media/libaudioclient/Android.bp | 16 +- media/libaudioclient/AudioEffect.cpp | 17 +- media/libaudioclient/AudioRecord.cpp | 32 +-- media/libaudioclient/AudioSystem.cpp | 10 +- media/libaudioclient/AudioTrack.cpp | 48 +++-- media/libaudioclient/ToneGenerator.cpp | 13 +- .../aidl/android/media/AudioClient.aidl | 4 +- .../android/media/CreateEffectRequest.aidl | 4 +- .../android/media/CreateRecordRequest.aidl | 1 - .../android/media/IAudioPolicyService.aidl | 6 +- media/libaudioclient/fuzzer/Android.bp | 2 +- .../fuzzer/audioflinger_fuzzer.cpp | 30 +-- .../include/media/AudioClient.h | 4 +- .../include/media/AudioEffect.h | 8 +- .../include/media/AudioRecord.h | 12 +- .../include/media/AudioSystem.h | 8 +- .../libaudioclient/include/media/AudioTrack.h | 23 ++- .../include/media/IAudioFlinger.h | 3 +- media/libaudioclient/tests/Android.bp | 2 + .../tests/test_create_audiorecord.cpp | 15 +- media/libmedia/Android.bp | 8 +- media/libmedia/IMediaPlayerService.cpp | 22 +- .../include/media/IMediaPlayerService.h | 8 +- .../include/media/MediaRecorderBase.h | 8 +- media/libmedia/include/media/mediaplayer.h | 8 +- media/libmedia/include/media/mediarecorder.h | 4 +- media/libmedia/mediaplayer.cpp | 13 +- media/libmedia/mediarecorder.cpp | 7 +- media/libmediaplayerservice/Android.bp | 6 +- .../MediaPlayerService.cpp | 65 +++--- .../MediaPlayerService.h | 18 +- .../MediaRecorderClient.cpp | 13 +- .../MediaRecorderClient.h | 6 +- .../StagefrightRecorder.cpp | 17 +- .../StagefrightRecorder.h | 8 +- .../tests/stagefrightRecorder/Android.bp | 2 +- .../StagefrightRecorderTest.cpp | 9 +- media/libstagefright/Android.bp | 6 +- media/libstagefright/AudioSource.cpp | 23 ++- .../include/media/stagefright/AudioSource.h | 6 +- .../tests/fuzzers/WriterFuzzer.cpp | 15 +- media/libstagefright/webm/Android.bp | 2 +- media/utils/Android.bp | 5 +- media/utils/ServiceUtilities.cpp | 192 ++++++++++-------- media/utils/fuzzers/Android.bp | 3 +- media/utils/fuzzers/ServiceUtilitiesFuzz.cpp | 29 +-- .../include/mediautils/ServiceUtilities.h | 34 ++-- services/audioflinger/Android.bp | 3 +- services/audioflinger/AudioFlinger.cpp | 78 +++---- services/audioflinger/AudioFlinger.h | 8 +- services/audioflinger/MmapTracks.h | 2 +- services/audioflinger/PlaybackTracks.h | 12 +- services/audioflinger/RecordTracks.h | 13 +- services/audioflinger/Threads.cpp | 44 ++-- services/audioflinger/Threads.h | 4 +- services/audioflinger/Tracks.cpp | 122 +++++------ services/audiopolicy/AudioPolicyInterface.h | 8 +- services/audiopolicy/fuzzer/Android.bp | 2 +- .../audiopolicy/fuzzer/audiopolicy_fuzzer.cpp | 24 ++- .../audiopolicy/managerdefault/Android.bp | 2 +- .../managerdefault/AudioPolicyManager.cpp | 10 +- .../managerdefault/AudioPolicyManager.h | 6 +- services/audiopolicy/service/Android.bp | 6 +- .../service/AudioPolicyEffects.cpp | 23 ++- .../service/AudioPolicyInterfaceImpl.cpp | 117 ++++++----- .../service/AudioPolicyService.cpp | 15 +- .../audiopolicy/service/AudioPolicyService.h | 35 ++-- services/audiopolicy/tests/Android.bp | 3 +- .../tests/audiopolicymanager_tests.cpp | 22 +- .../oboeservice/AAudioEndpointManager.cpp | 2 +- services/oboeservice/AAudioService.cpp | 29 +-- .../oboeservice/AAudioServiceEndpointMMAP.cpp | 14 +- .../oboeservice/AAudioServiceStreamBase.cpp | 14 +- .../oboeservice/AAudioServiceStreamBase.h | 6 +- services/oboeservice/Android.bp | 4 +- services/oboeservice/fuzzer/Android.bp | 2 +- .../oboeservice/fuzzer/oboeservice_fuzzer.cpp | 13 +- 88 files changed, 817 insertions(+), 728 deletions(-) diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk index 03a8dc91d6..803c4a477a 100644 --- a/cmds/stagefright/Android.mk +++ b/cmds/stagefright/Android.mk @@ -16,9 +16,9 @@ LOCAL_SHARED_LIBRARIES := \ libstagefright_foundation libjpeg libui libgui libcutils liblog \ libhidlbase libdatasource libaudioclient \ android.hardware.media.omx@1.0 \ - media_permission-aidl-cpp + framework-permission-aidl-cpp -LOCAL_STATIC_LIBRARIES := media_permission-aidl-cpp +LOCAL_STATIC_LIBRARIES := framework-permission-aidl-cpp LOCAL_C_INCLUDES:= \ frameworks/av/media/libstagefright \ @@ -52,7 +52,7 @@ LOCAL_HEADER_LIBRARIES := \ LOCAL_SHARED_LIBRARIES := \ libstagefright libmedia liblog libutils libbinder \ libstagefright_foundation libdatasource libaudioclient \ - media_permission-aidl-cpp + framework-permission-aidl-cpp LOCAL_C_INCLUDES:= \ frameworks/av/camera/include \ @@ -90,7 +90,7 @@ LOCAL_C_INCLUDES:= \ frameworks/av/media/libstagefright \ frameworks/native/include/media/openmax \ frameworks/native/include/media/hardware \ - media_permission-aidl-cpp + framework-permission-aidl-cpp LOCAL_CFLAGS += -Wno-multichar -Werror -Wall @@ -119,7 +119,7 @@ LOCAL_HEADER_LIBRARIES := \ LOCAL_SHARED_LIBRARIES := \ libstagefright libmedia liblog libutils libbinder \ libstagefright_foundation libaudioclient \ - media_permission-aidl-cpp + framework-permission-aidl-cpp LOCAL_C_INCLUDES:= \ frameworks/av/media/libstagefright \ diff --git a/cmds/stagefright/audioloop.cpp b/cmds/stagefright/audioloop.cpp index c86a611b59..4b41ff8095 100644 --- a/cmds/stagefright/audioloop.cpp +++ b/cmds/stagefright/audioloop.cpp @@ -24,7 +24,7 @@ #include -#include +#include #include #include #include @@ -39,7 +39,7 @@ using namespace android; -using media::permission::Identity; +using content::AttributionSourceState; static void usage(const char* name) { @@ -113,10 +113,10 @@ int main(int argc, char* argv[]) audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER; attr.source = AUDIO_SOURCE_MIC; - // TODO b/182392769: use identity util + // TODO b/182392769: use attribution source util source = new AudioSource( &attr, - Identity(), + AttributionSourceState(), sampleRate, channels); } else { diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index 5e054c5106..cb08b1c76b 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -111,6 +111,7 @@ cc_library { "libcutils", "libutils", "libbinder", + "framework-permission-aidl-cpp", ], sanitize: { @@ -152,7 +153,7 @@ cc_library { export_header_lib_headers: ["libaaudio_headers"], export_shared_lib_headers: [ - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], shared_libs: [ @@ -165,15 +166,11 @@ cc_library { "libcutils", "libutils", "libbinder", + "framework-permission-aidl-cpp", "aaudio-aidl-cpp", - "media_permission-aidl-cpp", "libaudioclient_aidl_conversion", ], - static_libs: [ - "media_permission-aidl-cpp", - ], - cflags: [ "-Wno-unused-parameter", "-Wall", @@ -250,7 +247,7 @@ aidl_interface { imports: [ "audioclient-types-aidl", "shared-file-region-aidl", - "media_permission-aidl", + "framework-permission-aidl", ], backend: { diff --git a/media/libaaudio/src/binding/AAudioStreamRequest.cpp b/media/libaaudio/src/binding/AAudioStreamRequest.cpp index 09f7a1c01e..a4cc2bd9cb 100644 --- a/media/libaaudio/src/binding/AAudioStreamRequest.cpp +++ b/media/libaaudio/src/binding/AAudioStreamRequest.cpp @@ -31,7 +31,7 @@ using namespace aaudio; AAudioStreamRequest::AAudioStreamRequest(const StreamRequest& parcelable) : mConfiguration(parcelable.params), - mIdentity(parcelable.identity), + mAttributionSource(parcelable.attributionSource), mSharingModeMatchRequired(parcelable.sharingModeMatchRequired), mInService(parcelable.inService) { } @@ -39,7 +39,7 @@ AAudioStreamRequest::AAudioStreamRequest(const StreamRequest& parcelable) : StreamRequest AAudioStreamRequest::parcelable() const { StreamRequest result; result.params = mConfiguration.parcelable(); - result.identity = mIdentity; + result.attributionSource = mAttributionSource; result.sharingModeMatchRequired = mSharingModeMatchRequired; result.inService = mInService; return result; @@ -50,7 +50,7 @@ aaudio_result_t AAudioStreamRequest::validate() const { } void AAudioStreamRequest::dump() const { - ALOGD("mIdentity = %s", mIdentity.toString().c_str()); + ALOGD("mAttributionSource = %s", mAttributionSource.toString().c_str()); ALOGD("mSharingModeMatchRequired = %d", mSharingModeMatchRequired); ALOGD("mInService = %d", mInService); mConfiguration.dump(); diff --git a/media/libaaudio/src/binding/AAudioStreamRequest.h b/media/libaaudio/src/binding/AAudioStreamRequest.h index 02341c8d2f..cc43a4814b 100644 --- a/media/libaaudio/src/binding/AAudioStreamRequest.h +++ b/media/libaaudio/src/binding/AAudioStreamRequest.h @@ -23,10 +23,12 @@ #include #include "binding/AAudioStreamConfiguration.h" -#include +#include namespace aaudio { +using android::content::AttributionSourceState; + class AAudioStreamRequest { public: AAudioStreamRequest() = default; @@ -34,12 +36,12 @@ public: // Construct based on a parcelable representation. explicit AAudioStreamRequest(const StreamRequest& parcelable); - const android::media::permission::Identity &getIdentity() const { - return mIdentity; + const AttributionSourceState &getAttributionSource() const { + return mAttributionSource; } - void setIdentity(const android::media::permission::Identity &identity) { - mIdentity = identity; + void setAttributionSource(const AttributionSourceState &attributionSource) { + mAttributionSource = attributionSource; } bool isSharingModeMatchRequired() const { @@ -75,7 +77,7 @@ public: private: AAudioStreamConfiguration mConfiguration; - android::media::permission::Identity mIdentity; + AttributionSourceState mAttributionSource; bool mSharingModeMatchRequired = false; bool mInService = false; // Stream opened by AAudioservice }; diff --git a/media/libaaudio/src/binding/aidl/aaudio/StreamRequest.aidl b/media/libaaudio/src/binding/aidl/aaudio/StreamRequest.aidl index 12802e6239..53787a0ed5 100644 --- a/media/libaaudio/src/binding/aidl/aaudio/StreamRequest.aidl +++ b/media/libaaudio/src/binding/aidl/aaudio/StreamRequest.aidl @@ -17,11 +17,11 @@ package aaudio; import aaudio.StreamParameters; -import android.media.permission.Identity; +import android.content.AttributionSourceState; parcelable StreamRequest { - StreamParameters params; - Identity identity; - boolean sharingModeMatchRequired; // = false; - boolean inService; // = false; // Stream opened by AAudioservice + StreamParameters params; + AttributionSourceState attributionSource; + boolean sharingModeMatchRequired; // = false; + boolean inService; // = false; // Stream opened by AAudioservice } \ No newline at end of file diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp index a747e896a4..e5844251f9 100644 --- a/media/libaaudio/src/client/AudioStreamInternal.cpp +++ b/media/libaaudio/src/client/AudioStreamInternal.cpp @@ -49,7 +49,7 @@ // This is needed to make sense of the logs more easily. #define LOG_TAG (mInService ? "AudioStreamInternal_Service" : "AudioStreamInternal_Client") -using android::media::permission::Identity; +using android::content::AttributionSourceState; using namespace aaudio; @@ -106,15 +106,16 @@ aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) { // Request FLOAT for the shared mixer or the device. request.getConfiguration().setFormat(AUDIO_FORMAT_PCM_FLOAT); - // TODO b/182392769: use identity util - Identity identity; - identity.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid())); - identity.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid())); - identity.packageName = builder.getOpPackageName(); - identity.attributionTag = builder.getAttributionTag(); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid())); + attributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid())); + attributionSource.packageName = builder.getOpPackageName(); + attributionSource.attributionTag = builder.getAttributionTag(); + attributionSource.token = sp::make(); // Build the request to send to the server. - request.setIdentity(identity); + request.setAttributionSource(attributionSource); request.setSharingModeMatchRequired(isSharingModeMatchRequired()); request.setInService(isInService()); diff --git a/media/libaaudio/src/legacy/AudioStreamRecord.cpp b/media/libaaudio/src/legacy/AudioStreamRecord.cpp index 9ca4e60abd..20b909a465 100644 --- a/media/libaaudio/src/legacy/AudioStreamRecord.cpp +++ b/media/libaaudio/src/legacy/AudioStreamRecord.cpp @@ -32,7 +32,7 @@ #include "utility/AudioClock.h" #include "utility/FixedBlockWriter.h" -using android::media::permission::Identity; +using android::content::AttributionSourceState; using namespace android; using namespace aaudio; @@ -157,12 +157,13 @@ aaudio_result_t AudioStreamRecord::open(const AudioStreamBuilder& builder) .tags = "" }; - // TODO b/182392769: use identity util - Identity identity; - identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); - identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); - identity.packageName = builder.getOpPackageName(); - identity.attributionTag = builder.getAttributionTag(); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); + attributionSource.packageName = builder.getOpPackageName(); + attributionSource.attributionTag = builder.getAttributionTag(); + attributionSource.token = sp::make(); // ----------- open the AudioRecord --------------------- // Might retry, but never more than once. @@ -170,7 +171,7 @@ aaudio_result_t AudioStreamRecord::open(const AudioStreamBuilder& builder) const audio_format_t requestedInternalFormat = getDeviceFormat(); mAudioRecord = new AudioRecord( - identity + attributionSource ); mAudioRecord->set( AUDIO_SOURCE_DEFAULT, // ignored because we pass attributes below diff --git a/media/libaaudio/src/legacy/AudioStreamRecord.h b/media/libaaudio/src/legacy/AudioStreamRecord.h index 7d0a197b33..692651d5d7 100644 --- a/media/libaaudio/src/legacy/AudioStreamRecord.h +++ b/media/libaaudio/src/legacy/AudioStreamRecord.h @@ -25,7 +25,7 @@ #include "AAudioLegacy.h" #include "legacy/AudioStreamLegacy.h" #include "utility/FixedBlockWriter.h" -#include +#include namespace aaudio { @@ -87,7 +87,7 @@ private: FixedBlockWriter mFixedBlockWriter; // TODO add 64-bit position reporting to AudioRecord and use it. - android::media::permission::Identity mIdentity; + android::content::AttributionSourceState mAttributionSource; // Only one type of conversion buffer is used. std::unique_ptr mFormatConversionBufferFloat; diff --git a/media/libaaudio/src/legacy/AudioStreamTrack.cpp b/media/libaaudio/src/legacy/AudioStreamTrack.cpp index 3078d96167..62f583c1d0 100644 --- a/media/libaaudio/src/legacy/AudioStreamTrack.cpp +++ b/media/libaaudio/src/legacy/AudioStreamTrack.cpp @@ -33,7 +33,7 @@ using namespace android; using namespace aaudio; -using media::permission::Identity; +using android::content::AttributionSourceState; // Arbitrary and somewhat generous number of bursts. #define DEFAULT_BURSTS_PER_BUFFER_CAPACITY 8 @@ -151,7 +151,7 @@ aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder) }; mAudioTrack = new AudioTrack(); - // TODO b/182392769: use identity util + // TODO b/182392769: use attribution source util mAudioTrack->set( AUDIO_STREAM_DEFAULT, // ignored because we pass attributes below getSampleRate(), @@ -167,7 +167,7 @@ aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder) sessionId, streamTransferType, nullptr, // DEFAULT audio_offload_info_t - Identity(), // DEFAULT uid and pid + AttributionSourceState(), // DEFAULT uid and pid &attributes, // WARNING - If doNotReconnect set true then audio stops after plugging and unplugging // headphones a few times. diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index d250440665..21b4244932 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -1182,7 +1182,7 @@ ConversionResult aidl2legacy_AudioClient_AudioClient( const media::AudioClient& aidl) { AudioClient legacy; legacy.clientTid = VALUE_OR_RETURN(aidl2legacy_int32_t_pid_t(aidl.clientTid)); - legacy.identity = aidl.identity; + legacy.attributionSource = aidl.attributionSource; return legacy; } @@ -1190,7 +1190,7 @@ ConversionResult legacy2aidl_AudioClient_AudioClient( const AudioClient& legacy) { media::AudioClient aidl; aidl.clientTid = VALUE_OR_RETURN(legacy2aidl_pid_t_int32_t(legacy.clientTid)); - aidl.identity = legacy.identity; + aidl.attributionSource = legacy.attributionSource; return aidl; } diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 85c33a0ecf..37e68bb595 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -132,12 +132,12 @@ cc_library { "libshmemcompat", "libutils", "libvibrator", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libbinder", ], @@ -164,7 +164,6 @@ cc_library { // for memory heap analysis "libc_malloc_debug_backtrace", "shared-file-region-aidl-cpp", - "media_permission-aidl-cpp", ], cflags: [ "-Wall", @@ -232,7 +231,7 @@ cc_library { "libshmemcompat", "libutils", "shared-file-region-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ "audioclient-types-aidl-cpp", @@ -355,7 +354,8 @@ aidl_interface { "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ - "media_permission-aidl", + "android.media.audio.common.types", + "framework-permission-aidl", ], backend: { cpp: { @@ -441,7 +441,7 @@ aidl_interface { "av-types-aidl", "effect-aidl", "shared-file-region-aidl", - "media_permission-aidl", + "framework-permission-aidl", ], double_loadable: true, backend: { @@ -469,7 +469,6 @@ aidl_interface { "aidl/android/media/GetOutputForAttrResponse.aidl", "aidl/android/media/Int.aidl", "aidl/android/media/RecordClientInfo.aidl", - "aidl/android/media/IAudioPolicyService.aidl", "aidl/android/media/IAudioPolicyServiceClient.aidl", ], @@ -477,8 +476,9 @@ aidl_interface { "audioclient-types-aidl", "audiopolicy-types-aidl", "capture_state_listener-aidl", - "media_permission-aidl", + "framework-permission-aidl", ], + double_loadable: true, backend: { cpp: { diff --git a/media/libaudioclient/AudioEffect.cpp b/media/libaudioclient/AudioEffect.cpp index d5047b1b6d..6ad548364c 100644 --- a/media/libaudioclient/AudioEffect.cpp +++ b/media/libaudioclient/AudioEffect.cpp @@ -42,7 +42,6 @@ namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::IAudioPolicyService; -using media::permission::Identity; namespace { @@ -58,8 +57,8 @@ void appendToBuffer(const void* data, // --------------------------------------------------------------------------- -AudioEffect::AudioEffect(const Identity& identity) - : mClientIdentity(identity) +AudioEffect::AudioEffect(const android::content::AttributionSourceState& attributionSource) + : mClientAttributionSource(attributionSource) { } @@ -108,12 +107,12 @@ status_t AudioEffect::set(const effect_uuid_t *type, mDescriptor.type = *(type != NULL ? type : EFFECT_UUID_NULL); mDescriptor.uuid = *(uuid != NULL ? uuid : EFFECT_UUID_NULL); - // TODO b/182392769: use identity util + // TODO b/182392769: use attribution source util mIEffectClient = new EffectClient(this); pid_t pid = IPCThreadState::self()->getCallingPid(); - mClientIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(pid)); + mClientAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(pid)); pid_t uid = IPCThreadState::self()->getCallingUid(); - mClientIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid)); + mClientAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid)); media::CreateEffectRequest request; request.desc = VALUE_OR_RETURN_STATUS( @@ -123,7 +122,7 @@ status_t AudioEffect::set(const effect_uuid_t *type, request.output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(io)); request.sessionId = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(mSessionId)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(device)); - request.identity = mClientIdentity; + request.attributionSource = mClientAttributionSource; request.probe = probe; media::CreateEffectResponse response; @@ -178,7 +177,7 @@ status_t AudioEffect::set(const effect_uuid_t *type, IInterface::asBinder(iEffect)->linkToDeath(mIEffectClient); ALOGV("set() %p OK effect: %s id: %d status %d enabled %d pid %d", this, mDescriptor.name, mId, - mStatus, mEnabled, mClientIdentity.pid); + mStatus, mEnabled, mClientAttributionSource.pid); if (!audio_is_global_session(mSessionId)) { AudioSystem::acquireAudioSessionId(mSessionId, pid, uid); @@ -223,7 +222,7 @@ AudioEffect::~AudioEffect() if (!mProbe && (mStatus == NO_ERROR || mStatus == ALREADY_EXISTS)) { if (!audio_is_global_session(mSessionId)) { AudioSystem::releaseAudioSessionId(mSessionId, - VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientIdentity.pid))); + VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientAttributionSource.pid))); } if (mIEffect != NULL) { mIEffect->disconnect(); diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp index 1a4bde9b13..a1d3bdbb27 100644 --- a/media/libaudioclient/AudioRecord.cpp +++ b/media/libaudioclient/AudioRecord.cpp @@ -39,7 +39,7 @@ namespace android { -using android::media::permission::Identity; +using android::content::AttributionSourceState; using aidl_utils::statusTFromBinderStatus; // --------------------------------------------------------------------------- @@ -126,11 +126,11 @@ status_t AudioRecord::getMetrics(mediametrics::Item * &item) return NO_ERROR; } -AudioRecord::AudioRecord(const Identity &client) - : mActive(false), mStatus(NO_INIT), mClientIdentity(client), mSessionId(AUDIO_SESSION_ALLOCATE), - mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT), - mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE), - mSelectedMicDirection(MIC_DIRECTION_UNSPECIFIED), +AudioRecord::AudioRecord(const AttributionSourceState &client) + : mActive(false), mStatus(NO_INIT), mClientAttributionSource(client), + mSessionId(AUDIO_SESSION_ALLOCATE), mPreviousPriority(ANDROID_PRIORITY_NORMAL), + mPreviousSchedulingGroup(SP_DEFAULT), mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), + mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE), mSelectedMicDirection(MIC_DIRECTION_UNSPECIFIED), mSelectedMicFieldDimension(MIC_FIELD_DIMENSION_DEFAULT) { } @@ -140,7 +140,7 @@ AudioRecord::AudioRecord( uint32_t sampleRate, audio_format_t format, audio_channel_mask_t channelMask, - const Identity& client, + const AttributionSourceState& client, size_t frameCount, callback_t cbf, void* user, @@ -154,14 +154,14 @@ AudioRecord::AudioRecord( float microphoneFieldDimension) : mActive(false), mStatus(NO_INIT), - mClientIdentity(client), + mClientAttributionSource(client), mSessionId(AUDIO_SESSION_ALLOCATE), mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT), mProxy(NULL) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mClientIdentity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientIdentity.pid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mClientAttributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientAttributionSource.pid)); (void)set(inputSource, sampleRate, format, channelMask, frameCount, cbf, user, notificationFrames, false /*threadCanCallJava*/, sessionId, transferType, flags, uid, pid, pAttributes, selectedDeviceId, selectedMicDirection, @@ -191,7 +191,7 @@ AudioRecord::~AudioRecord() IPCThreadState::self()->flushCommands(); ALOGV("%s(%d): releasing session id %d", __func__, mPortId, mSessionId); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientIdentity.pid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientAttributionSource.pid)); AudioSystem::releaseAudioSessionId(mSessionId, pid); } } @@ -243,11 +243,11 @@ status_t AudioRecord::set( // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set. ALOGV("%s(): inputSource %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, " - "notificationFrames %u, sessionId %d, transferType %d, flags %#x, identity %s" + "notificationFrames %u, sessionId %d, transferType %d, flags %#x, attributionSource %s" "uid %d, pid %d", __func__, inputSource, sampleRate, format, channelMask, frameCount, notificationFrames, - sessionId, transferType, flags, mClientIdentity.toString().c_str(), uid, pid); + sessionId, transferType, flags, mClientAttributionSource.toString().c_str(), uid, pid); // TODO b/182392553: refactor or remove pid_t callingPid = IPCThreadState::self()->getCallingPid(); @@ -256,13 +256,13 @@ status_t AudioRecord::set( if (pid == -1 || (callingPid != myPid)) { adjPid = callingPid; } - mClientIdentity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(adjPid)); + mClientAttributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(adjPid)); uid_t adjUid = uid; if (uid == -1 || (callingPid != myPid)) { adjUid = IPCThreadState::self()->getCallingUid(); } - mClientIdentity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(adjUid)); + mClientAttributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(adjUid)); mTracker.reset(new RecordingActivityTracker()); @@ -801,7 +801,7 @@ status_t AudioRecord::createRecord_l(const Modulo &epoch) input.config.sample_rate = mSampleRate; input.config.channel_mask = mChannelMask; input.config.format = mFormat; - input.clientInfo.identity = mClientIdentity; + input.clientInfo.attributionSource = mClientAttributionSource; input.clientInfo.clientTid = -1; if (mFlags & AUDIO_INPUT_FLAG_FAST) { if (mAudioRecordThread != 0) { diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 48b74f1158..1748d3fbf2 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -52,7 +52,7 @@ namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::IAudioPolicyService; -using media::permission::Identity; +using android::content::AttributionSourceState; // client singleton for AudioFlinger binder interface Mutex AudioSystem::gLock; @@ -941,7 +941,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, audio_io_handle_t* output, audio_session_t session, audio_stream_type_t* stream, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_t* config, audio_output_flags_t flags, audio_port_handle_t* selectedDeviceId, @@ -984,7 +984,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, media::GetOutputForAttrResponse responseAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( - aps->getOutputForAttr(attrAidl, sessionAidl, identity, configAidl, flagsAidl, + aps->getOutputForAttr(attrAidl, sessionAidl, attributionSource, configAidl, flagsAidl, selectedDeviceIdAidl, &responseAidl))); *output = VALUE_OR_RETURN_STATUS( @@ -1038,7 +1038,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, audio_io_handle_t* input, audio_unique_id_t riid, audio_session_t session, - const Identity &identity, + const AttributionSourceState &attributionSource, const audio_config_base_t* config, audio_input_flags_t flags, audio_port_handle_t* selectedDeviceId, @@ -1077,7 +1077,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, media::GetInputForAttrResponse response; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( - aps->getInputForAttr(attrAidl, inputAidl, riidAidl, sessionAidl, identity, + aps->getInputForAttr(attrAidl, inputAidl, riidAidl, sessionAidl, attributionSource, configAidl, flagsAidl, selectedDeviceIdAidl, &response))); *input = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.input)); diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 1bc3baacb1..6765bdb169 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -48,7 +48,7 @@ namespace android { // --------------------------------------------------------------------------- using media::VolumeShaper; -using media::permission::Identity; +using android::content::AttributionSourceState; // TODO: Move to a separate .h @@ -225,11 +225,11 @@ status_t AudioTrack::getMetrics(mediametrics::Item * &item) return NO_ERROR; } -AudioTrack::AudioTrack() : AudioTrack(Identity()) +AudioTrack::AudioTrack() : AudioTrack(AttributionSourceState()) { } -AudioTrack::AudioTrack(const Identity& identity) +AudioTrack::AudioTrack(const AttributionSourceState& attributionSource) : mStatus(NO_INIT), mState(STATE_STOPPED), mPreviousPriority(ANDROID_PRIORITY_NORMAL), @@ -237,7 +237,7 @@ AudioTrack::AudioTrack(const Identity& identity) mPausedPosition(0), mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE), mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE), - mClientIdentity(identity), + mClientAttributionSource(attributionSource), mAudioTrackCallback(new AudioTrackCallback()) { mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN; @@ -259,7 +259,7 @@ AudioTrack::AudioTrack( audio_session_t sessionId, transfer_type transferType, const audio_offload_info_t *offloadInfo, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_attributes_t* pAttributes, bool doNotReconnect, float maxRequiredSpeed, @@ -275,8 +275,8 @@ AudioTrack::AudioTrack( (void)set(streamType, sampleRate, format, channelMask, frameCount, flags, cbf, user, notificationFrames, - 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, - offloadInfo, identity, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId); + 0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo, + attributionSource, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId); } AudioTrack::AudioTrack( @@ -292,7 +292,7 @@ AudioTrack::AudioTrack( audio_session_t sessionId, transfer_type transferType, const audio_offload_info_t *offloadInfo, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_attributes_t* pAttributes, bool doNotReconnect, float maxRequiredSpeed) @@ -309,7 +309,7 @@ AudioTrack::AudioTrack( (void)set(streamType, sampleRate, format, channelMask, 0 /*frameCount*/, flags, cbf, user, notificationFrames, sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo, - identity, pAttributes, doNotReconnect, maxRequiredSpeed); + attributionSource, pAttributes, doNotReconnect, maxRequiredSpeed); } AudioTrack::~AudioTrack() @@ -335,7 +335,7 @@ AudioTrack::~AudioTrack() mCblkMemory.clear(); mSharedBuffer.clear(); IPCThreadState::self()->flushCommands(); - pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientIdentity.pid)); + pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mClientAttributionSource.pid)); ALOGV("%s(%d), releasing session id %d from %d on behalf of %d", __func__, mPortId, mSessionId, IPCThreadState::self()->getCallingPid(), clientPid); @@ -381,7 +381,7 @@ status_t AudioTrack::set( audio_session_t sessionId, transfer_type transferType, const audio_offload_info_t *offloadInfo, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_attributes_t* pAttributes, bool doNotReconnect, float maxRequiredSpeed, @@ -391,15 +391,15 @@ status_t AudioTrack::set( uint32_t channelCount; pid_t callingPid; pid_t myPid; - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); // Note mPortId is not valid until the track is created, so omit mPortId in ALOG for set. ALOGV("%s(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, " "flags #%x, notificationFrames %d, sessionId %d, transferType %d, uid %d, pid %d", __func__, streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames, - sessionId, transferType, identity.uid, identity.pid); + sessionId, transferType, attributionSource.uid, attributionSource.pid); mThreadCanCallJava = threadCanCallJava; mSelectedDeviceId = selectedDeviceId; @@ -596,18 +596,15 @@ status_t AudioTrack::set( } mNotificationFramesAct = 0; // TODO b/182392553: refactor or remove + mClientAttributionSource = AttributionSourceState(attributionSource); callingPid = IPCThreadState::self()->getCallingPid(); myPid = getpid(); if (uid == -1 || (callingPid != myPid)) { - mClientIdentity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t( + mClientAttributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t( IPCThreadState::self()->getCallingUid())); - } else { - mClientIdentity.uid = identity.uid; } if (pid == (pid_t)-1 || (callingPid != myPid)) { - mClientIdentity.pid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(callingPid)); - } else { - mClientIdentity.pid = identity.pid; + mClientAttributionSource.pid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(callingPid)); } mAuxEffectId = 0; mOrigFlags = mFlags = flags; @@ -692,13 +689,14 @@ status_t AudioTrack::set( float maxRequiredSpeed, audio_port_handle_t selectedDeviceId) { - Identity identity; - identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(uid)); - identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(pid)); + AttributionSourceState attributionSource; + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(uid)); + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(pid)); + attributionSource.token = sp::make(); return set(streamType, sampleRate, format, static_cast(channelMask), frameCount, flags, cbf, user, notificationFrames, sharedBuffer, - threadCanCallJava, sessionId, transferType, offloadInfo, identity, + threadCanCallJava, sessionId, transferType, offloadInfo, attributionSource, pAttributes, doNotReconnect, maxRequiredSpeed, selectedDeviceId); } @@ -1700,7 +1698,7 @@ status_t AudioTrack::createTrack_l() input.config.channel_mask = mChannelMask; input.config.format = mFormat; input.config.offload_info = mOffloadInfoCopy; - input.clientInfo.identity = mClientIdentity; + input.clientInfo.attributionSource = mClientAttributionSource; input.clientInfo.clientTid = -1; if (mFlags & AUDIO_OUTPUT_FLAG_FAST) { // It is currently meaningless to request SCHED_FIFO for a Java thread. Even if the diff --git a/media/libaudioclient/ToneGenerator.cpp b/media/libaudioclient/ToneGenerator.cpp index 451c4b17c6..e5e8496753 100644 --- a/media/libaudioclient/ToneGenerator.cpp +++ b/media/libaudioclient/ToneGenerator.cpp @@ -27,7 +27,7 @@ namespace android { -using media::permission::Identity; +using android::content::AttributionSourceState; // Descriptors for all available tones (See ToneGenerator::ToneDescriptor class declaration for details) const ToneGenerator::ToneDescriptor ToneGenerator::sToneDescriptors[] = { @@ -1260,10 +1260,11 @@ void ToneGenerator::stopTone() { //////////////////////////////////////////////////////////////////////////////// bool ToneGenerator::initAudioTrack() { // Open audio track in mono, PCM 16bit, default sampling rate. - // TODO b/182392769: use identity util - Identity identity = Identity(); - identity.packageName = mOpPackageName; - mpAudioTrack = new AudioTrack(identity); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource = AttributionSourceState(); + attributionSource.packageName = mOpPackageName; + attributionSource.token = sp::make(); + mpAudioTrack = new AudioTrack(attributionSource); ALOGV("AudioTrack(%p) created", mpAudioTrack.get()); audio_attributes_t attr; @@ -1289,7 +1290,7 @@ bool ToneGenerator::initAudioTrack() { AUDIO_SESSION_ALLOCATE, AudioTrack::TRANSFER_CALLBACK, nullptr, - identity, + attributionSource, &attr); // Set caller name so it can be logged in destructor. // MediaMetricsConstants.h: AMEDIAMETRICS_PROP_CALLERNAME_VALUE_TONEGENERATOR diff --git a/media/libaudioclient/aidl/android/media/AudioClient.aidl b/media/libaudioclient/aidl/android/media/AudioClient.aidl index aa4d8f5a2e..e98fed3998 100644 --- a/media/libaudioclient/aidl/android/media/AudioClient.aidl +++ b/media/libaudioclient/aidl/android/media/AudioClient.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.permission.Identity; +import android.content.AttributionSourceState; /** * {@hide} @@ -24,5 +24,5 @@ import android.media.permission.Identity; parcelable AudioClient { /** Interpreted as pid_t. */ int clientTid; - Identity identity; + AttributionSourceState attributionSource; } diff --git a/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl b/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl index 5737fcda7f..2d274f4e1b 100644 --- a/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl +++ b/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl @@ -19,7 +19,7 @@ package android.media; import android.media.AudioDevice; import android.media.EffectDescriptor; import android.media.IEffectClient; -import android.media.permission.Identity; +import android.content.AttributionSourceState; /** * Input arguments of the createEffect() method. @@ -35,6 +35,6 @@ parcelable CreateEffectRequest { /** Interpreted as audio_session_t. */ int sessionId; AudioDevice device; - Identity identity; + AttributionSourceState attributionSource; boolean probe; } diff --git a/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl b/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl index 5b26d22e6f..7e3c24018f 100644 --- a/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl +++ b/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl @@ -19,7 +19,6 @@ package android.media; import android.media.AudioAttributesInternal; import android.media.AudioClient; import android.media.AudioConfigBase; -import android.media.permission.Identity; /** * CreateRecordRequest contains all input arguments sent by AudioRecord to AudioFlinger diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index d90b9323e0..184b024be3 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -17,6 +17,7 @@ package android.media; import android.media.AudioFormatSys; +import android.content.AttributionSourceState; import android.media.AudioAttributesEx; import android.media.AudioAttributesInternal; @@ -48,7 +49,6 @@ import android.media.GetOutputForAttrResponse; import android.media.IAudioPolicyServiceClient; import android.media.ICaptureStateListener; import android.media.Int; -import android.media.permission.Identity; import android.media.SoundTriggerSession; /** @@ -81,7 +81,7 @@ interface IAudioPolicyService { GetOutputForAttrResponse getOutputForAttr(in AudioAttributesInternal attr, int /* audio_session_t */ session, - in Identity identity, + in AttributionSourceState attributionSource, in AudioConfig config, int /* Bitmask, indexed by AudioOutputFlags */ flags, int /* audio_port_handle_t */ selectedDeviceId); @@ -96,7 +96,7 @@ interface IAudioPolicyService { int /* audio_io_handle_t */ input, int /* audio_unique_id_t */ riid, int /* audio_session_t */ session, - in Identity identity, + in AttributionSourceState attributionSource, in AudioConfigBase config, int /* Bitmask, indexed by AudioInputFlags */ flags, int /* audio_port_handle_t */ selectedDeviceId); diff --git a/media/libaudioclient/fuzzer/Android.bp b/media/libaudioclient/fuzzer/Android.bp index 21e25b9e81..b290aa82e8 100644 --- a/media/libaudioclient/fuzzer/Android.bp +++ b/media/libaudioclient/fuzzer/Android.bp @@ -65,7 +65,7 @@ cc_fuzz { "libutils", "libxml2", "mediametricsservice-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], header_libs: [ "libaudiofoundation_headers", diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp index 1b75917d2f..d03c6fadd6 100644 --- a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp +++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp @@ -23,7 +23,7 @@ */ #include -#include +#include #include #include #include @@ -48,7 +48,7 @@ namespace xsd { using namespace ::android::audio::policy::configuration::V7_0; } -using media::permission::Identity; +using android::content::AttributionSourceState; constexpr audio_unique_id_use_t kUniqueIds[] = { AUDIO_UNIQUE_ID_USE_UNSPECIFIED, AUDIO_UNIQUE_ID_USE_SESSION, AUDIO_UNIQUE_ID_USE_MODULE, @@ -225,15 +225,16 @@ void AudioFlingerFuzzer::invokeAudioTrack() { attributes.usage = usage; sp track = new AudioTrack(); - // TODO b/182392769: use identity util - Identity i; - i.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); - i.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); + attributionSource.token = sp::make(); track->set(AUDIO_STREAM_DEFAULT, sampleRate, format, channelMask, frameCount, flags, nullptr, nullptr, notificationFrames, sharedBuffer, false, sessionId, ((fast && sharedBuffer == 0) || offload) ? AudioTrack::TRANSFER_CALLBACK : AudioTrack::TRANSFER_DEFAULT, - offload ? &offloadInfo : nullptr, i, &attributes, false, 1.0f, + offload ? &offloadInfo : nullptr, attributionSource, &attributes, false, 1.0f, AUDIO_PORT_HANDLE_NONE); status_t status = track->initCheck(); @@ -308,10 +309,11 @@ void AudioFlingerFuzzer::invokeAudioRecord() { attributes.source = inputSource; - // TODO b/182392769: use identity util - Identity i; - i.packageName = std::string(mFdp.ConsumeRandomLengthString().c_str()); - sp record = new AudioRecord(i); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.packageName = std::string(mFdp.ConsumeRandomLengthString().c_str()); + attributionSource.token = sp::make(); + sp record = new AudioRecord(attributionSource); record->set(AUDIO_SOURCE_DEFAULT, sampleRate, format, channelMask, frameCount, nullptr, nullptr, notificationFrames, false, sessionId, fast ? AudioRecord::TRANSFER_CALLBACK : AudioRecord::TRANSFER_DEFAULT, flags, @@ -418,9 +420,9 @@ status_t AudioFlingerFuzzer::invokeAudioEffect() { request.output = io; request.sessionId = sessionId; request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(device)); - // TODO b/182392769: use identity util - request.identity.packageName = opPackageName; - request.identity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(getpid())); + // TODO b/182392769: use attribution source util + request.attributionSource.packageName = opPackageName; + request.attributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(getpid())); request.probe = false; media::CreateEffectResponse response{}; diff --git a/media/libaudioclient/include/media/AudioClient.h b/media/libaudioclient/include/media/AudioClient.h index 295fd4f78a..3be8ce214a 100644 --- a/media/libaudioclient/include/media/AudioClient.h +++ b/media/libaudioclient/include/media/AudioClient.h @@ -19,7 +19,7 @@ #define ANDROID_AUDIO_CLIENT_H #include -#include +#include namespace android { @@ -29,7 +29,7 @@ class AudioClient { clientTid(-1) {} pid_t clientTid; - android::media::permission::Identity identity; + android::content::AttributionSourceState attributionSource; }; }; // namespace android diff --git a/media/libaudioclient/include/media/AudioEffect.h b/media/libaudioclient/include/media/AudioEffect.h index 974ce62724..3c19ec1d65 100644 --- a/media/libaudioclient/include/media/AudioEffect.h +++ b/media/libaudioclient/include/media/AudioEffect.h @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include @@ -337,9 +337,9 @@ public: * * Parameters: * - * client: Identity for app-op checks + * client: Attribution source for app-op checks */ - explicit AudioEffect(const media::permission::Identity& client); + explicit AudioEffect(const android::content::AttributionSourceState& client); /* Terminates the AudioEffect and unregisters it from AudioFlinger. * The effect engine is also destroyed if this AudioEffect was the last controlling @@ -531,7 +531,7 @@ public: static const uint32_t kMaxPreProcessing = 10; protected: - media::permission::Identity mClientIdentity; // Identity used for app op checks. + android::content::AttributionSourceState mClientAttributionSource; // source for app op checks. bool mEnabled = false; // enable state audio_session_t mSessionId = AUDIO_SESSION_OUTPUT_MIX; // audio session ID int32_t mPriority = 0; // priority for effect control diff --git a/media/libaudioclient/include/media/AudioRecord.h b/media/libaudioclient/include/media/AudioRecord.h index 9965e25f69..326919ac28 100644 --- a/media/libaudioclient/include/media/AudioRecord.h +++ b/media/libaudioclient/include/media/AudioRecord.h @@ -32,7 +32,7 @@ #include #include "android/media/IAudioRecord.h" -#include +#include namespace android { @@ -149,9 +149,9 @@ public: * * Parameters: * - * clientIdentity: The identity of the owner of the record + * client: The attribution source of the owner of the record */ - AudioRecord(const media::permission::Identity& clientIdentity); + AudioRecord(const android::content::AttributionSourceState& client); /* Creates an AudioRecord object and registers it with AudioFlinger. * Once created, the track needs to be started before it can be used. @@ -164,7 +164,7 @@ public: * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed * 16 bits per sample). * channelMask: Channel mask, such that audio_is_input_channel(channelMask) is true. - * client: The identity of the owner of the record + * client: The attribution source of the owner of the record * frameCount: Minimum size of track PCM buffer in frames. This defines the * application's contribution to the * latency of the track. The actual size selected by the AudioRecord could @@ -187,7 +187,7 @@ public: uint32_t sampleRate, audio_format_t format, audio_channel_mask_t channelMask, - const media::permission::Identity& clientIdentity, + const android::content::AttributionSourceState& client, size_t frameCount = 0, callback_t cbf = NULL, void* user = NULL, @@ -696,7 +696,7 @@ private: status_t mStatus; - media::permission::Identity mClientIdentity; // The identity of the owner of this record + android::content::AttributionSourceState mClientAttributionSource; // Owner's attribution source size_t mFrameCount; // corresponds to current IAudioRecord, value is // reported back by AudioFlinger to the client diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 4c99dbd160..5e7def13d2 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -38,6 +38,8 @@ #include #include +using android::content::AttributionSourceState; + namespace android { struct record_client_info { @@ -264,7 +266,7 @@ public: audio_io_handle_t *output, audio_session_t session, audio_stream_type_t *stream, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_t *config, audio_output_flags_t flags, audio_port_handle_t *selectedDeviceId, @@ -280,7 +282,7 @@ public: audio_io_handle_t *input, audio_unique_id_t riid, audio_session_t session, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_base_t *config, audio_input_flags_t flags, audio_port_handle_t *selectedDeviceId, diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h index c293343771..f61eef2abb 100644 --- a/media/libaudioclient/include/media/AudioTrack.h +++ b/media/libaudioclient/include/media/AudioTrack.h @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include @@ -36,6 +36,8 @@ namespace android { +using content::AttributionSourceState; + // ---------------------------------------------------------------------------- struct audio_track_cblk_t; @@ -182,7 +184,7 @@ public: */ AudioTrack(); - AudioTrack(const media::permission::Identity& identity); + AudioTrack(const AttributionSourceState& attributionSourceState); /* Creates an AudioTrack object and registers it with AudioFlinger. * Once created, the track needs to be started before it can be used. @@ -230,7 +232,8 @@ public: * transferType: How data is transferred to AudioTrack. * offloadInfo: If not NULL, provides offload parameters for * AudioSystem::getOutputForAttr(). - * identity: The identity of the app which initiallly requested this AudioTrack. + * attributionSource: The attribution source of the app which initially requested this + * AudioTrack. * Includes the UID and PID for power management tracking, or -1 for * current user/process ID, plus the package name. * pAttributes: If not NULL, supersedes streamType for use case selection. @@ -259,8 +262,8 @@ public: audio_session_t sessionId = AUDIO_SESSION_ALLOCATE, transfer_type transferType = TRANSFER_DEFAULT, const audio_offload_info_t *offloadInfo = NULL, - const media::permission::Identity& identity = - media::permission::Identity(), + const AttributionSourceState& attributionSource = + AttributionSourceState(), const audio_attributes_t* pAttributes = NULL, bool doNotReconnect = false, float maxRequiredSpeed = 1.0f, @@ -290,8 +293,8 @@ public: audio_session_t sessionId = AUDIO_SESSION_ALLOCATE, transfer_type transferType = TRANSFER_DEFAULT, const audio_offload_info_t *offloadInfo = NULL, - const media::permission::Identity& identity = - media::permission::Identity(), + const AttributionSourceState& attributionSource = + AttributionSourceState(), const audio_attributes_t* pAttributes = NULL, bool doNotReconnect = false, float maxRequiredSpeed = 1.0f); @@ -338,8 +341,8 @@ public: audio_session_t sessionId = AUDIO_SESSION_ALLOCATE, transfer_type transferType = TRANSFER_DEFAULT, const audio_offload_info_t *offloadInfo = NULL, - const media::permission::Identity& identity = - media::permission::Identity(), + const AttributionSourceState& attributionSource = + AttributionSourceState(), const audio_attributes_t* pAttributes = NULL, bool doNotReconnect = false, float maxRequiredSpeed = 1.0f, @@ -1347,7 +1350,7 @@ private: sp mDeathNotifier; uint32_t mSequence; // incremented for each new IAudioTrack attempt - media::permission::Identity mClientIdentity; + AttributionSourceState mClientAttributionSource; wp mDeviceCallback; diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index a21fb5128a..80320dd8a3 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -40,7 +40,7 @@ #include #include #include -#include +#include #include "android/media/CreateEffectRequest.h" #include "android/media/CreateEffectResponse.h" #include "android/media/CreateRecordRequest.h" @@ -131,7 +131,6 @@ public: audio_attributes_t attr; audio_config_base_t config; AudioClient clientInfo; - media::permission::Identity identity; audio_unique_id_t riid; int32_t maxSharedAudioHistoryMs; diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp index 3c1da4d4ef..def7ca6bfc 100644 --- a/media/libaudioclient/tests/Android.bp +++ b/media/libaudioclient/tests/Android.bp @@ -37,6 +37,7 @@ cc_test { "libmediametrics_headers", ], shared_libs: [ + "framework-permission-aidl-cpp", "libaudioclient", "libbinder", "libcutils", @@ -59,6 +60,7 @@ cc_test { "libbinder", "libcutils", "libutils", + "framework-permission-aidl-cpp", ], data: ["record_test_input_*.txt"], } diff --git a/media/libaudioclient/tests/test_create_audiorecord.cpp b/media/libaudioclient/tests/test_create_audiorecord.cpp index 57676c18a9..1cbcb71225 100644 --- a/media/libaudioclient/tests/test_create_audiorecord.cpp +++ b/media/libaudioclient/tests/test_create_audiorecord.cpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include #include @@ -33,7 +33,7 @@ namespace android { -using media::permission::Identity; +using android::content::AttributionSourceState; int testRecord(FILE *inputFile, int outputFileFd) { @@ -41,16 +41,17 @@ int testRecord(FILE *inputFile, int outputFileFd) uint32_t testCount = 0; Vector args; int ret = 0; - // TODO b/182392769: use identity util - Identity identity; - identity.packageName = PACKAGE_NAME; + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.packageName = std::string(PACKAGE_NAME); + attributionSource.token = sp::make(); if (inputFile == nullptr) { sp record = new AudioRecord(AUDIO_SOURCE_DEFAULT, 0 /* sampleRate */, AUDIO_FORMAT_DEFAULT, AUDIO_CHANNEL_IN_MONO, - identity); + attributionSource); if (record == 0 || record->initCheck() != NO_ERROR) { write(outputFileFd, "Error creating AudioRecord\n", sizeof("Error creating AudioRecord\n")); @@ -96,7 +97,7 @@ int testRecord(FILE *inputFile, int outputFileFd) memset(&attributes, 0, sizeof(attributes)); attributes.source = inputSource; - sp record = new AudioRecord(identity); + sp record = new AudioRecord(attributionSource); record->set(AUDIO_SOURCE_DEFAULT, sampleRate, diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp index e471c7b18b..e98d7d858e 100644 --- a/media/libmedia/Android.bp +++ b/media/libmedia/Android.bp @@ -365,7 +365,7 @@ cc_library { "libaudioclient", "libmedia_codeclist", "libmedia_omx", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ @@ -374,17 +374,17 @@ cc_library { "libandroidicu", //"libsonivox", "libmedia_omx", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], static_libs: [ "resourcemanager_aidl_interface-ndk_platform", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_static_lib_headers: [ "resourcemanager_aidl_interface-ndk_platform", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_include_dirs: [ diff --git a/media/libmedia/IMediaPlayerService.cpp b/media/libmedia/IMediaPlayerService.cpp index 0f189ee50c..07c0ac5979 100644 --- a/media/libmedia/IMediaPlayerService.cpp +++ b/media/libmedia/IMediaPlayerService.cpp @@ -35,7 +35,7 @@ namespace android { -using media::permission::Identity; +using android::content::AttributionSourceState; enum { CREATE = IBinder::FIRST_CALL_TRANSACTION, @@ -65,22 +65,22 @@ public: virtual sp create( const sp& client, audio_session_t audioSessionId, - const Identity& identity) { + const AttributionSourceState& attributionSource) { Parcel data, reply; data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor()); data.writeStrongBinder(IInterface::asBinder(client)); data.writeInt32(audioSessionId); - data.writeParcelable(identity); + data.writeParcelable(attributionSource); remote()->transact(CREATE, data, &reply); return interface_cast(reply.readStrongBinder()); } - virtual sp createMediaRecorder(const Identity& identity) + virtual sp createMediaRecorder(const AttributionSourceState& attributionSource) { Parcel data, reply; data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor()); - data.writeParcelable(identity); + data.writeParcelable(attributionSource); remote()->transact(CREATE_MEDIA_RECORDER, data, &reply); return interface_cast(reply.readStrongBinder()); } @@ -131,23 +131,23 @@ status_t BnMediaPlayerService::onTransact( sp client = interface_cast(data.readStrongBinder()); audio_session_t audioSessionId = (audio_session_t) data.readInt32(); - Identity identity; - status_t status = data.readParcelable(&identity); + AttributionSourceState attributionSource; + status_t status = data.readParcelable(&attributionSource); if (status != NO_ERROR) { return status; } - sp player = create(client, audioSessionId, identity); + sp player = create(client, audioSessionId, attributionSource); reply->writeStrongBinder(IInterface::asBinder(player)); return NO_ERROR; } break; case CREATE_MEDIA_RECORDER: { CHECK_INTERFACE(IMediaPlayerService, data, reply); - Identity identity; - status_t status = data.readParcelable(&identity); + AttributionSourceState attributionSource; + status_t status = data.readParcelable(&attributionSource); if (status != NO_ERROR) { return status; } - sp recorder = createMediaRecorder(identity); + sp recorder = createMediaRecorder(attributionSource); reply->writeStrongBinder(IInterface::asBinder(recorder)); return NO_ERROR; } break; diff --git a/media/libmedia/include/media/IMediaPlayerService.h b/media/libmedia/include/media/IMediaPlayerService.h index 243e9c7ef1..6070673cfa 100644 --- a/media/libmedia/include/media/IMediaPlayerService.h +++ b/media/libmedia/include/media/IMediaPlayerService.h @@ -27,7 +27,7 @@ #include #include -#include +#include #include @@ -48,12 +48,12 @@ public: DECLARE_META_INTERFACE(MediaPlayerService); virtual sp createMediaRecorder( - const android::media::permission::Identity &identity) = 0; + const android::content::AttributionSourceState &attributionSource) = 0; virtual sp createMetadataRetriever() = 0; virtual sp create(const sp& client, audio_session_t audioSessionId = AUDIO_SESSION_ALLOCATE, - const android::media::permission::Identity& identity = - android::media::permission::Identity()) = 0; + const android::content::AttributionSourceState &attributionSource = + android::content::AttributionSourceState()) = 0; virtual sp getCodecList() const = 0; // Connects to a remote display. diff --git a/media/libmedia/include/media/MediaRecorderBase.h b/media/libmedia/include/media/MediaRecorderBase.h index b5325cefaf..2b7818d66d 100644 --- a/media/libmedia/include/media/MediaRecorderBase.h +++ b/media/libmedia/include/media/MediaRecorderBase.h @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include @@ -34,8 +34,8 @@ class IGraphicBufferProducer; struct PersistentSurface; struct MediaRecorderBase { - explicit MediaRecorderBase(const media::permission::Identity &client) - : mClient(client) {} + explicit MediaRecorderBase(const android::content::AttributionSourceState &attributionSource) + : mAttributionSource(attributionSource) {} virtual ~MediaRecorderBase() {} virtual status_t init() = 0; @@ -84,7 +84,7 @@ struct MediaRecorderBase { protected: - media::permission::Identity mClient; + android::content::AttributionSourceState mAttributionSource; private: MediaRecorderBase(const MediaRecorderBase &); diff --git a/media/libmedia/include/media/mediaplayer.h b/media/libmedia/include/media/mediaplayer.h index fbba39849c..de4c7dbb31 100644 --- a/media/libmedia/include/media/mediaplayer.h +++ b/media/libmedia/include/media/mediaplayer.h @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include @@ -212,8 +212,8 @@ class MediaPlayer : public BnMediaPlayerClient, public virtual IMediaDeathNotifier { public: - explicit MediaPlayer(const android::media::permission::Identity& mIdentity = - android::media::permission::Identity()); + explicit MediaPlayer(const android::content::AttributionSourceState& mAttributionSource = + android::content::AttributionSourceState()); ~MediaPlayer(); void died(); void disconnect(); @@ -317,7 +317,7 @@ private: float mSendLevel; struct sockaddr_in mRetransmitEndpoint; bool mRetransmitEndpointValid; - const android::media::permission::Identity mIdentity; + const android::content::AttributionSourceState mAttributionSource; }; }; // namespace android diff --git a/media/libmedia/include/media/mediarecorder.h b/media/libmedia/include/media/mediarecorder.h index 96a3293f79..d54ff3285b 100644 --- a/media/libmedia/include/media/mediarecorder.h +++ b/media/libmedia/include/media/mediarecorder.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include namespace android { @@ -227,7 +227,7 @@ class MediaRecorder : public BnMediaRecorderClient, public virtual IMediaDeathNotifier { public: - explicit MediaRecorder(const media::permission::Identity& identity); + explicit MediaRecorder(const android::content::AttributionSourceState& attributionSource); ~MediaRecorder(); void died(); diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp index 7504787a4f..1c9b9e4941 100644 --- a/media/libmedia/mediaplayer.cpp +++ b/media/libmedia/mediaplayer.cpp @@ -40,9 +40,10 @@ namespace android { using media::VolumeShaper; -using media::permission::Identity; +using content::AttributionSourceState; -MediaPlayer::MediaPlayer(const Identity& identity) : mIdentity(identity) +MediaPlayer::MediaPlayer(const AttributionSourceState& attributionSource) + : mAttributionSource(attributionSource) { ALOGV("constructor"); mListener = NULL; @@ -153,7 +154,7 @@ status_t MediaPlayer::setDataSource( if (url != NULL) { const sp service(getMediaPlayerService()); if (service != 0) { - sp player(service->create(this, mAudioSessionId, mIdentity)); + sp player(service->create(this, mAudioSessionId, mAttributionSource)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); @@ -170,7 +171,7 @@ status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length) status_t err = UNKNOWN_ERROR; const sp service(getMediaPlayerService()); if (service != 0) { - sp player(service->create(this, mAudioSessionId, mIdentity)); + sp player(service->create(this, mAudioSessionId, mAttributionSource)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(fd, offset, length))) { player.clear(); @@ -186,7 +187,7 @@ status_t MediaPlayer::setDataSource(const sp &source) status_t err = UNKNOWN_ERROR; const sp service(getMediaPlayerService()); if (service != 0) { - sp player(service->create(this, mAudioSessionId, mIdentity)); + sp player(service->create(this, mAudioSessionId, mAttributionSource)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(source))) { player.clear(); @@ -202,7 +203,7 @@ status_t MediaPlayer::setDataSource(const String8& rtpParams) status_t err = UNKNOWN_ERROR; const sp service(getMediaPlayerService()); if (service != 0) { - sp player(service->create(this, mAudioSessionId, mIdentity)); + sp player(service->create(this, mAudioSessionId, mAttributionSource)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(rtpParams))) { player.clear(); diff --git a/media/libmedia/mediarecorder.cpp b/media/libmedia/mediarecorder.cpp index da2b190bd2..cf12c36c2d 100644 --- a/media/libmedia/mediarecorder.cpp +++ b/media/libmedia/mediarecorder.cpp @@ -33,7 +33,7 @@ namespace android { -using media::permission::Identity; +using content::AttributionSourceState; status_t MediaRecorder::setCamera(const sp& camera, const sp& proxy) @@ -760,13 +760,14 @@ status_t MediaRecorder::release() return INVALID_OPERATION; } -MediaRecorder::MediaRecorder(const Identity &identity) : mSurfaceMediaSource(NULL) +MediaRecorder::MediaRecorder(const AttributionSourceState &attributionSource) + : mSurfaceMediaSource(NULL) { ALOGV("constructor"); const sp service(getMediaPlayerService()); if (service != NULL) { - mMediaRecorder = service->createMediaRecorder(identity); + mMediaRecorder = service->createMediaRecorder(attributionSource); } if (mMediaRecorder != NULL) { mCurrentState = MEDIA_RECORDER_IDLE; diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp index 287317d2f3..f55678da32 100644 --- a/media/libmediaplayerservice/Android.bp +++ b/media/libmediaplayerservice/Android.bp @@ -35,7 +35,7 @@ cc_library { "android.hardware.media.c2@1.0", "android.hardware.media.omx@1.0", "av-types-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", "libbase", "libactivitymanager_aidl", @@ -76,12 +76,12 @@ cc_library { "libstagefright_nuplayer", "libstagefright_rtsp", "libstagefright_timedtext", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ "libmedia", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], include_dirs: [ diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp index dc4aea50e7..d278a01976 100644 --- a/media/libmediaplayerservice/MediaPlayerService.cpp +++ b/media/libmediaplayerservice/MediaPlayerService.cpp @@ -95,7 +95,7 @@ using android::BAD_VALUE; using android::NOT_ENOUGH_DATA; using android::Parcel; using android::media::VolumeShaper; -using android::media::permission::Identity; +using android::content::AttributionSourceState; // Max number of entries in the filter. const int kMaxFilterSize = 64; // I pulled that out of thin air. @@ -455,21 +455,22 @@ MediaPlayerService::~MediaPlayerService() ALOGV("MediaPlayerService destroyed"); } -sp MediaPlayerService::createMediaRecorder(const Identity& identity) +sp MediaPlayerService::createMediaRecorder( + const AttributionSourceState& attributionSource) { - // TODO b/182392769: use identity util - Identity verifiedIdentity = identity; - verifiedIdentity.uid = VALUE_OR_FATAL( + // TODO b/182392769: use attribution source util + AttributionSourceState verifiedAttributionSource = attributionSource; + verifiedAttributionSource.uid = VALUE_OR_FATAL( legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); - verifiedIdentity.pid = VALUE_OR_FATAL( + verifiedAttributionSource.pid = VALUE_OR_FATAL( legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid())); sp recorder = - new MediaRecorderClient(this, verifiedIdentity); + new MediaRecorderClient(this, verifiedAttributionSource); wp w = recorder; Mutex::Autolock lock(mLock); mMediaRecorderClients.add(w); ALOGV("Create new media recorder client from pid %s", - verifiedIdentity.toString().c_str()); + verifiedAttributionSource.toString().c_str()); return recorder; } @@ -489,21 +490,21 @@ sp MediaPlayerService::createMetadataRetriever() } sp MediaPlayerService::create(const sp& client, - audio_session_t audioSessionId, const Identity& identity) + audio_session_t audioSessionId, const AttributionSourceState& attributionSource) { int32_t connId = android_atomic_inc(&mNextConnId); - // TODO b/182392769: use identity util - Identity verifiedIdentity = identity; - verifiedIdentity.pid = VALUE_OR_FATAL( + // TODO b/182392769: use attribution source util + AttributionSourceState verifiedAttributionSource = attributionSource; + verifiedAttributionSource.pid = VALUE_OR_FATAL( legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid())); - verifiedIdentity.uid = VALUE_OR_FATAL( + verifiedAttributionSource.uid = VALUE_OR_FATAL( legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); sp c = new Client( - this, verifiedIdentity, connId, client, audioSessionId); + this, verifiedAttributionSource, connId, client, audioSessionId); ALOGV("Create new client(%d) from %s, ", connId, - verifiedIdentity.toString().c_str()); + verifiedAttributionSource.toString().c_str()); wp w = c; { @@ -556,8 +557,8 @@ status_t MediaPlayerService::Client::dump(int fd, const Vector& args) char buffer[SIZE]; String8 result; result.append(" Client\n"); - snprintf(buffer, 255, " Identity(%s), connId(%d), status(%d), looping(%s)\n", - mIdentity.toString().c_str(), mConnId, mStatus, mLoop?"true": "false"); + snprintf(buffer, 255, " AttributionSource(%s), connId(%d), status(%d), looping(%s)\n", + mAttributionSource.toString().c_str(), mConnId, mStatus, mLoop?"true": "false"); result.append(buffer); sp p; @@ -621,7 +622,8 @@ status_t MediaPlayerService::dump(int fd, const Vector& args) for (int i = 0, n = mMediaRecorderClients.size(); i < n; ++i) { sp c = mMediaRecorderClients[i].promote(); if (c != 0) { - snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", c->mIdentity.pid); + snprintf(buffer, 255, " MediaRecorderClient pid(%d)\n", + c->mAttributionSource.pid); result.append(buffer); write(fd, result.string(), result.size()); result = "\n"; @@ -744,10 +746,10 @@ bool MediaPlayerService::hasClient(wp client) } MediaPlayerService::Client::Client( - const sp& service, const Identity& identity, + const sp& service, const AttributionSourceState& attributionSource, int32_t connId, const sp& client, audio_session_t audioSessionId) - : mIdentity(identity) + : mAttributionSource(attributionSource) { ALOGV("Client(%d) constructor", connId); mConnId = connId; @@ -768,7 +770,8 @@ MediaPlayerService::Client::Client( MediaPlayerService::Client::~Client() { - ALOGV("Client(%d) destructor identity = %s", mConnId, mIdentity.toString().c_str()); + ALOGV("Client(%d) destructor AttributionSource = %s", mConnId, + mAttributionSource.toString().c_str()); mAudioOutput.clear(); wp client(this); disconnect(); @@ -781,7 +784,8 @@ MediaPlayerService::Client::~Client() void MediaPlayerService::Client::disconnect() { - ALOGV("disconnect(%d) from identity %s", mConnId, mIdentity.toString().c_str()); + ALOGV("disconnect(%d) from AttributionSource %s", mConnId, + mAttributionSource.toString().c_str()); // grab local reference and clear main reference to prevent future // access to object sp p; @@ -822,11 +826,11 @@ sp MediaPlayerService::Client::createPlayer(player_type playerT } if (p == NULL) { p = MediaPlayerFactory::createPlayer(playerType, mListener, - VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mIdentity.pid))); + VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid))); } if (p != NULL) { - p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mIdentity.uid))); + p->setUID(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid))); } return p; @@ -934,7 +938,7 @@ sp MediaPlayerService::Client::setDataSource_pre( mAudioDeviceUpdatedListener = new AudioDeviceUpdatedNotifier(p); if (!p->hardwareOutput()) { - mAudioOutput = new AudioOutput(mAudioSessionId, mIdentity, + mAudioOutput = new AudioOutput(mAudioSessionId, mAttributionSource, mAudioAttributes, mAudioDeviceUpdatedListener); static_cast(p.get())->setAudioSink(mAudioOutput); } @@ -1784,8 +1788,9 @@ int Antagonizer::callbackThread(void* user) #undef LOG_TAG #define LOG_TAG "AudioSink" -MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, const Identity& identity, - const audio_attributes_t* attr, const sp& deviceCallback) +MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, + const AttributionSourceState& attributionSource, const audio_attributes_t* attr, + const sp& deviceCallback) : mCallback(NULL), mCallbackCookie(NULL), mCallbackData(NULL), @@ -1797,7 +1802,7 @@ MediaPlayerService::AudioOutput::AudioOutput(audio_session_t sessionId, const Id mMsecsPerFrame(0), mFrameSize(0), mSessionId(sessionId), - mIdentity(identity), + mAttributionSource(attributionSource), mSendLevel(0.0), mAuxEffectId(0), mFlags(AUDIO_OUTPUT_FLAG_NONE), @@ -2193,7 +2198,7 @@ status_t MediaPlayerService::AudioOutput::open( mSessionId, AudioTrack::TRANSFER_CALLBACK, offloadInfo, - mIdentity, + mAttributionSource, mAttributes, doNotReconnect, 1.0f, // default value for maxRequiredSpeed @@ -2220,7 +2225,7 @@ status_t MediaPlayerService::AudioOutput::open( mSessionId, AudioTrack::TRANSFER_DEFAULT, NULL, // offload info - mIdentity, + mAttributionSource, mAttributes, doNotReconnect, targetSpeed, diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h index 35a65d3780..98091befb4 100644 --- a/media/libmediaplayerservice/MediaPlayerService.h +++ b/media/libmediaplayerservice/MediaPlayerService.h @@ -33,12 +33,14 @@ #include #include #include -#include +#include #include namespace android { +using content::AttributionSourceState; + class AudioTrack; struct AVSyncSettings; class DeathNotifier; @@ -80,7 +82,7 @@ class MediaPlayerService : public BnMediaPlayerService public: AudioOutput( audio_session_t sessionId, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_attributes_t * attr, const sp& deviceCallback); virtual ~AudioOutput(); @@ -169,7 +171,7 @@ class MediaPlayerService : public BnMediaPlayerService float mMsecsPerFrame; size_t mFrameSize; audio_session_t mSessionId; - media::permission::Identity mIdentity; + AttributionSourceState mAttributionSource; float mSendLevel; int mAuxEffectId; audio_output_flags_t mFlags; @@ -231,13 +233,13 @@ public: static void instantiate(); // IMediaPlayerService interface - virtual sp createMediaRecorder(const media::permission::Identity &identity); + virtual sp createMediaRecorder(const AttributionSourceState &attributionSource); void removeMediaRecorderClient(const wp& client); virtual sp createMetadataRetriever(); virtual sp create(const sp& client, audio_session_t audioSessionId, - const media::permission::Identity& identity); + const AttributionSourceState& attributionSource); virtual sp getCodecList() const; @@ -380,7 +382,7 @@ private: void notify(int msg, int ext1, int ext2, const Parcel *obj); pid_t pid() const { - return VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mIdentity.pid)); + return VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAttributionSource.pid)); } virtual status_t dump(int fd, const Vector& args); @@ -411,7 +413,7 @@ private: friend class MediaPlayerService; Client( const sp& service, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, int32_t connId, const sp& client, audio_session_t audioSessionId); @@ -458,7 +460,7 @@ private: sp mService; sp mClient; sp mAudioOutput; - const media::permission::Identity mIdentity; + const AttributionSourceState mAttributionSource; status_t mStatus; bool mLoop; int32_t mConnId; diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp index daa923e758..a914006294 100644 --- a/media/libmediaplayerservice/MediaRecorderClient.cpp +++ b/media/libmediaplayerservice/MediaRecorderClient.cpp @@ -126,8 +126,9 @@ status_t MediaRecorderClient::setAudioSource(int as) } if ((as == AUDIO_SOURCE_FM_TUNER - && !(captureAudioOutputAllowed(mIdentity) || captureTunerAudioInputAllowed(mIdentity))) - || !recordingAllowed(mIdentity, (audio_source_t)as)) { + && !(captureAudioOutputAllowed(mAttributionSource) + || captureTunerAudioInputAllowed(mAttributionSource))) + || !recordingAllowed(mAttributionSource, (audio_source_t)as)) { return PERMISSION_DENIED; } Mutex::Autolock lock(mLock); @@ -377,12 +378,12 @@ status_t MediaRecorderClient::release() } MediaRecorderClient::MediaRecorderClient(const sp& service, - const Identity& identity) + const AttributionSourceState& attributionSource) { ALOGV("Client constructor"); - // identity already validated in createMediaRecorder - mIdentity = identity; - mRecorder = new StagefrightRecorder(identity); + // attribution source already validated in createMediaRecorder + mAttributionSource = attributionSource; + mRecorder = new StagefrightRecorder(attributionSource); mMediaPlayerService = service; } diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h index 24c6ee1fef..dcb9f828c2 100644 --- a/media/libmediaplayerservice/MediaRecorderClient.h +++ b/media/libmediaplayerservice/MediaRecorderClient.h @@ -22,7 +22,7 @@ #include #include -#include +#include #include @@ -94,13 +94,13 @@ private: MediaRecorderClient( const sp& service, - const media::permission::Identity& identity); + const content::AttributionSourceState& attributionSource); virtual ~MediaRecorderClient(); std::vector mDeathNotifiers; sp mAudioDeviceUpdatedNotifier; - media::permission::Identity mIdentity; + content::AttributionSourceState mAttributionSource; mutable Mutex mLock; MediaRecorderBase *mRecorder; sp mMediaPlayerService; diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp index ce642f3f60..bffd7b3243 100644 --- a/media/libmediaplayerservice/StagefrightRecorder.cpp +++ b/media/libmediaplayerservice/StagefrightRecorder.cpp @@ -116,8 +116,8 @@ static void addBatteryData(uint32_t params) { } -StagefrightRecorder::StagefrightRecorder(const Identity& clientIdentity) - : MediaRecorderBase(clientIdentity), +StagefrightRecorder::StagefrightRecorder(const AttributionSourceState& client) + : MediaRecorderBase(client), mWriter(NULL), mOutputFd(-1), mAudioSource((audio_source_t)AUDIO_SOURCE_CNT), // initialize with invalid value @@ -159,7 +159,7 @@ void StagefrightRecorder::updateMetrics() { // we run as part of the media player service; what we really want to // know is the app which requested the recording. - mMetricsItem->setUid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mClient.uid))); + mMetricsItem->setUid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid))); mMetricsItem->setCString(kRecorderLogSessionId, mLogSessionId.c_str()); @@ -1144,7 +1144,8 @@ status_t StagefrightRecorder::setListener(const sp &listen status_t StagefrightRecorder::setClientName(const String16& clientName) { - mClient.packageName = VALUE_OR_RETURN_STATUS(legacy2aidl_String16_string(clientName)); + mAttributionSource.packageName = VALUE_OR_RETURN_STATUS( + legacy2aidl_String16_string(clientName)); return OK; } @@ -1355,7 +1356,7 @@ sp StagefrightRecorder::createAudioSource() { sp audioSource = new AudioSource( &attr, - mClient, + mAttributionSource, sourceSampleRate, mAudioChannels, mSampleRate, @@ -1880,10 +1881,10 @@ status_t StagefrightRecorder::setupCameraSource( Size videoSize; videoSize.width = mVideoWidth; videoSize.height = mVideoHeight; - uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(mClient.uid)); - pid_t pid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(mClient.pid)); + uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(mAttributionSource.uid)); + pid_t pid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(mAttributionSource.pid)); String16 clientName = VALUE_OR_RETURN_STATUS( - aidl2legacy_string_view_String16(mClient.packageName.value_or(""))); + aidl2legacy_string_view_String16(mAttributionSource.packageName.value_or(""))); if (mCaptureFpsEnable) { if (!(mCaptureFps > 0.)) { ALOGE("Invalid mCaptureFps value: %lf", mCaptureFps); diff --git a/media/libmediaplayerservice/StagefrightRecorder.h b/media/libmediaplayerservice/StagefrightRecorder.h index 59a080e505..d6de47f3cd 100644 --- a/media/libmediaplayerservice/StagefrightRecorder.h +++ b/media/libmediaplayerservice/StagefrightRecorder.h @@ -26,12 +26,12 @@ #include #include -#include - -using namespace android::media::permission; +#include namespace android { +using content::AttributionSourceState; + class Camera; class ICameraRecordingProxy; class CameraSource; @@ -45,7 +45,7 @@ class MediaProfiles; struct ALooper; struct StagefrightRecorder : public MediaRecorderBase { - explicit StagefrightRecorder(const Identity& clientIdentity); + explicit StagefrightRecorder(const AttributionSourceState& attributionSource); virtual ~StagefrightRecorder(); virtual status_t init(); virtual status_t setLogSessionId(const String8 &id); diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp index 5b169113af..92236ea0bd 100644 --- a/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp +++ b/media/libmediaplayerservice/tests/stagefrightRecorder/Android.bp @@ -73,7 +73,7 @@ cc_test { "libstagefright", "libstagefright_foundation", "libutils", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", ], diff --git a/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp b/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp index 6dea53d3bc..162c187b2c 100644 --- a/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp +++ b/media/libmediaplayerservice/tests/stagefrightRecorder/StagefrightRecorderTest.cpp @@ -59,10 +59,11 @@ class StagefrightRecorderTest } void SetUp() override { - // TODO b/182392769: use identity util - Identity identity; - identity.packageName = std::string(LOG_TAG); - mStfRecorder = new StagefrightRecorder(identity); + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.packageName = std::string(LOG_TAG); + attributionSource.token = sp::make(); + mStfRecorder = new StagefrightRecorder(attributionSource); ASSERT_NE(mStfRecorder, nullptr) << "Failed to create the instance of recorder"; mOutputAudioFp = fopen(OUTPUT_FILE_NAME_AUDIO, "wb"); diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index d6e36b94c3..a052a7050b 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -338,7 +338,7 @@ cc_library { "android.hardware.cas.native@1.0", "android.hardware.drm@1.0", "android.hardware.media.omx@1.0", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", ], @@ -352,7 +352,7 @@ cc_library { "libogg", "libwebm", "libstagefright_id3", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libmediandk_format", "libmedia_ndkformatpriv", ], @@ -370,7 +370,7 @@ cc_library { "libhidlmemory", "libmedia", "android.hidl.allocator@1.0", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], export_include_dirs: [ diff --git a/media/libstagefright/AudioSource.cpp b/media/libstagefright/AudioSource.cpp index 89fe56f6d2..b6acdc8fb4 100644 --- a/media/libstagefright/AudioSource.cpp +++ b/media/libstagefright/AudioSource.cpp @@ -34,7 +34,7 @@ namespace android { -using android::media::permission::Identity; +using content::AttributionSourceState; static void AudioRecordCallbackFunction(int event, void *user, void *info) { AudioSource *source = (AudioSource *) user; @@ -54,13 +54,13 @@ static void AudioRecordCallbackFunction(int event, void *user, void *info) { } AudioSource::AudioSource( - const audio_attributes_t *attr, const Identity& identity, + const audio_attributes_t *attr, const AttributionSourceState& attributionSource, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate, audio_port_handle_t selectedDeviceId, audio_microphone_direction_t selectedMicDirection, float selectedMicFieldDimension) { - set(attr, identity, sampleRate, channelCount, outSampleRate, selectedDeviceId, + set(attr, attributionSource, sampleRate, channelCount, outSampleRate, selectedDeviceId, selectedMicDirection, selectedMicFieldDimension); } @@ -71,17 +71,18 @@ AudioSource::AudioSource( audio_microphone_direction_t selectedMicDirection, float selectedMicFieldDimension) { - // TODO b/182392769: use identity util - Identity identity; - identity.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(opPackageName)); - identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(uid)); - identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(pid)); - set(attr, identity, sampleRate, channelCount, outSampleRate, selectedDeviceId, + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(opPackageName)); + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(uid)); + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(pid)); + attributionSource.token = sp::make(); + set(attr, attributionSource, sampleRate, channelCount, outSampleRate, selectedDeviceId, selectedMicDirection, selectedMicFieldDimension); } void AudioSource::set( - const audio_attributes_t *attr, const Identity& identity, + const audio_attributes_t *attr, const AttributionSourceState& attributionSource, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate, audio_port_handle_t selectedDeviceId, audio_microphone_direction_t selectedMicDirection, @@ -126,7 +127,7 @@ void AudioSource::set( mRecord = new AudioRecord( AUDIO_SOURCE_DEFAULT, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), - identity, + attributionSource, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, diff --git a/media/libstagefright/include/media/stagefright/AudioSource.h b/media/libstagefright/include/media/stagefright/AudioSource.h index d1dcdb5acc..43d50f14a9 100644 --- a/media/libstagefright/include/media/stagefright/AudioSource.h +++ b/media/libstagefright/include/media/stagefright/AudioSource.h @@ -31,6 +31,8 @@ namespace android { +using content::AttributionSourceState; + class AudioRecord; struct AudioSource : public MediaSource, public MediaBufferObserver { @@ -38,7 +40,7 @@ struct AudioSource : public MediaSource, public MediaBufferObserver { // _not_ a bitmask of audio_channels_t constants. AudioSource( const audio_attributes_t *attr, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, uint32_t sampleRate, uint32_t channels, uint32_t outSampleRate = 0, @@ -145,7 +147,7 @@ private: void set( const audio_attributes_t *attr, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, uint32_t sampleRate, uint32_t channels, uint32_t outSampleRate = 0, diff --git a/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp b/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp index 969c6e15fc..97d11600d8 100644 --- a/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp +++ b/media/libstagefright/tests/fuzzers/WriterFuzzer.cpp @@ -17,7 +17,7 @@ // dylan.katz@leviathansecurity.com #include -#include +#include #include #include #include @@ -40,7 +40,7 @@ static constexpr uint16_t kMaxMediaBlobSize = 1000; namespace android { -using media::permission::Identity; +using android::content::AttributionSourceState; std::string getFourCC(FuzzedDataProvider *fdp) { std::string fourCC = fdp->ConsumeRandomLengthString(4); @@ -166,11 +166,12 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { StandardWriters writerType = dataProvider.ConsumeEnum(); sp writer = createWriter(tf.fd, writerType, fileMeta); - Identity i; - i.packageName = dataProvider.ConsumeRandomLengthString(kMaxPackageNameLen); - i.uid = dataProvider.ConsumeIntegral(); - i.pid = dataProvider.ConsumeIntegral(); - sp mr = new MediaRecorder(i); + AttributionSourceState attributionSource; + attributionSource.packageName = dataProvider.ConsumeRandomLengthString(kMaxPackageNameLen); + attributionSource.uid = dataProvider.ConsumeIntegral(); + attributionSource.pid = dataProvider.ConsumeIntegral(); + attributionSource.token = sp::make(); + sp mr = new MediaRecorder(attributionSource); writer->setListener(mr); uint8_t baseOpLen = operations.size(); diff --git a/media/libstagefright/webm/Android.bp b/media/libstagefright/webm/Android.bp index 3ceacfe78a..32a22ba4c7 100644 --- a/media/libstagefright/webm/Android.bp +++ b/media/libstagefright/webm/Android.bp @@ -40,7 +40,7 @@ cc_library_static { "libstagefright_foundation", "libutils", "liblog", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], header_libs: [ diff --git a/media/utils/Android.bp b/media/utils/Android.bp index 9e48c1f843..bfe73d5ebb 100644 --- a/media/utils/Android.bp +++ b/media/utils/Android.bp @@ -46,12 +46,11 @@ cc_library { "libbinder", "libcutils", "liblog", - "libpermission", "libutils", "libhidlbase", + "libpermission", "android.hardware.graphics.bufferqueue@1.0", "android.hidl.token@1.0-utils", - "media_permission-aidl-cpp", ], export_static_lib_headers: [ "libbatterystats_aidl", @@ -71,7 +70,7 @@ cc_library { ], export_shared_lib_headers: [ - "media_permission-aidl-cpp" + "libpermission", ], include_dirs: [ diff --git a/media/utils/ServiceUtilities.cpp b/media/utils/ServiceUtilities.cpp index 214a174ca1..bc413d156d 100644 --- a/media/utils/ServiceUtilities.cpp +++ b/media/utils/ServiceUtilities.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include #include #include @@ -40,7 +40,7 @@ namespace android { -using media::permission::Identity; +using content::AttributionSourceState; static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO"); static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE"); @@ -81,92 +81,101 @@ int32_t getOpForSource(audio_source_t source) { } } -static bool checkRecordingInternal(const Identity& identity, const String16& msg, - bool start, audio_source_t source) { +std::optional resolveAttributionSource( + const AttributionSourceState& callerAttributionSource) { + AttributionSourceState nextAttributionSource = callerAttributionSource; + + if (!nextAttributionSource.packageName.has_value()) { + nextAttributionSource = AttributionSourceState(nextAttributionSource); + PermissionController permissionController; + const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid)); + nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string( + resolveCallingPackage(permissionController, VALUE_OR_FATAL( + aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))), + uid))); + if (!nextAttributionSource.packageName.has_value()) { + return std::nullopt; + } + } + + AttributionSourceState myAttributionSource; + myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid())); + myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid())); + myAttributionSource.token = sp::make(); + myAttributionSource.next.push_back(nextAttributionSource); + + return std::optional{myAttributionSource}; +} + +static bool checkRecordingInternal(const AttributionSourceState& attributionSource, + const String16& msg, bool start, audio_source_t source) { // Okay to not track in app ops as audio server or media server is us and if // device is rooted security model is considered compromised. // system_server loses its RECORD_AUDIO permission when a secondary // user is active, but it is a core system service so let it through. // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0 - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true; // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder) - // may open a record track on behalf of a client. Note that pid may be a tid. + // may open a record track on behalf of a client. Note that pid may be a tid. // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE. - PermissionController permissionController; - const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio, - identity.pid, identity.uid); - if (!ok) { - ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str()); - return false; - } - - String16 resolvedOpPackageName = resolveCallingPackage( - permissionController, VALUE_OR_FATAL(aidl2legacy_string_view_String16( - identity.packageName.value_or(""))), uid); - if (resolvedOpPackageName.size() == 0) { + const std::optional resolvedAttributionSource = + resolveAttributionSource(attributionSource); + if (!resolvedAttributionSource.has_value()) { return false; } + const int32_t attributedOpCode = getOpForSource(source); - AppOpsManager appOps; - const int32_t op = getOpForSource(source); + permission::PermissionChecker permissionChecker; + bool permitted = false; if (start) { - if (int32_t mode = appOps.startOpNoThrow(op, identity.uid, - resolvedOpPackageName, /*startIfModeDefault*/ false, - VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16( - identity.attributionTag)), msg) == AppOpsManager::MODE_ERRORED) { - ALOGE("Request start for \"%s\" (uid %d) denied by app op: %d, mode: %d", - String8(resolvedOpPackageName).c_str(), identity.uid, op, mode); - return false; - } + permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource( + sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg, + attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED); } else { - if (int32_t mode = appOps.checkOp(op, uid, - resolvedOpPackageName) == AppOpsManager::MODE_ERRORED) { - ALOGE("Request check for \"%s\" (uid %d) denied by app op: %d, mode: %d", - String8(resolvedOpPackageName).c_str(), identity.uid, op, mode); - return false; - } + permitted = (permissionChecker.checkPermissionForPreflightFromDatasource( + sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg, + attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED); } - return true; + return permitted; } -bool recordingAllowed(const Identity& identity, audio_source_t source) { - return checkRecordingInternal(identity, String16(), /*start*/ false, source); +bool recordingAllowed(const AttributionSourceState& attributionSource, audio_source_t source) { + return checkRecordingInternal(attributionSource, String16(), /*start*/ false, source); } -bool startRecording(const Identity& identity, const String16& msg, audio_source_t source) { - return checkRecordingInternal(identity, msg, /*start*/ true, source); +bool startRecording(const AttributionSourceState& attributionSource, const String16& msg, + audio_source_t source) { + return checkRecordingInternal(attributionSource, msg, /*start*/ true, source); } -void finishRecording(const Identity& identity, audio_source_t source) { +void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source) { // Okay to not track in app ops as audio server is us and if // device is rooted security model is considered compromised. - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - if (isAudioServerOrRootUid(uid)) return; - - PermissionController permissionController; - String16 resolvedOpPackageName = resolveCallingPackage( - permissionController, - VALUE_OR_FATAL(aidl2legacy_string_view_String16(identity.packageName.value_or(""))), - VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid))); - if (resolvedOpPackageName.size() == 0) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return; + + // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder) + // may open a record track on behalf of a client. Note that pid may be a tid. + // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE. + const std::optional resolvedAttributionSource = + resolveAttributionSource(attributionSource); + if (!resolvedAttributionSource.has_value()) { return; } - AppOpsManager appOps; - - const int32_t op = getOpForSource(source); - appOps.finishOp(op, identity.uid, resolvedOpPackageName, - VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16( - identity.attributionTag))); + const int32_t attributedOpCode = getOpForSource(source); + permission::PermissionChecker permissionChecker; + permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode, + resolvedAttributionSource.value()); } -bool captureAudioOutputAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerOrRootUid(uid)) return true; static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT"); bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid); @@ -174,9 +183,9 @@ bool captureAudioOutputAllowed(const Identity& identity) { return ok; } -bool captureMediaOutputAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerOrRootUid(uid)) return true; static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT"); bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid); @@ -184,9 +193,9 @@ bool captureMediaOutputAllowed(const Identity& identity) { return ok; } -bool captureTunerAudioInputAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerOrRootUid(uid)) return true; static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT"); bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid); @@ -194,9 +203,9 @@ bool captureTunerAudioInputAllowed(const Identity& identity) { return ok; } -bool captureVoiceCommunicationOutputAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerOrRootUid(uid)) return true; static const String16 sCaptureVoiceCommOutput( "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT"); @@ -205,11 +214,11 @@ bool captureVoiceCommunicationOutputAllowed(const Identity& identity) { return ok; } -bool captureHotwordAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool captureHotwordAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission - bool ok = recordingAllowed(identity); + bool ok = recordingAllowed(attributionSource); if (ok) { static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD"); @@ -230,12 +239,12 @@ bool settingsAllowed() { } bool modifyAudioRoutingAllowed() { - return modifyAudioRoutingAllowed(getCallingIdentity()); + return modifyAudioRoutingAllowed(getCallingAttributionSource()); } -bool modifyAudioRoutingAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true; // IMPORTANT: Use PermissionCache - not a runtime permission and may not change. bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid); @@ -245,12 +254,12 @@ bool modifyAudioRoutingAllowed(const Identity& identity) { } bool modifyDefaultAudioEffectsAllowed() { - return modifyDefaultAudioEffectsAllowed(getCallingIdentity()); + return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource()); } -bool modifyDefaultAudioEffectsAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true; static const String16 sModifyDefaultAudioEffectsAllowed( @@ -271,18 +280,18 @@ bool dumpAllowed() { return ok; } -bool modifyPhoneStateAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid); ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str()); return ok; } // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver -bool bypassInterruptionPolicyAllowed(const Identity& identity) { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); - pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid)); +bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) { + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); + pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid)); static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS"); bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid) || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid) @@ -292,11 +301,14 @@ bool bypassInterruptionPolicyAllowed(const Identity& identity) { return ok; } -Identity getCallingIdentity() { - Identity identity = Identity(); - identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid())); - identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); - return identity; +AttributionSourceState getCallingAttributionSource() { + AttributionSourceState attributionSource = AttributionSourceState(); + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t( + IPCThreadState::self()->getCallingPid())); + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t( + IPCThreadState::self()->getCallingUid())); + attributionSource.token = sp::make(); + return attributionSource; } void purgePermissionCache() { diff --git a/media/utils/fuzzers/Android.bp b/media/utils/fuzzers/Android.bp index b245834da3..c1698dc4d5 100644 --- a/media/utils/fuzzers/Android.bp +++ b/media/utils/fuzzers/Android.bp @@ -16,7 +16,8 @@ cc_defaults { "liblog", "libmediautils", "libutils", - "media_permission-aidl-cpp", + "libbinder", + "framework-permission-aidl-cpp", ], cflags: [ diff --git a/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp b/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp index 2f9e7800b5..51e8d7a26a 100644 --- a/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp +++ b/media/utils/fuzzers/ServiceUtilitiesFuzz.cpp @@ -19,14 +19,14 @@ #include #include -#include +#include #include "fuzzer/FuzzedDataProvider.h" #include "mediautils/ServiceUtilities.h" static constexpr int kMaxOperations = 50; static constexpr int kMaxStringLen = 256; -using android::media::permission::Identity; +using android::content::AttributionSourceState; const std::vector> operations = { @@ -54,10 +54,11 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::string packageNameStr = data_provider.ConsumeRandomLengthString(kMaxStringLen); std::string msgStr = data_provider.ConsumeRandomLengthString(kMaxStringLen); android::String16 msgStr16(packageNameStr.c_str()); - Identity identity; - identity.packageName = packageNameStr; - identity.uid = uid; - identity.pid = pid; + AttributionSourceState attributionSource; + attributionSource.packageName = packageNameStr; + attributionSource.uid = uid; + attributionSource.pid = pid; + attributionSource.token = android::sp::make(); // There is not state here, and order is not significant, // so we can simply call all of the target functions @@ -65,14 +66,14 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { android::isAudioServerUid(uid); android::isAudioServerOrSystemServerUid(uid); android::isAudioServerOrMediaServerUid(uid); - android::recordingAllowed(identity); - android::startRecording(identity, msgStr16, source); - android::finishRecording(identity, source); - android::captureAudioOutputAllowed(identity); - android::captureMediaOutputAllowed(identity); - android::captureHotwordAllowed(identity); - android::modifyPhoneStateAllowed(identity); - android::bypassInterruptionPolicyAllowed(identity); + android::recordingAllowed(attributionSource); + android::startRecording(attributionSource, msgStr16, source); + android::finishRecording(attributionSource, source); + android::captureAudioOutputAllowed(attributionSource); + android::captureMediaOutputAllowed(attributionSource); + android::captureHotwordAllowed(attributionSource); + android::modifyPhoneStateAllowed(attributionSource); + android::bypassInterruptionPolicyAllowed(attributionSource); android::settingsAllowed(); android::modifyAudioRoutingAllowed(); android::modifyDefaultAudioEffectsAllowed(); diff --git a/media/utils/include/mediautils/ServiceUtilities.h b/media/utils/include/mediautils/ServiceUtilities.h index e7132b857f..734313cabd 100644 --- a/media/utils/include/mediautils/ServiceUtilities.h +++ b/media/utils/include/mediautils/ServiceUtilities.h @@ -25,7 +25,9 @@ #include #include #include -#include +#include +#include +#include #include #include @@ -35,6 +37,8 @@ namespace android { +using content::AttributionSourceState; + // Audio permission utilities // Used for calls that should originate from system services. @@ -80,28 +84,30 @@ static inline bool isAudioServerOrMediaServerUid(uid_t uid) { } } -bool recordingAllowed(const media::permission::Identity& identity, +bool recordingAllowed(const AttributionSourceState& attributionSource, audio_source_t source = AUDIO_SOURCE_DEFAULT); -bool startRecording(const media::permission::Identity& identity, +bool startRecording(const AttributionSourceState& attributionSource, const String16& msg, audio_source_t source); -void finishRecording(const media::permission::Identity& identity, audio_source_t source); -bool captureAudioOutputAllowed(const media::permission::Identity& identity); -bool captureMediaOutputAllowed(const media::permission::Identity& identity); -bool captureTunerAudioInputAllowed(const media::permission::Identity& identity); -bool captureVoiceCommunicationOutputAllowed(const media::permission::Identity& identity); -bool captureHotwordAllowed(const media::permission::Identity& identity); +void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source); +std::optional resolveAttributionSource( + const AttributionSourceState& callerAttributionSource); +bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource); +bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource); +bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource); +bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource); +bool captureHotwordAllowed(const AttributionSourceState& attributionSource); bool settingsAllowed(); bool modifyAudioRoutingAllowed(); -bool modifyAudioRoutingAllowed(const media::permission::Identity& identity); +bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource); bool modifyDefaultAudioEffectsAllowed(); -bool modifyDefaultAudioEffectsAllowed(const media::permission::Identity& identity); +bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource); bool dumpAllowed(); -bool modifyPhoneStateAllowed(const media::permission::Identity& identity); -bool bypassInterruptionPolicyAllowed(const media::permission::Identity& identity); +bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource); +bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource); void purgePermissionCache(); int32_t getOpForSource(audio_source_t source); -media::permission::Identity getCallingIdentity(); +AttributionSourceState getCallingAttributionSource(); status_t checkIMemory(const sp& iMemory); diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp index a7d47fbaf4..b91f302c8e 100644 --- a/services/audioflinger/Android.bp +++ b/services/audioflinger/Android.bp @@ -81,12 +81,12 @@ cc_library_shared { "libmedia_helper", "libshmemcompat", "libvibrator", - "media_permission-aidl-cpp", ], static_libs: [ "libcpustats", "libsndfile", + "libpermission", ], header_libs: [ @@ -97,7 +97,6 @@ cc_library_shared { export_shared_lib_headers: [ "libpermission", - "media_permission-aidl-cpp", ], cflags: [ diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 00f423c7bb..d4f930222e 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -103,7 +103,7 @@ namespace android { using media::IEffectClient; -using media::permission::Identity; +using android::content::AttributionSourceState; static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; static const char kHardwareLockedString[] = "Hardware lock is taken\n"; @@ -163,31 +163,32 @@ class DevicesFactoryHalCallbackImpl : public DevicesFactoryHalCallback { } }; -// TODO b/182392769: use identity util +// TODO b/182392769: use attribution source util /* static */ -media::permission::Identity AudioFlinger::checkIdentityPackage( - const media::permission::Identity& identity) { +AttributionSourceState AudioFlinger::checkAttributionSourcePackage( + const AttributionSourceState& attributionSource) { Vector packages; - PermissionController{}.getPackagesForUid(identity.uid, packages); + PermissionController{}.getPackagesForUid(attributionSource.uid, packages); - Identity checkedIdentity = identity; - if (!identity.packageName.has_value() || identity.packageName.value().size() == 0) { + AttributionSourceState checkedAttributionSource = attributionSource; + if (!attributionSource.packageName.has_value() + || attributionSource.packageName.value().size() == 0) { if (!packages.isEmpty()) { - checkedIdentity.packageName = + checkedAttributionSource.packageName = std::move(legacy2aidl_String16_string(packages[0]).value()); } } else { String16 opPackageLegacy = VALUE_OR_FATAL( - aidl2legacy_string_view_String16(identity.packageName.value_or(""))); + aidl2legacy_string_view_String16(attributionSource.packageName.value_or(""))); if (std::find_if(packages.begin(), packages.end(), [&opPackageLegacy](const auto& package) { return opPackageLegacy == package; }) == packages.end()) { ALOGW("The package name(%s) provided does not correspond to the uid %d", - identity.packageName.value_or("").c_str(), identity.uid); - checkedIdentity.packageName = std::optional(); + attributionSource.packageName.value_or("").c_str(), attributionSource.uid); + checkedAttributionSource.packageName = std::optional(); } } - return checkedIdentity; + return checkedAttributionSource; } // ---------------------------------------------------------------------------- @@ -430,7 +431,7 @@ status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t di ret = AudioSystem::getOutputForAttr(&localAttr, &io, actualSessionId, - &streamType, client.identity, + &streamType, client.attributionSource, &fullConfig, (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT), @@ -441,7 +442,7 @@ status_t AudioFlinger::openMmapStream(MmapStreamInterface::stream_direction_t di ret = AudioSystem::getInputForAttr(&localAttr, &io, RECORD_RIID_INVALID, actualSessionId, - client.identity, + client.attributionSource, config, AUDIO_INPUT_FLAG_MMAP_NOIRQ, deviceId, &portId); } @@ -847,21 +848,21 @@ status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input, // TODO b/182392553: refactor or make clearer pid_t clientPid = - VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.identity.pid)); + VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(input.clientInfo.attributionSource.pid)); bool updatePid = (clientPid == (pid_t)-1); const uid_t callingUid = IPCThreadState::self()->getCallingUid(); uid_t clientUid = - VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.identity.uid)); + VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(input.clientInfo.attributionSource.uid)); audio_io_handle_t effectThreadId = AUDIO_IO_HANDLE_NONE; std::vector effectIds; audio_attributes_t localAttr = input.attr; - Identity adjIdentity = input.clientInfo.identity; + AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource; if (!isAudioServerOrMediaServerUid(callingUid)) { ALOGW_IF(clientUid != callingUid, "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid); - adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); + adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); clientUid = callingUid; updatePid = true; } @@ -871,7 +872,7 @@ status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input, "%s uid %d pid %d tried to pass itself off as pid %d", __func__, callingUid, callingPid, clientPid); clientPid = callingPid; - adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); + adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); } audio_session_t sessionId = input.sessionId; @@ -886,7 +887,7 @@ status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input, output.outputId = AUDIO_IO_HANDLE_NONE; output.selectedDeviceId = input.selectedDeviceId; lStatus = AudioSystem::getOutputForAttr(&localAttr, &output.outputId, sessionId, &streamType, - adjIdentity, &input.config, input.flags, + adjAttributionSource, &input.config, input.flags, &output.selectedDeviceId, &portId, &secondaryOutputs); if (lStatus != NO_ERROR || output.outputId == AUDIO_IO_HANDLE_NONE) { @@ -951,7 +952,7 @@ status_t AudioFlinger::createTrack(const media::CreateTrackRequest& _input, &output.frameCount, &output.notificationFrameCount, input.notificationsPerBuffer, input.speed, input.sharedBuffer, sessionId, &output.flags, - callingPid, adjIdentity, input.clientInfo.clientTid, + callingPid, adjAttributionSource, input.clientInfo.clientTid, &lStatus, portId, input.audioTrackCallback); LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (track == 0)); // we don't abort yet if lStatus != NO_ERROR; there is still work to be done regardless @@ -2030,24 +2031,26 @@ status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input, output.inputId = AUDIO_IO_HANDLE_NONE; // TODO b/182392553: refactor or clean up - Identity adjIdentity = input.clientInfo.identity; - bool updatePid = (adjIdentity.pid == -1); + AttributionSourceState adjAttributionSource = input.clientInfo.attributionSource; + bool updatePid = (adjAttributionSource.pid == -1); const uid_t callingUid = IPCThreadState::self()->getCallingUid(); - const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(adjIdentity.uid)); + const uid_t currentUid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t( + adjAttributionSource.uid)); if (!isAudioServerOrMediaServerUid(callingUid)) { ALOGW_IF(currentUid != callingUid, "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, currentUid); - adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); + adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); updatePid = true; } const pid_t callingPid = IPCThreadState::self()->getCallingPid(); - const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjIdentity.pid)); + const pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t( + adjAttributionSource.pid)); if (updatePid) { ALOGW_IF(currentPid != (pid_t)-1 && currentPid != callingPid, "%s uid %d pid %d tried to pass itself off as pid %d", __func__, callingUid, callingPid, currentPid); - adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); + adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); } // we don't yet support anything other than linear PCM @@ -2075,7 +2078,7 @@ status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input, output.selectedDeviceId = input.selectedDeviceId; output.flags = input.flags; - client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjIdentity.pid))); + client = registerPid(VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid))); // Not a conventional loop, but a retry loop for at most two iterations total. // Try first maybe with FAST flag then try again without FAST flag if that fails. @@ -2095,7 +2098,7 @@ status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input, input.riid, sessionId, // FIXME compare to AudioTrack - adjIdentity, + adjAttributionSource, &input.config, output.flags, &output.selectedDeviceId, &portId); if (lStatus != NO_ERROR) { @@ -2122,7 +2125,7 @@ status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input, input.config.format, input.config.channel_mask, &output.frameCount, sessionId, &output.notificationFrameCount, - callingPid, adjIdentity, &output.flags, + callingPid, adjAttributionSource, &output.flags, input.clientInfo.clientTid, &lStatus, portId, input.maxSharedAudioHistoryMs); LOG_ALWAYS_FATAL_IF((lStatus == NO_ERROR) && (recordTrack == 0)); @@ -3605,7 +3608,7 @@ status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request, const int32_t priority = request.priority; const AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioDeviceTypeAddress(request.device)); - Identity adjIdentity = request.identity; + AttributionSourceState adjAttributionSource = request.attributionSource; const audio_session_t sessionId = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_session_t(request.sessionId)); audio_io_handle_t io = VALUE_OR_RETURN_STATUS( @@ -3623,19 +3626,20 @@ status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request, // TODO b/182392553: refactor or make clearer const uid_t callingUid = IPCThreadState::self()->getCallingUid(); - adjIdentity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); - pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjIdentity.pid)); + adjAttributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); + pid_t currentPid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_pid_t(adjAttributionSource.pid)); if (currentPid == -1 || !isAudioServerOrMediaServerUid(callingUid)) { const pid_t callingPid = IPCThreadState::self()->getCallingPid(); ALOGW_IF(currentPid != -1 && currentPid != callingPid, "%s uid %d pid %d tried to pass itself off as pid %d", __func__, callingUid, callingPid, currentPid); - adjIdentity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); + adjAttributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_pid_t_int32_t(callingPid)); currentPid = callingPid; } ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d, factory %p", - adjIdentity.pid, effectClient.get(), priority, sessionId, io, mEffectsFactoryHal.get()); + adjAttributionSource.pid, effectClient.get(), priority, sessionId, io, + mEffectsFactoryHal.get()); if (mEffectsFactoryHal == 0) { ALOGE("%s: no effects factory hal", __func__); @@ -3663,7 +3667,7 @@ status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request, goto Exit; } } else if (sessionId == AUDIO_SESSION_DEVICE) { - if (!modifyDefaultAudioEffectsAllowed(adjIdentity)) { + if (!modifyDefaultAudioEffectsAllowed(adjAttributionSource)) { ALOGE("%s: device effect permission denied for uid %d", __func__, callingUid); lStatus = PERMISSION_DENIED; goto Exit; @@ -3708,7 +3712,7 @@ status_t AudioFlinger::createEffect(const media::CreateEffectRequest& request, // check recording permission for visualizer if ((memcmp(&descOut.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) && // TODO: Do we need to start/stop op - i.e. is there recording being performed? - !recordingAllowed(adjIdentity)) { + !recordingAllowed(adjAttributionSource)) { lStatus = PERMISSION_DENIED; goto Exit; } diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index b12f52e8a1..fff61f8fc6 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -37,6 +37,8 @@ #include #include #include +#include + #include #include @@ -124,13 +126,15 @@ static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3); #define INCLUDING_FROM_AUDIOFLINGER_H +using android::content::AttributionSourceState; + class AudioFlinger : public AudioFlingerServerAdapter::Delegate { public: static void instantiate() ANDROID_API; - static media::permission::Identity checkIdentityPackage( - const media::permission::Identity& identity); + static AttributionSourceState checkAttributionSourcePackage( + const AttributionSourceState& attributionSource); status_t dump(int fd, const Vector& args) override; diff --git a/services/audioflinger/MmapTracks.h b/services/audioflinger/MmapTracks.h index ba868d72f3..eb640bb17e 100644 --- a/services/audioflinger/MmapTracks.h +++ b/services/audioflinger/MmapTracks.h @@ -29,7 +29,7 @@ public: audio_channel_mask_t channelMask, audio_session_t sessionId, bool isOut, - const media::permission::Identity& identity, + const android::content::AttributionSourceState& attributionSource, pid_t creatorPid, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); virtual ~MmapTrack(); diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h index 30a24327f0..51a41af6de 100644 --- a/services/audioflinger/PlaybackTracks.h +++ b/services/audioflinger/PlaybackTracks.h @@ -15,8 +15,6 @@ ** limitations under the License. */ -#include - #ifndef INCLUDING_FROM_AUDIOFLINGER_H #error This header file should only be included from AudioFlinger.h #endif @@ -28,12 +26,12 @@ public: bool hasOpPlayAudio() const; static sp createIfNeeded( - const android::media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_attributes_t& attr, int id, audio_stream_type_t streamType); private: - OpPlayAudioMonitor(const android::media::permission::Identity& identity, + OpPlayAudioMonitor(const AttributionSourceState& attributionSource, audio_usage_t usage, int id); void onFirstRef() override; static void getPackagesForUid(uid_t uid, Vector& packages); @@ -54,7 +52,7 @@ private: void checkPlayAudioForUsage(); std::atomic_bool mHasOpPlayAudio; - const android::media::permission::Identity mIdentity; + const AttributionSourceState mAttributionSource; const int32_t mUsage; // on purpose not audio_usage_t because always checked in appOps as int32_t const int mId; // for logging purposes only }; @@ -75,7 +73,7 @@ public: const sp& sharedBuffer, audio_session_t sessionId, pid_t creatorPid, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, audio_output_flags_t flags, track_type type, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE, @@ -334,7 +332,7 @@ public: audio_format_t format, audio_channel_mask_t channelMask, size_t frameCount, - const android::media::permission::Identity& identity); + const AttributionSourceState& attributionSource); virtual ~OutputTrack(); virtual status_t start(AudioSystem::sync_event_t event = diff --git a/services/audioflinger/RecordTracks.h b/services/audioflinger/RecordTracks.h index a1c2de7a73..88aa7cb064 100644 --- a/services/audioflinger/RecordTracks.h +++ b/services/audioflinger/RecordTracks.h @@ -15,6 +15,8 @@ ** limitations under the License. */ +#include + #ifndef INCLUDING_FROM_AUDIOFLINGER_H #error This header file should only be included from AudioFlinger.h #endif @@ -26,11 +28,12 @@ public: bool hasOp() const; int32_t getOp() const { return mAppOp; } - static sp createIfNeeded - (const media::permission::Identity& identity, const audio_attributes_t& attr); + static sp createIfNeeded(const AttributionSourceState& attributionSource, + const audio_attributes_t& attr); private: - OpRecordAudioMonitor(const media::permission::Identity& identity, int32_t appOp); + OpRecordAudioMonitor(const AttributionSourceState& attributionSource, int32_t appOp); + void onFirstRef() override; AppOpsManager mAppOpsManager; @@ -50,7 +53,7 @@ private: void checkOp(); std::atomic_bool mHasOp; - const media::permission::Identity mIdentity; + const AttributionSourceState mAttributionSource; const int32_t mAppOp; }; @@ -68,7 +71,7 @@ public: size_t bufferSize, audio_session_t sessionId, pid_t creatorPid, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, audio_input_flags_t flags, track_type type, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE, diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 25a19a2409..47b4b18a12 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -118,7 +118,7 @@ static inline T min(const T& a, const T& b) namespace android { using media::IEffectClient; -using media::permission::Identity; +using content::AttributionSourceState; // retry counts for buffer fill timeout // 50 * ~20msecs = 1 second @@ -2129,7 +2129,7 @@ sp AudioFlinger::PlaybackThread::createTrac audio_session_t sessionId, audio_output_flags_t *flags, pid_t creatorPid, - const Identity& identity, + const AttributionSourceState& attributionSource, pid_t tid, status_t *status, audio_port_handle_t portId, @@ -2424,8 +2424,8 @@ sp AudioFlinger::PlaybackThread::createTrac track = new Track(this, client, streamType, attr, sampleRate, format, channelMask, frameCount, nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer, - sessionId, creatorPid, identity, trackFlags, TrackBase::TYPE_DEFAULT, - portId, SIZE_MAX /*frameCountToBeReady*/, speed); + sessionId, creatorPid, attributionSource, trackFlags, + TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed); lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY; if (lStatus != NO_ERROR) { @@ -6886,19 +6886,20 @@ void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread) // from different OutputTracks and their associated MixerThreads (e.g. one may // nearly empty and the other may be dropping data). - // TODO b/182392769: use identity util, move to server edge - Identity identity = Identity(); - identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t( + // TODO b/182392769: use attribution source util, move to server edge + AttributionSourceState attributionSource = AttributionSourceState(); + attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t( IPCThreadState::self()->getCallingUid())); - identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t( + attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t( IPCThreadState::self()->getCallingPid())); + attributionSource.token = sp::make(); sp outputTrack = new OutputTrack(thread, this, mSampleRate, mFormat, mChannelMask, frameCount, - identity); + attributionSource); status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY; if (status != NO_ERROR) { ALOGE("addOutputTrack() initCheck failed %d", status); @@ -7822,7 +7823,7 @@ sp AudioFlinger::RecordThread::createRe audio_session_t sessionId, size_t *pNotificationFrameCount, pid_t creatorPid, - const Identity& identity, + const AttributionSourceState& attributionSource, audio_input_flags_t *flags, pid_t tid, status_t *status, @@ -7836,7 +7837,8 @@ sp AudioFlinger::RecordThread::createRe audio_input_flags_t inputFlags = mInput->flags; audio_input_flags_t requestedFlags = *flags; uint32_t sampleRate; - Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity); + AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage( + attributionSource); lStatus = initCheck(); if (lStatus != NO_ERROR) { @@ -7851,7 +7853,7 @@ sp AudioFlinger::RecordThread::createRe } if (maxSharedAudioHistoryMs != 0) { - if (!captureHotwordAllowed(checkedIdentity)) { + if (!captureHotwordAllowed(checkedAttributionSource)) { lStatus = PERMISSION_DENIED; goto Exit; } @@ -7973,16 +7975,17 @@ sp AudioFlinger::RecordThread::createRe Mutex::Autolock _l(mLock); int32_t startFrames = -1; if (!mSharedAudioPackageName.empty() - && mSharedAudioPackageName == checkedIdentity.packageName + && mSharedAudioPackageName == checkedAttributionSource.packageName && mSharedAudioSessionId == sessionId - && captureHotwordAllowed(checkedIdentity)) { + && captureHotwordAllowed(checkedAttributionSource)) { startFrames = mSharedAudioStartFrames; } track = new RecordTrack(this, client, attr, sampleRate, format, channelMask, frameCount, nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, - checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames); + checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId, + startFrames); lStatus = track->initCheck(); if (lStatus != NO_ERROR) { @@ -9174,7 +9177,7 @@ status_t AudioFlinger::MmapThread::start(const AudioClient& client, audio_port_handle_t *handle) { ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__, - client.identity.uid, mStandby, mPortId, *handle); + client.attributionSource.uid, mStandby, mPortId, *handle); if (mHalStream == 0) { return NO_INIT; } @@ -9206,7 +9209,7 @@ status_t AudioFlinger::MmapThread::start(const AudioClient& client, ret = AudioSystem::getOutputForAttr(&mAttr, &io, mSessionId, &stream, - client.identity, + client.attributionSource, &config, flags, &deviceId, @@ -9223,7 +9226,7 @@ status_t AudioFlinger::MmapThread::start(const AudioClient& client, ret = AudioSystem::getInputForAttr(&mAttr, &io, RECORD_RIID_INVALID, mSessionId, - client.identity, + client.attributionSource, &config, AUDIO_INPUT_FLAG_MMAP_NOIRQ, &deviceId, @@ -9263,7 +9266,8 @@ status_t AudioFlinger::MmapThread::start(const AudioClient& client, // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ? sp track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat, - mChannelMask, mSessionId, isOutput(), client.identity, + mChannelMask, mSessionId, isOutput(), + client.attributionSource, IPCThreadState::self()->getCallingPid(), portId); if (isOutput()) { @@ -9271,7 +9275,7 @@ status_t AudioFlinger::MmapThread::start(const AudioClient& client, mHalVolFloat = -1.0f; } else if (!track->isSilenced_l()) { for (const sp &t : mActiveTracks) { - if (t->isSilenced_l() && t->uid() != client.identity.uid) + if (t->isSilenced_l() && t->uid() != client.attributionSource.uid) t->invalidate(); } } diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h index d4fb995f41..eee1f2be40 100644 --- a/services/audioflinger/Threads.h +++ b/services/audioflinger/Threads.h @@ -918,7 +918,7 @@ public: audio_session_t sessionId, audio_output_flags_t *flags, pid_t creatorPid, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, pid_t tid, status_t *status /*non-NULL*/, audio_port_handle_t portId, @@ -1698,7 +1698,7 @@ public: audio_session_t sessionId, size_t *pNotificationFrameCount, pid_t creatorPid, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, audio_input_flags_t *flags, pid_t tid, status_t *status /*non-NULL*/, diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp index 09e5ec5272..57ff0d71f1 100644 --- a/services/audioflinger/Tracks.cpp +++ b/services/audioflinger/Tracks.cpp @@ -65,7 +65,7 @@ namespace android { using ::android::aidl_utils::binderStatusFromStatusT; using binder::Status; -using media::permission::Identity; +using content::AttributionSourceState; using media::VolumeShaper; // ---------------------------------------------------------------------------- // TrackBase @@ -238,12 +238,13 @@ AudioFlinger::ThreadBase::TrackBase::TrackBase( } } -// TODO b/182392769: use identity util -static Identity audioServerIdentity(pid_t pid) { - Identity i{}; - i.uid = AID_AUDIOSERVER; - i.pid = pid; - return i; +// TODO b/182392769: use attribution source util +static AttributionSourceState audioServerAttributionSource(pid_t pid) { + AttributionSourceState attributionSource{}; + attributionSource.uid = AID_AUDIOSERVER; + attributionSource.pid = pid; + attributionSource.token = sp::make(); + return attributionSource; } status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const @@ -498,11 +499,11 @@ Status AudioFlinger::TrackHandle::setPlaybackRateParameters( // static sp AudioFlinger::PlaybackThread::OpPlayAudioMonitor::createIfNeeded( - const Identity& identity, const audio_attributes_t& attr, int id, + const AttributionSourceState& attributionSource, const audio_attributes_t& attr, int id, audio_stream_type_t streamType) { Vector packages; - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); getPackagesForUid(uid, packages); if (isServiceUid(uid)) { if (packages.isEmpty()) { @@ -525,13 +526,15 @@ AudioFlinger::PlaybackThread::OpPlayAudioMonitor::createIfNeeded( return nullptr; } - Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity); - return new OpPlayAudioMonitor(checkedIdentity, attr.usage, id); + AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage( + attributionSource); + return new OpPlayAudioMonitor(checkedAttributionSource, attr.usage, id); } AudioFlinger::PlaybackThread::OpPlayAudioMonitor::OpPlayAudioMonitor( - const Identity& identity, audio_usage_t usage, int id) - : mHasOpPlayAudio(true), mIdentity(identity), mUsage((int32_t) usage), mId(id) + const AttributionSourceState& attributionSource, audio_usage_t usage, int id) + : mHasOpPlayAudio(true), mAttributionSource(attributionSource), mUsage((int32_t) usage), + mId(id) { } @@ -546,10 +549,11 @@ AudioFlinger::PlaybackThread::OpPlayAudioMonitor::~OpPlayAudioMonitor() void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::onFirstRef() { checkPlayAudioForUsage(); - if (mIdentity.packageName.has_value()) { + if (mAttributionSource.packageName.has_value()) { mOpCallback = new PlayAudioOpCallback(this); mAppOpsManager.startWatchingMode(AppOpsManager::OP_PLAY_AUDIO, - VALUE_OR_FATAL(aidl2legacy_string_view_String16(mIdentity.packageName.value_or(""))) + VALUE_OR_FATAL(aidl2legacy_string_view_String16( + mAttributionSource.packageName.value_or(""))) , mOpCallback); } } @@ -563,12 +567,12 @@ bool AudioFlinger::PlaybackThread::OpPlayAudioMonitor::hasOpPlayAudio() const { // - not called from PlayAudioOpCallback because the callback is not installed in this case void AudioFlinger::PlaybackThread::OpPlayAudioMonitor::checkPlayAudioForUsage() { - if (!mIdentity.packageName.has_value()) { + if (!mAttributionSource.packageName.has_value()) { mHasOpPlayAudio.store(false); } else { - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mIdentity.uid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAttributionSource.uid)); String16 packageName = VALUE_OR_FATAL( - aidl2legacy_string_view_String16(mIdentity.packageName.value_or(""))); + aidl2legacy_string_view_String16(mAttributionSource.packageName.value_or(""))); bool hasIt = mAppOpsManager.checkAudioOpNoThrow(AppOpsManager::OP_PLAY_AUDIO, mUsage, uid, packageName) == AppOpsManager::MODE_ALLOWED; ALOGD("OpPlayAudio: track:%d usage:%d %smuted", mId, mUsage, hasIt ? "not " : ""); @@ -620,7 +624,7 @@ AudioFlinger::PlaybackThread::Track::Track( const sp& sharedBuffer, audio_session_t sessionId, pid_t creatorPid, - const Identity& identity, + const AttributionSourceState& attributionSource, audio_output_flags_t flags, track_type type, audio_port_handle_t portId, @@ -634,7 +638,7 @@ AudioFlinger::PlaybackThread::Track::Track( (sharedBuffer != 0) ? sharedBuffer->unsecurePointer() : buffer, (sharedBuffer != 0) ? sharedBuffer->size() : bufferSize, sessionId, creatorPid, - VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)), true /*isOut*/, + VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)), true /*isOut*/, (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK, type, portId, @@ -649,7 +653,7 @@ AudioFlinger::PlaybackThread::Track::Track( mPresentationCompleteFrames(0), mFrameMap(16 /* sink-frame-to-track-frame map memory */), mVolumeHandler(new media::VolumeHandler(sampleRate)), - mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(identity, attr, id(), + mOpPlayAudioMonitor(OpPlayAudioMonitor::createIfNeeded(attributionSource, attr, id(), streamType)), // mSinkTimestamp mFastIndex(-1), @@ -672,7 +676,7 @@ AudioFlinger::PlaybackThread::Track::Track( return; } - uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)); + uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)); if (!thread->isTrackAllowed_l(channelMask, format, sessionId, uid)) { ALOGE("%s(%d): no more tracks available", __func__, mId); releaseCblk(); // this makes the track invalid. @@ -718,8 +722,8 @@ AudioFlinger::PlaybackThread::Track::Track( // HapticGenerator effect, which will generate haptic data, on the track. In that case, // external vibration is always created for all tracks attached to haptic playback thread. mAudioVibrationController = new AudioVibrationController(this); - std::string packageName = identity.packageName.has_value() ? - identity.packageName.value() : ""; + std::string packageName = attributionSource.packageName.has_value() ? + attributionSource.packageName.value() : ""; mExternalVibration = new os::ExternalVibration( mUid, packageName, mAttr, mAudioVibrationController); } @@ -1840,12 +1844,12 @@ AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( audio_format_t format, audio_channel_mask_t channelMask, size_t frameCount, - const Identity& identity) + const AttributionSourceState& attributionSource) : Track(playbackThread, NULL, AUDIO_STREAM_PATCH, audio_attributes_t{} /* currently unused for output track */, sampleRate, format, channelMask, frameCount, nullptr /* buffer */, (size_t)0 /* bufferSize */, nullptr /* sharedBuffer */, - AUDIO_SESSION_NONE, getpid(), identity, AUDIO_OUTPUT_FLAG_NONE, + AUDIO_SESSION_NONE, getpid(), attributionSource, AUDIO_OUTPUT_FLAG_NONE, TYPE_OUTPUT), mActive(false), mSourceThread(sourceThread) { @@ -2075,7 +2079,7 @@ AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThr audio_attributes_t{} /* currently unused for patch track */, sampleRate, format, channelMask, frameCount, buffer, bufferSize, nullptr /* sharedBuffer */, - AUDIO_SESSION_NONE, getpid(), audioServerIdentity(getpid()), flags, + AUDIO_SESSION_NONE, getpid(), audioServerAttributionSource(getpid()), flags, TYPE_PATCH, AUDIO_PORT_HANDLE_NONE, frameCountToBeReady), PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true), *playbackThread, timeout) @@ -2213,32 +2217,33 @@ void AudioFlinger::PlaybackThread::PatchTrack::restartIfDisabled() // static sp AudioFlinger::RecordThread::OpRecordAudioMonitor::createIfNeeded( - const Identity& identity, const audio_attributes_t& attr) + const AttributionSourceState& attributionSource, const audio_attributes_t& attr) { - if (isServiceUid(identity.uid)) { + if (isServiceUid(attributionSource.uid)) { ALOGV("not silencing record for service %s", - identity.toString().c_str()); + attributionSource.toString().c_str()); return nullptr; } // Capturing from FM TUNER output is not controlled by an app op // because it does not affect users privacy as does capturing from an actual microphone. if (attr.source == AUDIO_SOURCE_FM_TUNER) { - ALOGV("not muting FM TUNER capture for uid %d", identity.uid); + ALOGV("not muting FM TUNER capture for uid %d", attributionSource.uid); return nullptr; } - Identity checkedIdentity = AudioFlinger::checkIdentityPackage(identity); - if (!checkedIdentity.packageName.has_value() - || checkedIdentity.packageName.value().size() == 0) { + AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage( + attributionSource); + if (!checkedAttributionSource.packageName.has_value() + || checkedAttributionSource.packageName.value().size() == 0) { return nullptr; } - return new OpRecordAudioMonitor(checkedIdentity, getOpForSource(attr.source)); + return new OpRecordAudioMonitor(checkedAttributionSource, getOpForSource(attr.source)); } AudioFlinger::RecordThread::OpRecordAudioMonitor::OpRecordAudioMonitor( - const Identity& identity, int32_t appOp) - : mHasOp(true), mIdentity(identity), mAppOp(appOp) + const AttributionSourceState& attributionSource, int32_t appOp) + : mHasOp(true), mAttributionSource(attributionSource), mAppOp(appOp) { } @@ -2254,9 +2259,11 @@ void AudioFlinger::RecordThread::OpRecordAudioMonitor::onFirstRef() { checkOp(); mOpCallback = new RecordAudioOpCallback(this); - ALOGV("start watching op %d for %s", mAppOp, mIdentity.toString().c_str()); - mAppOpsManager.startWatchingMode(mAppOp, - VALUE_OR_FATAL(aidl2legacy_string_view_String16(mIdentity.packageName.value_or(""))), + ALOGV("start watching op %d for %s", mAppOp, mAttributionSource.toString().c_str()); + // TODO: We need to always watch AppOpsManager::OP_RECORD_AUDIO too + // since it controls the mic permission for legacy apps. + mAppOpsManager.startWatchingMode(mAppOp, VALUE_OR_FATAL(aidl2legacy_string_view_String16( + mAttributionSource.packageName.value_or(""))), mOpCallback); } @@ -2272,17 +2279,17 @@ bool AudioFlinger::RecordThread::OpRecordAudioMonitor::hasOp() const { // - not called from RecordAudioOpCallback because the callback is not installed in this case void AudioFlinger::RecordThread::OpRecordAudioMonitor::checkOp() { - + // TODO: We need to always check AppOpsManager::OP_RECORD_AUDIO too + // since it controls the mic permission for legacy apps. const int32_t mode = mAppOpsManager.checkOp(mAppOp, - mIdentity.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16( - mIdentity.packageName.value_or("")))); - const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED); + mAttributionSource.uid, VALUE_OR_FATAL(aidl2legacy_string_view_String16( + mAttributionSource.packageName.value_or("")))); + const bool hasIt = (mode == AppOpsManager::MODE_ALLOWED); // verbose logging only log when appOp changed ALOGI_IF(hasIt != mHasOp.load(), "App op %d missing, %ssilencing record %s", - mAppOp, hasIt ? "un" : "", mIdentity.toString().c_str()); + mAppOp, hasIt ? "un" : "", mAttributionSource.toString().c_str()); mHasOp.store(hasIt); - } AudioFlinger::RecordThread::OpRecordAudioMonitor::RecordAudioOpCallback::RecordAudioOpCallback( @@ -2382,7 +2389,7 @@ AudioFlinger::RecordThread::RecordTrack::RecordTrack( size_t bufferSize, audio_session_t sessionId, pid_t creatorPid, - const Identity& identity, + const AttributionSourceState& attributionSource, audio_input_flags_t flags, track_type type, audio_port_handle_t portId, @@ -2390,7 +2397,7 @@ AudioFlinger::RecordThread::RecordTrack::RecordTrack( : TrackBase(thread, client, attr, sampleRate, format, channelMask, frameCount, buffer, bufferSize, sessionId, creatorPid, - VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)), + VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)), false /*isOut*/, (type == TYPE_DEFAULT) ? ((flags & AUDIO_INPUT_FLAG_FAST) ? ALLOC_PIPE : ALLOC_CBLK) : @@ -2403,7 +2410,7 @@ AudioFlinger::RecordThread::RecordTrack::RecordTrack( mRecordBufferConverter(NULL), mFlags(flags), mSilenced(false), - mOpRecordAudioMonitor(OpRecordAudioMonitor::createIfNeeded(identity, attr)), + mOpRecordAudioMonitor(OpRecordAudioMonitor::createIfNeeded(attributionSource, attr)), mStartFrames(startFrames) { if (mCblk == NULL) { @@ -2712,10 +2719,11 @@ status_t AudioFlinger::RecordThread::RecordTrack::shareAudioHistory( return PERMISSION_DENIED; } - Identity identity{}; - identity.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); - identity.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingPid)); - if (!captureHotwordAllowed(identity)) { + AttributionSourceState attributionSource{}; + attributionSource.uid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); + attributionSource.pid = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(callingPid)); + attributionSource.token = sp::make(); + if (!captureHotwordAllowed(attributionSource)) { return PERMISSION_DENIED; } @@ -2751,7 +2759,7 @@ AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread, audio_attributes_t{} /* currently unused for patch track */, sampleRate, format, channelMask, frameCount, buffer, bufferSize, AUDIO_SESSION_NONE, getpid(), - audioServerIdentity(getpid()), flags, TYPE_PATCH), + audioServerAttributionSource(getpid()), flags, TYPE_PATCH), PatchTrackBase(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true), *recordThread, timeout) { @@ -3028,19 +3036,19 @@ AudioFlinger::MmapThread::MmapTrack::MmapTrack(ThreadBase *thread, audio_channel_mask_t channelMask, audio_session_t sessionId, bool isOut, - const Identity& identity, + const AttributionSourceState& attributionSource, pid_t creatorPid, audio_port_handle_t portId) : TrackBase(thread, NULL, attr, sampleRate, format, channelMask, (size_t)0 /* frameCount */, nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, - VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)), + VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid)), isOut, ALLOC_NONE, TYPE_DEFAULT, portId, std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_MMAP) + std::to_string(portId)), - mPid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.pid))), + mPid(VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.pid))), mSilenced(false), mSilencedNotified(false) { // Once this item is logged by the server, the client can add properties. diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h index a904321116..2e49e714dd 100644 --- a/services/audiopolicy/AudioPolicyInterface.h +++ b/services/audiopolicy/AudioPolicyInterface.h @@ -22,11 +22,13 @@ #include #include #include -#include +#include #include namespace android { +using content::AttributionSourceState; + // ---------------------------------------------------------------------------- // The AudioPolicyInterface and AudioPolicyClientInterface classes define the communication interfaces @@ -124,7 +126,7 @@ public: audio_io_handle_t *output, audio_session_t session, audio_stream_type_t *stream, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSouce, const audio_config_t *config, audio_output_flags_t *flags, audio_port_handle_t *selectedDeviceId, @@ -143,7 +145,7 @@ public: audio_io_handle_t *input, audio_unique_id_t riid, audio_session_t session, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSouce, const audio_config_base_t *config, audio_input_flags_t flags, audio_port_handle_t *selectedDeviceId, diff --git a/services/audiopolicy/fuzzer/Android.bp b/services/audiopolicy/fuzzer/Android.bp index 38bdedcf6a..faf15d6769 100644 --- a/services/audiopolicy/fuzzer/Android.bp +++ b/services/audiopolicy/fuzzer/Android.bp @@ -50,7 +50,7 @@ cc_fuzz { "libbinder", "libaudiopolicy", "libaudiopolicymanagerdefault", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], static_libs: [ "android.hardware.audio.common@7.0-enums", diff --git a/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp b/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp index 1177b95cc9..7000cd94da 100644 --- a/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp +++ b/services/audiopolicy/fuzzer/audiopolicy_fuzzer.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -47,7 +47,7 @@ namespace xsd { using namespace ::android::audio::policy::configuration::V7_0; } -using media::permission::Identity; +using content::AttributionSourceState; static const std::vector kAudioFormats = [] { std::vector result; @@ -249,11 +249,12 @@ bool AudioPolicyManagerFuzzer::getOutputForAttr( *portId = AUDIO_PORT_HANDLE_NONE; AudioPolicyInterface::output_type_t outputType; - // TODO b/182392769: use identity util - Identity i; - i.uid = 0; - if (mManager->getOutputForAttr(&attr, output, AUDIO_SESSION_NONE, &stream, i, &config, - &flags, selectedDeviceId, portId, {}, &outputType) != OK) { + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource; + attributionSource.uid = 0; + attributionSource.token = sp::make(); + if (mManager->getOutputForAttr(&attr, output, AUDIO_SESSION_NONE, &stream, attributionSource, + &config, &flags, selectedDeviceId, portId, {}, &outputType) != OK) { return false; } if (*output == AUDIO_IO_HANDLE_NONE || *portId == AUDIO_PORT_HANDLE_NONE) { @@ -276,10 +277,11 @@ bool AudioPolicyManagerFuzzer::getInputForAttr( *portId = AUDIO_PORT_HANDLE_NONE; AudioPolicyInterface::input_type_t inputType; - Identity i; - i.uid = 0; - if (mManager->getInputForAttr(&attr, &input, riid, AUDIO_SESSION_NONE, i, &config, - flags, selectedDeviceId, &inputType, portId) != OK) { + AttributionSourceState attributionSource; + attributionSource.uid = 0; + attributionSource.token = sp::make(); + if (mManager->getInputForAttr(&attr, &input, riid, AUDIO_SESSION_NONE, attributionSource, + &config, flags, selectedDeviceId, &inputType, portId) != OK) { return false; } if (*portId == AUDIO_PORT_HANDLE_NONE || input == AUDIO_IO_HANDLE_NONE) { diff --git a/services/audiopolicy/managerdefault/Android.bp b/services/audiopolicy/managerdefault/Android.bp index b111db4b90..0165dc888d 100644 --- a/services/audiopolicy/managerdefault/Android.bp +++ b/services/audiopolicy/managerdefault/Android.bp @@ -34,7 +34,7 @@ cc_library_shared { // a dependency on it in the device makefile. There will be no build time // conflict with libaudiopolicyenginedefault. "libaudiopolicyenginedefault", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", ], diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp index c8ddbc6e56..2e866ff11c 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp @@ -53,7 +53,7 @@ namespace android { -using media::permission::Identity; +using content::AttributionSourceState; //FIXME: workaround for truncated touch sounds // to be removed when the problem is handled by system UI @@ -1133,7 +1133,7 @@ status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, audio_io_handle_t *output, audio_session_t session, audio_stream_type_t *stream, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_t *config, audio_output_flags_t *flags, audio_port_handle_t *selectedDeviceId, @@ -1146,7 +1146,7 @@ status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr, return INVALID_OPERATION; } const uid_t uid = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_uid_t(identity.uid)); + aidl2legacy_int32_t_uid_t(attributionSource.uid)); const audio_port_handle_t requestedPortId = *selectedDeviceId; audio_attributes_t resultAttr; bool isRequestedDeviceForExclusiveUse = false; @@ -2115,7 +2115,7 @@ status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, audio_io_handle_t *input, audio_unique_id_t riid, audio_session_t session, - const Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_base_t *config, audio_input_flags_t flags, audio_port_handle_t *selectedDeviceId, @@ -2134,7 +2134,7 @@ status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, sp inputDesc; sp clientDesc; audio_port_handle_t requestedDeviceId = *selectedDeviceId; - uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(identity.uid)); + uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid)); bool isSoundTrigger; // The supplied portId must be AUDIO_PORT_HANDLE_NONE diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h index f5dd20c23d..98f96d1951 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.h +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h @@ -52,6 +52,8 @@ namespace android { +using content::AttributionSourceState; + // ---------------------------------------------------------------------------- // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB @@ -116,7 +118,7 @@ public: audio_io_handle_t *output, audio_session_t session, audio_stream_type_t *stream, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_t *config, audio_output_flags_t *flags, audio_port_handle_t *selectedDeviceId, @@ -130,7 +132,7 @@ public: audio_io_handle_t *input, audio_unique_id_t riid, audio_session_t session, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_config_base_t *config, audio_input_flags_t flags, audio_port_handle_t *selectedDeviceId, diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 14be671232..0273d292d0 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -45,12 +45,12 @@ cc_library_shared { "audiopolicy-aidl-cpp", "audiopolicy-types-aidl-cpp", "capture_state_listener-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], static_libs: [ "libaudiopolicycomponents", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], header_libs: [ @@ -70,6 +70,6 @@ cc_library_shared { export_shared_lib_headers: [ "libactivitymanager_aidl", "libsensorprivacy", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], } diff --git a/services/audiopolicy/service/AudioPolicyEffects.cpp b/services/audiopolicy/service/AudioPolicyEffects.cpp index 8426a77b51..3f01de9f57 100644 --- a/services/audiopolicy/service/AudioPolicyEffects.cpp +++ b/services/audiopolicy/service/AudioPolicyEffects.cpp @@ -35,7 +35,7 @@ namespace android { -using media::permission::Identity; +using content::AttributionSourceState; // ---------------------------------------------------------------------------- // AudioPolicyEffects Implementation @@ -123,9 +123,10 @@ status_t AudioPolicyEffects::addInputEffects(audio_io_handle_t input, Vector effects = mInputSources.valueAt(index)->mEffects; for (size_t i = 0; i < effects.size(); i++) { EffectDesc *effect = effects[i]; - Identity identity; - identity.packageName = "android"; - sp fx = new AudioEffect(identity); + AttributionSourceState attributionSource; + attributionSource.packageName = "android"; + attributionSource.token = sp::make(); + sp fx = new AudioEffect(attributionSource); fx->set(NULL, &effect->mUuid, -1, 0, 0, audioSession, input); status_t status = fx->initCheck(); if (status != NO_ERROR && status != ALREADY_EXISTS) { @@ -274,9 +275,10 @@ status_t AudioPolicyEffects::addOutputSessionEffects(audio_io_handle_t output, Vector effects = mOutputStreams.valueAt(index)->mEffects; for (size_t i = 0; i < effects.size(); i++) { EffectDesc *effect = effects[i]; - Identity identity; - identity.packageName = "android"; - sp fx = new AudioEffect(identity); + AttributionSourceState attributionSource; + attributionSource.packageName = "android"; + attributionSource.token = sp::make(); + sp fx = new AudioEffect(attributionSource); fx->set(NULL, &effect->mUuid, 0, 0, 0, audioSession, output); status_t status = fx->initCheck(); if (status != NO_ERROR && status != ALREADY_EXISTS) { @@ -976,9 +978,10 @@ void AudioPolicyEffects::initDefaultDeviceEffects() for (const auto& deviceEffectsIter : mDeviceEffects) { const auto& deviceEffects = deviceEffectsIter.second; for (const auto& effectDesc : deviceEffects->mEffectDescriptors->mEffects) { - Identity identity; - identity.packageName = "android"; - sp fx = new AudioEffect(identity); + AttributionSourceState attributionSource; + attributionSource.packageName = "android"; + attributionSource.token = sp::make(); + sp fx = new AudioEffect(attributionSource); fx->set(EFFECT_UUID_NULL, &effectDesc->mUuid, 0, nullptr, nullptr, AUDIO_SESSION_DEVICE, AUDIO_IO_HANDLE_NONE, AudioDeviceTypeAddr{deviceEffects->getDeviceType(), diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 22c091b8b3..1ebf76b5bf 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include #define VALUE_OR_RETURN_BINDER_STATUS(x) \ ({ auto _tmp = (x); \ @@ -43,7 +43,7 @@ namespace android { using binder::Status; using aidl_utils::binderStatusFromStatusT; -using media::permission::Identity; +using content::AttributionSourceState; const std::vector& SYSTEM_USAGES = { AUDIO_USAGE_CALL_ASSISTANT, @@ -64,15 +64,16 @@ bool AudioPolicyService::isSupportedSystemUsage(audio_usage_t usage) { } status_t AudioPolicyService::validateUsage(audio_usage_t usage) { - return validateUsage(usage, getCallingIdentity()); + return validateUsage(usage, getCallingAttributionSource()); } -status_t AudioPolicyService::validateUsage(audio_usage_t usage, const Identity& identity) { +status_t AudioPolicyService::validateUsage(audio_usage_t usage, + const AttributionSourceState& attributionSource) { if (isSystemUsage(usage)) { if (isSupportedSystemUsage(usage)) { - if (!modifyAudioRoutingAllowed(identity)) { + if (!modifyAudioRoutingAllowed(attributionSource)) { ALOGE(("permission denied: modify audio routing not allowed " - "for identity %s"), identity.toString().c_str()); + "for attributionSource %s"), attributionSource.toString().c_str()); return PERMISSION_DENIED; } } else { @@ -279,7 +280,7 @@ Status AudioPolicyService::getOutput(media::AudioStreamType streamAidl, int32_t* Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal& attrAidl, int32_t sessionAidl, - const Identity& identity, + const AttributionSourceState& attributionSource, const media::AudioConfig& configAidl, int32_t flagsAidl, int32_t selectedDeviceIdAidl, @@ -307,28 +308,28 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal RETURN_IF_BINDER_ERROR( binderStatusFromStatusT(AudioValidator::validateAudioAttributes(attr, "68953950"))); - RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr.usage, identity))); + RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr.usage, attributionSource))); ALOGV("%s()", __func__); Mutex::Autolock _l(mLock); // TODO b/182392553: refactor or remove - Identity adjIdentity = identity; + AttributionSourceState adjAttributionSource = attributionSource; const uid_t callingUid = IPCThreadState::self()->getCallingUid(); - if (!isAudioServerOrMediaServerUid(callingUid) || identity.uid == -1) { + if (!isAudioServerOrMediaServerUid(callingUid) || attributionSource.uid == -1) { int32_t callingUidAidl = VALUE_OR_RETURN_BINDER_STATUS( legacy2aidl_uid_t_int32_t(callingUid)); - ALOGW_IF(identity.uid != -1 && identity.uid != callingUidAidl, + ALOGW_IF(attributionSource.uid != -1 && attributionSource.uid != callingUidAidl, "%s uid %d tried to pass itself off as %d", __func__, - callingUidAidl, identity.uid); - adjIdentity.uid = callingUidAidl; + callingUidAidl, attributionSource.uid); + adjAttributionSource.uid = callingUidAidl; } if (!mPackageManager.allowPlaybackCapture(VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_uid_t(adjIdentity.uid)))) { + aidl2legacy_int32_t_uid_t(adjAttributionSource.uid)))) { attr.flags = static_cast(attr.flags | AUDIO_FLAG_NO_MEDIA_PROJECTION); } if (((attr.flags & (AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE)) != 0) - && !bypassInterruptionPolicyAllowed(identity)) { + && !bypassInterruptionPolicyAllowed(adjAttributionSource)) { attr.flags = static_cast( attr.flags & ~(AUDIO_FLAG_BYPASS_INTERRUPTION_POLICY|AUDIO_FLAG_BYPASS_MUTE)); } @@ -336,7 +337,7 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal AudioPolicyInterface::output_type_t outputType; status_t result = mAudioPolicyManager->getOutputForAttr(&attr, &output, session, &stream, - adjIdentity, + adjAttributionSource, &config, &flags, &selectedDeviceId, &portId, &secondaryOutputs, @@ -349,16 +350,16 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal case AudioPolicyInterface::API_OUTPUT_LEGACY: break; case AudioPolicyInterface::API_OUTPUT_TELEPHONY_TX: - if (!modifyPhoneStateAllowed(adjIdentity)) { + if (!modifyPhoneStateAllowed(adjAttributionSource)) { ALOGE("%s() permission denied: modify phone state not allowed for uid %d", - __func__, adjIdentity.uid); + __func__, adjAttributionSource.uid); result = PERMISSION_DENIED; } break; case AudioPolicyInterface::API_OUT_MIX_PLAYBACK: - if (!modifyAudioRoutingAllowed(adjIdentity)) { + if (!modifyAudioRoutingAllowed(adjAttributionSource)) { ALOGE("%s() permission denied: modify audio routing not allowed for uid %d", - __func__, adjIdentity.uid); + __func__, adjAttributionSource.uid); result = PERMISSION_DENIED; } break; @@ -371,7 +372,7 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal if (result == NO_ERROR) { sp client = - new AudioPlaybackClient(attr, output, adjIdentity, session, + new AudioPlaybackClient(attr, output, adjAttributionSource, session, portId, selectedDeviceId, stream); mAudioPlaybackClients.add(portId, client); @@ -508,7 +509,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& int32_t inputAidl, int32_t riidAidl, int32_t sessionAidl, - const Identity& identity, + const AttributionSourceState& attributionSource, const media::AudioConfigBase& configAidl, int32_t flagsAidl, int32_t selectedDeviceIdAidl, @@ -551,42 +552,46 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& return binderStatusFromStatusT(BAD_VALUE); } - // Make sure identity represents the current caller - Identity adjIdentity = identity; + // Make sure attribution source represents the current caller + AttributionSourceState adjAttributionSource = attributionSource; // TODO b/182392553: refactor or remove - bool updatePid = (identity.pid == -1); + bool updatePid = (attributionSource.pid == -1); const uid_t callingUid =IPCThreadState::self()->getCallingUid(); - const uid_t currentUid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(identity.uid)); + const uid_t currentUid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t( + attributionSource.uid)); if (!isAudioServerOrMediaServerUid(callingUid)) { ALOGW_IF(currentUid != (uid_t)-1 && currentUid != callingUid, "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, currentUid); - adjIdentity.uid = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_uid_t_int32_t(callingUid)); + adjAttributionSource.uid = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_uid_t_int32_t( + callingUid)); updatePid = true; } if (updatePid) { const int32_t callingPid = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_pid_t_int32_t( IPCThreadState::self()->getCallingPid())); - ALOGW_IF(identity.pid != -1 && identity.pid != callingPid, + ALOGW_IF(attributionSource.pid != -1 && attributionSource.pid != callingPid, "%s uid %d pid %d tried to pass itself off as pid %d", - __func__, adjIdentity.uid, callingPid, identity.pid); - adjIdentity.pid = callingPid; + __func__, adjAttributionSource.uid, callingPid, attributionSource.pid); + adjAttributionSource.pid = callingPid; } - RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr.usage, adjIdentity))); + RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(validateUsage(attr.usage, + adjAttributionSource))); // check calling permissions. // Capturing from FM_TUNER source is controlled by captureTunerAudioInputAllowed() and // captureAudioOutputAllowed() (deprecated) as this does not affect users privacy // as does capturing from an actual microphone. - if (!(recordingAllowed(adjIdentity, attr.source) || attr.source == AUDIO_SOURCE_FM_TUNER)) { + if (!(recordingAllowed(adjAttributionSource, attr.source) + || attr.source == AUDIO_SOURCE_FM_TUNER)) { ALOGE("%s permission denied: recording not allowed for %s", - __func__, adjIdentity.toString().c_str()); + __func__, adjAttributionSource.toString().c_str()); return binderStatusFromStatusT(PERMISSION_DENIED); } - bool canCaptureOutput = captureAudioOutputAllowed(adjIdentity); + bool canCaptureOutput = captureAudioOutputAllowed(adjAttributionSource); if ((inputSource == AUDIO_SOURCE_VOICE_UPLINK || inputSource == AUDIO_SOURCE_VOICE_DOWNLINK || inputSource == AUDIO_SOURCE_VOICE_CALL || @@ -596,12 +601,12 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& } if (inputSource == AUDIO_SOURCE_FM_TUNER - && !captureTunerAudioInputAllowed(adjIdentity) + && !captureTunerAudioInputAllowed(adjAttributionSource) && !canCaptureOutput) { return binderStatusFromStatusT(PERMISSION_DENIED); } - bool canCaptureHotword = captureHotwordAllowed(adjIdentity); + bool canCaptureHotword = captureHotwordAllowed(adjAttributionSource); if ((inputSource == AUDIO_SOURCE_HOTWORD) && !canCaptureHotword) { return binderStatusFromStatusT(PERMISSION_DENIED); } @@ -609,7 +614,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& if (((flags & AUDIO_INPUT_FLAG_HW_HOTWORD) != 0) && !canCaptureHotword) { ALOGE("%s: permission denied: hotword mode not allowed" - " for uid %d pid %d", __func__, adjIdentity.uid, adjIdentity.pid); + " for uid %d pid %d", __func__, adjAttributionSource.uid, adjAttributionSource.pid); return binderStatusFromStatusT(PERMISSION_DENIED); } @@ -623,7 +628,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& AutoCallerClear acc; // the audio_in_acoustics_t parameter is ignored by get_input() status = mAudioPolicyManager->getInputForAttr(&attr, &input, riid, session, - adjIdentity, &config, + adjAttributionSource, &config, flags, &selectedDeviceId, &inputType, &portId); @@ -647,7 +652,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& } break; case AudioPolicyInterface::API_INPUT_MIX_EXT_POLICY_REROUTE: - if (!modifyAudioRoutingAllowed(adjIdentity)) { + if (!modifyAudioRoutingAllowed(adjAttributionSource)) { ALOGE("getInputForAttr() permission denied: modify audio routing not allowed"); status = PERMISSION_DENIED; } @@ -668,7 +673,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& } sp client = new AudioRecordClient(attr, input, session, portId, - selectedDeviceId, adjIdentity, + selectedDeviceId, adjAttributionSource, canCaptureOutput, canCaptureHotword); mAudioRecordClients.add(portId, client); } @@ -723,11 +728,11 @@ Status AudioPolicyService::startInput(int32_t portIdAidl) msg << "Audio recording on session " << client->session; // check calling permissions - if (!(startRecording(client->identity, String16(msg.str().c_str()), + if (!(startRecording(client->attributionSource, String16(msg.str().c_str()), client->attributes.source) || client->attributes.source == AUDIO_SOURCE_FM_TUNER)) { - ALOGE("%s permission denied: recording not allowed for identity %s", - __func__, client->identity.toString().c_str()); + ALOGE("%s permission denied: recording not allowed for attribution source %s", + __func__, client->attributionSource.toString().c_str()); return binderStatusFromStatusT(PERMISSION_DENIED); } @@ -771,13 +776,13 @@ Status AudioPolicyService::startInput(int32_t portIdAidl) item->setCString(kAudioPolicyRqstSrc, toString(client->attributes.source).c_str()); item->setInt32(kAudioPolicyRqstSession, client->session); - if (client->identity.packageName.has_value() && - client->identity.packageName.value().size() != 0) { + if (client->attributionSource.packageName.has_value() && + client->attributionSource.packageName.value().size() != 0) { item->setCString(kAudioPolicyRqstPkg, - client->identity.packageName.value().c_str()); + client->attributionSource.packageName.value().c_str()); } else { item->setCString(kAudioPolicyRqstPkg, - std::to_string(client->identity.uid).c_str()); + std::to_string(client->attributionSource.uid).c_str()); } item->setCString( kAudioPolicyRqstDevice, getDeviceTypeStrForPortId(client->deviceId).c_str()); @@ -793,13 +798,13 @@ Status AudioPolicyService::startInput(int32_t portIdAidl) item->setCString(kAudioPolicyActiveSrc, toString(other->attributes.source).c_str()); item->setInt32(kAudioPolicyActiveSession, other->session); - if (other->identity.packageName.has_value() && - other->identity.packageName.value().size() != 0) { + if (other->attributionSource.packageName.has_value() && + other->attributionSource.packageName.value().size() != 0) { item->setCString(kAudioPolicyActivePkg, - other->identity.packageName.value().c_str()); + other->attributionSource.packageName.value().c_str()); } else { item->setCString(kAudioPolicyRqstPkg, std::to_string( - other->identity.uid).c_str()); + other->attributionSource.uid).c_str()); } item->setCString(kAudioPolicyActiveDevice, getDeviceTypeStrForPortId(other->deviceId).c_str()); @@ -815,7 +820,7 @@ Status AudioPolicyService::startInput(int32_t portIdAidl) client->active = false; client->startTimeNs = 0; updateUidStates_l(); - finishRecording(client->identity, client->attributes.source); + finishRecording(client->attributionSource, client->attributes.source); } return binderStatusFromStatusT(status); @@ -844,7 +849,7 @@ Status AudioPolicyService::stopInput(int32_t portIdAidl) updateUidStates_l(); // finish the recording app op - finishRecording(client->identity, client->attributes.source); + finishRecording(client->attributionSource, client->attributes.source); AutoCallerClear acc; return binderStatusFromStatusT(mAudioPolicyManager->stopInput(portId)); } @@ -1641,15 +1646,15 @@ Status AudioPolicyService::registerPolicyMixes(const std::vector current = mAudioRecordClients[i]; - uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(current->identity.uid)); + uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t( + current->attributionSource.uid)); if (!current->active) { continue; } @@ -641,7 +642,7 @@ void AudioPolicyService::updateUidStates_l() || (isInCommunication && currentUid == mPhoneStateOwnerUid)) { if (!isInCommunication || latestSensitiveActiveOrComm == nullptr || VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t( - latestSensitiveActiveOrComm->identity.uid)) + latestSensitiveActiveOrComm->attributionSource.uid)) != mPhoneStateOwnerUid) { latestSensitiveActiveOrComm = current; latestSensitiveStartNs = current->startTimeNs; @@ -676,7 +677,7 @@ void AudioPolicyService::updateUidStates_l() // if audio mode is IN_COMMUNICATION, favor audio mode owner over an app with // foreground UI in case both are capturing with privacy sensitive flag. uid_t latestActiveUid = VALUE_OR_FATAL( - aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->identity.uid)); + aidl2legacy_int32_t_uid_t(latestSensitiveActiveOrComm->attributionSource.uid)); if (isInCommunication && latestActiveUid == mPhoneStateOwnerUid) { topSensitiveActive = latestSensitiveActiveOrComm; topSensitiveStartNs = latestSensitiveStartNs; @@ -696,20 +697,20 @@ void AudioPolicyService::updateUidStates_l() for (size_t i =0; i < mAudioRecordClients.size(); i++) { sp current = mAudioRecordClients[i]; uid_t currentUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t( - current->identity.uid)); + current->attributionSource.uid)); if (!current->active) { continue; } audio_source_t source = current->attributes.source; bool isTopOrLatestActive = topActive == nullptr ? false : - current->identity.uid == topActive->identity.uid; + current->attributionSource.uid == topActive->attributionSource.uid; bool isTopOrLatestSensitive = topSensitiveActive == nullptr ? false : - current->identity.uid == topSensitiveActive->identity.uid; + current->attributionSource.uid == topSensitiveActive->attributionSource.uid; auto canCaptureIfInCallOrCommunication = [&](const auto &recordClient) REQUIRES(mLock) { uid_t recordUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t( - recordClient->identity.uid)); + recordClient->attributionSource.uid)); bool canCaptureCall = recordClient->canCaptureOutput; bool canCaptureCommunication = recordClient->canCaptureOutput || !isPhoneStateOwnerActive diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 40192b89da..84bec22d6d 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -1,3 +1,4 @@ + /* * Copyright (C) 2009 The Android Open Source Project * @@ -38,12 +39,14 @@ #include "CaptureStateNotifier.h" #include #include -#include +#include #include namespace android { +using content::AttributionSourceState; + // ---------------------------------------------------------------------------- class AudioPolicyService : @@ -81,7 +84,7 @@ public: media::AudioPolicyForcedConfig* _aidl_return) override; binder::Status getOutput(media::AudioStreamType stream, int32_t* _aidl_return) override; binder::Status getOutputForAttr(const media::AudioAttributesInternal& attr, int32_t session, - const media::permission::Identity &identity, + const AttributionSourceState &attributionSource, const media::AudioConfig& config, int32_t flags, int32_t selectedDeviceId, media::GetOutputForAttrResponse* _aidl_return) override; @@ -90,7 +93,7 @@ public: binder::Status releaseOutput(int32_t portId) override; binder::Status getInputForAttr(const media::AudioAttributesInternal& attr, int32_t input, int32_t riid, int32_t session, - const media::permission::Identity &identity, + const AttributionSourceState &attributionSource, const media::AudioConfigBase& config, int32_t flags, int32_t selectedDeviceId, media::GetInputForAttrResponse* _aidl_return) override; @@ -344,7 +347,7 @@ private: bool isSupportedSystemUsage(audio_usage_t usage); status_t validateUsage(audio_usage_t usage); - status_t validateUsage(audio_usage_t usage, const media::permission::Identity& identity); + status_t validateUsage(audio_usage_t usage, const AttributionSourceState& attributionSource); void updateUidStates(); void updateUidStates_l() REQUIRES(mLock); @@ -791,17 +794,18 @@ private: public: AudioClient(const audio_attributes_t attributes, const audio_io_handle_t io, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, const audio_session_t session, audio_port_handle_t portId, const audio_port_handle_t deviceId) : - attributes(attributes), io(io), identity(identity), - session(session), portId(portId), deviceId(deviceId), active(false) {} + attributes(attributes), io(io), attributionSource( + attributionSource), session(session), portId(portId), + deviceId(deviceId), active(false) {} ~AudioClient() override = default; const audio_attributes_t attributes; // source, flags ... const audio_io_handle_t io; // audio HAL stream IO handle - const media::permission::Identity& identity; //client identity + const AttributionSourceState& attributionSource; //client attributionsource const audio_session_t session; // audio session ID const audio_port_handle_t portId; const audio_port_handle_t deviceId; // selected input device port ID @@ -817,14 +821,15 @@ private: const audio_io_handle_t io, const audio_session_t session, audio_port_handle_t portId, const audio_port_handle_t deviceId, - const media::permission::Identity& identity, + const AttributionSourceState& attributionSource, bool canCaptureOutput, bool canCaptureHotword) : - AudioClient(attributes, io, identity, - session, portId, deviceId), identity(identity), startTimeNs(0), - canCaptureOutput(canCaptureOutput), canCaptureHotword(canCaptureHotword) {} + AudioClient(attributes, io, attributionSource, + session, portId, deviceId), attributionSource(attributionSource), + startTimeNs(0), canCaptureOutput(canCaptureOutput), + canCaptureHotword(canCaptureHotword) {} ~AudioRecordClient() override = default; - const media::permission::Identity identity; // identity of client + const AttributionSourceState attributionSource; // attribution source of client nsecs_t startTimeNs; const bool canCaptureOutput; const bool canCaptureHotword; @@ -836,10 +841,10 @@ private: class AudioPlaybackClient : public AudioClient { public: AudioPlaybackClient(const audio_attributes_t attributes, - const audio_io_handle_t io, media::permission::Identity identity, + const audio_io_handle_t io, AttributionSourceState attributionSource, const audio_session_t session, audio_port_handle_t portId, audio_port_handle_t deviceId, audio_stream_type_t stream) : - AudioClient(attributes, io, identity, session, portId, + AudioClient(attributes, io, attributionSource, session, portId, deviceId), stream(stream) {} ~AudioPlaybackClient() override = default; diff --git a/services/audiopolicy/tests/Android.bp b/services/audiopolicy/tests/Android.bp index f4802101fa..8fbe8b28da 100644 --- a/services/audiopolicy/tests/Android.bp +++ b/services/audiopolicy/tests/Android.bp @@ -25,7 +25,8 @@ cc_test { "libmedia_helper", "libutils", "libxml2", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", + "libbinder", ], static_libs: [ diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp index 8f12ecf5d5..a16ab7d2b1 100644 --- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp +++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp @@ -25,7 +25,7 @@ #define LOG_TAG "APM_Test" #include #include -#include +#include #include #include #include @@ -40,7 +40,7 @@ using namespace android; using testing::UnorderedElementsAre; -using media::permission::Identity; +using android::content::AttributionSourceState; TEST(AudioPolicyManagerTestInit, EngineFailure) { AudioPolicyTestClient client; @@ -216,11 +216,12 @@ void AudioPolicyManagerTest::getOutputForAttr( if (!portId) portId = &localPortId; *portId = AUDIO_PORT_HANDLE_NONE; AudioPolicyInterface::output_type_t outputType; - // TODO b/182392769: use identity util - Identity i = Identity(); - i.uid = 0; + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource = AttributionSourceState(); + attributionSource.uid = 0; + attributionSource.token = sp::make(); ASSERT_EQ(OK, mManager->getOutputForAttr( - &attr, output, AUDIO_SESSION_NONE, &stream, i, &config, &flags, + &attr, output, AUDIO_SESSION_NONE, &stream, attributionSource, &config, &flags, selectedDeviceId, portId, {}, &outputType)); ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId); ASSERT_NE(AUDIO_IO_HANDLE_NONE, *output); @@ -244,11 +245,12 @@ void AudioPolicyManagerTest::getInputForAttr( if (!portId) portId = &localPortId; *portId = AUDIO_PORT_HANDLE_NONE; AudioPolicyInterface::input_type_t inputType; - // TODO b/182392769: use identity util - Identity i = Identity(); - i.uid = 0; + // TODO b/182392769: use attribution source util + AttributionSourceState attributionSource = AttributionSourceState(); + attributionSource.uid = 0; + attributionSource.token = sp::make(); ASSERT_EQ(OK, mManager->getInputForAttr( - &attr, &input, riid, AUDIO_SESSION_NONE, i, &config, flags, + &attr, &input, riid, AUDIO_SESSION_NONE, attributionSource, &config, flags, selectedDeviceId, &inputType, portId)); ASSERT_NE(AUDIO_PORT_HANDLE_NONE, *portId); } diff --git a/services/oboeservice/AAudioEndpointManager.cpp b/services/oboeservice/AAudioEndpointManager.cpp index 3224cfcc58..20e4cc528d 100644 --- a/services/oboeservice/AAudioEndpointManager.cpp +++ b/services/oboeservice/AAudioEndpointManager.cpp @@ -184,7 +184,7 @@ sp AAudioEndpointManager::openExclusiveEndpoint( // An app can avoid having this happen by closing their streams when // the app is paused. pid_t pid = VALUE_OR_FATAL( - aidl2legacy_int32_t_pid_t(request.getIdentity().pid)); + aidl2legacy_int32_t_pid_t(request.getAttributionSource().pid)); AAudioClientTracker::getInstance().setExclusiveEnabled(pid, false); endpointToSteal = endpoint; // return it to caller } diff --git a/services/oboeservice/AAudioService.cpp b/services/oboeservice/AAudioService.cpp index 0b69bf6d32..40a664eecb 100644 --- a/services/oboeservice/AAudioService.cpp +++ b/services/oboeservice/AAudioService.cpp @@ -22,7 +22,7 @@ #include #include -#include +#include #include #include #include @@ -47,18 +47,18 @@ using namespace aaudio; std::move(_tmp.value()); }) using android::AAudioService; -using android::media::permission::Identity; +using android::content::AttributionSourceState; using binder::Status; android::AAudioService::AAudioService() : BnAAudioService(), mAdapter(this) { // TODO consider using geteuid() - // TODO b/182392769: use identity util - mAudioClient.identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); - mAudioClient.identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); - mAudioClient.identity.packageName = std::nullopt; - mAudioClient.identity.attributionTag = std::nullopt; + // TODO b/182392769: use attribution source util + mAudioClient.attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); + mAudioClient.attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(getpid())); + mAudioClient.attributionSource.packageName = std::nullopt; + mAudioClient.attributionSource.attributionTag = std::nullopt; AAudioClientTracker::getInstance().setAAudioService(this); } @@ -115,13 +115,14 @@ AAudioService::openStream(const StreamRequest &_request, StreamParameters* _para aaudio_sharing_mode_t sharingMode = configurationInput.getSharingMode(); // Enforce limit on client processes. - Identity callingIdentity = request.getIdentity(); + AttributionSourceState attributionSource = request.getAttributionSource(); pid_t pid = IPCThreadState::self()->getCallingPid(); - callingIdentity.pid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS( + attributionSource.pid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS( legacy2aidl_pid_t_int32_t(pid)); - callingIdentity.uid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS( + attributionSource.uid = VALUE_OR_RETURN_ILLEGAL_ARG_STATUS( legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); - if (callingIdentity.pid != mAudioClient.identity.pid) { + attributionSource.token = sp::make(); + if (attributionSource.pid != mAudioClient.attributionSource.pid) { int32_t count = AAudioClientTracker::getInstance().getStreamCount(pid); if (count >= MAX_STREAMS_PER_PROCESS) { ALOGE("openStream(): exceeded max streams per process %d >= %d", @@ -280,8 +281,8 @@ Status AAudioService::unregisterAudioThread(int32_t streamHandle, int32_t client } bool AAudioService::isCallerInService() { - pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAudioClient.identity.pid)); - uid_t clientUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAudioClient.identity.uid)); + pid_t clientPid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(mAudioClient.attributionSource.pid)); + uid_t clientUid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid)); return clientPid == IPCThreadState::self()->getCallingPid() && clientUid == IPCThreadState::self()->getCallingUid(); } @@ -307,7 +308,7 @@ sp AAudioService::convertHandleToServiceStream( const uid_t callingUserId = IPCThreadState::self()->getCallingUid(); const uid_t ownerUserId = serviceStream->getOwnerUserId(); const uid_t clientUid = VALUE_OR_FATAL( - aidl2legacy_int32_t_uid_t(mAudioClient.identity.uid)); + aidl2legacy_int32_t_uid_t(mAudioClient.attributionSource.uid)); bool callerOwnsIt = callingUserId == ownerUserId; bool serverCalling = callingUserId == clientUid; bool serverOwnsIt = ownerUserId == clientUid; diff --git a/services/oboeservice/AAudioServiceEndpointMMAP.cpp b/services/oboeservice/AAudioServiceEndpointMMAP.cpp index b4efd1ae76..117218a337 100644 --- a/services/oboeservice/AAudioServiceEndpointMMAP.cpp +++ b/services/oboeservice/AAudioServiceEndpointMMAP.cpp @@ -71,11 +71,11 @@ std::string AAudioServiceEndpointMMAP::dump() const { aaudio_result_t AAudioServiceEndpointMMAP::open(const aaudio::AAudioStreamRequest &request) { aaudio_result_t result = AAUDIO_OK; copyFrom(request.getConstantConfiguration()); - mMmapClient.identity = request.getIdentity(); - // TODO b/182392769: use identity util - mMmapClient.identity.uid = VALUE_OR_FATAL( + mMmapClient.attributionSource = request.getAttributionSource(); + // TODO b/182392769: use attribution source util + mMmapClient.attributionSource.uid = VALUE_OR_FATAL( legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); - mMmapClient.identity.pid = VALUE_OR_FATAL( + mMmapClient.attributionSource.pid = VALUE_OR_FATAL( legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid())); audio_format_t audioFormat = getFormat(); @@ -165,8 +165,8 @@ aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFo this, // callback mMmapStream, &mPortHandle); - ALOGD("%s() mMapClient.identity = %s => portHandle = %d\n", - __func__, mMmapClient.identity.toString().c_str(), mPortHandle); + ALOGD("%s() mMapClient.attributionSource = %s => portHandle = %d\n", + __func__, mMmapClient.attributionSource.toString().c_str(), mPortHandle); if (status != OK) { // This can happen if the resource is busy or the config does // not match the hardware. @@ -216,7 +216,7 @@ aaudio_result_t AAudioServiceEndpointMMAP::openWithFormat(audio_format_t audioFo // Exclusive mode can only be used by the service because the FD cannot be shared. int32_t audioServiceUid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(getuid())); - if ((mMmapClient.identity.uid != audioServiceUid) && + if ((mMmapClient.attributionSource.uid != audioServiceUid) && getSharingMode() == AAUDIO_SHARING_MODE_EXCLUSIVE) { ALOGW("%s() - exclusive FD cannot be used by client", __func__); result = AAUDIO_ERROR_UNAVAILABLE; diff --git a/services/oboeservice/AAudioServiceStreamBase.cpp b/services/oboeservice/AAudioServiceStreamBase.cpp index dbacd75dd1..34ddd4d3b7 100644 --- a/services/oboeservice/AAudioServiceStreamBase.cpp +++ b/services/oboeservice/AAudioServiceStreamBase.cpp @@ -39,7 +39,7 @@ using namespace android; // TODO just import names needed using namespace aaudio; // TODO just import names needed -using media::permission::Identity; +using content::AttributionSourceState; /** * Base class for streams in the service. @@ -50,7 +50,7 @@ AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService) : mTimestampThread("AATime") , mAtomicStreamTimestamp() , mAudioService(audioService) { - mMmapClient.identity = Identity(); + mMmapClient.attributionSource = AttributionSourceState(); } AAudioServiceStreamBase::~AAudioServiceStreamBase() { @@ -81,7 +81,7 @@ std::string AAudioServiceStreamBase::dump() const { result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle << std::dec << std::setfill(' ') ; - result << std::setw(6) << mMmapClient.identity.uid; + result << std::setw(6) << mMmapClient.attributionSource.uid; result << std::setw(7) << mClientHandle; result << std::setw(4) << (isRunning() ? "yes" : " no"); result << std::setw(6) << getState(); @@ -127,11 +127,11 @@ aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance(); aaudio_result_t result = AAUDIO_OK; - mMmapClient.identity = request.getIdentity(); - // TODO b/182392769: use identity util - mMmapClient.identity.uid = VALUE_OR_FATAL( + mMmapClient.attributionSource = request.getAttributionSource(); + // TODO b/182392769: use attribution source util + mMmapClient.attributionSource.uid = VALUE_OR_FATAL( legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid())); - mMmapClient.identity.pid = VALUE_OR_FATAL( + mMmapClient.attributionSource.pid = VALUE_OR_FATAL( legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid())); // Limit scope of lock to avoid recursive lock in close(). diff --git a/services/oboeservice/AAudioServiceStreamBase.h b/services/oboeservice/AAudioServiceStreamBase.h index c42df0f453..976996d226 100644 --- a/services/oboeservice/AAudioServiceStreamBase.h +++ b/services/oboeservice/AAudioServiceStreamBase.h @@ -160,11 +160,13 @@ public: } uid_t getOwnerUserId() const { - return VALUE_OR_FATAL(android::aidl2legacy_int32_t_uid_t(mMmapClient.identity.uid)); + return VALUE_OR_FATAL(android::aidl2legacy_int32_t_uid_t( + mMmapClient.attributionSource.uid)); } pid_t getOwnerProcessId() const { - return VALUE_OR_FATAL(android::aidl2legacy_int32_t_pid_t(mMmapClient.identity.pid)); + return VALUE_OR_FATAL(android::aidl2legacy_int32_t_pid_t( + mMmapClient.attributionSource.pid)); } aaudio_handle_t getHandle() const { diff --git a/services/oboeservice/Android.bp b/services/oboeservice/Android.bp index a419dd5633..4c580402f7 100644 --- a/services/oboeservice/Android.bp +++ b/services/oboeservice/Android.bp @@ -66,13 +66,13 @@ cc_library { "liblog", "libutils", "aaudio-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", ], export_shared_lib_headers: [ "libaaudio_internal", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", ], header_libs: [ diff --git a/services/oboeservice/fuzzer/Android.bp b/services/oboeservice/fuzzer/Android.bp index f4e8a8131f..605ac012d4 100644 --- a/services/oboeservice/fuzzer/Android.bp +++ b/services/oboeservice/fuzzer/Android.bp @@ -46,7 +46,7 @@ cc_fuzz { "liblog", "libutils", "aaudio-aidl-cpp", - "media_permission-aidl-cpp", + "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", ], static_libs: [ diff --git a/services/oboeservice/fuzzer/oboeservice_fuzzer.cpp b/services/oboeservice/fuzzer/oboeservice_fuzzer.cpp index 8e508d3049..4bc661c52a 100644 --- a/services/oboeservice/fuzzer/oboeservice_fuzzer.cpp +++ b/services/oboeservice/fuzzer/oboeservice_fuzzer.cpp @@ -23,7 +23,7 @@ #include #include #include "aaudio/BnAAudioClient.h" -#include +#include #define UNUSED_PARAM __attribute__((unused)) @@ -295,11 +295,12 @@ void OboeserviceFuzzer::process(const uint8_t *data, size_t size) { ? fdp.ConsumeIntegral() : kAAudioFormats[fdp.ConsumeIntegralInRange(0, kNumAAudioFormats - 1)])); - // TODO b/182392769: use identity util - media::permission::Identity identity; - identity.uid = getuid(); - identity.pid = getpid(); - request.setIdentity(identity); + // TODO b/182392769: use attribution source util + android::content::AttributionSourceState attributionSource; + attributionSource.uid = getuid(); + attributionSource.pid = getpid(); + attributionSource.token = sp::make(); + request.setAttributionSource(attributionSource); request.setInService(fdp.ConsumeBool()); request.getConfiguration().setDeviceId(fdp.ConsumeIntegral()); -- GitLab From 2f2c1980ecc9830e27d70307a59b371b3970bf17 Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Wed, 2 Jun 2021 14:03:11 +0200 Subject: [PATCH 049/694] audio policy: add more log for preferred device selection Add more verbose log to audio policy manager AudioTrack and AudioRecord to debug issues related to preferred capture device selection. Test: make Change-Id: I9685b4c3dfc2b84d7f89a4b33613858138e48a6f --- media/libaudioclient/AudioRecord.cpp | 2 ++ media/libaudioclient/AudioTrack.cpp | 2 ++ services/audiopolicy/managerdefault/AudioPolicyManager.cpp | 5 +++-- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp index a1d3bdbb27..a02a373193 100644 --- a/media/libaudioclient/AudioRecord.cpp +++ b/media/libaudioclient/AudioRecord.cpp @@ -668,6 +668,8 @@ status_t AudioRecord::getTimestamp(ExtendedTimestamp *timestamp) // ---- Explicit Routing --------------------------------------------------- status_t AudioRecord::setInputDevice(audio_port_handle_t deviceId) { AutoMutex lock(mLock); + ALOGV("%s(%d): deviceId=%d mSelectedDeviceId=%d", + __func__, mPortId, deviceId, mSelectedDeviceId); if (mSelectedDeviceId != deviceId) { mSelectedDeviceId = deviceId; if (mStatus == NO_ERROR) { diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 6765bdb169..594c3f30b9 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -1555,6 +1555,8 @@ audio_io_handle_t AudioTrack::getOutput() const status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) { AutoMutex lock(mLock); + ALOGV("%s(%d): deviceId=%d mSelectedDeviceId=%d", + __func__, mPortId, deviceId, mSelectedDeviceId); if (mSelectedDeviceId != deviceId) { mSelectedDeviceId = deviceId; if (mStatus == NO_ERROR) { diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp index 2e866ff11c..ccb82f2036 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp @@ -2123,8 +2123,9 @@ status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr, audio_port_handle_t *portId) { ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, " - "flags %#x attributes=%s", __func__, attr->source, config->sample_rate, - config->format, config->channel_mask, session, flags, toString(*attr).c_str()); + "flags %#x attributes=%s requested device ID %d", + __func__, attr->source, config->sample_rate, config->format, config->channel_mask, + session, flags, toString(*attr).c_str(), *selectedDeviceId); status_t status = NO_ERROR; audio_source_t halInputSource; -- GitLab From 2d8df4e83e9f025e7208816165affc5bba4000b5 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 3 Jun 2021 13:59:13 -0700 Subject: [PATCH 050/694] Add AudioChannelMask to Framework SAIDL definition Framework SAIDL used to use 'int' for the channel mask type. To help finding all the places where channel masks are used, add a designated type. Currently it's an enum, but it will be changed to a more extendable type soon (see the bug and the plan document). Bug: 188932434 Test: m Change-Id: If2d958fcc92b8e549493d3fa83b35c12dcda2ccc --- media/libaudioclient/AidlConversion.cpp | 46 +++++++++---------- media/libaudioclient/Android.bp | 1 + media/libaudioclient/IAudioFlinger.cpp | 9 ++-- .../aidl/android/media/AudioChannelMask.aidl | 45 ++++++++++++++++++ .../aidl/android/media/AudioConfig.aidl | 9 ++-- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioGain.aidl | 5 +- .../aidl/android/media/AudioGainConfig.aidl | 5 +- .../aidl/android/media/AudioIoDescriptor.aidl | 6 +-- .../aidl/android/media/AudioPortConfig.aidl | 5 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 3 +- .../include/media/AidlConversion.h | 6 ++- .../include/media/IAudioFlinger.h | 2 +- media/libaudiofoundation/AudioGain.cpp | 4 +- media/libaudiofoundation/AudioPort.cpp | 8 ++-- media/libaudiofoundation/AudioProfile.cpp | 7 +-- 17 files changed, 108 insertions(+), 61 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioChannelMask.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 21b4244932..0e98e5db76 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -273,18 +273,14 @@ ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy) { enumToMask_index); } -ConversionResult aidl2legacy_int32_t_audio_channel_mask_t(int32_t aidl) { - // TODO(ytai): should we convert bit-by-bit? - // One problem here is that the representation is both opaque and is different based on the - // context (input vs. output). Can determine based on type and role, as per useInChannelMask(). +ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( + media::AudioChannelMask aidl) { return convertReinterpret(aidl); } -ConversionResult legacy2aidl_audio_channel_mask_t_int32_t(audio_channel_mask_t legacy) { - // TODO(ytai): should we convert bit-by-bit? - // One problem here is that the representation is both opaque and is different based on the - // context (input vs. output). Can determine based on type and role, as per useInChannelMask(). - return convertReinterpret(legacy); +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( + audio_channel_mask_t legacy) { + return convertReinterpret(legacy); } ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event( @@ -465,7 +461,7 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = - VALUE_OR_RETURN(aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; const bool isJoint = bitmaskIsSet(aidl.mode, media::AudioGainMode::JOINT); size_t numValues = isJoint ? 1 @@ -487,7 +483,7 @@ ConversionResult legacy2aidl_audio_gain_config_AudioGain aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); aidl.channelMask = - VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; const bool isJoint = (legacy.mode & AUDIO_GAIN_MODE_JOINT) != 0; size_t numValues = isJoint ? 1 @@ -1054,7 +1050,8 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::CHANNEL_MASK)) { legacy.channel_mask = - VALUE_OR_RETURN(aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + VALUE_OR_RETURN( + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); @@ -1083,7 +1080,8 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { aidl.channelMask = - VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); @@ -1154,7 +1152,7 @@ ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDes legacy->mSamplingRate = VALUE_OR_RETURN(convertIntegral(aidl.samplingRate)); legacy->mFormat = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); legacy->mChannelMask = - VALUE_OR_RETURN(aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy->mFrameCount = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); legacy->mFrameCountHAL = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); legacy->mLatency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); @@ -1170,7 +1168,7 @@ ConversionResult legacy2aidl_AudioIoDescriptor_AudioIo aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->mSamplingRate)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy->mFormat)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(legacy->mChannelMask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->mChannelMask)); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->mFrameCount)); aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->mFrameCountHAL)); aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->mLatency)); @@ -1503,7 +1501,7 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le aidl.version = VALUE_OR_RETURN(convertIntegral(legacy.version)); aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.config.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.config.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); aidl.streamType = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(legacy.stream_type)); @@ -1535,7 +1533,7 @@ aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { audio_config_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); @@ -1548,7 +1546,7 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { media::AudioConfig aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); @@ -1561,7 +1559,7 @@ aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& ai audio_config_base_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); return legacy; } @@ -1571,7 +1569,7 @@ legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legac media::AudioConfigBase aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); return aidl; } @@ -1916,7 +1914,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { } RETURN_IF_ERROR( convertRange(aidl.channelMasks.begin(), aidl.channelMasks.end(), legacy.channel_masks, - aidl2legacy_int32_t_audio_channel_mask_t)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t)); legacy.num_channel_masks = aidl.channelMasks.size(); legacy.encapsulation_type = VALUE_OR_RETURN( @@ -1943,7 +1941,7 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { RETURN_IF_ERROR( convertRange(legacy.channel_masks, legacy.channel_masks + legacy.num_channel_masks, std::back_inserter(aidl.channelMasks), - legacy2aidl_audio_channel_mask_t_int32_t)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask)); aidl.encapsulationType = VALUE_OR_RETURN( legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( @@ -1956,7 +1954,7 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_int32_t_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -1971,7 +1969,7 @@ legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); aidl.maxValue = VALUE_OR_RETURN(convertIntegral(legacy.max_value)); aidl.defaultValue = VALUE_OR_RETURN(convertIntegral(legacy.default_value)); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 37e68bb595..4652a18513 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -302,6 +302,7 @@ aidl_interface { local_include_dir: "aidl", srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", + "aidl/android/media/AudioChannelMask.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", "aidl/android/media/AudioConfigBase.aidl", diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index b5175883ff..f89de97da7 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -408,8 +408,8 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); media::AudioFormatSys formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormat(format)); - int32_t channelMaskAidl = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_int32_t(channelMask)); + media::AudioChannelMask channelMaskAidl = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(channelMask)); int64_t aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( mDelegate->getInputBufferSize(sampleRateAidl, formatAidl, channelMaskAidl, @@ -927,12 +927,13 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioFormat_audio_format_t(format)); audio_channel_mask_t channelMaskLegacy = VALUE_OR_RETURN_BINDER( - aidl2legacy_int32_t_audio_channel_mask_t(channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(channelMask)); size_t size = mDelegate->getInputBufferSize(sampleRateLegacy, formatLegacy, channelMaskLegacy); *_aidl_return = VALUE_OR_RETURN_BINDER(convertIntegral(size)); return Status::ok(); diff --git a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl new file mode 100644 index 0000000000..1e7e6e5e23 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * AudioChannelMask is an opaque type and its internal layout should not be + * assumed as it may change in the future. + * + * This is a temporary implementation to provide a distinct type (instead of + * 'int') in all the places that need a channel mask. Later the enum will be + * replaced with a type which is more extensible by vendors. + * + * The actual value range of this enum is the same as of + * the 'audio_channel_mask_t' enum. + * + * {@hide} + */ +@Backing(type="int") +enum AudioChannelMask { + /** + * Framework use only, do not constitute a valid channel mask. + */ + INVALID = 0xC0000000, + + NONE = 0, + /** + * Since the current code never uses the values of the SAIDL enum + * directly--it uses the values of the C enum and coerces the type-- + * we don't specify any other values here. + */ +} diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 907fa83c2c..dc4e9e4024 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -16,19 +16,16 @@ package android.media; -import android.media.AudioOffloadInfo; +import android.media.AudioChannelMask; import android.media.AudioFormatSys; +import android.media.AudioOffloadInfo; /** * {@hide} */ parcelable AudioConfig { int sampleRate; - /** - * Interpreted as audio_channel_mask_t. - * TODO(ytai): Create a designated type. - */ - int channelMask; + AudioChannelMask channelMask; AudioFormatSys format; AudioOffloadInfo offloadInfo; long frameCount; diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index 306af1791e..59fbee695d 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,6 +16,7 @@ package android.media; +import android.media.AudioChannelMask; import android.media.AudioFormatSys; /** @@ -23,7 +24,6 @@ import android.media.AudioFormatSys; */ parcelable AudioConfigBase { int sampleRate; - /** Interpreted as audio_channel_mask_t. */ - int channelMask; + AudioChannelMask channelMask; AudioFormatSys format; } diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 048b295bc0..58cf1c984c 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioChannelMask; + /** * {@hide} */ @@ -25,8 +27,7 @@ parcelable AudioGain { boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; - /** Interpreted as audio_channel_mask_t. */ - int channelMask; + AudioChannelMask channelMask; int minValue; int maxValue; int defaultValue; diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl index b93c2dc4ac..67b77a5742 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioChannelMask; + /** * {@hide} */ @@ -28,9 +30,8 @@ parcelable AudioGainConfig { /** * Channels which gain value follows. N/A in joint mode. - * Interpreted as audio_channel_mask_t. */ - int channelMask; + AudioChannelMask channelMask; /** * Gain values in millibels. diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index 7d845d41d4..80dfdcd32f 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -16,8 +16,9 @@ package android.media; -import android.media.AudioPatch; +import android.media.AudioChannelMask; import android.media.AudioFormatSys; +import android.media.AudioPatch; /** * {@hide} @@ -28,8 +29,7 @@ parcelable AudioIoDescriptor { AudioPatch patch; int samplingRate; AudioFormatSys format; - /** Interpreted as audio_channel_mask_t. */ - int channelMask; + AudioChannelMask channelMask; long frameCount; long frameCountHAL; /** Only valid for output. */ diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index f1f338eb25..7489792eca 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,6 +16,7 @@ package android.media; +import android.media.AudioChannelMask; import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; @@ -43,10 +44,8 @@ parcelable AudioPortConfig { int sampleRate; /** * Channel mask, if applicable. - * Interpreted as audio_channel_mask_t. - * TODO: bitmask? */ - int channelMask; + AudioChannelMask channelMask; /** * Format, if applicable. */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index e73bb9e82c..0de7ca96e2 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,6 +16,7 @@ package android.media; +import android.media.AudioChannelMask; import android.media.AudioEncapsulationType; import android.media.AudioFormatSys; @@ -26,8 +27,7 @@ parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ AudioFormatSys format; - /** Interpreted as audio_channel_mask_t. */ - int[] channelMasks; + AudioChannelMask[] channelMasks; int[] samplingRates; boolean isDynamicFormat; boolean isDynamicChannels; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index df747d15b2..98a3e3bfe8 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,6 +16,7 @@ package android.media; +import android.media.AudioChannelMask; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -116,7 +117,7 @@ interface IAudioFlingerService { // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, AudioFormatSys format, - int /* audio_channel_mask_t */ channelMask); + AudioChannelMask channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); int /* audio_io_handle_t */ openDuplicateOutput(int /* audio_io_handle_t */ output1, diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index b00ef37dd9..fc8a1e8681 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -96,8 +96,10 @@ ConversionResult legacy2aidl_int32_t_AudioPortConfig ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl); ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy); -ConversionResult aidl2legacy_int32_t_audio_channel_mask_t(int32_t aidl); -ConversionResult legacy2aidl_audio_channel_mask_t_int32_t(audio_channel_mask_t legacy); +ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( + media::AudioChannelMask aidl); +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( + audio_channel_mask_t legacy); ConversionResult aidl2legacy_int32_t_pid_t(int32_t aidl); ConversionResult legacy2aidl_pid_t_int32_t(pid_t legacy); diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 80320dd8a3..634326ec0b 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -585,7 +585,7 @@ public: getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; Status getInputBufferSize(int32_t sampleRate, media::AudioFormatSys format, - int32_t channelMask, int64_t* _aidl_return) override; + media::AudioChannelMask channelMask, int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; Status openDuplicateOutput(int32_t output1, int32_t output2, int32_t* _aidl_return) override; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 1dee938fc2..5cc2b2f5f2 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -142,7 +142,7 @@ status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_int32_t(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -166,7 +166,7 @@ status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index fafabd9022..fc67c594f3 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -340,13 +340,13 @@ status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); parcelable->format = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_format_t_AudioFormat(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_int32_t(mChannelMask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mChannelMask)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); parcelable->gain.index = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.index)); parcelable->gain.mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->gain.channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_int32_t(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); parcelable->gain.rampDurationMs = VALUE_OR_RETURN_STATUS( convertIntegral(mGain.ramp_duration_ms)); parcelable->gain.values = VALUE_OR_RETURN_STATUS(convertContainer>( @@ -364,13 +364,13 @@ status_t AudioPortConfig::readFromParcelable(const media::AudioPortConfig& parce mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); mFormat = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioFormat_audio_format_t(parcelable.format)); mChannelMask = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); mGain.index = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.index)); mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.gain.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_audio_channel_mask_t(parcelable.gain.channelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.gain.channelMask)); mGain.ramp_duration_ms = VALUE_OR_RETURN_STATUS( convertIntegral(parcelable.gain.rampDurationMs)); if (parcelable.gain.values.size() > std::size(mGain.values)) { diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index 8ac3f734cb..72431316a4 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -165,8 +165,9 @@ AudioProfile::toParcelable() const { parcelable.name = mName; parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( - convertContainer>(mChannelMasks, - legacy2aidl_audio_channel_mask_t_int32_t)); + convertContainer>( + mChannelMasks, + legacy2aidl_audio_channel_mask_t_AudioChannelMask)); parcelable.samplingRates = VALUE_OR_RETURN( convertContainer>(mSamplingRates, convertIntegral)); @@ -194,7 +195,7 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { legacy->mFormat = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, - aidl2legacy_int32_t_audio_channel_mask_t)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t)); legacy->mSamplingRates = VALUE_OR_RETURN( convertContainer(parcelable.samplingRates, convertIntegral)); -- GitLab From e128b8e315fb188c3238f5b33d67db04d675f123 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 4 Jun 2021 17:31:03 -0700 Subject: [PATCH 051/694] Define an extensible audio format description The new way for describing audio formats which can be used both in framework <-> framework and framework <-> HAL interfaces and directly supports extensions by vendors. The mapping is defined between the legacy audio_format_t and the new descriptions. The new description will replace the AudioFormatSys SAIDL enum. For bitstream types, MIME Media Types are used. Stagefright's list of media types is extended. Bug: 188932434 Test: atest audio_aidl_conversion_tests Change-Id: Id0a0186b44c15dcb65980daf4b8a4257ef6adb72 --- media/libaudioclient/AidlConversion.cpp | 401 ++++++++++++++++++ media/libaudioclient/Android.bp | 4 + media/libaudioclient/TEST_MAPPING | 7 + .../android/media/AudioFormatDescription.aidl | 84 ++++ .../aidl/android/media/AudioFormatType.aidl | 48 +++ .../aidl/android/media/PcmType.aidl | 53 +++ .../include/media/AidlConversion.h | 6 + .../include/media/AudioCommonTypes.h | 33 +- media/libaudioclient/tests/Android.bp | 36 +- .../audio_aidl_legacy_conversion_tests.cpp | 111 +++++ media/libstagefright/foundation/MediaDefs.cpp | 12 +- .../media/stagefright/foundation/MediaDefs.h | 12 +- 12 files changed, 799 insertions(+), 8 deletions(-) create mode 100644 media/libaudioclient/TEST_MAPPING create mode 100644 media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioFormatType.aidl create mode 100644 media/libaudioclient/aidl/android/media/PcmType.aidl create mode 100644 media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 0e98e5db76..8f3d9962ec 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -14,6 +14,11 @@ * limitations under the License. */ +#include +#include +#include +#include + #define LOG_TAG "AidlConversion" //#define LOG_NDEBUG 0 #include @@ -21,6 +26,7 @@ #include "media/AidlConversion.h" #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// // Utilities @@ -403,6 +409,401 @@ ConversionResult legacy2aidl_audio_format_t_AudioFormat( return static_cast(legacy); } +namespace { + +namespace detail { +using AudioFormatPair = std::pair; +using AudioFormatPairs = std::vector; +} + +media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { + media::AudioFormatDescription result; + result.type = type; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(media::PcmType pcm) { + auto result = make_AudioFormatDescription(media::AudioFormatType::PCM); + result.pcm = pcm; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { + media::AudioFormatDescription result; + result.encoding = encoding; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(media::PcmType transport, + const std::string& encoding) { + auto result = make_AudioFormatDescription(encoding); + result.pcm = transport; + return result; +} + +const detail::AudioFormatPairs& getAudioFormatPairs() { + static const detail::AudioFormatPairs pairs = {{ + { + AUDIO_FORMAT_INVALID, + make_AudioFormatDescription(media::AudioFormatType::SYS_RESERVED_INVALID) + }, + { + AUDIO_FORMAT_DEFAULT, media::AudioFormatDescription{} + }, + { + AUDIO_FORMAT_PCM_16_BIT, make_AudioFormatDescription(media::PcmType::INT_16_BIT) + }, + { + AUDIO_FORMAT_PCM_8_BIT, make_AudioFormatDescription(media::PcmType::UINT_8_BIT) + }, + { + AUDIO_FORMAT_PCM_32_BIT, make_AudioFormatDescription(media::PcmType::INT_32_BIT) + }, + { + AUDIO_FORMAT_PCM_8_24_BIT, make_AudioFormatDescription(media::PcmType::FIXED_Q_8_24) + }, + { + AUDIO_FORMAT_PCM_FLOAT, make_AudioFormatDescription(media::PcmType::FLOAT_32_BIT) + }, + { + AUDIO_FORMAT_PCM_24_BIT_PACKED, make_AudioFormatDescription(media::PcmType::INT_24_BIT) + }, + { + // See the comment in MediaDefs.h. + AUDIO_FORMAT_MP3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEG) + }, + { + AUDIO_FORMAT_AMR_NB, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AMR_NB) + }, + { + AUDIO_FORMAT_AMR_WB, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AMR_WB) + }, + { + // Note: in MediaDefs.cpp MEDIA_MIMETYPE_AUDIO_AAC = "audio/mp4a-latm". + AUDIO_FORMAT_AAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_FORMAT) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_MAIN, make_AudioFormatDescription("audio/aac.main") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LC, make_AudioFormatDescription("audio/aac.lc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_SSR, make_AudioFormatDescription("audio/aac.ssr") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LTP, make_AudioFormatDescription("audio/aac.ltp") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_HE_V1, make_AudioFormatDescription("audio/aac.he.v1") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_SCALABLE, make_AudioFormatDescription("audio/aac.scalable") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ERLC, make_AudioFormatDescription("audio/aac.erlc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LD, make_AudioFormatDescription("audio/aac.ld") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_HE_V2, make_AudioFormatDescription("audio/aac.he.v2") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ELD, make_AudioFormatDescription("audio/aac.eld") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_XHE, make_AudioFormatDescription("audio/aac.xhe") + }, + // AUDIO_FORMAT_HE_AAC_V1 and HE_AAC_V2 are removed since they were deprecated long time + // ago. + { + AUDIO_FORMAT_VORBIS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_VORBIS) + }, + { + AUDIO_FORMAT_OPUS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_OPUS) + }, + { + AUDIO_FORMAT_AC3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AC3) + }, + { + AUDIO_FORMAT_E_AC3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EAC3) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_E_AC3_JOC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EAC3_JOC) + }, + { + AUDIO_FORMAT_DTS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DTS) + }, + { + AUDIO_FORMAT_DTS_HD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DTS_HD) + }, + // In the future, we would like to represent encapsulated bitstreams as + // nested AudioFormatDescriptions. The legacy 'AUDIO_FORMAT_IEC61937' type doesn't + // specify the format of the encapsulated bitstream. + { + // Note: not in the IANA registry. + AUDIO_FORMAT_IEC61937, + make_AudioFormatDescription(media::PcmType::INT_16_BIT, "audio/x-iec61937") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_DOLBY_TRUEHD, make_AudioFormatDescription("audio/vnd.dolby.truehd") + }, + { + AUDIO_FORMAT_EVRC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRC) + }, + { + AUDIO_FORMAT_EVRCB, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRCB) + }, + { + AUDIO_FORMAT_EVRCWB, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRCWB) + }, + { + AUDIO_FORMAT_EVRCNW, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRCNW) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADIF, make_AudioFormatDescription("audio/aac.adif") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_WMA, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_WMA) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_WMA_PRO, make_AudioFormatDescription("audio/x-ms-wma.pro") + }, + { + AUDIO_FORMAT_AMR_WB_PLUS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MP2, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II) + }, + { + AUDIO_FORMAT_QCELP, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_QCELP) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_DSD, make_AudioFormatDescription("audio/vnd.sony.dsd") + }, + { + AUDIO_FORMAT_FLAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_FLAC) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_ALAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_ALAC) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_APE, make_AudioFormatDescription("audio/x-ape") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_MAIN, make_AudioFormatDescription("audio/aac-adts.main") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_LC, make_AudioFormatDescription("audio/aac-adts.lc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_SSR, make_AudioFormatDescription("audio/aac-adts.ssr") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_LTP, make_AudioFormatDescription("audio/aac-adts.ltp") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_HE_V1, make_AudioFormatDescription("audio/aac-adts.he.v1") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_SCALABLE, make_AudioFormatDescription("audio/aac-adts.scalable") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_ERLC, make_AudioFormatDescription("audio/aac-adts.erlc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_LD, make_AudioFormatDescription("audio/aac-adts.ld") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_HE_V2, make_AudioFormatDescription("audio/aac-adts.he.v2") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_ELD, make_AudioFormatDescription("audio/aac-adts.eld") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_ADTS_XHE, make_AudioFormatDescription("audio/aac-adts.xhe") + }, + { + // Note: not in the IANA registry. "vnd.octel.sbc" is not BT SBC. + AUDIO_FORMAT_SBC, make_AudioFormatDescription("audio/x-sbc") + }, + { + AUDIO_FORMAT_APTX, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_APTX) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_APTX_HD, make_AudioFormatDescription("audio/vnd.qcom.aptx.hd") + }, + { + // Note: not in the IANA registry. Matches MediaDefs.cpp. + AUDIO_FORMAT_AC4, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AC4) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_LDAC, make_AudioFormatDescription("audio/vnd.sony.ldac") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MAT, make_AudioFormatDescription("audio/vnd.dolby.mat") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MAT_1_0, make_AudioFormatDescription("audio/vnd.dolby.mat.1.0") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MAT_2_0, make_AudioFormatDescription("audio/vnd.dolby.mat.2.0") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MAT_2_1, make_AudioFormatDescription("audio/vnd.dolby.mat.2.1") + }, + { + AUDIO_FORMAT_AAC_LATM, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC) + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LATM_LC, make_AudioFormatDescription("audio/mp4a-latm.lc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LATM_HE_V1, make_AudioFormatDescription("audio/mp4a-latm.he.v1") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_AAC_LATM_HE_V2, make_AudioFormatDescription("audio/mp4a-latm.he.v2") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_CELT, make_AudioFormatDescription("audio/x-celt") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_APTX_ADAPTIVE, make_AudioFormatDescription("audio/vnd.qcom.aptx.adaptive") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_LHDC, make_AudioFormatDescription("audio/vnd.savitech.lhdc") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_LHDC_LL, make_AudioFormatDescription("audio/vnd.savitech.lhdc.ll") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_APTX_TWSP, make_AudioFormatDescription("audio/vnd.qcom.aptx.twsp") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_LC3, make_AudioFormatDescription("audio/x-lc3") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MPEGH, make_AudioFormatDescription("audio/x-mpegh") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MPEGH_BL_L3, make_AudioFormatDescription("audio/x-mpegh.bl.l3") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MPEGH_BL_L4, make_AudioFormatDescription("audio/x-mpegh.bl.l4") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MPEGH_LC_L3, make_AudioFormatDescription("audio/x-mpegh.lc.l3") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_MPEGH_LC_L4, make_AudioFormatDescription("audio/x-mpegh.lc.l4") + }, + { + // Note: not in the IANA registry. + AUDIO_FORMAT_IEC60958, + make_AudioFormatDescription(media::PcmType::INT_24_BIT, "audio/x-iec60958") + }, + { + AUDIO_FORMAT_DTS_UHD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DTS_UHD) + }, + { + AUDIO_FORMAT_DRA, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DRA) + }, + }}; + return pairs; +} + +} // namespace + +ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( + const media::AudioFormatDescription& aidl) { + static const std::unordered_map m = + [](const detail::AudioFormatPairs& f) { + std::unordered_map r; + std::transform(f.begin(), f.end(), std::inserter(r, r.begin()), + [](const detail::AudioFormatPair& p) { + return std::make_pair(p.second, p.first); + }); + return r; + }(getAudioFormatPairs()); + if (auto it = m.find(aidl); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no legacy audio_format_t found for %s", __func__, aidl.toString().c_str()); + return unexpected(BAD_VALUE); + } +} + +ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( + audio_format_t legacy) { + static const std::unordered_map m = + [](const detail::AudioFormatPairs& f) { + return std::unordered_map( + f.begin(), f.end()); }(getAudioFormatPairs()); + if (auto it = m.find(legacy); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no AudioFormatDescription found for legacy audio_format_t value 0x%x", + __func__, legacy); + return unexpected(BAD_VALUE); + } +} + ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl) { switch (aidl) { case media::AudioGainMode::JOINT: diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 4652a18513..809a26b4cc 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -229,6 +229,7 @@ cc_library { "libbinder", "liblog", "libshmemcompat", + "libstagefright_foundation", "libutils", "shared-file-region-aidl-cpp", "framework-permission-aidl-cpp", @@ -312,6 +313,8 @@ aidl_interface { "aidl/android/media/AudioEncapsulationMode.aidl", "aidl/android/media/AudioEncapsulationMetadataType.aidl", "aidl/android/media/AudioEncapsulationType.aidl", + "aidl/android/media/AudioFormatDescription.aidl", + "aidl/android/media/AudioFormatType.aidl", "aidl/android/media/AudioFormatSys.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", @@ -352,6 +355,7 @@ aidl_interface { "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", "aidl/android/media/ExtraAudioDescriptor.aidl", + "aidl/android/media/PcmType.aidl", "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ diff --git a/media/libaudioclient/TEST_MAPPING b/media/libaudioclient/TEST_MAPPING new file mode 100644 index 0000000000..d8c18c040d --- /dev/null +++ b/media/libaudioclient/TEST_MAPPING @@ -0,0 +1,7 @@ +{ + "presubmit": [ + { + "name": "audio_aidl_conversion_tests" + } + ] +} diff --git a/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl b/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl new file mode 100644 index 0000000000..a6563485f6 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.AudioFormatType; +import android.media.PcmType; + +/** + * An extensible type for specifying audio formats. All formats are largely + * divided into two classes: PCM and non-PCM (bitstreams). Bitstreams can + * be encapsulated into PCM streams. + * + * The type defined in a way to make each format uniquely identifiable, so + * that if the framework and the HAL construct a value for the same type + * (e.g. PCM 16 bit), they will produce identical parcelables which will have + * identical hashes. This makes possible deduplicating type descriptions + * by the framework when they are received from different HAL modules without + * relying on having some centralized registry of enumeration values. + * + * {@hide} + */ +parcelable AudioFormatDescription { + /** + * The type of the audio format. See the 'AudioFormatType' for the + * list of supported values. + */ + AudioFormatType type = AudioFormatType.DEFAULT; + /** + * The type of the PCM stream or the transport stream for PCM + * encapsulations. See 'PcmType' for the list of supported values. + */ + PcmType pcm = PcmType.DEFAULT; + /** + * Optional encoding specification. Must be left empty when: + * + * - 'type == DEFAULT && pcm == DEFAULT' -- that means "default" type; + * - 'type == PCM' -- that means a regular PCM stream (not an encapsulation + * of an encoded bitstream). + * + * For PCM encapsulations of encoded bitstreams (e.g. an encapsulation + * according to IEC-61937 standard), the value of the 'pcm' field must + * be set accordingly, as an example, PCM_INT_16_BIT must be used for + * IEC-61937. Note that 'type == NON_PCM' in this case. + * + * Encoding names mostly follow IANA standards for media types (MIME), and + * frameworks/av/media/libstagefright/foundation/MediaDefs.cpp with the + * latter having priority. Since there are still many audio types not found + * in any of these lists, the following rules are applied: + * + * - If there is a direct MIME type for the encoding, the MIME type name + * is used as is, e.g. "audio/eac3" for the EAC-3 format. + * - If the encoding is a "subformat" of a MIME-registered format, + * the latter is augmented with a suffix, e.g. "audio/eac3-joc" for the + * JOC extension of EAC-3. + * - If it's a proprietary format, a "vnd." prefix is added, similar to + * IANA rules, e.g. "audio/vnd.dolby.truehd". + * - Otherwise, "x-" prefix is added, e.g. "audio/x-iec61937". + * - All MIME types not found in the IANA formats list have an associated + * comment. + * + * For PCM encapsulations with a known bitstream format, the latter + * is added to the encapsulation encoding as a suffix, after a "+" char. + * For example, an IEC61937 encapsulation of AC3 has the following + * representation: + * type = NON_PCM, + * pcm = PcmType.INT_16_BIT, + * encoding = "audio/x-iec61937+audio/ac3" + */ + @utf8InCpp String encoding; +} diff --git a/media/libaudioclient/aidl/android/media/AudioFormatType.aidl b/media/libaudioclient/aidl/android/media/AudioFormatType.aidl new file mode 100644 index 0000000000..31ed2be376 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioFormatType.aidl @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * The type of the audio format. Only used as part of 'AudioFormatDescription' + * structure. + */ +@Backing(type="byte") +enum AudioFormatType { + /** + * "Default" type is used when the client does not care about the actual + * format. All fields of 'AudioFormatDescription' must have default / empty + * / null values. + */ + DEFAULT = 0, + /** + * When the 'encoding' field of 'AudioFormatDescription' is not empty, it + * specifies the codec used for bitstream (non-PCM) data. It is also used + * in the case when the bitstream data is encapsulated into a PCM stream, + * see the documentation for 'AudioFormatDescription'. + */ + NON_PCM = DEFAULT, + /** + * PCM type. The 'pcm' field of 'AudioFormatDescription' is used to specify + * the actual sample size and representation. + */ + PCM = 1, + /** + * Value reserved for system use only. HALs must never return this value to + * the system or accept it from the system. + */ + SYS_RESERVED_INVALID = -1, +} diff --git a/media/libaudioclient/aidl/android/media/PcmType.aidl b/media/libaudioclient/aidl/android/media/PcmType.aidl new file mode 100644 index 0000000000..c9e327cb71 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/PcmType.aidl @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * The type of the encoding used for representing PCM samples. Only used as + * part of 'AudioFormatDescription' structure. + */ +@Backing(type="byte") +enum PcmType { + /** + * "Default" value used when the type 'AudioFormatDescription' is "default". + */ + DEFAULT = 0, + /** + * Unsigned 8-bit integer. + */ + UINT_8_BIT = DEFAULT, + /** + * Signed 16-bit integer. + */ + INT_16_BIT = 1, + /** + * Signed 32-bit integer. + */ + INT_32_BIT = 2, + /** + * Q8.24 fixed point format. + */ + FIXED_Q_8_24 = 3, + /** + * IEEE 754 32-bit floating point format. + */ + FLOAT_32_BIT = 4, + /** + * Signed 24-bit integer. + */ + INT_24_BIT = 5, +} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index fc8a1e8681..305dbc3d06 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -138,6 +139,11 @@ ConversionResult aidl2legacy_AudioFormat_audio_format_t( ConversionResult legacy2aidl_audio_format_t_AudioFormat( audio_format_t legacy); +ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( + const media::AudioFormatDescription& aidl); +ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( + audio_format_t legacy); + ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl); ConversionResult diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index 5dfe5fc9c3..607b99c9c0 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -17,9 +17,39 @@ #pragma once +#include + +#include +#include #include #include -#include + +namespace { +// see boost::hash_combine +#if defined(__clang__) +__attribute__((no_sanitize("unsigned-integer-overflow"))) +#endif +static size_t hash_combine(size_t seed, size_t v) { + return std::hash{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); +} +} + +namespace std { + +// Note: when extending AudioFormatDescription we need to account for the +// possibility of comparison between different versions of it, e.g. a HAL +// may be using a previous version of the AIDL interface. +template<> struct hash +{ + std::size_t operator()(const android::media::AudioFormatDescription& afd) const noexcept { + return hash_combine( + std::hash{}(afd.type), + hash_combine( + std::hash{}(afd.pcm), + std::hash{}(afd.encoding))); + } +}; +} // namespace std namespace android { @@ -45,4 +75,3 @@ enum volume_group_t : uint32_t; static const volume_group_t VOLUME_GROUP_NONE = static_cast(-1); } // namespace android - diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp index def7ca6bfc..2279244f8b 100644 --- a/media/libaudioclient/tests/Android.bp +++ b/media/libaudioclient/tests/Android.bp @@ -9,10 +9,34 @@ package { cc_defaults { name: "libaudioclient_tests_defaults", + test_suites: ["device-tests"], cflags: [ "-Wall", "-Werror", ], + sanitize: { + misc_undefined: [ + "unsigned-integer-overflow", + "signed-integer-overflow", + ], + }, +} + +cc_test { + name: "audio_aidl_conversion_tests", + defaults: ["libaudioclient_tests_defaults"], + srcs: ["audio_aidl_legacy_conversion_tests.cpp"], + shared_libs: [ + "libbinder", + "libcutils", + "liblog", + "libutils", + ], + static_libs: [ + "audioclient-types-aidl-cpp", + "libaudioclient_aidl_conversion", + "libstagefright_foundation", + ], } cc_test { @@ -30,8 +54,10 @@ cc_test { cc_test { name: "test_create_audiotrack", defaults: ["libaudioclient_tests_defaults"], - srcs: ["test_create_audiotrack.cpp", - "test_create_utils.cpp"], + srcs: [ + "test_create_audiotrack.cpp", + "test_create_utils.cpp", + ], header_libs: [ "libmedia_headers", "libmediametrics_headers", @@ -49,8 +75,10 @@ cc_test { cc_test { name: "test_create_audiorecord", defaults: ["libaudioclient_tests_defaults"], - srcs: ["test_create_audiorecord.cpp", - "test_create_utils.cpp"], + srcs: [ + "test_create_audiorecord.cpp", + "test_create_utils.cpp", + ], header_libs: [ "libmedia_headers", "libmediametrics_headers", diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp new file mode 100644 index 0000000000..e4bc9f06b3 --- /dev/null +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +using namespace android; +using namespace android::aidl_utils; + +namespace { + +size_t afdHash(const media::AudioFormatDescription& afd) { + return std::hash{}(afd); +} + +media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { + media::AudioFormatDescription result; + result.type = type; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(media::PcmType pcm) { + auto result = make_AudioFormatDescription(media::AudioFormatType::PCM); + result.pcm = pcm; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { + media::AudioFormatDescription result; + result.encoding = encoding; + return result; +} + +media::AudioFormatDescription make_AudioFormatDescription(media::PcmType transport, + const std::string& encoding) { + auto result = make_AudioFormatDescription(encoding); + result.pcm = transport; + return result; +} + +media::AudioFormatDescription make_AFD_Invalid() { + return make_AudioFormatDescription(media::AudioFormatType::SYS_RESERVED_INVALID); +} + +media::AudioFormatDescription make_AFD_Pcm16Bit() { + return make_AudioFormatDescription(media::PcmType::INT_16_BIT); +} + +media::AudioFormatDescription make_AFD_Bitstream() { + return make_AudioFormatDescription("example"); +} + +media::AudioFormatDescription make_AFD_Encap() { + return make_AudioFormatDescription(media::PcmType::INT_16_BIT, "example.encap"); +} + +media::AudioFormatDescription make_AFD_Encap_with_Enc() { + auto afd = make_AFD_Encap(); + afd.encoding += "+example"; + return afd; +} + +} // namespace + +// Verify that two independently constructed AFDs have the same hash. +// This ensures that regardless of whether the AFD instance originates +// from, it can be correctly compared to other AFD instance. Thus, +// for example, a 16-bit integer format description provided by HAL +// is identical to the same format description constructed by the framework. +TEST(audio_aidl_legacy_conversion_tests, AudioFormatDescriptionHashIdentity) { + EXPECT_EQ(afdHash(make_AFD_Invalid()), afdHash(make_AFD_Invalid())); + EXPECT_EQ(afdHash(media::AudioFormatDescription{}), afdHash(media::AudioFormatDescription{})); + EXPECT_EQ(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Pcm16Bit())); + EXPECT_NE(afdHash(media::AudioFormatDescription{}), afdHash(make_AFD_Invalid())); + EXPECT_NE(afdHash(media::AudioFormatDescription{}), afdHash(make_AFD_Pcm16Bit())); + EXPECT_EQ(afdHash(make_AFD_Bitstream()), afdHash(make_AFD_Bitstream())); + EXPECT_NE(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Bitstream())); + EXPECT_EQ(afdHash(make_AFD_Encap()), afdHash(make_AFD_Encap())); + EXPECT_NE(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Encap())); + EXPECT_EQ(afdHash(make_AFD_Encap_with_Enc()), afdHash(make_AFD_Encap_with_Enc())); + EXPECT_NE(afdHash(make_AFD_Encap()), afdHash(make_AFD_Encap_with_Enc())); +} + +class AudioFormatDescriptionRoundTripTest : + public testing::TestWithParam {}; +TEST_P(AudioFormatDescriptionRoundTripTest, Aidl2Legacy2Aidl) { + const auto initial = GetParam(); + auto conv = aidl2legacy_AudioFormatDescription_audio_format_t(initial); + ASSERT_TRUE(conv.ok()); + auto convBack = legacy2aidl_audio_format_t_AudioFormatDescription(conv.value()); + ASSERT_TRUE(convBack.ok()); + EXPECT_EQ(initial, convBack.value()); +} +INSTANTIATE_TEST_SUITE_P(AudioFormatDescriptionRoundTrip, + AudioFormatDescriptionRoundTripTest, + testing::Values(make_AFD_Invalid(), media::AudioFormatDescription{}, make_AFD_Pcm16Bit())); diff --git a/media/libstagefright/foundation/MediaDefs.cpp b/media/libstagefright/foundation/MediaDefs.cpp index ada5d818b1..0ec5ad5c3f 100644 --- a/media/libstagefright/foundation/MediaDefs.cpp +++ b/media/libstagefright/foundation/MediaDefs.cpp @@ -65,7 +65,17 @@ const char *MEDIA_MIMETYPE_AUDIO_ALAC = "audio/alac"; const char *MEDIA_MIMETYPE_AUDIO_WMA = "audio/x-ms-wma"; const char *MEDIA_MIMETYPE_AUDIO_MS_ADPCM = "audio/x-adpcm-ms"; const char *MEDIA_MIMETYPE_AUDIO_DVI_IMA_ADPCM = "audio/x-adpcm-dvi-ima"; - +const char *MEDIA_MIMETYPE_AUDIO_DTS = "audio/vnd.dts"; +const char *MEDIA_MIMETYPE_AUDIO_DTS_HD = "audio/vnd.dts.hd"; +const char *MEDIA_MIMETYPE_AUDIO_DTS_UHD = "audio/vnd.dts.uhd"; +const char *MEDIA_MIMETYPE_AUDIO_EVRC = "audio/evrc"; +const char *MEDIA_MIMETYPE_AUDIO_EVRCB = "audio/evrcb"; +const char *MEDIA_MIMETYPE_AUDIO_EVRCWB = "audio/evrcwb"; +const char *MEDIA_MIMETYPE_AUDIO_EVRCNW = "audio/evrcnw"; +const char *MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS = "audio/amr-wb+"; +const char *MEDIA_MIMETYPE_AUDIO_APTX = "audio/aptx"; +const char *MEDIA_MIMETYPE_AUDIO_DRA = "audio/vnd.dra"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_FORMAT = "audio/aac"; const char *MEDIA_MIMETYPE_CONTAINER_MPEG4 = "video/mp4"; const char *MEDIA_MIMETYPE_CONTAINER_WAV = "audio/x-wav"; diff --git a/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h b/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h index f5ceceffd9..afa0c6ddc3 100644 --- a/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h +++ b/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h @@ -67,7 +67,17 @@ extern const char *MEDIA_MIMETYPE_AUDIO_ALAC; extern const char *MEDIA_MIMETYPE_AUDIO_WMA; extern const char *MEDIA_MIMETYPE_AUDIO_MS_ADPCM; extern const char *MEDIA_MIMETYPE_AUDIO_DVI_IMA_ADPCM; - +extern const char *MEDIA_MIMETYPE_AUDIO_DTS; +extern const char *MEDIA_MIMETYPE_AUDIO_DTS_HD; +extern const char *MEDIA_MIMETYPE_AUDIO_DTS_UHD; +extern const char *MEDIA_MIMETYPE_AUDIO_EVRC; +extern const char *MEDIA_MIMETYPE_AUDIO_EVRCB; +extern const char *MEDIA_MIMETYPE_AUDIO_EVRCWB; +extern const char *MEDIA_MIMETYPE_AUDIO_EVRCNW; +extern const char *MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS; +extern const char *MEDIA_MIMETYPE_AUDIO_APTX; +extern const char *MEDIA_MIMETYPE_AUDIO_DRA; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_FORMAT; extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG4; extern const char *MEDIA_MIMETYPE_CONTAINER_WAV; -- GitLab From 190a2d56157f269be5299dd88d85d03c3fd59ac7 Mon Sep 17 00:00:00 2001 From: Ray Chi Date: Tue, 1 Jun 2021 16:40:33 +0800 Subject: [PATCH 052/694] MTP: add a new parameter for cancelEvents function Currently, cancelEvents in MTP will cancel the requests one by one, and it will check each response to confirm success or failure. However, if kernel usb controller driver got the cancel request, the driver will handle all requests in the same endpoint so that the second io_cancel in cancelEvents will be useless. This behavior change start from kernel 5.x. This patch will add a parameter to check whether kernel usb controller driver uses the new behavior so that MTP could cancel the requests correctly. Bug: 181729410 Test: cancel a transmitting file and then check the MTP operation Change-Id: I8a2097e40feaa880de1d57921f5363eb98dbeb44 Merged-In: I8a2097e40feaa880de1d57921f5363eb98dbeb44 (cherry picked from commit 305e62ec197f65ebf29d79e8d03ea3b296b4e690) (cherry picked from commit bd3a649f47df22b43dbcb844ffa9218c1f919f96) --- media/mtp/MtpFfsHandle.cpp | 14 ++++++++++---- media/mtp/MtpFfsHandle.h | 5 ++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/media/mtp/MtpFfsHandle.cpp b/media/mtp/MtpFfsHandle.cpp index c8b4a03d3d..4d50d6697c 100644 --- a/media/mtp/MtpFfsHandle.cpp +++ b/media/mtp/MtpFfsHandle.cpp @@ -74,6 +74,7 @@ int MtpFfsHandle::getPacketSize(int ffs_fd) { MtpFfsHandle::MtpFfsHandle(int controlFd) { mControl.reset(controlFd); + mBatchCancel = android::base::GetBoolProperty("sys.usb.mtp.batchcancel", false); } MtpFfsHandle::~MtpFfsHandle() {} @@ -370,7 +371,7 @@ void MtpFfsHandle::cancelTransaction() { } int MtpFfsHandle::cancelEvents(struct iocb **iocb, struct io_event *events, unsigned start, - unsigned end) { + unsigned end, bool is_batch_cancel) { // Some manpages for io_cancel are out of date and incorrect. // io_cancel will return -EINPROGRESS on success and does // not place the event in the given memory. We have to use @@ -386,6 +387,10 @@ int MtpFfsHandle::cancelEvents(struct iocb **iocb, struct io_event *events, unsi } else { num_events++; } + if (is_batch_cancel && num_events == 1) { + num_events = end - start; + break; + } } if (num_events != end - start) { ret = -1; @@ -495,7 +500,8 @@ int MtpFfsHandle::receiveFile(mtp_file_range mfr, bool zero_packet) { num_events += this_events; if (event_ret == -1) { - cancelEvents(mIobuf[i].iocb.data(), ioevs, num_events, mIobuf[i].actual); + cancelEvents(mIobuf[i].iocb.data(), ioevs, num_events, mIobuf[i].actual, + mBatchCancel); return -1; } ret += event_ret; @@ -512,7 +518,7 @@ int MtpFfsHandle::receiveFile(mtp_file_range mfr, bool zero_packet) { } } if (short_packet) { - if (cancelEvents(mIobuf[i].iocb.data(), ioevs, short_i, mIobuf[i].actual)) { + if (cancelEvents(mIobuf[i].iocb.data(), ioevs, short_i, mIobuf[i].actual, false)) { write_error = true; } } @@ -613,7 +619,7 @@ int MtpFfsHandle::sendFile(mtp_file_range mfr) { &num_events) != ret) { error = true; cancelEvents(mIobuf[(i-1)%NUM_IO_BUFS].iocb.data(), ioevs, num_events, - mIobuf[(i-1)%NUM_IO_BUFS].actual); + mIobuf[(i-1)%NUM_IO_BUFS].actual, false); } has_write = false; } diff --git a/media/mtp/MtpFfsHandle.h b/media/mtp/MtpFfsHandle.h index fe343f74f6..e552e03bec 100644 --- a/media/mtp/MtpFfsHandle.h +++ b/media/mtp/MtpFfsHandle.h @@ -17,6 +17,7 @@ #ifndef _MTP_FFS_HANDLE_H #define _MTP_FFS_HANDLE_H +#include #include #include #include @@ -57,6 +58,7 @@ protected: static int getPacketSize(int ffs_fd); bool mCanceled; + bool mBatchCancel; android::base::unique_fd mControl; // "in" from the host's perspective => sink for mtp server @@ -76,7 +78,8 @@ protected: int iobufSubmit(struct io_buffer *buf, int fd, unsigned length, bool read); // Cancel submitted requests from start to end in the given array. Return 0 or -1. - int cancelEvents(struct iocb **iocb, struct io_event *events, unsigned start, unsigned end); + int cancelEvents(struct iocb **iocb, struct io_event *events, unsigned start, unsigned end, + bool is_batch_cancel); // Wait for at minimum the given number of events. Returns the amount of data in the returned // events. Increments counter by the number of events returned. -- GitLab From 09a73810255e97081121bd3fd072140a12ec4c1f Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 17 Jun 2021 18:00:55 -0700 Subject: [PATCH 053/694] Define an extensible audio device description The new way for describing audio devices which can be used both in framework <-> framework and framework <-> HAL interfaces and directly supports extensions by vendors. The mapping is defined between the legacy audio_devices_t and the new descriptions. Bug: 188932434 Test: atest audio_aidl_conversion_tests Change-Id: Ifef9fdb510e21765aa548a2877edb84cdf46ac75 --- media/libaudioclient/AidlConversion.cpp | 251 +++++++++++++++++- media/libaudioclient/Android.bp | 2 + .../android/media/AudioDeviceDescription.aidl | 101 +++++++ .../aidl/android/media/AudioDeviceType.aidl | 158 +++++++++++ .../include/media/AidlConversion.h | 6 + .../include/media/AudioCommonTypes.h | 12 +- .../audio_aidl_legacy_conversion_tests.cpp | 98 +++++-- 7 files changed, 600 insertions(+), 28 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioDeviceType.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 8f3d9962ec..fa78f43e31 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -412,10 +412,205 @@ ConversionResult legacy2aidl_audio_format_t_AudioFormat( namespace { namespace detail { +using AudioDevicePair = std::pair; +using AudioDevicePairs = std::vector; using AudioFormatPair = std::pair; using AudioFormatPairs = std::vector; } +media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, + const std::string& connection = "") { + media::AudioDeviceDescription result; + result.type = type; + result.connection = connection; + return result; +} + +void append_AudioDeviceDescription(detail::AudioDevicePairs& pairs, + audio_devices_t inputType, audio_devices_t outputType, + media::AudioDeviceType inType, media::AudioDeviceType outType, + const std::string& connection = "") { + pairs.push_back(std::make_pair(inputType, make_AudioDeviceDescription(inType, connection))); + pairs.push_back(std::make_pair(outputType, make_AudioDeviceDescription(outType, connection))); +} + +const detail::AudioDevicePairs& getAudioDevicePairs() { + static const detail::AudioDevicePairs pairs = []() { + detail::AudioDevicePairs pairs = {{ + { + AUDIO_DEVICE_NONE, media::AudioDeviceDescription{} + }, + { + AUDIO_DEVICE_OUT_EARPIECE, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_SPEAKER_EARPIECE) + }, + { + AUDIO_DEVICE_OUT_SPEAKER, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_SPEAKER) + }, + { + AUDIO_DEVICE_OUT_WIRED_HEADPHONE, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_HEADPHONE, + media::AudioDeviceDescription::CONNECTION_ANALOG()) + }, + { + AUDIO_DEVICE_OUT_BLUETOOTH_SCO, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_BT_SCO()) + }, + { + AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_CARKIT, + media::AudioDeviceDescription::CONNECTION_BT_SCO()) + }, + { + AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_HEADPHONE, + media::AudioDeviceDescription::CONNECTION_BT_A2DP()) + }, + { + AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_SPEAKER, + media::AudioDeviceDescription::CONNECTION_BT_A2DP()) + }, + { + AUDIO_DEVICE_OUT_TELEPHONY_TX, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_TELEPHONY_TX) + }, + { + AUDIO_DEVICE_OUT_AUX_LINE, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_LINE_AUX) + }, + { + AUDIO_DEVICE_OUT_SPEAKER_SAFE, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_SPEAKER_SAFE) + }, + { + AUDIO_DEVICE_OUT_HEARING_AID, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_HEARING_AID, + media::AudioDeviceDescription::CONNECTION_WIRELESS()) + }, + { + AUDIO_DEVICE_OUT_ECHO_CANCELLER, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_ECHO_CANCELLER) + }, + { + AUDIO_DEVICE_OUT_BLE_SPEAKER, make_AudioDeviceDescription( + media::AudioDeviceType::OUT_SPEAKER, + media::AudioDeviceDescription::CONNECTION_BT_LE()) + }, + // AUDIO_DEVICE_IN_AMBIENT and IN_COMMUNICATION are removed since they were deprecated. + { + AUDIO_DEVICE_IN_BUILTIN_MIC, make_AudioDeviceDescription( + media::AudioDeviceType::IN_MICROPHONE) + }, + { + AUDIO_DEVICE_IN_BACK_MIC, make_AudioDeviceDescription( + media::AudioDeviceType::IN_MICROPHONE_BACK) + }, + { + AUDIO_DEVICE_IN_TELEPHONY_RX, make_AudioDeviceDescription( + media::AudioDeviceType::IN_TELEPHONY_RX) + }, + { + AUDIO_DEVICE_IN_TV_TUNER, make_AudioDeviceDescription( + media::AudioDeviceType::IN_TV_TUNER) + }, + { + AUDIO_DEVICE_IN_LOOPBACK, make_AudioDeviceDescription( + media::AudioDeviceType::IN_LOOPBACK) + }, + { + AUDIO_DEVICE_IN_BLUETOOTH_BLE, make_AudioDeviceDescription( + media::AudioDeviceType::IN_DEVICE, + media::AudioDeviceDescription::CONNECTION_BT_LE()) + }, + { + AUDIO_DEVICE_IN_ECHO_REFERENCE, make_AudioDeviceDescription( + media::AudioDeviceType::IN_ECHO_REFERENCE) + } + }}; + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_DEFAULT, AUDIO_DEVICE_OUT_DEFAULT, + media::AudioDeviceType::IN_DEFAULT, media::AudioDeviceType::OUT_DEFAULT); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_ANALOG()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_BT_SCO()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_HDMI, AUDIO_DEVICE_OUT_HDMI, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_HDMI()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX, + media::AudioDeviceType::IN_SUBMIX, media::AudioDeviceType::OUT_SUBMIX); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_ANALOG_DOCK()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_DIGITAL_DOCK()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_USB_ACCESSORY, AUDIO_DEVICE_OUT_USB_ACCESSORY, + media::AudioDeviceType::IN_ACCESSORY, media::AudioDeviceType::OUT_ACCESSORY, + media::AudioDeviceDescription::CONNECTION_USB()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_OUT_USB_DEVICE, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_USB()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_FM_TUNER, AUDIO_DEVICE_OUT_FM, + media::AudioDeviceType::IN_FM_TUNER, media::AudioDeviceType::OUT_FM); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_LINE, AUDIO_DEVICE_OUT_LINE, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_ANALOG()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_SPDIF, AUDIO_DEVICE_OUT_SPDIF, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_SPDIF()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_BT_A2DP()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_IP, AUDIO_DEVICE_OUT_IP, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_IP_V4()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_OUT_BUS, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_BUS()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_PROXY, AUDIO_DEVICE_OUT_PROXY, + media::AudioDeviceType::IN_AFE_PROXY, media::AudioDeviceType::OUT_AFE_PROXY); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_OUT_USB_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_USB()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_ARC, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_HDMI_ARC()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_HDMI_EARC, AUDIO_DEVICE_OUT_HDMI_EARC, + media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, + media::AudioDeviceDescription::CONNECTION_HDMI_EARC()); + append_AudioDeviceDescription(pairs, + AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_OUT_BLE_HEADSET, + media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_BT_LE()); + return pairs; + }(); + return pairs; +} + media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { media::AudioFormatDescription result; result.type = type; @@ -768,19 +963,55 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { return pairs; } +template +std::unordered_map make_DirectMap(const std::vector>& v) { + std::unordered_map result(v.begin(), v.end()); + LOG_ALWAYS_FATAL_IF(result.size() != v.size(), "Duplicate key elements detected"); + return result; +} + +template +std::unordered_map make_ReverseMap(const std::vector>& v) { + std::unordered_map result; + std::transform(v.begin(), v.end(), std::inserter(result, result.begin()), + [](const std::pair& p) { + return std::make_pair(p.second, p.first); + }); + LOG_ALWAYS_FATAL_IF(result.size() != v.size(), "Duplicate key elements detected"); + return result; +} + } // namespace +ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( + const media::AudioDeviceDescription& aidl) { + static const std::unordered_map m = + make_ReverseMap(getAudioDevicePairs()); + if (auto it = m.find(aidl); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no legacy audio_devices_t found for %s", __func__, aidl.toString().c_str()); + return unexpected(BAD_VALUE); + } +} + +ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( + audio_devices_t legacy) { + static const std::unordered_map m = + make_DirectMap(getAudioDevicePairs()); + if (auto it = m.find(legacy); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no AudioDeviceDescription found for legacy audio_devices_t value 0x%x", + __func__, legacy); + return unexpected(BAD_VALUE); + } +} + ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( const media::AudioFormatDescription& aidl) { static const std::unordered_map m = - [](const detail::AudioFormatPairs& f) { - std::unordered_map r; - std::transform(f.begin(), f.end(), std::inserter(r, r.begin()), - [](const detail::AudioFormatPair& p) { - return std::make_pair(p.second, p.first); - }); - return r; - }(getAudioFormatPairs()); + make_ReverseMap(getAudioFormatPairs()); if (auto it = m.find(aidl); it != m.end()) { return it->second; } else { @@ -792,9 +1023,7 @@ ConversionResult aidl2legacy_AudioFormatDescription_audio_format ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( audio_format_t legacy) { static const std::unordered_map m = - [](const detail::AudioFormatPairs& f) { - return std::unordered_map( - f.begin(), f.end()); }(getAudioFormatPairs()); + make_DirectMap(getAudioFormatPairs()); if (auto it = m.find(legacy); it != m.end()) { return it->second; } else { diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 809a26b4cc..a23c844933 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -309,6 +309,8 @@ aidl_interface { "aidl/android/media/AudioConfigBase.aidl", "aidl/android/media/AudioContentType.aidl", "aidl/android/media/AudioDevice.aidl", + "aidl/android/media/AudioDeviceDescription.aidl", + "aidl/android/media/AudioDeviceType.aidl", "aidl/android/media/AudioDualMonoMode.aidl", "aidl/android/media/AudioEncapsulationMode.aidl", "aidl/android/media/AudioEncapsulationMetadataType.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl b/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl new file mode 100644 index 0000000000..f7548b957f --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.AudioDeviceType; + +parcelable AudioDeviceDescription { + /** + * Type and directionality of the device. For bidirectional audio devices + * two descriptions need to be created, having the same value for + * the 'connection' field. + * + * See 'AudioDeviceType' for the list of supported values. + */ + AudioDeviceType type = AudioDeviceType.NONE; + /** + * Specifies the type of the connection of the device to the audio system. + * Usually it's some kind of a communication protocol, e.g. Bluetooth SCO or + * USB. There is a list of connection types recognized by the framework, + * defined using 'CONNECTION_' constants. Vendors can add their own + * connection types with "vx.." prefix. + * + * When the 'connection' field is left empty and 'type != NONE | DEFAULT', + * it is assumed that the device is permanently attached to the audio + * system, e.g. a built-in speaker or microphone. + * + * The 'connection' field must be left empty if 'type' is 'NONE' or + * '{IN|OUT}_DEFAULT'. + */ + @utf8InCpp String connection; + /** + * Analog connection, for example, via 3.5 mm analog jack. + */ + const @utf8InCpp String CONNECTION_ANALOG = "analog"; + /** + * Low-End (Analog) Desk Dock. + */ + const @utf8InCpp String CONNECTION_ANALOG_DOCK = "analog-dock"; + /** + * Bluetooth A2DP connection. + */ + const @utf8InCpp String CONNECTION_BT_A2DP = "bt-a2dp"; + /** + * Bluetooth Low Energy (LE) connection. + */ + const @utf8InCpp String CONNECTION_BT_LE = "bt-le"; + /** + * Bluetooth SCO connection. + */ + const @utf8InCpp String CONNECTION_BT_SCO = "bt-sco"; + /** + * Bus connection. Mostly used in automotive scenarios. + */ + const @utf8InCpp String CONNECTION_BUS = "bus"; + /** + * High-End (Digital) Desk Dock. + */ + const @utf8InCpp String CONNECTION_DIGITAL_DOCK = "digital-dock"; + /** + * HDMI connection. + */ + const @utf8InCpp String CONNECTION_HDMI = "hdmi"; + /** + * HDMI ARC connection. + */ + const @utf8InCpp String CONNECTION_HDMI_ARC = "hdmi-arc"; + /** + * HDMI eARC connection. + */ + const @utf8InCpp String CONNECTION_HDMI_EARC = "hdmi-earc"; + /** + * IP v4 connection. + */ + const @utf8InCpp String CONNECTION_IP_V4 = "ip-v4"; + /** + * SPDIF connection. + */ + const @utf8InCpp String CONNECTION_SPDIF = "spdif"; + /** + * A wireless connection when the actual protocol is unspecified. + */ + const @utf8InCpp String CONNECTION_WIRELESS = "wireless"; + /** + * USB connection. + */ + const @utf8InCpp String CONNECTION_USB = "usb"; +} diff --git a/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl b/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl new file mode 100644 index 0000000000..4da9fd66c3 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * The type of the audio device. Only used as part of 'AudioDeviceDescription' + * structure. + * + * Types are divided into "input" and "output" categories. Audio devices that + * have both audio input and output, for example, headsets, are represented by a + * pair of input and output device types. + * + * The 'AudioDeviceType' intentionally binds together directionality and 'kind' + * of the device to avoid making them fully orthogonal. This is because not all + * types of devices are bidirectional, for example, speakers can only be used + * for output and microphones can only be used for input (at least, in the + * context of the audio framework). + */ +@Backing(type="int") +enum AudioDeviceType { + /** + * "None" type is a "null" value. All fields of 'AudioDeviceDescription' + * must have default / empty / null values. + */ + NONE = 0, + /** + * The "default" device is used when the client does not have any + * preference for a particular device. + */ + IN_DEFAULT = 1, + /** + * A device implementing Android Open Accessory protocol. + */ + IN_ACCESSORY = 2, + /** + * Input from a DSP front-end proxy device. + */ + IN_AFE_PROXY = 3, + /** + * Used when only the connection protocol is known, e.g. a "HDMI Device." + */ + IN_DEVICE = 4, + /** + * A device providing reference input for echo canceller. + */ + IN_ECHO_REFERENCE = 5, + /** + * FM Tuner input. + */ + IN_FM_TUNER = 6, + /** + * A microphone of a headset. + */ + IN_HEADSET = 7, + /** + * Loopback input. + */ + IN_LOOPBACK = 8, + /** + * The main microphone (the frontal mic on mobile devices). + */ + IN_MICROPHONE = 9, + /** + * The secondary microphone (the back mic on mobile devices). + */ + IN_MICROPHONE_BACK = 10, + /** + * Input from a submix of other streams. + */ + IN_SUBMIX = 11, + /** + * Audio received via the telephone line. + */ + IN_TELEPHONY_RX = 12, + /** + * TV Tuner audio input. + */ + IN_TV_TUNER = 13, + /** + * The "default" device is used when the client does not have any + * preference for a particular device. + */ + OUT_DEFAULT = 129, + /** + * A device implementing Android Open Accessory protocol. + */ + OUT_ACCESSORY = 130, + /** + * Output from a DSP front-end proxy device. + */ + OUT_AFE_PROXY = 131, + /** + * Car audio system. + */ + OUT_CARKIT = 132, + /** + * Used when only the connection protocol is known, e.g. a "HDMI Device." + */ + OUT_DEVICE = 133, + /** + * The echo canceller device. + */ + OUT_ECHO_CANCELLER = 134, + /** + * The FM Tuner device. + */ + OUT_FM = 135, + /** + * Headphones. + */ + OUT_HEADPHONE = 136, + /** + * Headphones of a headset. + */ + OUT_HEADSET = 137, + /** + * Hearing aid. + */ + OUT_HEARING_AID = 138, + /** + * Secondary line level output. + */ + OUT_LINE_AUX = 139, + /** + * The main speaker. + */ + OUT_SPEAKER = 140, + /** + * The speaker of a mobile device in the case when it is close to the ear. + */ + OUT_SPEAKER_EARPIECE = 141, + /** + * The main speaker with overload / overheating protection. + */ + OUT_SPEAKER_SAFE = 142, + /** + * Output into a submix. + */ + OUT_SUBMIX = 143, + /** + * Output into a telephone line. + */ + OUT_TELEPHONY_TX = 144, +} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 305dbc3d06..422d94f8e6 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -139,6 +140,11 @@ ConversionResult aidl2legacy_AudioFormat_audio_format_t( ConversionResult legacy2aidl_audio_format_t_AudioFormat( audio_format_t legacy); +ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( + const media::AudioDeviceDescription& aidl); +ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( + audio_devices_t legacy); + ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( const media::AudioFormatDescription& aidl); ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index 607b99c9c0..613d6bd7d7 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -19,6 +19,7 @@ #include +#include #include #include #include @@ -36,9 +37,18 @@ static size_t hash_combine(size_t seed, size_t v) { namespace std { -// Note: when extending AudioFormatDescription we need to account for the +// Note: when extending Audio{Device|Format}Description we need to account for the // possibility of comparison between different versions of it, e.g. a HAL // may be using a previous version of the AIDL interface. +template<> struct hash +{ + std::size_t operator()(const android::media::AudioDeviceDescription& add) const noexcept { + return hash_combine( + std::hash{}(add.type), + std::hash{}(add.connection)); + } +}; + template<> struct hash { std::size_t operator()(const android::media::AudioFormatDescription& afd) const noexcept { diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index e4bc9f06b3..ca609ab0c4 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -24,10 +24,44 @@ using namespace android::aidl_utils; namespace { -size_t afdHash(const media::AudioFormatDescription& afd) { +size_t hash(const media::AudioDeviceDescription& add) { + return std::hash{}(add); +} + +size_t hash(const media::AudioFormatDescription& afd) { return std::hash{}(afd); } +media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, + const std::string& connection = "") { + media::AudioDeviceDescription result; + result.type = type; + result.connection = connection; + return result; +} + +media::AudioDeviceDescription make_ADD_None() { + return media::AudioDeviceDescription{}; +} + +media::AudioDeviceDescription make_ADD_DefaultIn() { + return make_AudioDeviceDescription(media::AudioDeviceType::IN_DEFAULT); +} + +media::AudioDeviceDescription make_ADD_DefaultOut() { + return make_AudioDeviceDescription(media::AudioDeviceType::OUT_DEFAULT); +} + +media::AudioDeviceDescription make_ADD_WiredHeadset() { + return make_AudioDeviceDescription(media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_ANALOG()); +} + +media::AudioDeviceDescription make_ADD_BtScoHeadset() { + return make_AudioDeviceDescription(media::AudioDeviceType::OUT_HEADSET, + media::AudioDeviceDescription::CONNECTION_BT_SCO()); +} + media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { media::AudioFormatDescription result; result.type = type; @@ -53,6 +87,10 @@ media::AudioFormatDescription make_AudioFormatDescription(media::PcmType transpo return result; } +media::AudioFormatDescription make_AFD_Default() { + return media::AudioFormatDescription{}; +} + media::AudioFormatDescription make_AFD_Invalid() { return make_AudioFormatDescription(media::AudioFormatType::SYS_RESERVED_INVALID); } @@ -77,24 +115,52 @@ media::AudioFormatDescription make_AFD_Encap_with_Enc() { } // namespace -// Verify that two independently constructed AFDs have the same hash. -// This ensures that regardless of whether the AFD instance originates -// from, it can be correctly compared to other AFD instance. Thus, +// Verify that two independently constructed ADDs/AFDs have the same hash. +// This ensures that regardless of whether the ADD/AFD instance originates +// from, it can be correctly compared to other ADD/AFD instance. Thus, // for example, a 16-bit integer format description provided by HAL // is identical to the same format description constructed by the framework. -TEST(audio_aidl_legacy_conversion_tests, AudioFormatDescriptionHashIdentity) { - EXPECT_EQ(afdHash(make_AFD_Invalid()), afdHash(make_AFD_Invalid())); - EXPECT_EQ(afdHash(media::AudioFormatDescription{}), afdHash(media::AudioFormatDescription{})); - EXPECT_EQ(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Pcm16Bit())); - EXPECT_NE(afdHash(media::AudioFormatDescription{}), afdHash(make_AFD_Invalid())); - EXPECT_NE(afdHash(media::AudioFormatDescription{}), afdHash(make_AFD_Pcm16Bit())); - EXPECT_EQ(afdHash(make_AFD_Bitstream()), afdHash(make_AFD_Bitstream())); - EXPECT_NE(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Bitstream())); - EXPECT_EQ(afdHash(make_AFD_Encap()), afdHash(make_AFD_Encap())); - EXPECT_NE(afdHash(make_AFD_Pcm16Bit()), afdHash(make_AFD_Encap())); - EXPECT_EQ(afdHash(make_AFD_Encap_with_Enc()), afdHash(make_AFD_Encap_with_Enc())); - EXPECT_NE(afdHash(make_AFD_Encap()), afdHash(make_AFD_Encap_with_Enc())); +class HashIdentityTest : public ::testing::Test { + public: + template void verifyHashIdentity(const std::vector>& valueGens) { + for (size_t i = 0; i < valueGens.size(); ++i) { + for (size_t j = 0; j < valueGens.size(); ++j) { + if (i == j) { + EXPECT_EQ(hash(valueGens[i]()), hash(valueGens[i]())) << i; + } else { + EXPECT_NE(hash(valueGens[i]()), hash(valueGens[j]())) << i << ", " << j; + } + } + } + } +}; + +TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { + verifyHashIdentity({ + make_ADD_None, make_ADD_DefaultIn, make_ADD_DefaultOut, make_ADD_WiredHeadset, + make_ADD_BtScoHeadset}); +} + +TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { + verifyHashIdentity({ + make_AFD_Default, make_AFD_Invalid, make_AFD_Pcm16Bit, make_AFD_Bitstream, + make_AFD_Encap, make_AFD_Encap_with_Enc}); +} + +class AudioDeviceDescriptionRoundTripTest : + public testing::TestWithParam {}; +TEST_P(AudioDeviceDescriptionRoundTripTest, Aidl2Legacy2Aidl) { + const auto initial = GetParam(); + auto conv = aidl2legacy_AudioDeviceDescription_audio_devices_t(initial); + ASSERT_TRUE(conv.ok()); + auto convBack = legacy2aidl_audio_devices_t_AudioDeviceDescription(conv.value()); + ASSERT_TRUE(convBack.ok()); + EXPECT_EQ(initial, convBack.value()); } +INSTANTIATE_TEST_SUITE_P(AudioDeviceDescriptionRoundTrip, + AudioDeviceDescriptionRoundTripTest, + testing::Values(media::AudioDeviceDescription{}, make_ADD_DefaultIn(), + make_ADD_DefaultOut(), make_ADD_WiredHeadset(), make_ADD_BtScoHeadset())); class AudioFormatDescriptionRoundTripTest : public testing::TestWithParam {}; -- GitLab From c3278fe1c1a1dd74e0ceed72ffd9cca75bb3ddff Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Wed, 23 Jun 2021 16:51:40 +0000 Subject: [PATCH 054/694] Start linear ramps at the initial volume set. Currently this ramp starts at 0 for the first ramp for no reason. Start this at the initial volume set. Bug: 190662772 Test: atest test_flowgraph#module_ramp_linear Change-Id: I24dde6fb2c725176a696f0277c5addf1da18f392 --- media/libaaudio/src/flowgraph/RampLinear.cpp | 4 ++++ media/libaaudio/tests/test_flowgraph.cpp | 23 ++++++++++++++------ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/media/libaaudio/src/flowgraph/RampLinear.cpp b/media/libaaudio/src/flowgraph/RampLinear.cpp index a260828696..0cc32e5c3a 100644 --- a/media/libaaudio/src/flowgraph/RampLinear.cpp +++ b/media/libaaudio/src/flowgraph/RampLinear.cpp @@ -37,6 +37,10 @@ void RampLinear::setLengthInFrames(int32_t frames) { void RampLinear::setTarget(float target) { mTarget.store(target); + // If the ramp has not been used then start immediately at this level. + if (mLastFramePosition < 0) { + forceCurrent(target); + } } float RampLinear::interpolateCurrent() { diff --git a/media/libaaudio/tests/test_flowgraph.cpp b/media/libaaudio/tests/test_flowgraph.cpp index d563a7e8da..611cbf7254 100644 --- a/media/libaaudio/tests/test_flowgraph.cpp +++ b/media/libaaudio/tests/test_flowgraph.cpp @@ -76,31 +76,40 @@ TEST(test_flowgraph, module_mono_to_stereo) { } TEST(test_flowgraph, module_ramp_linear) { + constexpr int singleNumOutput = 1; constexpr int rampSize = 5; constexpr int numOutput = 100; constexpr float value = 1.0f; - constexpr float target = 100.0f; + constexpr float initialTarget = 10.0f; + constexpr float finalTarget = 100.0f; + constexpr float tolerance = 0.0001f; // arbitrary float output[numOutput] = {}; RampLinear rampLinear{1}; SinkFloat sinkFloat{1}; rampLinear.input.setValue(value); rampLinear.setLengthInFrames(rampSize); - rampLinear.setTarget(target); - rampLinear.forceCurrent(0.0f); - rampLinear.output.connect(&sinkFloat.input); + // Check that the values go to the initial target instantly. + rampLinear.setTarget(initialTarget); + int32_t singleNumRead = sinkFloat.read(output, singleNumOutput); + ASSERT_EQ(singleNumRead, singleNumOutput); + EXPECT_NEAR(value * initialTarget, output[0], tolerance); + + // Now set target and check that the linear ramp works as expected. + rampLinear.setTarget(finalTarget); int32_t numRead = sinkFloat.read(output, numOutput); + const float incrementSize = (finalTarget - initialTarget) / rampSize; ASSERT_EQ(numOutput, numRead); - constexpr float tolerance = 0.0001f; // arbitrary + int i = 0; for (; i < rampSize; i++) { - float expected = i * value * target / rampSize; + float expected = value * (initialTarget + i * incrementSize); EXPECT_NEAR(expected, output[i], tolerance); } for (; i < numOutput; i++) { - float expected = value * target; + float expected = value * finalTarget; EXPECT_NEAR(expected, output[i], tolerance); } } -- GitLab From cf2fa818199e3f86f2b8d3aae1415662893d1427 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 25 Jun 2021 09:03:37 -0700 Subject: [PATCH 055/694] Define an extensible audio channel layout description The new way for describing audio channel layouts which can be used both in framework <-> framework and framework <-> HAL interfaces and directly supports extensions by vendors. The mapping is defined between the legacy audio_channel_mask_t and the new descriptions. Bug: 188932434 Test: atest audio_aidl_conversion_tests Change-Id: I23e387b2424e1d07a7637a2797f0e905a02feab1 --- media/libaudioclient/AidlConversion.cpp | 179 +++++++++++++ media/libaudioclient/Android.bp | 1 + .../android/media/AudioChannelLayout.aidl | 240 ++++++++++++++++++ .../include/media/AidlConversion.h | 6 + .../include/media/AudioCommonTypes.h | 27 +- .../audio_aidl_legacy_conversion_tests.cpp | 46 +++- 6 files changed, 492 insertions(+), 7 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index fa78f43e31..298e5964d8 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -412,12 +412,121 @@ ConversionResult legacy2aidl_audio_format_t_AudioFormat( namespace { namespace detail { +using AudioChannelPair = std::pair; +using AudioChannelPairs = std::vector; using AudioDevicePair = std::pair; using AudioDevicePairs = std::vector; using AudioFormatPair = std::pair; using AudioFormatPairs = std::vector; } +const detail::AudioChannelPairs& getIndexAudioChannelPairs() { + static const detail::AudioChannelPairs pairs = { +#define DEFINE_INDEX_MASK(n) \ + { \ + AUDIO_CHANNEL_INDEX_MASK_##n, \ + media::AudioChannelLayout::make( \ + media::AudioChannelLayout::INDEX_MASK_##n) \ + } + + DEFINE_INDEX_MASK(1), + DEFINE_INDEX_MASK(2), + DEFINE_INDEX_MASK(3), + DEFINE_INDEX_MASK(4), + DEFINE_INDEX_MASK(5), + DEFINE_INDEX_MASK(6), + DEFINE_INDEX_MASK(7), + DEFINE_INDEX_MASK(8), + DEFINE_INDEX_MASK(9), + DEFINE_INDEX_MASK(10), + DEFINE_INDEX_MASK(11), + DEFINE_INDEX_MASK(12), + DEFINE_INDEX_MASK(13), + DEFINE_INDEX_MASK(14), + DEFINE_INDEX_MASK(15), + DEFINE_INDEX_MASK(16), + DEFINE_INDEX_MASK(17), + DEFINE_INDEX_MASK(18), + DEFINE_INDEX_MASK(19), + DEFINE_INDEX_MASK(20), + DEFINE_INDEX_MASK(21), + DEFINE_INDEX_MASK(22), + DEFINE_INDEX_MASK(23), + DEFINE_INDEX_MASK(24) +#undef DEFINE_INDEX_MASK + }; + return pairs; +} + +const detail::AudioChannelPairs& getInAudioChannelPairs() { + static const detail::AudioChannelPairs pairs = { +#define DEFINE_INPUT_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_IN_##n, \ + media::AudioChannelLayout::make( \ + media::AudioChannelLayout::LAYOUT_##n) \ + } + + DEFINE_INPUT_LAYOUT(MONO), + DEFINE_INPUT_LAYOUT(STEREO), + DEFINE_INPUT_LAYOUT(FRONT_BACK), + // AUDIO_CHANNEL_IN_6 not supported + DEFINE_INPUT_LAYOUT(2POINT0POINT2), + DEFINE_INPUT_LAYOUT(2POINT1POINT2), + DEFINE_INPUT_LAYOUT(3POINT0POINT2), + DEFINE_INPUT_LAYOUT(3POINT1POINT2), + DEFINE_INPUT_LAYOUT(5POINT1), + DEFINE_INPUT_LAYOUT(VOICE_UPLINK_MONO), + DEFINE_INPUT_LAYOUT(VOICE_DNLINK_MONO), + DEFINE_INPUT_LAYOUT(VOICE_CALL_MONO) +#undef DEFINE_INPUT_LAYOUT + }; + return pairs; +} + +const detail::AudioChannelPairs& getOutAudioChannelPairs() { + static const detail::AudioChannelPairs pairs = { +#define DEFINE_OUTPUT_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_OUT_##n, \ + media::AudioChannelLayout::make( \ + media::AudioChannelLayout::LAYOUT_##n) \ + } + + DEFINE_OUTPUT_LAYOUT(MONO), + DEFINE_OUTPUT_LAYOUT(STEREO), + DEFINE_OUTPUT_LAYOUT(2POINT1), + DEFINE_OUTPUT_LAYOUT(TRI), + DEFINE_OUTPUT_LAYOUT(TRI_BACK), + DEFINE_OUTPUT_LAYOUT(3POINT1), + DEFINE_OUTPUT_LAYOUT(2POINT0POINT2), + DEFINE_OUTPUT_LAYOUT(2POINT1POINT2), + DEFINE_OUTPUT_LAYOUT(3POINT0POINT2), + DEFINE_OUTPUT_LAYOUT(3POINT1POINT2), + DEFINE_OUTPUT_LAYOUT(QUAD), + DEFINE_OUTPUT_LAYOUT(QUAD_SIDE), + DEFINE_OUTPUT_LAYOUT(SURROUND), + DEFINE_OUTPUT_LAYOUT(PENTA), + DEFINE_OUTPUT_LAYOUT(5POINT1), + DEFINE_OUTPUT_LAYOUT(5POINT1_SIDE), + DEFINE_OUTPUT_LAYOUT(5POINT1POINT2), + DEFINE_OUTPUT_LAYOUT(5POINT1POINT4), + DEFINE_OUTPUT_LAYOUT(6POINT1), + DEFINE_OUTPUT_LAYOUT(7POINT1), + DEFINE_OUTPUT_LAYOUT(7POINT1POINT2), + DEFINE_OUTPUT_LAYOUT(7POINT1POINT4), + DEFINE_OUTPUT_LAYOUT(13POINT_360RA), + DEFINE_OUTPUT_LAYOUT(22POINT2), + DEFINE_OUTPUT_LAYOUT(MONO_HAPTIC_A), + DEFINE_OUTPUT_LAYOUT(STEREO_HAPTIC_A), + DEFINE_OUTPUT_LAYOUT(HAPTIC_AB), + DEFINE_OUTPUT_LAYOUT(MONO_HAPTIC_AB), + DEFINE_OUTPUT_LAYOUT(STEREO_HAPTIC_AB) +#undef DEFINE_OUTPUT_LAYOUT + }; + return pairs; +} + media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, const std::string& connection = "") { media::AudioDeviceDescription result; @@ -983,6 +1092,76 @@ std::unordered_map make_ReverseMap(const std::vector>& v) } // namespace +ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + const media::AudioChannelLayout& aidl, bool isOutput) { + using ReverseMap = std::unordered_map; + using Tag = media::AudioChannelLayout::Tag; + static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); + static const ReverseMap mIn = make_ReverseMap(getInAudioChannelPairs()); + static const ReverseMap mOut = make_ReverseMap(getOutAudioChannelPairs()); + + auto convert = [](const media::AudioChannelLayout& aidl, const ReverseMap& m, + const char* func, const char* type) -> ConversionResult { + if (auto it = m.find(aidl); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no legacy %s audio_channel_mask_t found for %s", func, type, + aidl.toString().c_str()); + return unexpected(BAD_VALUE); + } + }; + + switch (aidl.getTag()) { + case Tag::none: + return AUDIO_CHANNEL_NONE; + case Tag::invalid: + return AUDIO_CHANNEL_INVALID; + case Tag::indexMask: + return convert(aidl, mIdx, __func__, "index"); + case Tag::layoutMask: + return convert(aidl, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + } + ALOGE("%s: unexpected tag value %d", __func__, aidl.getTag()); + return unexpected(BAD_VALUE); +} + +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + audio_channel_mask_t legacy, bool isOutput) { + using DirectMap = std::unordered_map; + using Tag = media::AudioChannelLayout::Tag; + static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); + static const DirectMap mIn = make_DirectMap(getInAudioChannelPairs()); + static const DirectMap mOut = make_DirectMap(getOutAudioChannelPairs()); + + auto convert = [](const audio_channel_mask_t legacy, const DirectMap& m, + const char* func, const char* type) -> ConversionResult { + if (auto it = m.find(legacy); it != m.end()) { + return it->second; + } else { + ALOGE("%s: no AudioChannelLayout found for legacy %s audio_channel_mask_t value 0x%x", + func, type, legacy); + return unexpected(BAD_VALUE); + } + }; + + if (legacy == AUDIO_CHANNEL_NONE) { + return media::AudioChannelLayout{}; + } else if (legacy == AUDIO_CHANNEL_INVALID) { + return media::AudioChannelLayout::make(0); + } + + const audio_channel_representation_t repr = audio_channel_mask_get_representation(legacy); + if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { + return convert(legacy, mIdx, __func__, "index"); + } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { + return convert(legacy, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + } + + ALOGE("%s: unknown representation %d in audio_channel_mask_t value 0x%x", + __func__, repr, legacy); + return unexpected(BAD_VALUE); +} + ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl) { static const std::unordered_map m = diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index a23c844933..778436c48f 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -303,6 +303,7 @@ aidl_interface { local_include_dir: "aidl", srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", + "aidl/android/media/AudioChannelLayout.aidl", "aidl/android/media/AudioChannelMask.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl new file mode 100644 index 0000000000..9b6d59f862 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl @@ -0,0 +1,240 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * This structure describes a layout of a multi-channel stream. + * There are two possible ways for representing a layout: + * + * - indexed mask, which tells what channels of an audio frame are used, but + * doesn't label them in any way, thus a correspondence between channels in + * the same position of frames originating from different streams must be + * established externally; + * + * - layout mask, which gives a label to each channel, thus allowing to + * match channels between streams of different layouts. + * + * Both representations are agnostic of the direction of audio transfer. Also, + * by construction, the number of bits set to '1' in the mask indicates the + * number of channels in the audio frame. A channel mask per se only defines the + * presence or absence of a channel, not the order. Please see 'INTERLEAVE_*' + * constants for the platform convention of order. + */ +union AudioChannelLayout { + /** + * This variant is used for representing the "null" ("none") value + * for the channel layout. The field value must always be '0'. + */ + int none = 0; + /** + * This variant is used for indicating an "invalid" layout for use by the + * framework only. HAL implementations must not accept or emit + * AudioChannelLayout values for this variant. The field value must always + * be '0'. + */ + int invalid = 0; + /** + * This variant is used for representing indexed masks. The value + * must be one of the 'INDEX_MASK_*' constants. The 'indexMask' field + * must have at least one bit set. + */ + int indexMask; + /** + * This variant is used for representing layout masks. + * It is recommended to use one of 'LAYOUT_*' values. The 'layoutMask' field + * must have at least one bit set. + */ + int layoutMask; + + /** + * 'INDEX_MASK_' constants define how many channels are used. + */ + const int INDEX_MASK_1 = (1 << 1) - 1; + const int INDEX_MASK_2 = (1 << 2) - 1; + const int INDEX_MASK_3 = (1 << 3) - 1; + const int INDEX_MASK_4 = (1 << 4) - 1; + const int INDEX_MASK_5 = (1 << 5) - 1; + const int INDEX_MASK_6 = (1 << 6) - 1; + const int INDEX_MASK_7 = (1 << 7) - 1; + const int INDEX_MASK_8 = (1 << 8) - 1; + const int INDEX_MASK_9 = (1 << 9) - 1; + const int INDEX_MASK_10 = (1 << 10) - 1; + const int INDEX_MASK_11 = (1 << 11) - 1; + const int INDEX_MASK_12 = (1 << 12) - 1; + const int INDEX_MASK_13 = (1 << 13) - 1; + const int INDEX_MASK_14 = (1 << 14) - 1; + const int INDEX_MASK_15 = (1 << 15) - 1; + const int INDEX_MASK_16 = (1 << 16) - 1; + const int INDEX_MASK_17 = (1 << 17) - 1; + const int INDEX_MASK_18 = (1 << 18) - 1; + const int INDEX_MASK_19 = (1 << 19) - 1; + const int INDEX_MASK_20 = (1 << 20) - 1; + const int INDEX_MASK_21 = (1 << 21) - 1; + const int INDEX_MASK_22 = (1 << 22) - 1; + const int INDEX_MASK_23 = (1 << 23) - 1; + const int INDEX_MASK_24 = (1 << 24) - 1; + + /** + * 'LAYOUT_*' constants define channel layouts recognized by + * the audio system. The order of the channels in the frame is assumed + * to be from the LSB to MSB for all the bits set to '1'. + */ + const int LAYOUT_MONO = CHANNEL_FRONT_LEFT; + const int LAYOUT_STEREO = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT; + const int LAYOUT_2POINT1 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_LOW_FREQUENCY; + const int LAYOUT_TRI = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_FRONT_CENTER; + const int LAYOUT_TRI_BACK = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_BACK_CENTER; + const int LAYOUT_3POINT1 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_FRONT_CENTER | + CHANNEL_LOW_FREQUENCY; + const int LAYOUT_2POINT0POINT2 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; + const int LAYOUT_2POINT1POINT2 = + LAYOUT_2POINT0POINT2 | CHANNEL_LOW_FREQUENCY; + const int LAYOUT_3POINT0POINT2 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; + const int LAYOUT_3POINT1POINT2 = + LAYOUT_3POINT0POINT2 | CHANNEL_LOW_FREQUENCY; + const int LAYOUT_QUAD = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT; + const int LAYOUT_QUAD_SIDE = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; + const int LAYOUT_SURROUND = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER; + const int LAYOUT_PENTA = LAYOUT_QUAD | CHANNEL_FRONT_CENTER; + const int LAYOUT_5POINT1 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | + CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT; + const int LAYOUT_5POINT1_SIDE = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | + CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; + const int LAYOUT_5POINT1POINT2 = LAYOUT_5POINT1 | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; + const int LAYOUT_5POINT1POINT4 = LAYOUT_5POINT1 | + CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | + CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT; + const int LAYOUT_6POINT1 = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | + CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT | CHANNEL_BACK_CENTER; + const int LAYOUT_7POINT1 = LAYOUT_5POINT1 | + CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; + const int LAYOUT_7POINT1POINT2 = LAYOUT_7POINT1 | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; + const int LAYOUT_7POINT1POINT4 = LAYOUT_7POINT1 | + CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | + CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT; + const int LAYOUT_9POINT1POINT4 = LAYOUT_7POINT1POINT4 | + CHANNEL_FRONT_WIDE_LEFT | CHANNEL_FRONT_WIDE_RIGHT; + const int LAYOUT_9POINT1POINT6 = LAYOUT_9POINT1POINT4 | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; + const int LAYOUT_13POINT_360RA = + CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | + CHANNEL_FRONT_CENTER | + CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT | + CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | + CHANNEL_TOP_FRONT_CENTER | + CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT | + CHANNEL_BOTTOM_FRONT_LEFT | CHANNEL_BOTTOM_FRONT_RIGHT | + CHANNEL_BOTTOM_FRONT_CENTER; + const int LAYOUT_22POINT2 = LAYOUT_7POINT1POINT4 | + CHANNEL_FRONT_LEFT_OF_CENTER | CHANNEL_FRONT_RIGHT_OF_CENTER | + CHANNEL_BACK_CENTER | CHANNEL_TOP_CENTER | + CHANNEL_TOP_FRONT_CENTER | CHANNEL_TOP_BACK_CENTER | + CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT | + CHANNEL_BOTTOM_FRONT_LEFT | CHANNEL_BOTTOM_FRONT_RIGHT | + CHANNEL_BOTTOM_FRONT_CENTER | + CHANNEL_LOW_FREQUENCY_2; + const int LAYOUT_MONO_HAPTIC_A = + LAYOUT_MONO | CHANNEL_HAPTIC_A; + const int LAYOUT_STEREO_HAPTIC_A = + LAYOUT_STEREO | CHANNEL_HAPTIC_A; + const int LAYOUT_HAPTIC_AB = + CHANNEL_HAPTIC_A | CHANNEL_HAPTIC_B; + const int LAYOUT_MONO_HAPTIC_AB = + LAYOUT_MONO | LAYOUT_HAPTIC_AB; + const int LAYOUT_STEREO_HAPTIC_AB = + LAYOUT_STEREO | LAYOUT_HAPTIC_AB; + const int LAYOUT_FRONT_BACK = + CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER; + const int LAYOUT_VOICE_UPLINK_MONO = + LAYOUT_MONO | CHANNEL_VOICE_UPLINK; + const int LAYOUT_VOICE_DNLINK_MONO = + LAYOUT_MONO | CHANNEL_VOICE_DNLINK; + const int LAYOUT_VOICE_CALL_MONO = + CHANNEL_VOICE_UPLINK | CHANNEL_VOICE_DNLINK; + + /** + * Expresses the convention when stereo audio samples are stored interleaved + * in an array. This should improve readability by allowing code to use + * symbolic indices instead of hard-coded [0] and [1]. + * + * For multi-channel beyond stereo, the platform convention is that channels + * are interleaved in order from least significant channel mask bit to most + * significant channel mask bit, with unused bits skipped. Any exceptions + * to this convention will be noted at the appropriate API. + */ + const int INTERLEAVE_LEFT = 0; + const int INTERLEAVE_RIGHT = 1; + + /** + * 'CHANNEL_*' constants are used to build 'LAYOUT_*' masks. + * Each constant must have exactly one bit set. + */ + const int CHANNEL_FRONT_LEFT = 1 << 0; + const int CHANNEL_FRONT_RIGHT = 1 << 1; + const int CHANNEL_FRONT_CENTER = 1 << 2; + const int CHANNEL_LOW_FREQUENCY = 1 << 3; + const int CHANNEL_BACK_LEFT = 1 << 4; + const int CHANNEL_BACK_RIGHT = 1 << 5; + const int CHANNEL_FRONT_LEFT_OF_CENTER = 1 << 6; + const int CHANNEL_FRONT_RIGHT_OF_CENTER = 1 << 7; + const int CHANNEL_BACK_CENTER = 1 << 8; + const int CHANNEL_SIDE_LEFT = 1 << 9; + const int CHANNEL_SIDE_RIGHT = 1 << 10; + const int CHANNEL_TOP_CENTER = 1 << 11; + const int CHANNEL_TOP_FRONT_LEFT = 1 << 12; + const int CHANNEL_TOP_FRONT_CENTER = 1 << 13; + const int CHANNEL_TOP_FRONT_RIGHT = 1 << 14; + const int CHANNEL_TOP_BACK_LEFT = 1 << 15; + const int CHANNEL_TOP_BACK_CENTER = 1 << 16; + const int CHANNEL_TOP_BACK_RIGHT = 1 << 17; + const int CHANNEL_TOP_SIDE_LEFT = 1 << 18; + const int CHANNEL_TOP_SIDE_RIGHT = 1 << 19; + const int CHANNEL_BOTTOM_FRONT_LEFT = 1 << 20; + const int CHANNEL_BOTTOM_FRONT_CENTER = 1 << 21; + const int CHANNEL_BOTTOM_FRONT_RIGHT = 1 << 22; + const int CHANNEL_LOW_FREQUENCY_2 = 1 << 23; + const int CHANNEL_FRONT_WIDE_LEFT = 1 << 24; + const int CHANNEL_FRONT_WIDE_RIGHT = 1 << 25; + const int CHANNEL_VOICE_UPLINK = 1 << 26; + const int CHANNEL_VOICE_DNLINK = 1 << 27; + const int CHANNEL_HAPTIC_B = 1 << 28; // B then A to match legacy const. + const int CHANNEL_HAPTIC_A = 1 << 29; +} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 422d94f8e6..eb84b2ddab 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -140,6 +141,11 @@ ConversionResult aidl2legacy_AudioFormat_audio_format_t( ConversionResult legacy2aidl_audio_format_t_AudioFormat( audio_format_t legacy); +ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + const media::AudioChannelLayout& aidl, bool isOutput); +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + audio_channel_mask_t legacy, bool isOutput); + ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl); ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index 613d6bd7d7..2a46e05a7c 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -19,6 +19,7 @@ #include +#include #include #include #include @@ -37,9 +38,29 @@ static size_t hash_combine(size_t seed, size_t v) { namespace std { -// Note: when extending Audio{Device|Format}Description we need to account for the -// possibility of comparison between different versions of it, e.g. a HAL -// may be using a previous version of the AIDL interface. +// Note: when extending the types hashed below we need to account for the +// possibility of processing types belonging to different versions of the type, +// e.g. a HAL may be using a previous version of the AIDL interface. + +template<> struct hash +{ + std::size_t operator()(const android::media::AudioChannelLayout& acl) const noexcept { + using Tag = android::media::AudioChannelLayout::Tag; + const size_t seed = std::hash{}(acl.getTag()); + switch (acl.getTag()) { + case Tag::none: + return hash_combine(seed, std::hash{}(acl.get())); + case Tag::invalid: + return hash_combine(seed, std::hash{}(acl.get())); + case Tag::indexMask: + return hash_combine(seed, std::hash{}(acl.get())); + case Tag::layoutMask: + return hash_combine(seed, std::hash{}(acl.get())); + } + return seed; + } +}; + template<> struct hash { std::size_t operator()(const android::media::AudioDeviceDescription& add) const noexcept { diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index ca609ab0c4..e54935447d 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -24,12 +24,26 @@ using namespace android::aidl_utils; namespace { -size_t hash(const media::AudioDeviceDescription& add) { - return std::hash{}(add); +template size_t hash(const T& t) { + return std::hash{}(t); } -size_t hash(const media::AudioFormatDescription& afd) { - return std::hash{}(afd); +media::AudioChannelLayout make_ACL_None() { + return media::AudioChannelLayout{}; +} + +media::AudioChannelLayout make_ACL_Invalid() { + return media::AudioChannelLayout::make(0); +} + +media::AudioChannelLayout make_ACL_Stereo() { + return media::AudioChannelLayout::make( + media::AudioChannelLayout::LAYOUT_STEREO); +} + +media::AudioChannelLayout make_ACL_ChannelIndex2() { + return media::AudioChannelLayout::make( + media::AudioChannelLayout::INDEX_MASK_2); } media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, @@ -135,6 +149,11 @@ class HashIdentityTest : public ::testing::Test { } }; +TEST_F(HashIdentityTest, AudioChannelLayoutHashIdentity) { + verifyHashIdentity({ + make_ACL_None, make_ACL_Invalid, make_ACL_Stereo, make_ACL_ChannelIndex2}); +} + TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { verifyHashIdentity({ make_ADD_None, make_ADD_DefaultIn, make_ADD_DefaultOut, make_ADD_WiredHeadset, @@ -147,6 +166,25 @@ TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { make_AFD_Encap, make_AFD_Encap_with_Enc}); } +using ChannelLayoutParam = std::tuple; +class AudioChannelLayoutRoundTripTest : + public testing::TestWithParam {}; +TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { + const auto initial = std::get<0>(GetParam()); + const bool isOutput = std::get<1>(GetParam()); + auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isOutput); + ASSERT_TRUE(conv.ok()); + auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isOutput); + ASSERT_TRUE(convBack.ok()); + EXPECT_EQ(initial, convBack.value()); +} +INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, + AudioChannelLayoutRoundTripTest, + testing::Combine( + testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), + make_ACL_ChannelIndex2()), + testing::Values(true, false))); + class AudioDeviceDescriptionRoundTripTest : public testing::TestWithParam {}; TEST_P(AudioDeviceDescriptionRoundTripTest, Aidl2Legacy2Aidl) { -- GitLab From 5362a14bb304e7f4d890032a0b3d0f7ac7beb537 Mon Sep 17 00:00:00 2001 From: Dorin Drimus Date: Tue, 6 Jul 2021 16:15:03 +0200 Subject: [PATCH 056/694] Allow non pcm formats for setBufferSizeInFrames For compressed formats the buffer size is actual bytes (or a frame is considered equal to 1 byte). Test: atest AudioTrackLatencyTest#testSetBufferSize Test: manual test to set buffer size for an EAC3 AudioTrack Bug: 192343963 Change-Id: Id9ba3da8e431208f38639004a47a4a27235e9d71 --- media/libaudioclient/AudioTrack.cpp | 4 ---- media/libaudioclient/include/media/AudioTrack.h | 3 +-- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 594c3f30b9..c7c88236be 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -1275,10 +1275,6 @@ ssize_t AudioTrack::setBufferSizeInFrames(size_t bufferSizeInFrames) if (mOutput == AUDIO_IO_HANDLE_NONE || mProxy.get() == 0) { return NO_INIT; } - // Reject if timed track or compressed audio. - if (!audio_is_linear_pcm(mFormat)) { - return INVALID_OPERATION; - } ssize_t originalBufferSize = mProxy->getBufferSizeInFrames(); ssize_t finalBufferSize = mProxy->setBufferSizeInFrames((uint32_t) bufferSizeInFrames); diff --git a/media/libaudioclient/include/media/AudioTrack.h b/media/libaudioclient/include/media/AudioTrack.h index f61eef2abb..3000c28594 100644 --- a/media/libaudioclient/include/media/AudioTrack.h +++ b/media/libaudioclient/include/media/AudioTrack.h @@ -427,8 +427,7 @@ public: * less than or equal to the getBufferCapacityInFrames(). * It may also be adjusted slightly for internal reasons. * - * Return the final size or a negative error if the track is unitialized - * or does not support variable sizes. + * Return the final size or a negative value (NO_INIT) if the track is uninitialized. */ ssize_t setBufferSizeInFrames(size_t size); -- GitLab From 5478fc18ccaccad1e7591700cf64466a0909464b Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 8 Jul 2021 16:13:29 -0700 Subject: [PATCH 057/694] Convert getDevicesForStream to return a DeviceTypeSet As a pre-requisite for switching from 'int' to 'AudioDeviceDescription' in the framework AIDL interfaces, get rid of the usage of 'int' as a mask of 'audio_devices_t' values. This is needed because 'AudioDeviceDescription' can't be coerced into an int directly, and interpreting a mask of multiple 'audio_devices_t' values is ambiguous due to presence of multi-bit device types. Note that at the Java layer the returned DeviceTypeSet is still collapsed into a single integer value. This needs to be addressed separately. Bug: 188932434 Test: check audio on device Change-Id: I1bc2a28ac2e1037a38b7be7967349b33845f88de --- media/libaudioclient/AudioSystem.cpp | 12 ++++++------ .../aidl/android/media/IAudioPolicyService.aidl | 2 +- media/libaudioclient/include/media/AudioSystem.h | 3 ++- services/audiopolicy/AudioPolicyInterface.h | 3 ++- .../managerdefault/AudioPolicyManager.cpp | 7 +++---- .../audiopolicy/managerdefault/AudioPolicyManager.h | 2 +- .../audiopolicy/service/AudioPolicyInterfaceImpl.cpp | 9 +++++---- services/audiopolicy/service/AudioPolicyService.h | 2 +- 8 files changed, 21 insertions(+), 19 deletions(-) diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 640f547bac..3ac4eeee8f 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -1259,19 +1259,19 @@ product_strategy_t AudioSystem::getStrategyForStream(audio_stream_type_t stream) return result.value_or(PRODUCT_STRATEGY_NONE); } -audio_devices_t AudioSystem::getDevicesForStream(audio_stream_type_t stream) { +DeviceTypeSet AudioSystem::getDevicesForStream(audio_stream_type_t stream) { const sp& aps = AudioSystem::get_audio_policy_service(); - if (aps == 0) return AUDIO_DEVICE_NONE; + if (aps == 0) return DeviceTypeSet{}; - auto result = [&]() -> ConversionResult { + auto result = [&]() -> ConversionResult { media::AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); - int32_t resultAidl; + std::vector resultAidl; RETURN_IF_ERROR(statusTFromBinderStatus( aps->getDevicesForStream(streamAidl, &resultAidl))); - return aidl2legacy_int32_t_audio_devices_t(resultAidl); + return convertContainer(resultAidl, aidl2legacy_int32_t_audio_devices_t); }(); - return result.value_or(AUDIO_DEVICE_NONE); + return result.value_or(DeviceTypeSet{}); } status_t AudioSystem::getDevicesForAttributes(const AudioAttributes& aa, diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 184b024be3..2919624e61 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -132,7 +132,7 @@ interface IAudioPolicyService { int /* product_strategy_t */ getStrategyForStream(AudioStreamType stream); - int /* bitmask of audio_devices_t */ getDevicesForStream(AudioStreamType stream); + int[] /* audio_devices_t */ getDevicesForStream(AudioStreamType stream); AudioDevice[] getDevicesForAttributes(in AudioAttributesEx attr); diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index a9109c80cb..3d0cac4bf7 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -318,7 +319,7 @@ public: static status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index); static product_strategy_t getStrategyForStream(audio_stream_type_t stream); - static audio_devices_t getDevicesForStream(audio_stream_type_t stream); + static DeviceTypeSet getDevicesForStream(audio_stream_type_t stream); static status_t getDevicesForAttributes(const AudioAttributes &aa, AudioDeviceTypeAddrVector *devices); diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h index 2e49e714dd..a8bb7dabd6 100644 --- a/services/audiopolicy/AudioPolicyInterface.h +++ b/services/audiopolicy/AudioPolicyInterface.h @@ -18,6 +18,7 @@ #define ANDROID_AUDIOPOLICY_INTERFACE_H #include +#include #include #include #include @@ -198,7 +199,7 @@ public: virtual product_strategy_t getStrategyForStream(audio_stream_type_t stream) = 0; // return the enabled output devices for the given stream type - virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream) = 0; + virtual DeviceTypeSet getDevicesForStream(audio_stream_type_t stream) = 0; // retrieves the list of enabled output devices for the given audio attributes virtual status_t getDevicesForAttributes(const audio_attributes_t &attr, diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp index 49db0d1852..18bc7bdd0a 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp @@ -5917,13 +5917,13 @@ bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1, return (stream1 == stream2); } -audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { +DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) { // By checking the range of stream before calling getStrategy, we avoid // getOutputDevicesForStream's behavior for invalid streams. // engine's getOutputDevicesForStream would fallback on its default behavior (most probably // device for music stream), but we want to return the empty set. if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) { - return AUDIO_DEVICE_NONE; + return DeviceTypeSet{}; } DeviceVector activeDevices; DeviceVector devices; @@ -5954,8 +5954,7 @@ audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stre devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER)); devices.remove(speakerSafeDevices); } - // FIXME: use DeviceTypeSet when Java layer is ready for it. - return deviceTypesToBitMask(devices.types()); + return devices.types(); } status_t AudioPolicyManager::getDevicesForAttributes( diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h index 98f96d1951..8534923327 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.h +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h @@ -193,7 +193,7 @@ public: } // return the enabled output devices for the given stream type - virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream); + virtual DeviceTypeSet getDevicesForStream(audio_stream_type_t stream); virtual status_t getDevicesForAttributes( const audio_attributes_t &attributes, diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 90332af70f..4183fd8289 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -1076,13 +1076,12 @@ Status AudioPolicyService::getStrategyForStream(media::AudioStreamType streamAid //audio policy: use audio_device_t appropriately Status AudioPolicyService::getDevicesForStream(media::AudioStreamType streamAidl, - int32_t* _aidl_return) { + std::vector* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) { - *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - legacy2aidl_audio_devices_t_int32_t(AUDIO_DEVICE_NONE)); + *_aidl_return = std::vector{}; return Status::ok(); } if (mAudioPolicyManager == NULL) { @@ -1091,7 +1090,9 @@ Status AudioPolicyService::getDevicesForStream(media::AudioStreamType streamAidl Mutex::Autolock _l(mLock); AutoCallerClear acc; *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - legacy2aidl_audio_devices_t_int32_t(mAudioPolicyManager->getDevicesForStream(stream))); + convertContainer>( + mAudioPolicyManager->getDevicesForStream(stream), + legacy2aidl_audio_devices_t_int32_t)); return Status::ok(); } diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index ed9f44e963..11212f60ea 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -118,7 +118,7 @@ public: binder::Status getStrategyForStream(media::AudioStreamType stream, int32_t* _aidl_return) override; binder::Status getDevicesForStream(media::AudioStreamType stream, - int32_t* _aidl_return) override; + std::vector* _aidl_return) override; binder::Status getDevicesForAttributes(const media::AudioAttributesEx& attr, std::vector* _aidl_return) override; binder::Status getOutputForEffect(const media::EffectDescriptor& desc, -- GitLab From 21a32ec9accd3aba2543f6ff2f33ea79056fb65e Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 8 Jul 2021 14:40:12 -0700 Subject: [PATCH 058/694] Switch the framework AIDL to use AudioDeviceDescription 'AudioDeviceDescription' is a new type that will be used both by HAL and framework interfaces. This CL changes the framework interfaces to use it instead of 'int' type which was used to pass legacy 'audio_devices_t' transparently via the AIDL layer. Bug: 188932434 Test: check audio on device Change-Id: Ie275ea82db89011c855ac21f0af4f6546ceb2d13 --- media/libaudioclient/AidlConversion.cpp | 20 +++----- media/libaudioclient/AudioSystem.cpp | 32 ++++++++----- media/libaudioclient/PolicyAidlConversion.cpp | 6 ++- .../aidl/android/media/AudioDevice.aidl | 5 +- .../media/AudioPortConfigDeviceExt.aidl | 8 ++-- .../android/media/IAudioPolicyService.aidl | 13 +++--- .../android/media/SoundTriggerSession.aidl | 6 ++- .../include/media/AidlConversion.h | 3 -- .../AudioDeviceTypeAddr.cpp | 5 +- services/audioflinger/AudioFlinger.cpp | 6 +-- .../service/AudioPolicyInterfaceImpl.cpp | 46 +++++++++++-------- .../audiopolicy/service/AudioPolicyService.h | 20 +++++--- 12 files changed, 94 insertions(+), 76 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 298e5964d8..4e8fad3d79 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -1254,16 +1254,6 @@ ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_ enumToMask_index); } -ConversionResult aidl2legacy_int32_t_audio_devices_t(int32_t aidl) { - // TODO(ytai): bitfield? - return convertReinterpret(aidl); -} - -ConversionResult legacy2aidl_audio_devices_t_int32_t(audio_devices_t legacy) { - // TODO(ytai): bitfield? - return convertReinterpret(legacy); -} - ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( const media::AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type) { audio_gain_config legacy; @@ -1527,7 +1517,7 @@ aidl2legacy_AudioPortConfigDeviceExt_audio_port_config_device_ext( const media::AudioPortConfigDeviceExt& aidl) { audio_port_config_device_ext legacy; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - legacy.type = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_devices_t(aidl.type)); + legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); RETURN_IF_ERROR(aidl2legacy_string(aidl.address, legacy.address, AUDIO_DEVICE_MAX_ADDRESS_LEN)); return legacy; } @@ -1537,7 +1527,7 @@ legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( const audio_port_config_device_ext& legacy) { media::AudioPortConfigDeviceExt aidl; aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(legacy.type)); + aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.type)); aidl.address = VALUE_OR_RETURN( legacy2aidl_string(legacy.address, AUDIO_DEVICE_MAX_ADDRESS_LEN)); return aidl; @@ -2592,7 +2582,8 @@ ConversionResult aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl) { audio_port_device_ext legacy; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - legacy.type = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_devices_t(aidl.device.type)); + legacy.type = VALUE_OR_RETURN( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.device.type)); RETURN_IF_ERROR( aidl2legacy_string(aidl.device.address, legacy.address, sizeof(legacy.address))); legacy.encapsulation_modes = VALUE_OR_RETURN( @@ -2606,7 +2597,8 @@ ConversionResult legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(const audio_port_device_ext& legacy) { media::AudioPortDeviceExt aidl; aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.device.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(legacy.type)); + aidl.device.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.type)); aidl.device.address = VALUE_OR_RETURN( legacy2aidl_string(legacy.address, sizeof(legacy.address))); aidl.encapsulationModes = VALUE_OR_RETURN( diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 3ac4eeee8f..540f2791a5 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -846,7 +846,8 @@ status_t AudioSystem::setDeviceConnectionState(audio_devices_t device, } media::AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + deviceAidl.type = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = address; return statusTFromBinderStatus( @@ -865,7 +866,8 @@ audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t d auto result = [&]() -> ConversionResult { media::AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(device)); + deviceAidl.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = device_address; media::AudioPolicyDeviceState result; @@ -895,7 +897,8 @@ status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device, } media::AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + deviceAidl.type = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = address; return statusTFromBinderStatus( @@ -1165,7 +1168,8 @@ status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream, media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral(index)); - int32_t deviceAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); return statusTFromBinderStatus( aps->setStreamVolumeIndex(streamAidl, deviceAidl, indexAidl)); } @@ -1178,7 +1182,8 @@ status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream, media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); - int32_t deviceAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); int32_t indexAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getStreamVolumeIndex(streamAidl, deviceAidl, &indexAidl))); @@ -1197,7 +1202,8 @@ status_t AudioSystem::setVolumeIndexForAttributes(const audio_attributes_t& attr media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral(index)); - int32_t deviceAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); return statusTFromBinderStatus( aps->setVolumeIndexForAttributes(attrAidl, deviceAidl, indexAidl)); } @@ -1210,7 +1216,8 @@ status_t AudioSystem::getVolumeIndexForAttributes(const audio_attributes_t& attr media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - int32_t deviceAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_devices_t_int32_t(device)); + media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); int32_t indexAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getVolumeIndexForAttributes(attrAidl, deviceAidl, &indexAidl))); @@ -1266,10 +1273,11 @@ DeviceTypeSet AudioSystem::getDevicesForStream(audio_stream_type_t stream) { auto result = [&]() -> ConversionResult { media::AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); - std::vector resultAidl; + std::vector resultAidl; RETURN_IF_ERROR(statusTFromBinderStatus( aps->getDevicesForStream(streamAidl, &resultAidl))); - return convertContainer(resultAidl, aidl2legacy_int32_t_audio_devices_t); + return convertContainer(resultAidl, + aidl2legacy_AudioDeviceDescription_audio_devices_t); }(); return result.value_or(DeviceTypeSet{}); } @@ -1690,7 +1698,8 @@ status_t AudioSystem::acquireSoundTriggerSession(audio_session_t* session, statusTFromBinderStatus(aps->acquireSoundTriggerSession(&retAidl))); *session = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_session_t(retAidl.session)); *ioHandle = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(retAidl.ioHandle)); - *device = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_devices_t(retAidl.device)); + *device = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioDeviceDescription_audio_devices_t(retAidl.device)); return OK; } @@ -1830,7 +1839,8 @@ AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devi media::AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN(convertIntegral(index)); - int32_t deviceAidl = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(device)); + media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); float retAidl; RETURN_IF_ERROR(statusTFromBinderStatus( aps->getStreamVolumeDB(streamAidl, indexAidl, deviceAidl, &retAidl))); diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index 25fdb4902e..d6611d1c94 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -235,7 +235,8 @@ aidl2legacy_AudioMix(const media::AudioMix& aidl) { legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.format)); legacy.mRouteFlags = VALUE_OR_RETURN( aidl2legacy_AudioMixRouteFlag_uint32_t_mask(aidl.routeFlags)); - legacy.mDeviceType = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_devices_t(aidl.device.type)); + legacy.mDeviceType = VALUE_OR_RETURN( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.device.type)); legacy.mDeviceAddress = VALUE_OR_RETURN(aidl2legacy_string_view_String8(aidl.device.address)); legacy.mCbFlags = VALUE_OR_RETURN(aidl2legacy_AudioMixCallbackFlag_uint32_t_mask(aidl.cbFlags)); legacy.mAllowPrivilegedMediaPlaybackCapture = aidl.allowPrivilegedMediaPlaybackCapture; @@ -254,7 +255,8 @@ legacy2aidl_AudioMix(const AudioMix& legacy) { aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(legacy.mFormat)); aidl.routeFlags = VALUE_OR_RETURN( legacy2aidl_uint32_t_AudioMixRouteFlag_mask(legacy.mRouteFlags)); - aidl.device.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(legacy.mDeviceType)); + aidl.device.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mDeviceType)); aidl.device.address = VALUE_OR_RETURN(legacy2aidl_String8_string(legacy.mDeviceAddress)); aidl.cbFlags = VALUE_OR_RETURN(legacy2aidl_uint32_t_AudioMixCallbackFlag_mask(legacy.mCbFlags)); aidl.allowPrivilegedMediaPlaybackCapture = legacy.mAllowPrivilegedMediaPlaybackCapture; diff --git a/media/libaudioclient/aidl/android/media/AudioDevice.aidl b/media/libaudioclient/aidl/android/media/AudioDevice.aidl index b2006970b3..a815874491 100644 --- a/media/libaudioclient/aidl/android/media/AudioDevice.aidl +++ b/media/libaudioclient/aidl/android/media/AudioDevice.aidl @@ -16,11 +16,12 @@ package android.media; +import android.media.AudioDeviceDescription; + /** * {@hide} */ parcelable AudioDevice { - /** Interpreted as audio_devices_t. */ - int type; + AudioDeviceDescription type; @utf8InCpp String address; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl index a99aa9bb3d..31e5330d9f 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioDeviceDescription; + /** * {@hide} */ @@ -26,11 +28,9 @@ parcelable AudioPortConfigDeviceExt { */ int hwModule; /** - * Device type (e.g AUDIO_DEVICE_OUT_SPEAKER). - * Interpreted as audio_devices_t. - * TODO: Convert to a standalone AIDL representation. + * Device type. */ - int type; + AudioDeviceDescription type; /** Device address. "" if N/A. */ @utf8InCpp String address; } diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 2919624e61..e16e3da81c 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -24,6 +24,7 @@ import android.media.AudioAttributesInternal; import android.media.AudioConfig; import android.media.AudioConfigBase; import android.media.AudioDevice; +import android.media.AudioDeviceDescription; import android.media.AudioMix; import android.media.AudioMode; import android.media.AudioOffloadInfo; @@ -113,18 +114,18 @@ interface IAudioPolicyService { int indexMax); void setStreamVolumeIndex(AudioStreamType stream, - int /* audio_devices_t */ device, + in AudioDeviceDescription device, int index); int getStreamVolumeIndex(AudioStreamType stream, - int /* audio_devices_t */ device); + in AudioDeviceDescription device); void setVolumeIndexForAttributes(in AudioAttributesInternal attr, - int /* audio_devices_t */ device, + in AudioDeviceDescription device, int index); int getVolumeIndexForAttributes(in AudioAttributesInternal attr, - int /* audio_devices_t */ device); + in AudioDeviceDescription device); int getMaxVolumeIndexForAttributes(in AudioAttributesInternal attr); @@ -132,7 +133,7 @@ interface IAudioPolicyService { int /* product_strategy_t */ getStrategyForStream(AudioStreamType stream); - int[] /* audio_devices_t */ getDevicesForStream(AudioStreamType stream); + AudioDeviceDescription[] getDevicesForStream(AudioStreamType stream); AudioDevice[] getDevicesForAttributes(in AudioAttributesEx attr); @@ -267,7 +268,7 @@ interface IAudioPolicyService { boolean getMasterMono(); - float getStreamVolumeDB(AudioStreamType stream, int index, int /* audio_devices_t */ device); + float getStreamVolumeDB(AudioStreamType stream, int index, in AudioDeviceDescription device); /** * Populates supported surround formats and their enabled state in formats and formatsEnabled. diff --git a/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl b/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl index a829e59375..b9708b2c97 100644 --- a/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl +++ b/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioDeviceDescription; + /** * {@hide} */ @@ -24,6 +26,6 @@ parcelable SoundTriggerSession { int session; /** Interpreted as audio_io_handle_t. */ int ioHandle; - /** Interpreted as audio_devices_t. */ - int device; + /** Device type. */ + AudioDeviceDescription device; } diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index eb84b2ddab..319c98b47a 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -164,9 +164,6 @@ legacy2aidl_audio_gain_mode_t_AudioGainMode(audio_gain_mode_t legacy); ConversionResult aidl2legacy_int32_t_audio_gain_mode_t_mask(int32_t aidl); ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_mode_t legacy); -ConversionResult aidl2legacy_int32_t_audio_devices_t(int32_t aidl); -ConversionResult legacy2aidl_audio_devices_t_int32_t(audio_devices_t legacy); - ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( const media::AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type); ConversionResult legacy2aidl_audio_gain_config_AudioGainConfig( diff --git a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp index c5d7da80d0..7f54474ea2 100644 --- a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp +++ b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp @@ -158,14 +158,15 @@ std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& devic ConversionResult aidl2legacy_AudioDeviceTypeAddress(const media::AudioDevice& aidl) { - audio_devices_t type = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_devices_t(aidl.type)); + audio_devices_t type = VALUE_OR_RETURN( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); return AudioDeviceTypeAddr(type, aidl.address); } ConversionResult legacy2aidl_AudioDeviceTypeAddress(const AudioDeviceTypeAddr& legacy) { media::AudioDevice aidl; - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_int32_t(legacy.mType)); + aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mType)); aidl.address = legacy.getAddress(); return aidl; } diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 54a642563f..1f19fc91d9 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -2810,7 +2810,9 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, { Mutex::Autolock _l(mLock); - if (request.device.type == AUDIO_DEVICE_NONE) { + AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioDeviceTypeAddress(request.device)); + if (device.mType == AUDIO_DEVICE_NONE) { return BAD_VALUE; } @@ -2818,8 +2820,6 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, aidl2legacy_int32_t_audio_io_handle_t(request.input)); audio_config_t config = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioConfig_audio_config_t(request.config)); - AudioDeviceTypeAddr device = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioDeviceTypeAddress(request.device)); sp thread = openInput_l( VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)), diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 4183fd8289..d41b5bdddc 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -101,7 +101,7 @@ Status AudioPolicyService::setDeviceConnectionState( const std::string& deviceNameAidl, media::AudioFormatSys encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl.type)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioPolicyDeviceState_audio_policy_dev_state_t(stateAidl)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( @@ -131,7 +131,7 @@ Status AudioPolicyService::setDeviceConnectionState( Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& deviceAidl, media::AudioPolicyDeviceState* _aidl_return) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl.type)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); if (mAudioPolicyManager == NULL) { *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState( @@ -151,7 +151,7 @@ Status AudioPolicyService::handleDeviceConfigChange( const std::string& deviceNameAidl, media::AudioFormatSys encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl.type)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioFormat_audio_format_t(encodedFormatAidl)); @@ -925,12 +925,13 @@ Status AudioPolicyService::initStreamVolume(media::AudioStreamType streamAidl, } Status AudioPolicyService::setStreamVolumeIndex(media::AudioStreamType streamAidl, - int32_t deviceAidl, int32_t indexAidl) { + const media::AudioDeviceDescription& deviceAidl, + int32_t indexAidl) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(indexAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); @@ -949,11 +950,12 @@ Status AudioPolicyService::setStreamVolumeIndex(media::AudioStreamType streamAid } Status AudioPolicyService::getStreamVolumeIndex(media::AudioStreamType streamAidl, - int32_t deviceAidl, int32_t* _aidl_return) { + const media::AudioDeviceDescription& deviceAidl, + int32_t* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl)); int index; if (mAudioPolicyManager == NULL) { @@ -971,12 +973,13 @@ Status AudioPolicyService::getStreamVolumeIndex(media::AudioStreamType streamAid } Status AudioPolicyService::setVolumeIndexForAttributes( - const media::AudioAttributesInternal& attrAidl, int32_t deviceAidl, int32_t indexAidl) { + const media::AudioAttributesInternal& attrAidl, + const media::AudioDeviceDescription& deviceAidl, int32_t indexAidl) { audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attrAidl)); int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(indexAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl)); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( AudioValidator::validateAudioAttributes(attributes, "169572641"))); @@ -993,11 +996,12 @@ Status AudioPolicyService::setVolumeIndexForAttributes( } Status AudioPolicyService::getVolumeIndexForAttributes( - const media::AudioAttributesInternal& attrAidl, int32_t deviceAidl, int32_t* _aidl_return) { + const media::AudioAttributesInternal& attrAidl, + const media::AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) { audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attrAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl)); int index; RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( AudioValidator::validateAudioAttributes(attributes, "169572641"))); @@ -1075,13 +1079,14 @@ Status AudioPolicyService::getStrategyForStream(media::AudioStreamType streamAid //audio policy: use audio_device_t appropriately -Status AudioPolicyService::getDevicesForStream(media::AudioStreamType streamAidl, - std::vector* _aidl_return) { +Status AudioPolicyService::getDevicesForStream( + media::AudioStreamType streamAidl, + std::vector* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) { - *_aidl_return = std::vector{}; + *_aidl_return = std::vector{}; return Status::ok(); } if (mAudioPolicyManager == NULL) { @@ -1090,9 +1095,9 @@ Status AudioPolicyService::getDevicesForStream(media::AudioStreamType streamAidl Mutex::Autolock _l(mLock); AutoCallerClear acc; *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>( + convertContainer>( mAudioPolicyManager->getDevicesForStream(stream), - legacy2aidl_audio_devices_t_int32_t)); + legacy2aidl_audio_devices_t_AudioDeviceDescription)); return Status::ok(); } @@ -1603,7 +1608,7 @@ Status AudioPolicyService::acquireSoundTriggerSession(media::SoundTriggerSession _aidl_return->ioHandle = VALUE_OR_RETURN_BINDER_STATUS( legacy2aidl_audio_io_handle_t_int32_t(ioHandle)); _aidl_return->device = VALUE_OR_RETURN_BINDER_STATUS( - legacy2aidl_audio_devices_t_int32_t(device)); + legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); return Status::ok(); } @@ -1803,13 +1808,14 @@ Status AudioPolicyService::getMasterMono(bool* _aidl_return) } -Status AudioPolicyService::getStreamVolumeDB(media::AudioStreamType streamAidl, int32_t indexAidl, - int32_t deviceAidl, float* _aidl_return) { +Status AudioPolicyService::getStreamVolumeDB( + media::AudioStreamType streamAidl, int32_t indexAidl, + const media::AudioDeviceDescription& deviceAidl, float* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(indexAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_int32_t_audio_devices_t(deviceAidl)); + aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 11212f60ea..93dbe99c39 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -103,22 +103,27 @@ public: binder::Status releaseInput(int32_t portId) override; binder::Status initStreamVolume(media::AudioStreamType stream, int32_t indexMin, int32_t indexMax) override; - binder::Status setStreamVolumeIndex(media::AudioStreamType stream, int32_t device, + binder::Status setStreamVolumeIndex(media::AudioStreamType stream, + const media::AudioDeviceDescription& device, int32_t index) override; - binder::Status getStreamVolumeIndex(media::AudioStreamType stream, int32_t device, + binder::Status getStreamVolumeIndex(media::AudioStreamType stream, + const media::AudioDeviceDescription& device, int32_t* _aidl_return) override; binder::Status setVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, - int32_t device, int32_t index) override; + const media::AudioDeviceDescription& device, + int32_t index) override; binder::Status getVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, - int32_t device, int32_t* _aidl_return) override; + const media::AudioDeviceDescription& device, + int32_t* _aidl_return) override; binder::Status getMaxVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, int32_t* _aidl_return) override; binder::Status getMinVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, int32_t* _aidl_return) override; binder::Status getStrategyForStream(media::AudioStreamType stream, int32_t* _aidl_return) override; - binder::Status getDevicesForStream(media::AudioStreamType stream, - std::vector* _aidl_return) override; + binder::Status getDevicesForStream( + media::AudioStreamType stream, + std::vector* _aidl_return) override; binder::Status getDevicesForAttributes(const media::AudioAttributesEx& attr, std::vector* _aidl_return) override; binder::Status getOutputForEffect(const media::EffectDescriptor& desc, @@ -187,7 +192,8 @@ public: binder::Status stopAudioSource(int32_t portId) override; binder::Status setMasterMono(bool mono) override; binder::Status getMasterMono(bool* _aidl_return) override; - binder::Status getStreamVolumeDB(media::AudioStreamType stream, int32_t index, int32_t device, + binder::Status getStreamVolumeDB(media::AudioStreamType stream, int32_t index, + const media::AudioDeviceDescription& device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, std::vector* formats, -- GitLab From e278ee054dee46e348693c1a156bfbfc084fad21 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Sat, 10 Jul 2021 12:35:28 -0700 Subject: [PATCH 059/694] Update OWNERS for media apex Bug: 193311604 Test: checkin Change-Id: Ib913f6b022091837b291c4611d68273e5e8d6bb0 --- apex/OWNERS | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apex/OWNERS b/apex/OWNERS index a60d04b21a..54802d4fef 100644 --- a/apex/OWNERS +++ b/apex/OWNERS @@ -1,9 +1,7 @@ -chz@google.com -dwkang@google.com +essick@google.com jiyong@google.com lajos@google.com -marcone@google.com -wjia@google.com +nchalko@google.com include platform/packages/modules/common:/MODULES_OWNERS -- GitLab From 2d4b14dd85f14db576d611bb5ddbdb55299fc7fd Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 13 Jul 2021 15:36:31 -0700 Subject: [PATCH 060/694] Update AudioChannelLayout to address some issues Changes made: - haptic channels moved to the MSB part of the integer; - "voice up/down link" channel moved into their own union variant. Bug: 188932434 Bug: 193562113 Bug: 193563345 Test: atest audio_aidl_conversion_tests Change-Id: Idedab7142fe05ecfcbcc57c8a359a9d541395c96 --- media/libaudioclient/AidlConversion.cpp | 41 ++++++++++++--- .../android/media/AudioChannelLayout.aidl | 52 ++++++++++++++----- .../include/media/AudioCommonTypes.h | 2 + .../audio_aidl_legacy_conversion_tests.cpp | 12 ++++- 4 files changed, 88 insertions(+), 19 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 298e5964d8..bb67b53c70 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -475,10 +475,7 @@ const detail::AudioChannelPairs& getInAudioChannelPairs() { DEFINE_INPUT_LAYOUT(2POINT1POINT2), DEFINE_INPUT_LAYOUT(3POINT0POINT2), DEFINE_INPUT_LAYOUT(3POINT1POINT2), - DEFINE_INPUT_LAYOUT(5POINT1), - DEFINE_INPUT_LAYOUT(VOICE_UPLINK_MONO), - DEFINE_INPUT_LAYOUT(VOICE_DNLINK_MONO), - DEFINE_INPUT_LAYOUT(VOICE_CALL_MONO) + DEFINE_INPUT_LAYOUT(5POINT1) #undef DEFINE_INPUT_LAYOUT }; return pairs; @@ -527,6 +524,22 @@ const detail::AudioChannelPairs& getOutAudioChannelPairs() { return pairs; } +const detail::AudioChannelPairs& getVoiceAudioChannelPairs() { + static const detail::AudioChannelPairs pairs = { +#define DEFINE_VOICE_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_IN_VOICE_##n, \ + media::AudioChannelLayout::make( \ + media::AudioChannelLayout::VOICE_##n) \ + } + DEFINE_VOICE_LAYOUT(UPLINK_MONO), + DEFINE_VOICE_LAYOUT(DNLINK_MONO), + DEFINE_VOICE_LAYOUT(CALL_MONO) +#undef DEFINE_VOICE_LAYOUT + }; + return pairs; +} + media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, const std::string& connection = "") { media::AudioDeviceDescription result; @@ -1079,6 +1092,17 @@ std::unordered_map make_DirectMap(const std::vector>& v) { return result; } +template +std::unordered_map make_DirectMap( + const std::vector>& v1, const std::vector>& v2) { + std::unordered_map result(v1.begin(), v1.end()); + LOG_ALWAYS_FATAL_IF(result.size() != v1.size(), "Duplicate key elements detected in v1"); + result.insert(v2.begin(), v2.end()); + LOG_ALWAYS_FATAL_IF(result.size() != v1.size() + v2.size(), + "Duplicate key elements detected in v1+v2"); + return result; +} + template std::unordered_map make_ReverseMap(const std::vector>& v) { std::unordered_map result; @@ -1099,6 +1123,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); static const ReverseMap mIn = make_ReverseMap(getInAudioChannelPairs()); static const ReverseMap mOut = make_ReverseMap(getOutAudioChannelPairs()); + static const ReverseMap mVoice = make_ReverseMap(getVoiceAudioChannelPairs()); auto convert = [](const media::AudioChannelLayout& aidl, const ReverseMap& m, const char* func, const char* type) -> ConversionResult { @@ -1120,6 +1145,8 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan return convert(aidl, mIdx, __func__, "index"); case Tag::layoutMask: return convert(aidl, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + case Tag::voiceMask: + return convert(aidl, mVoice, __func__, "voice"); } ALOGE("%s: unexpected tag value %d", __func__, aidl.getTag()); return unexpected(BAD_VALUE); @@ -1130,7 +1157,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud using DirectMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); - static const DirectMap mIn = make_DirectMap(getInAudioChannelPairs()); + static const DirectMap mInAndVoice = make_DirectMap( + getInAudioChannelPairs(), getVoiceAudioChannelPairs()); static const DirectMap mOut = make_DirectMap(getOutAudioChannelPairs()); auto convert = [](const audio_channel_mask_t legacy, const DirectMap& m, @@ -1154,7 +1182,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { return convert(legacy, mIdx, __func__, "index"); } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { - return convert(legacy, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + return convert(legacy, isOutput ? mOut : mInAndVoice, __func__, + isOutput ? "output" : "input / voice"); } ALOGE("%s: unknown representation %d in audio_channel_mask_t value 0x%x", diff --git a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl index 9b6d59f862..fdc8184f35 100644 --- a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl +++ b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl @@ -33,6 +33,10 @@ package android.media; * number of channels in the audio frame. A channel mask per se only defines the * presence or absence of a channel, not the order. Please see 'INTERLEAVE_*' * constants for the platform convention of order. + * + * The structure also defines a "voice mask" which is a special case of + * layout mask, intended for processing voice audio from telecommunication + * use cases. */ union AudioChannelLayout { /** @@ -59,6 +63,12 @@ union AudioChannelLayout { * must have at least one bit set. */ int layoutMask; + /** + * This variant is used for processing of voice audio input and output. + * It is recommended to use one of 'VOICE_*' values. The 'voiceMask' field + * must have at least one bit set. + */ + int voiceMask; /** * 'INDEX_MASK_' constants define how many channels are used. @@ -183,12 +193,6 @@ union AudioChannelLayout { LAYOUT_STEREO | LAYOUT_HAPTIC_AB; const int LAYOUT_FRONT_BACK = CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER; - const int LAYOUT_VOICE_UPLINK_MONO = - LAYOUT_MONO | CHANNEL_VOICE_UPLINK; - const int LAYOUT_VOICE_DNLINK_MONO = - LAYOUT_MONO | CHANNEL_VOICE_DNLINK; - const int LAYOUT_VOICE_CALL_MONO = - CHANNEL_VOICE_UPLINK | CHANNEL_VOICE_DNLINK; /** * Expresses the convention when stereo audio samples are stored interleaved @@ -204,8 +208,10 @@ union AudioChannelLayout { const int INTERLEAVE_RIGHT = 1; /** - * 'CHANNEL_*' constants are used to build 'LAYOUT_*' masks. - * Each constant must have exactly one bit set. + * 'CHANNEL_*' constants are used to build 'LAYOUT_*' masks. Each constant + * must have exactly one bit set. The values do not match + * 'android.media.AudioFormat.CHANNEL_OUT_*' constants from the SDK + * for better efficiency in masks processing. */ const int CHANNEL_FRONT_LEFT = 1 << 0; const int CHANNEL_FRONT_RIGHT = 1 << 1; @@ -233,8 +239,30 @@ union AudioChannelLayout { const int CHANNEL_LOW_FREQUENCY_2 = 1 << 23; const int CHANNEL_FRONT_WIDE_LEFT = 1 << 24; const int CHANNEL_FRONT_WIDE_RIGHT = 1 << 25; - const int CHANNEL_VOICE_UPLINK = 1 << 26; - const int CHANNEL_VOICE_DNLINK = 1 << 27; - const int CHANNEL_HAPTIC_B = 1 << 28; // B then A to match legacy const. - const int CHANNEL_HAPTIC_A = 1 << 29; + /** + * Haptic channels are not part of multichannel standards, however they + * enhance user experience when playing so they are packed together with the + * channels of the program. To avoid collision with positional channels the + * values for haptic channels start at the MSB of an integer (after the sign + * bit) and move down to LSB. + */ + const int CHANNEL_HAPTIC_B = 1 << 29; + const int CHANNEL_HAPTIC_A = 1 << 30; + + /** + * 'VOICE_*' constants define layouts for voice audio. The order of the + * channels in the frame is assumed to be from the LSB to MSB for all the + * bits set to '1'. + */ + const int VOICE_UPLINK_MONO = CHANNEL_VOICE_UPLINK; + const int VOICE_DNLINK_MONO = CHANNEL_VOICE_DNLINK; + const int VOICE_CALL_MONO = CHANNEL_VOICE_UPLINK | CHANNEL_VOICE_DNLINK; + + /** + * 'CHANNEL_VOICE_*' constants are used to build 'VOICE_*' masks. Each + * constant must have exactly one bit set. Use the same values as + * 'android.media.AudioFormat.CHANNEL_IN_VOICE_*' constants from the SDK. + */ + const int CHANNEL_VOICE_UPLINK = 0x4000; + const int CHANNEL_VOICE_DNLINK = 0x8000; } diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index 2a46e05a7c..a368e74630 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -56,6 +56,8 @@ template<> struct hash return hash_combine(seed, std::hash{}(acl.get())); case Tag::layoutMask: return hash_combine(seed, std::hash{}(acl.get())); + case Tag::voiceMask: + return hash_combine(seed, std::hash{}(acl.get())); } return seed; } diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index e54935447d..b6e597dbfc 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -46,6 +46,11 @@ media::AudioChannelLayout make_ACL_ChannelIndex2() { media::AudioChannelLayout::INDEX_MASK_2); } +media::AudioChannelLayout make_ACL_VoiceCall() { + return media::AudioChannelLayout::make( + media::AudioChannelLayout::VOICE_CALL_MONO); +} + media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, const std::string& connection = "") { media::AudioDeviceDescription result; @@ -151,7 +156,8 @@ class HashIdentityTest : public ::testing::Test { TEST_F(HashIdentityTest, AudioChannelLayoutHashIdentity) { verifyHashIdentity({ - make_ACL_None, make_ACL_Invalid, make_ACL_Stereo, make_ACL_ChannelIndex2}); + make_ACL_None, make_ACL_Invalid, make_ACL_Stereo, make_ACL_ChannelIndex2, + make_ACL_VoiceCall}); } TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { @@ -184,6 +190,10 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), make_ACL_ChannelIndex2()), testing::Values(true, false))); +INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, + AudioChannelLayoutRoundTripTest, + // In legacy constants the voice call is only defined for input. + testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(false))); class AudioDeviceDescriptionRoundTripTest : public testing::TestWithParam {}; -- GitLab From 7f3a15e4f9d46b344ad6bd1d3838c6b0d4785826 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Wed, 14 Jul 2021 22:34:32 +0000 Subject: [PATCH 061/694] Update AAudioStreamBuilder_setPackageName notes We discovered that requestStart sometimes returns -896, an internal error. This error comes from mic permissions not being correct on input streams when an invalid package name is used. This fix is to update documentation. Bug: 193684488 Test: Tested with OboeTester and ran Oboe tests Change-Id: I76c0ff59a3a0c51f01471ad8d06fbff25b629436 --- media/libaaudio/include/aaudio/AAudio.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h index 4b08295e2b..4096e0506b 100644 --- a/media/libaaudio/include/aaudio/AAudio.h +++ b/media/libaaudio/include/aaudio/AAudio.h @@ -643,8 +643,11 @@ AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder, * This is usually {@code Context#getPackageName()}. * * The default, if you do not call this function, is a random package in the calling uid. - * The vast majority of apps have only one package per calling UID. If the package - * name does not match the calling UID, then requests will be rejected. + * The vast majority of apps have only one package per calling UID. + * If an invalid package name is set, input streams may not be given permission to + * record when started. + * + * The package name is usually the applicationId in your app's build.gradle file. * * Available since API level 31. * -- GitLab From 853ca392a186dd9a44310653d6052f2d90d93a68 Mon Sep 17 00:00:00 2001 From: Aayush Soni Date: Fri, 18 Jun 2021 19:16:34 +0530 Subject: [PATCH 062/694] mpeg4enc: update resolution check Updated resolution check to limit encoder to 2048x2048 Bug: 190435883 Test: POC in bug descriptions Change-Id: I749a9a3fda0924c17b3a4ddfb1c6402d2ce8552f --- media/codecs/m4v_h263/enc/src/mp4enc_api.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp index 234faefbf7..00b2ab694f 100644 --- a/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp +++ b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp @@ -610,18 +610,19 @@ OSCL_EXPORT_REF Bool PVInitVideoEncoder(VideoEncControls *encoderControl, Vid /* Find the maximum width*height for memory allocation of the VOPs */ for (idx = 0; idx < nLayers; idx++) { - temp_w = video->encParams->LayerWidth[idx]; - temp_h = video->encParams->LayerHeight[idx]; + temp_w = ((video->encParams->LayerWidth[idx] + 15) >> 4) << 4; + temp_h = ((video->encParams->LayerHeight[idx] + 15) >> 4) << 4; + + if (temp_w > 2048 || temp_h > 2048) { + goto CLEAN_UP; + } if ((temp_w*temp_h) > max) { max = temp_w * temp_h; - max_width = ((temp_w + 15) >> 4) << 4; - max_height = ((temp_h + 15) >> 4) << 4; - if (((uint64_t)max_width * max_height) > (uint64_t)INT32_MAX - || temp_w > INT32_MAX - 15 || temp_h > INT32_MAX - 15) { - goto CLEAN_UP; - } + max_width = temp_w; + max_height = temp_h; + nTotalMB = ((max_width * max_height) >> 8); } -- GitLab From b60bd1b586b74ddf375257c4d07323e271d84ff3 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 15 Jul 2021 17:31:43 -0700 Subject: [PATCH 063/694] Switch the framework AIDL to use AudioFormatDescription 'AudioFormatDescription' is a new type that will be used both by HAL and framework interfaces. This CL changes the framework interfaces to use it instead of 'AudioFormatSys' type which was used to pass legacy 'audio_devices_t' transparently via the AIDL layer. Bug: 188932434 Test: check audio on device Change-Id: I9680d4d674950838f0ef0c9b4e45feaa662c5309 --- media/libaaudio/src/Android.bp | 1 + .../src/binding/AAudioStreamConfiguration.cpp | 18 +- .../binding/aidl/aaudio/StreamParameters.aidl | 4 +- media/libaudioclient/AidlConversion.cpp | 41 ++--- media/libaudioclient/Android.bp | 1 - media/libaudioclient/AudioSystem.cpp | 24 +-- media/libaudioclient/IAudioFlinger.cpp | 16 +- .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioFormatSys.aidl | 161 ------------------ .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioOffloadInfo.aidl | 1 - .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 6 +- .../android/media/IAudioPolicyService.aidl | 14 +- .../include/media/AidlConversion.h | 5 - .../include/media/IAudioFlinger.h | 4 +- media/libaudiofoundation/AudioPort.cpp | 6 +- media/libaudiofoundation/AudioProfile.cpp | 5 +- .../service/AudioPolicyInterfaceImpl.cpp | 28 +-- .../audiopolicy/service/AudioPolicyService.h | 12 +- 22 files changed, 103 insertions(+), 264 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioFormatSys.aidl diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index cb08b1c76b..da59da6e7f 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -168,6 +168,7 @@ cc_library { "libbinder", "framework-permission-aidl-cpp", "aaudio-aidl-cpp", + "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", ], diff --git a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp index f28e0d6bad..b8115e33b3 100644 --- a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp +++ b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp @@ -23,11 +23,13 @@ #include #include +#include + #include "binding/AAudioStreamConfiguration.h" using namespace aaudio; -using android::media::AudioFormatSys; +using android::media::AudioFormatDescription; AAudioStreamConfiguration::AAudioStreamConfiguration(const StreamParameters& parcelable) { setSamplesPerFrame(parcelable.samplesPerFrame); @@ -35,8 +37,9 @@ AAudioStreamConfiguration::AAudioStreamConfiguration(const StreamParameters& par setDeviceId(parcelable.deviceId); static_assert(sizeof(aaudio_sharing_mode_t) == sizeof(parcelable.sharingMode)); setSharingMode(parcelable.sharingMode); - static_assert(sizeof(audio_format_t) == sizeof(parcelable.audioFormat)); - setFormat(static_cast(parcelable.audioFormat)); + auto convFormat = android::aidl2legacy_AudioFormatDescription_audio_format_t( + parcelable.audioFormat); + setFormat(convFormat.ok() ? convFormat.value() : AUDIO_FORMAT_INVALID); static_assert(sizeof(aaudio_direction_t) == sizeof(parcelable.direction)); setDirection(parcelable.direction); static_assert(sizeof(audio_usage_t) == sizeof(parcelable.usage)); @@ -68,8 +71,13 @@ StreamParameters AAudioStreamConfiguration::parcelable() const { result.deviceId = getDeviceId(); static_assert(sizeof(aaudio_sharing_mode_t) == sizeof(result.sharingMode)); result.sharingMode = getSharingMode(); - static_assert(sizeof(audio_format_t) == sizeof(result.audioFormat)); - result.audioFormat = static_cast(getFormat()); + auto convAudioFormat = android::legacy2aidl_audio_format_t_AudioFormatDescription(getFormat()); + if (convAudioFormat.ok()) { + result.audioFormat = convAudioFormat.value(); + } else { + result.audioFormat = AudioFormatDescription{}; + result.audioFormat.type = android::media::AudioFormatType::SYS_RESERVED_INVALID; + } static_assert(sizeof(aaudio_direction_t) == sizeof(result.direction)); result.direction = getDirection(); static_assert(sizeof(audio_usage_t) == sizeof(result.usage)); diff --git a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl index d1ba9b302e..f8c06849c8 100644 --- a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl +++ b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl @@ -16,14 +16,14 @@ package aaudio; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; parcelable StreamParameters { int samplesPerFrame; // = AAUDIO_UNSPECIFIED; int sampleRate; // = AAUDIO_UNSPECIFIED; int deviceId; // = AAUDIO_UNSPECIFIED; int /* aaudio_sharing_mode_t */ sharingMode; // = AAUDIO_SHARING_MODE_SHARED; - AudioFormatSys audioFormat; // = AUDIO_FORMAT_DEFAULT; + AudioFormatDescription audioFormat; // = AUDIO_FORMAT_DEFAULT; int /* aaudio_direction_t */ direction; // = AAUDIO_DIRECTION_OUTPUT; int /* aaudio_usage_t */ usage; // = AAUDIO_UNSPECIFIED; int /* aaudio_content_type_t */ contentType; // = AAUDIO_UNSPECIFIED; diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index ed65bd6d13..2cfb916081 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -395,20 +395,6 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy return unexpected(BAD_VALUE); } -ConversionResult aidl2legacy_AudioFormat_audio_format_t( - media::AudioFormatSys aidl) { - // This relies on AudioFormatSys being kept in sync with audio_format_t. - static_assert(sizeof(media::AudioFormatSys) == sizeof(audio_format_t)); - return static_cast(aidl); -} - -ConversionResult legacy2aidl_audio_format_t_AudioFormat( - audio_format_t legacy) { - // This relies on AudioFormatSys being kept in sync with audio_format_t. - static_assert(sizeof(media::AudioFormatSys) == sizeof(audio_format_t)); - return static_cast(legacy); -} - namespace { namespace detail { @@ -1882,7 +1868,8 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { - legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); + legacy.format = VALUE_OR_RETURN( + aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::GAIN)) { legacy.gain = VALUE_OR_RETURN( @@ -1912,7 +1899,8 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); + aidl.format = VALUE_OR_RETURN( + legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_GAIN) { aidl.gain = VALUE_OR_RETURN(legacy2aidl_audio_gain_config_AudioGainConfig( @@ -1978,7 +1966,8 @@ ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDes legacy->mIoHandle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.ioHandle)); legacy->mPatch = VALUE_OR_RETURN(aidl2legacy_AudioPatch_audio_patch(aidl.patch)); legacy->mSamplingRate = VALUE_OR_RETURN(convertIntegral(aidl.samplingRate)); - legacy->mFormat = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); + legacy->mFormat = VALUE_OR_RETURN( + aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); legacy->mChannelMask = VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy->mFrameCount = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); @@ -1994,7 +1983,8 @@ ConversionResult legacy2aidl_AudioIoDescriptor_AudioIo aidl.ioHandle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy->mIoHandle)); aidl.patch = VALUE_OR_RETURN(legacy2aidl_audio_patch_AudioPatch(legacy->mPatch)); aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->mSamplingRate)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy->mFormat)); + aidl.format = VALUE_OR_RETURN( + legacy2aidl_audio_format_t_AudioFormatDescription(legacy->mFormat)); aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->mChannelMask)); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->mFrameCount)); @@ -2330,7 +2320,8 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.config.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); - aidl.config.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); + aidl.config.format = VALUE_OR_RETURN( + legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.streamType = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(legacy.stream_type)); aidl.bitRate = VALUE_OR_RETURN(convertIntegral(legacy.bit_rate)); @@ -2362,7 +2353,7 @@ aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); - legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); + legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); legacy.frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); @@ -2375,7 +2366,7 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy.frame_count)); @@ -2388,7 +2379,7 @@ aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& ai legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); - legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); + legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); return legacy; } @@ -2398,7 +2389,7 @@ legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legac aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); return aidl; } @@ -2729,7 +2720,7 @@ ConversionResult legacy2aidl_AudioPortExt( ConversionResult aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { audio_profile legacy; - legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(aidl.format)); + legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); if (aidl.samplingRates.size() > std::size(legacy.sample_rates)) { return unexpected(BAD_VALUE); @@ -2755,7 +2746,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { ConversionResult legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { media::AudioProfile aidl; - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(legacy.format)); + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); if (legacy.num_sample_rates > std::size(legacy.sample_rates)) { return unexpected(BAD_VALUE); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 778436c48f..64256a1880 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -318,7 +318,6 @@ aidl_interface { "aidl/android/media/AudioEncapsulationType.aidl", "aidl/android/media/AudioFormatDescription.aidl", "aidl/android/media/AudioFormatType.aidl", - "aidl/android/media/AudioFormatSys.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", "aidl/android/media/AudioGainConfig.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 540f2791a5..99b56d490c 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -856,7 +856,8 @@ status_t AudioSystem::setDeviceConnectionState(audio_devices_t device, VALUE_OR_RETURN_STATUS( legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState(state)), name, - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_format_t_AudioFormat(encodedFormat)))); + VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_format_t_AudioFormatDescription(encodedFormat)))); } audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t device, @@ -903,7 +904,7 @@ status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device, return statusTFromBinderStatus( aps->handleDeviceConfigChange(deviceAidl, name, VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_format_t_AudioFormat(encodedFormat)))); + legacy2aidl_audio_format_t_AudioFormatDescription(encodedFormat)))); } status_t AudioSystem::setPhoneState(audio_mode_t state, uid_t uid) { @@ -1875,7 +1876,7 @@ status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats, media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; std::vector surroundFormatsEnabledAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl, @@ -1885,7 +1886,7 @@ status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats, convertIntegral(numSurroundFormatsAidl.value)); RETURN_STATUS_IF_ERROR( convertRange(surroundFormatsAidl.begin(), surroundFormatsAidl.end(), surroundFormats, - aidl2legacy_AudioFormat_audio_format_t)); + aidl2legacy_AudioFormatDescription_audio_format_t)); std::copy(surroundFormatsEnabledAidl.begin(), surroundFormatsEnabledAidl.end(), surroundFormatsEnabled); return OK; @@ -1902,7 +1903,7 @@ status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormat media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getReportedSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl))); @@ -1910,7 +1911,7 @@ status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormat convertIntegral(numSurroundFormatsAidl.value)); RETURN_STATUS_IF_ERROR( convertRange(surroundFormatsAidl.begin(), surroundFormatsAidl.end(), surroundFormats, - aidl2legacy_AudioFormat_audio_format_t)); + aidl2legacy_AudioFormatDescription_audio_format_t)); return OK; } @@ -1918,8 +1919,8 @@ status_t AudioSystem::setSurroundFormatEnabled(audio_format_t audioFormat, bool const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::AudioFormatSys audioFormatAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_format_t_AudioFormat(audioFormat)); + media::AudioFormatDescription audioFormatAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_format_t_AudioFormatDescription(audioFormat)); return statusTFromBinderStatus( aps->setSurroundFormatEnabled(audioFormatAidl, enabled)); } @@ -1972,12 +1973,13 @@ status_t AudioSystem::getHwOffloadEncodingFormatsSupportedForA2DP( & aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - std::vector formatsAidl; + std::vector formatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getHwOffloadEncodingFormatsSupportedForA2DP(&formatsAidl))); *formats = VALUE_OR_RETURN_STATUS( - convertContainer>(formatsAidl, - aidl2legacy_AudioFormat_audio_format_t)); + convertContainer>( + formatsAidl, + aidl2legacy_AudioFormatDescription_audio_format_t)); return OK; } diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index f89de97da7..1965cae28a 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -238,9 +238,9 @@ uint32_t AudioFlingerClientAdapter::sampleRate(audio_io_handle_t ioHandle) const audio_format_t AudioFlingerClientAdapter::format(audio_io_handle_t output) const { auto result = [&]() -> ConversionResult { int32_t outputAidl = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(output)); - media::AudioFormatSys aidlRet; + media::AudioFormatDescription aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus(mDelegate->format(outputAidl, &aidlRet))); - return aidl2legacy_AudioFormat_audio_format_t(aidlRet); + return aidl2legacy_AudioFormatDescription_audio_format_t(aidlRet); }(); return result.value_or(AUDIO_FORMAT_INVALID); } @@ -406,8 +406,8 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ audio_channel_mask_t channelMask) const { auto result = [&]() -> ConversionResult { int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); - media::AudioFormatSys formatAidl = VALUE_OR_RETURN( - legacy2aidl_audio_format_t_AudioFormat(format)); + media::AudioFormatDescription formatAidl = VALUE_OR_RETURN( + legacy2aidl_audio_format_t_AudioFormatDescription(format)); media::AudioChannelMask channelMaskAidl = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelMask(channelMask)); int64_t aidlRet; @@ -798,11 +798,11 @@ Status AudioFlingerServerAdapter::sampleRate(int32_t ioHandle, int32_t* _aidl_re } Status AudioFlingerServerAdapter::format(int32_t output, - media::AudioFormatSys* _aidl_return) { + media::AudioFormatDescription* _aidl_return) { audio_io_handle_t outputLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_int32_t_audio_io_handle_t(output)); *_aidl_return = VALUE_OR_RETURN_BINDER( - legacy2aidl_audio_format_t_AudioFormat(mDelegate->format(outputLegacy))); + legacy2aidl_audio_format_t_AudioFormatDescription(mDelegate->format(outputLegacy))); return Status::ok(); } @@ -926,12 +926,12 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( - aidl2legacy_AudioFormat_audio_format_t(format)); + aidl2legacy_AudioFormatDescription_audio_format_t(format)); audio_channel_mask_t channelMaskLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioChannelMask_audio_channel_mask_t(channelMask)); size_t size = mDelegate->getInputBufferSize(sampleRateLegacy, formatLegacy, channelMaskLegacy); diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index dc4e9e4024..5fd25d50ac 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioChannelMask; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; import android.media.AudioOffloadInfo; /** @@ -26,7 +26,7 @@ import android.media.AudioOffloadInfo; parcelable AudioConfig { int sampleRate; AudioChannelMask channelMask; - AudioFormatSys format; + AudioFormatDescription format; AudioOffloadInfo offloadInfo; long frameCount; } diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index 59fbee695d..fb20404ad7 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioChannelMask; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; /** * {@hide} @@ -25,5 +25,5 @@ import android.media.AudioFormatSys; parcelable AudioConfigBase { int sampleRate; AudioChannelMask channelMask; - AudioFormatSys format; + AudioFormatDescription format; } diff --git a/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl b/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl deleted file mode 100644 index 95a37537be..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioFormatSys.aidl +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * Audio format is a 32-bit word that consists of: - * main format field (upper 8 bits) - * sub format field (lower 24 bits). - * - * The main format indicates the main codec type. The sub format field indicates - * options and parameters for each format. The sub format is mainly used for - * record to indicate for instance the requested bitrate or profile. It can - * also be used for certain formats to give informations not present in the - * encoded audio stream (e.g. octet alignement for AMR). - * - * This type corresponds to enums in system/audio.h, whereas 'AudioFormat.aidl' - * located in frameworks/base/media/java/android/media is the type used by SDK. - * Both types are in the 'android.media' package. - * - * {@hide} - */ -@Backing(type="int") -enum AudioFormatSys { - /** - * Framework use only, do not constitute valid formats. - */ - MAIN_MASK = 0xFF000000, - SUB_MASK = 0x00FFFFFF, - INVALID = 0xFFFFFFFF, - PCM = 0x00000000, - - DEFAULT = 0, - - PCM_16_BIT = 0x1, - PCM_8_BIT = 0x2, - PCM_32_BIT = 0x3, - PCM_8_24_BIT = 0x4, - PCM_FLOAT = 0x5, - PCM_24_BIT_PACKED = 0x6, - MP3 = 0x01000000, - AMR_NB = 0x02000000, - AMR_WB = 0x03000000, - AAC = 0x04000000, - AAC_MAIN = 0x04000001, - AAC_LC = 0x04000002, - AAC_SSR = 0x04000004, - AAC_LTP = 0x04000008, - AAC_HE_V1 = 0x04000010, - AAC_SCALABLE = 0x04000020, - AAC_ERLC = 0x04000040, - AAC_LD = 0x04000080, - AAC_HE_V2 = 0x040000100, - AAC_ELD = 0x040000200, - AAC_XHE = 0x040000300, - /** - * Deprecated, Use AAC_HE_V1. - */ - HE_AAC_V1 = 0x05000000, - /** - * Deprecated, Use AAC_HE_V2. - */ - HE_AAC_V2 = 0x06000000, - VORBIS = 0x07000000, - OPUS = 0x08000000, - AC3 = 0x09000000, - E_AC3 = 0x0A000000, - E_AC3_JOC = 0x0A000001, - DTS = 0x0B000000, - DTS_HD = 0x0C000000, - IEC61937 = 0x0D000000, - DOLBY_TRUEHD = 0x0E000000, - EVRC = 0x10000000, - EVRCB = 0x11000000, - EVRCWB = 0x12000000, - EVRCNW = 0x13000000, - AAC_ADIF = 0x14000000, - WMA = 0x15000000, - WMA_PRO = 0x16000000, - AMR_WB_PLUS = 0x17000000, - MP2 = 0x18000000, - QCELP = 0x19000000, - DSD = 0x1A000000, - FLAC = 0x1B000000, - ALAC = 0x1C000000, - APE = 0x1D000000, - AAC_ADTS = 0x1E000000, - AAC_ADTS_MAIN = 0x1E000001, - AAC_ADTS_LC = 0x1E000002, - AAC_ADTS_SSR = 0x1E000004, - AAC_ADTS_LTP = 0x1E000008, - AAC_ADTS_HE_V1 = 0x1E000010, - AAC_ADTS_SCALABLE = 0x1E000020, - AAC_ADTS_ERLC = 0x1E000040, - AAC_ADTS_LD = 0x1E000080, - AAC_ADTS_HE_V2 = 0x1E000100, - AAC_ADTS_ELD = 0x1E000200, - AAC_ADTS_XHE = 0x1E000300, - SBC = 0x1F000000, - APTX = 0x20000000, - APTX_HD = 0x21000000, - AC4 = 0x22000000, - LDAC = 0x23000000, - MAT = 0x24000000, - MAT_1_0 = 0x24000001, - MAT_2_0 = 0x24000002, - MAT_2_1 = 0x24000003, - AAC_LATM = 0x25000000, - AAC_LATM_LC = 0x25000002, - AAC_LATM_HE_V1 = 0x25000010, - AAC_LATM_HE_V2 = 0x25000100, - CELT = 0x26000000, - APTX_ADAPTIVE = 0x27000000, - LHDC = 0x28000000, - LHDC_LL = 0x29000000, - APTX_TWSP = 0x2A000000, - LC3 = 0x2B000000, - MPEGH = 0x2C000000, - MPEGH_BL_L3 = 0x2C000013, - MPEGH_BL_L4 = 0x2C000014, - MPEGH_LC_L3 = 0x2C000023, - MPEGH_LC_L4 = 0x2C000024, - IEC60958 = 0x2D000000, - DTS_UHD = 0x2E000000, - DRA = 0x2F000000, - /** - * Subformats. - */ - AAC_SUB_MAIN = 0x1, - AAC_SUB_LC = 0x2, - AAC_SUB_SSR = 0x4, - AAC_SUB_LTP = 0x8, - AAC_SUB_HE_V1 = 0x10, - AAC_SUB_SCALABLE = 0x20, - AAC_SUB_ERLC = 0x40, - AAC_SUB_LD = 0x80, - AAC_SUB_HE_V2 = 0x100, - AAC_SUB_ELD = 0x200, - AAC_SUB_XHE = 0x300, - E_AC3_SUB_JOC = 0x1, - MAT_SUB_1_0 = 0x1, - MAT_SUB_2_0 = 0x2, - MAT_SUB_2_1 = 0x3, - MPEGH_SUB_BL_L3 = 0x13, - MPEGH_SUB_BL_L4 = 0x14, - MPEGH_SUB_LC_L3 = 0x23, - MPEGH_SUB_LC_L4 = 0x24, -} diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index 80dfdcd32f..84f928f973 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioChannelMask; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; import android.media.AudioPatch; /** @@ -28,7 +28,7 @@ parcelable AudioIoDescriptor { int ioHandle; AudioPatch patch; int samplingRate; - AudioFormatSys format; + AudioFormatDescription format; AudioChannelMask channelMask; long frameCount; long frameCountHAL; diff --git a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl b/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl index 693c818e65..f326305996 100644 --- a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl +++ b/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl @@ -20,7 +20,6 @@ import android.media.AudioConfigBase; import android.media.AudioEncapsulationMode; import android.media.AudioStreamType; import android.media.AudioUsage; -import android.media.AudioFormatSys; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index 7489792eca..c4b572d7f3 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -23,7 +23,7 @@ import android.media.AudioPortConfigExt; import android.media.AudioPortConfigType; import android.media.AudioPortRole; import android.media.AudioPortType; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; /** * {@hide} @@ -49,7 +49,7 @@ parcelable AudioPortConfig { /** * Format, if applicable. */ - AudioFormatSys format; + AudioFormatDescription format; /** Gain to apply, if applicable. */ AudioGainConfig gain; /** Framework only: HW_AV_SYNC, DIRECT, ... */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 0de7ca96e2..34b8d35d14 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -18,7 +18,7 @@ package android.media; import android.media.AudioChannelMask; import android.media.AudioEncapsulationType; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; /** * {@hide} @@ -26,7 +26,7 @@ import android.media.AudioFormatSys; parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ - AudioFormatSys format; + AudioFormatDescription format; AudioChannelMask[] channelMasks; int[] samplingRates; boolean isDynamicFormat; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 98a3e3bfe8..f3327477aa 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -42,7 +42,7 @@ import android.media.IAudioTrack; import android.media.MicrophoneInfoData; import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; /** * {@hide} @@ -63,7 +63,7 @@ interface IAudioFlingerService { */ int sampleRate(int /* audio_io_handle_t */ ioHandle); - AudioFormatSys format(int /* audio_io_handle_t */ output); + AudioFormatDescription format(int /* audio_io_handle_t */ output); long frameCount(int /* audio_io_handle_t */ ioHandle); @@ -116,7 +116,7 @@ interface IAudioFlingerService { // Retrieve the audio recording buffer size in bytes. // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, - AudioFormatSys format, + in AudioFormatDescription format, AudioChannelMask channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index e16e3da81c..d54bd5e309 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioFormatSys; +import android.media.AudioFormatDescription; import android.content.AttributionSourceState; import android.media.AudioAttributesEx; @@ -63,13 +63,13 @@ interface IAudioPolicyService { void setDeviceConnectionState(in AudioDevice device, in AudioPolicyDeviceState state, @utf8InCpp String deviceName, - in AudioFormatSys encodedFormat); + in AudioFormatDescription encodedFormat); AudioPolicyDeviceState getDeviceConnectionState(in AudioDevice device); void handleDeviceConfigChange(in AudioDevice device, @utf8InCpp String deviceName, - in AudioFormatSys encodedFormat); + in AudioFormatDescription encodedFormat); void setPhoneState(AudioMode state, int /* uid_t */ uid); @@ -279,7 +279,7 @@ interface IAudioPolicyService { * number of elements without actually retrieving them. */ void getSurroundFormats(inout Int count, - out AudioFormatSys[] formats, + out AudioFormatDescription[] formats, out boolean[] formatsEnabled); /** @@ -291,11 +291,11 @@ interface IAudioPolicyService { * number of elements without actually retrieving them. */ void getReportedSurroundFormats(inout Int count, - out AudioFormatSys[] formats); + out AudioFormatDescription[] formats); - AudioFormatSys[] getHwOffloadEncodingFormatsSupportedForA2DP(); + AudioFormatDescription[] getHwOffloadEncodingFormatsSupportedForA2DP(); - void setSurroundFormatEnabled(AudioFormatSys audioFormat, boolean enabled); + void setSurroundFormatEnabled(in AudioFormatDescription audioFormat, boolean enabled); void setAssistantUid(int /* uid_t */ uid); diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 319c98b47a..9e606a05c8 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -136,11 +136,6 @@ ConversionResult aidl2legacy_AudioPortType_audio_port_type_t( ConversionResult legacy2aidl_audio_port_type_t_AudioPortType( audio_port_type_t legacy); -ConversionResult aidl2legacy_AudioFormat_audio_format_t( - media::AudioFormatSys aidl); -ConversionResult legacy2aidl_audio_format_t_AudioFormat( - audio_format_t legacy); - ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( const media::AudioChannelLayout& aidl, bool isOutput); ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 634326ec0b..7ff56ec23b 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -562,7 +562,7 @@ public: Status createRecord(const media::CreateRecordRequest& request, media::CreateRecordResponse* _aidl_return) override; Status sampleRate(int32_t ioHandle, int32_t* _aidl_return) override; - Status format(int32_t output, media::AudioFormatSys* _aidl_return) override; + Status format(int32_t output, media::AudioFormatDescription* _aidl_return) override; Status frameCount(int32_t ioHandle, int64_t* _aidl_return) override; Status latency(int32_t output, int32_t* _aidl_return) override; Status setMasterVolume(float value) override; @@ -584,7 +584,7 @@ public: Status getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; - Status getInputBufferSize(int32_t sampleRate, media::AudioFormatSys format, + Status getInputBufferSize(int32_t sampleRate, const media::AudioFormatDescription& format, media::AudioChannelMask channelMask, int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index fc67c594f3..24ecd78397 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -338,7 +338,8 @@ status_t AudioPortConfig::writeToParcel(Parcel *parcel) const { status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) const { parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); - parcelable->format = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_format_t_AudioFormat(mFormat)); + parcelable->format = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_channel_mask_t_AudioChannelMask(mChannelMask)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); @@ -362,7 +363,8 @@ status_t AudioPortConfig::readFromParcel(const Parcel *parcel) { status_t AudioPortConfig::readFromParcelable(const media::AudioPortConfig& parcelable) { mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); - mFormat = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioFormat_audio_format_t(parcelable.format)); + mFormat = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); mChannelMask = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index 72431316a4..f2bed258b0 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -163,7 +163,7 @@ ConversionResult AudioProfile::toParcelable() const { media::AudioProfile parcelable; parcelable.name = mName; - parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormat(mFormat)); + parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( convertContainer>( mChannelMasks, @@ -192,7 +192,8 @@ ConversionResult> AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { sp legacy = new AudioProfile(); legacy->mName = parcelable.name; - legacy->mFormat = VALUE_OR_RETURN(aidl2legacy_AudioFormat_audio_format_t(parcelable.format)); + legacy->mFormat = VALUE_OR_RETURN( + aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, aidl2legacy_AudioChannelMask_audio_channel_mask_t)); diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index d41b5bdddc..a1c9b10bf7 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -99,13 +99,13 @@ Status AudioPolicyService::setDeviceConnectionState( const media::AudioDevice& deviceAidl, media::AudioPolicyDeviceState stateAidl, const std::string& deviceNameAidl, - media::AudioFormatSys encodedFormatAidl) { + const media::AudioFormatDescription& encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioPolicyDeviceState_audio_policy_dev_state_t(stateAidl)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioFormat_audio_format_t(encodedFormatAidl)); + aidl2legacy_AudioFormatDescription_audio_format_t(encodedFormatAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); @@ -149,11 +149,11 @@ Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& de Status AudioPolicyService::handleDeviceConfigChange( const media::AudioDevice& deviceAidl, const std::string& deviceNameAidl, - media::AudioFormatSys encodedFormatAidl) { + const media::AudioFormatDescription& encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioFormat_audio_format_t(encodedFormatAidl)); + aidl2legacy_AudioFormatDescription_audio_format_t(encodedFormatAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); @@ -1827,7 +1827,7 @@ Status AudioPolicyService::getStreamVolumeDB( } Status AudioPolicyService::getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); @@ -1849,7 +1849,8 @@ Status AudioPolicyService::getSurroundFormats(media::Int* count, numSurroundFormatsReq = std::min(numSurroundFormats, numSurroundFormatsReq); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( convertRange(surroundFormats.get(), surroundFormats.get() + numSurroundFormatsReq, - std::back_inserter(*formats), legacy2aidl_audio_format_t_AudioFormat))); + std::back_inserter(*formats), + legacy2aidl_audio_format_t_AudioFormatDescription))); formatsEnabled->insert( formatsEnabled->begin(), surroundFormatsEnabled.get(), @@ -1859,7 +1860,7 @@ Status AudioPolicyService::getSurroundFormats(media::Int* count, } Status AudioPolicyService::getReportedSurroundFormats( - media::Int* count, std::vector* formats) { + media::Int* count, std::vector* formats) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); if (numSurroundFormats > MAX_ITEMS_PER_LIST) { @@ -1879,13 +1880,14 @@ Status AudioPolicyService::getReportedSurroundFormats( numSurroundFormatsReq = std::min(numSurroundFormats, numSurroundFormatsReq); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( convertRange(surroundFormats.get(), surroundFormats.get() + numSurroundFormatsReq, - std::back_inserter(*formats), legacy2aidl_audio_format_t_AudioFormat))); + std::back_inserter(*formats), + legacy2aidl_audio_format_t_AudioFormatDescription))); count->value = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(numSurroundFormats)); return Status::ok(); } Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) { + std::vector* _aidl_return) { std::vector formats; if (mAudioPolicyManager == NULL) { @@ -1896,16 +1898,16 @@ Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getHwOffloadEncodingFormatsSupportedForA2DP(&formats))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>( + convertContainer>( formats, - legacy2aidl_audio_format_t_AudioFormat)); + legacy2aidl_audio_format_t_AudioFormatDescription)); return Status::ok(); } Status AudioPolicyService::setSurroundFormatEnabled( - media::AudioFormatSys audioFormatAidl, bool enabled) { + const media::AudioFormatDescription& audioFormatAidl, bool enabled) { audio_format_t audioFormat = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioFormat_audio_format_t(audioFormatAidl)); + aidl2legacy_AudioFormatDescription_audio_format_t(audioFormatAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); } diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 93dbe99c39..e4adfe7cfd 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -71,13 +71,13 @@ public: const media::AudioDevice& device, media::AudioPolicyDeviceState state, const std::string& deviceName, - media::AudioFormatSys encodedFormat) override; + const media::AudioFormatDescription& encodedFormat) override; binder::Status getDeviceConnectionState(const media::AudioDevice& device, media::AudioPolicyDeviceState* _aidl_return) override; binder::Status handleDeviceConfigChange( const media::AudioDevice& device, const std::string& deviceName, - media::AudioFormatSys encodedFormat) override; + const media::AudioFormatDescription& encodedFormat) override; binder::Status setPhoneState(media::AudioMode state, int32_t uid) override; binder::Status setForceUse(media::AudioPolicyForceUse usage, media::AudioPolicyForcedConfig config) override; @@ -196,13 +196,13 @@ public: const media::AudioDeviceDescription& device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) override; binder::Status getReportedSurroundFormats( - media::Int* count, std::vector* formats) override; + media::Int* count, std::vector* formats) override; binder::Status getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) override; - binder::Status setSurroundFormatEnabled(media::AudioFormatSys audioFormat, + std::vector* _aidl_return) override; + binder::Status setSurroundFormatEnabled(const media::AudioFormatDescription& audioFormat, bool enabled) override; binder::Status setAssistantUid(int32_t uid) override; binder::Status setA11yServicesUids(const std::vector& uids) override; -- GitLab From 3b26818b0c572361e9198722e8eac3499982aef6 Mon Sep 17 00:00:00 2001 From: Cliff Wu Date: Tue, 6 Jul 2021 15:44:43 +0800 Subject: [PATCH 064/694] Solve the issue that the injection camera cannot be injected when the stream configuration is completed and the camera device is active MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It runs normally in “First call injectCamera() and then run configureStreamsLocked()" case, but there are the following issues in "First run configureStreamsLocked() and then call injectCamera()" case: - The streaming configuration of the internal camera is not stored correctly. Solution: Added storeInjectionConfig() to store internal configure when the stream configuration is completed and injectCamera() has not been called. - After internalPauseAndWaitLocked(), readOneCameraMetadataLocked() will have the problem of "Cannot read camera metadata from fmq", resulting in removeInFlightRequestIfReadyLocked() unable to completely clear mInFlightMap. The root cause is to directly override mResultMetadataQueue in injectionInitialize(), but the above issue will occur when the camera device is active. Solution: Generate mInjectionResultMetadataQueue during injectionInitialize(). When injecting camera, save the original mResultMetadataQueue into mBackupResultMetadataQueue, and replace the original mResultMetadataQueue with mInjectionResultMetadataQueue. - When the camera device is active, injectCamera() and stopInjection() will call internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked state (https://source.corp.google.com/android/system/core/libutils/include/utils/Condition.h;l=67) , so we need to add "Mutex::Autolock l(mLock)" here to lock the "mLock" before calling internalPauseAndWaitLocked() or internalResumeLocked(). If we don't do this, it may cause the mutex "mLock" state to be out of order. After that, all functions that use the mutex "mLock" will be in a waiting state, such as clearStreamingRequest() called when the camera is closed. Solution: Added "Mutex::Autolock l(mLock)" in injectCamera() and stopInjection(). - Unable to run stopInjection() function from app. Solution: First obtain the client descriptor from ActiveClientManager, and then call clearInjectionParameters(), otherwise mInjectionInternalCamId iscleared and the corresponding client descriptor cannot be obtained. Bug: 189289800 Test: Manual Change-Id: If5ca8d7a8431d58d97214d5e6faa7a0e5013f862 --- .../camera/libcameraservice/CameraService.cpp | 6 +-- .../device3/Camera3Device.cpp | 44 ++++++++++++--- .../libcameraservice/device3/Camera3Device.h | 24 ++++++++- .../device3/Camera3DeviceInjectionMethods.cpp | 54 ++++++++++++++----- 4 files changed, 101 insertions(+), 27 deletions(-) diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp index efb0a04ed4..7b138a64d2 100644 --- a/services/camera/libcameraservice/CameraService.cpp +++ b/services/camera/libcameraservice/CameraService.cpp @@ -3854,7 +3854,6 @@ void CameraService::InjectionStatusListener::removeListener() { void CameraService::InjectionStatusListener::notifyInjectionError( String8 injectedCamId, status_t err) { - Mutex::Autolock lock(mListenerLock); if (mCameraInjectionCallback == nullptr) { ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr"); return; @@ -3901,16 +3900,15 @@ void CameraService::InjectionStatusListener::notifyInjectionError( void CameraService::InjectionStatusListener::binderDied( const wp& /*who*/) { - Mutex::Autolock lock(mListenerLock); ALOGV("InjectionStatusListener: ICameraInjectionCallback has died"); auto parent = mParent.promote(); if (parent != nullptr) { - parent->clearInjectionParameters(); auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId); if (clientDescriptor != nullptr) { BasicClient* baseClientPtr = clientDescriptor->getValue().get(); baseClientPtr->stopInjection(); } + parent->clearInjectionParameters(); } } @@ -3928,7 +3926,6 @@ binder::Status CameraService::CameraInjectionSession::stopInjection() { } status_t res = NO_ERROR; - parent->clearInjectionParameters(); auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId); if (clientDescriptor != nullptr) { BasicClient* baseClientPtr = clientDescriptor->getValue().get(); @@ -3940,6 +3937,7 @@ binder::Status CameraService::CameraInjectionSession::stopInjection() { "Camera session encountered error"); } } + parent->clearInjectionParameters(); return binder::Status::ok(); } diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp index 0101c58c81..e4c299ca9e 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.cpp +++ b/services/camera/libcameraservice/device3/Camera3Device.cpp @@ -2823,17 +2823,28 @@ status_t Camera3Device::configureStreamsLocked(int operatingMode, mRequestBufferSM.onStreamsConfigured(); } + // First call injectCamera() and then run configureStreamsLocked() case: // Since the streams configuration of the injection camera is based on the internal camera, we - // must wait until the internal camera configure streams before calling injectCamera() to + // must wait until the internal camera configure streams before running the injection job to // configure the injection streams. if (mInjectionMethods->isInjecting()) { - ALOGV("%s: Injection camera %s: Start to configure streams.", + ALOGD("%s: Injection camera %s: Start to configure streams.", __FUNCTION__, mInjectionMethods->getInjectedCamId().string()); res = mInjectionMethods->injectCamera(config, bufferSizes); if (res != OK) { ALOGE("Can't finish inject camera process!"); return res; } + } else { + // First run configureStreamsLocked() and then call injectCamera() case: + // If the stream configuration has been completed and camera deive is active, but the + // injection camera has not been injected yet, we need to store the stream configuration of + // the internal camera (because the stream configuration of the injection camera is based + // on the internal camera). When injecting occurs later, this configuration can be used by + // the injection camera. + ALOGV("%s: The stream configuration is complete and the camera device is active, but the" + " injection camera has not been injected yet.", __FUNCTION__); + mInjectionMethods->storeInjectionConfig(config, bufferSizes); } return OK; @@ -6544,6 +6555,13 @@ status_t Camera3Device::injectCamera(const String8& injectedCamId, ALOGI("%s Injection camera: injectedCamId = %s", __FUNCTION__, injectedCamId.string()); ATRACE_CALL(); Mutex::Autolock il(mInterfaceLock); + // When the camera device is active, injectCamera() and stopInjection() will call + // internalPauseAndWaitLocked() and internalResumeLocked(), and then they will call + // mStatusChanged.waitRelative(mLock, timeout) of waitUntilStateThenRelock(). But + // mStatusChanged.waitRelative(mLock, timeout)'s parameter: mutex "mLock" must be in the locked + // state, so we need to add "Mutex::Autolock l(mLock)" to lock the "mLock" before calling + // waitUntilStateThenRelock(). + Mutex::Autolock l(mLock); status_t res = NO_ERROR; if (mInjectionMethods->isInjecting()) { @@ -6566,16 +6584,25 @@ status_t Camera3Device::injectCamera(const String8& injectedCamId, return res; } - camera3::camera_stream_configuration injectionConfig; - std::vector injectionBufferSizes; - mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes); // When the second display of android is cast to the remote device, and the opened camera is // also cast to the second display, in this case, because the camera has configured the streams // at this time, we can directly call injectCamera() to replace the internal camera with // injection camera. - if (mOperatingMode >= 0 && injectionConfig.num_streams > 0 - && injectionBufferSizes.size() > 0) { - ALOGV("%s: The opened camera is directly cast to the remote device.", __FUNCTION__); + if (mInjectionMethods->isStreamConfigCompleteButNotInjected()) { + ALOGD("%s: The opened camera is directly cast to the remote device.", __FUNCTION__); + + camera3::camera_stream_configuration injectionConfig; + std::vector injectionBufferSizes; + mInjectionMethods->getInjectionConfig(&injectionConfig, &injectionBufferSizes); + if (mOperatingMode < 0 || injectionConfig.num_streams <= 0 + || injectionBufferSizes.size() <= 0) { + ALOGE("Failed to inject camera due to abandoned configuration! " + "mOperatingMode: %d injectionConfig.num_streams: %d " + "injectionBufferSizes.size(): %zu", mOperatingMode, + injectionConfig.num_streams, injectionBufferSizes.size()); + return DEAD_OBJECT; + } + res = mInjectionMethods->injectCamera( injectionConfig, injectionBufferSizes); if (res != OK) { @@ -6590,6 +6617,7 @@ status_t Camera3Device::injectCamera(const String8& injectedCamId, status_t Camera3Device::stopInjection() { ALOGI("%s: Injection camera: stopInjection", __FUNCTION__); Mutex::Autolock il(mInterfaceLock); + Mutex::Autolock l(mLock); return mInjectionMethods->stopInjection(); } diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h index 53a696f6c2..e67777df86 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.h +++ b/services/camera/libcameraservice/device3/Camera3Device.h @@ -1361,25 +1361,34 @@ class Camera3Device : // when device is IDLE and request thread is paused. status_t injectCamera( camera3::camera_stream_configuration& injectionConfig, - std::vector& injectionBufferSizes); + const std::vector& injectionBufferSizes); // Stop the injection camera and switch back to backup hal interface. status_t stopInjection(); bool isInjecting(); + bool isStreamConfigCompleteButNotInjected(); + const String8& getInjectedCamId() const; void getInjectionConfig(/*out*/ camera3::camera_stream_configuration* injectionConfig, /*out*/ std::vector* injectionBufferSizes); + // When the streaming configuration is completed and the camera device is active, but the + // injection camera has not yet been injected, the streaming configuration of the internal + // camera will be stored first. + void storeInjectionConfig( + const camera3::camera_stream_configuration& injectionConfig, + const std::vector& injectionBufferSizes); + private: // Configure the streams of injection camera, it need wait until the // output streams are created and configured to the original camera before // proceeding. status_t injectionConfigureStreams( camera3::camera_stream_configuration& injectionConfig, - std::vector& injectionBufferSizes); + const std::vector& injectionBufferSizes); // Disconnect the injection camera and delete the hal interface. void injectionDisconnectImpl(); @@ -1397,6 +1406,17 @@ class Camera3Device : // Generated injection camera hal interface. sp mInjectedCamHalInterface; + // Backup of the original camera hal result FMQ. + std::unique_ptr mBackupResultMetadataQueue; + + // FMQ writes the result for the injection camera. Must be guarded by + // mProcessCaptureResultLock. + std::unique_ptr mInjectionResultMetadataQueue; + + // The flag indicates that the stream configuration is complete, the camera device is + // active, but the injection camera has not yet been injected. + bool mIsStreamConfigCompleteButNotInjected = false; + // Copy the configuration of the internal camera. camera3::camera_stream_configuration mInjectionConfig; diff --git a/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp b/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp index f145dac397..702693496c 100644 --- a/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp +++ b/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp @@ -86,7 +86,7 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectionInitialize( return DEAD_OBJECT; } - std::unique_ptr& resQueue = parent->mResultMetadataQueue; + std::unique_ptr& resQueue = mInjectionResultMetadataQueue; auto resultQueueRet = session->getCaptureResultMetadataQueue( [&resQueue](const auto& descriptor) { resQueue = std::make_unique(descriptor); @@ -127,10 +127,8 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectionInitialize( status_t Camera3Device::Camera3DeviceInjectionMethods::injectCamera( camera3::camera_stream_configuration& injectionConfig, - std::vector& injectionBufferSizes) { + const std::vector& injectionBufferSizes) { status_t res = NO_ERROR; - mInjectionConfig = injectionConfig; - mInjectionBufferSizes = injectionBufferSizes; if (mInjectedCamHalInterface == nullptr) { ALOGE("%s: mInjectedCamHalInterface does not exist!", __FUNCTION__); @@ -148,7 +146,6 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectCamera( if (parent->mStatus == STATUS_ACTIVE) { ALOGV("%s: Let the device be IDLE and the request thread is paused", __FUNCTION__); - parent->mPauseStateNotify = true; res = parent->internalPauseAndWaitLocked(maxExpectedDuration); if (res != OK) { ALOGE("%s: Can't pause captures to inject camera!", __FUNCTION__); @@ -188,7 +185,7 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectCamera( ALOGV("%s: Restarting activity to inject camera", __FUNCTION__); // Reuse current operating mode and session parameters for new stream // config. - parent->internalUpdateStatusLocked(STATUS_ACTIVE); + parent->internalResumeLocked(); } return OK; @@ -196,6 +193,11 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectCamera( status_t Camera3Device::Camera3DeviceInjectionMethods::stopInjection() { status_t res = NO_ERROR; + mIsStreamConfigCompleteButNotInjected = false; + if (mInjectionConfig.streams != nullptr) { + delete [] mInjectionConfig.streams; + mInjectionConfig.streams = nullptr; + } sp parent = mParent.promote(); if (parent == nullptr) { @@ -208,7 +210,6 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::stopInjection() { if (parent->mStatus == STATUS_ACTIVE) { ALOGV("%s: Let the device be IDLE and the request thread is paused", __FUNCTION__); - parent->mPauseStateNotify = true; res = parent->internalPauseAndWaitLocked(maxExpectedDuration); if (res != OK) { ALOGE("%s: Can't pause captures to stop injection!", __FUNCTION__); @@ -229,7 +230,7 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::stopInjection() { ALOGV("%s: Restarting activity to stop injection", __FUNCTION__); // Reuse current operating mode and session parameters for new stream // config. - parent->internalUpdateStatusLocked(STATUS_ACTIVE); + parent->internalResumeLocked(); } return OK; @@ -243,6 +244,10 @@ bool Camera3Device::Camera3DeviceInjectionMethods::isInjecting() { } } +bool Camera3Device::Camera3DeviceInjectionMethods::isStreamConfigCompleteButNotInjected() { + return mIsStreamConfigCompleteButNotInjected; +} + const String8& Camera3Device::Camera3DeviceInjectionMethods::getInjectedCamId() const { return mInjectedCamId; @@ -260,10 +265,26 @@ void Camera3Device::Camera3DeviceInjectionMethods::getInjectionConfig( *injectionBufferSizes = mInjectionBufferSizes; } +void Camera3Device::Camera3DeviceInjectionMethods::storeInjectionConfig( + const camera3::camera_stream_configuration& injectionConfig, + const std::vector& injectionBufferSizes) { + mIsStreamConfigCompleteButNotInjected = true; + if (mInjectionConfig.streams != nullptr) { + delete [] mInjectionConfig.streams; + mInjectionConfig.streams = nullptr; + } + mInjectionConfig = injectionConfig; + mInjectionConfig.streams = + (android::camera3::camera_stream_t **) new camera_stream_t*[injectionConfig.num_streams]; + for (size_t i = 0; i < injectionConfig.num_streams; i++) { + mInjectionConfig.streams[i] = injectionConfig.streams[i]; + } + mInjectionBufferSizes = injectionBufferSizes; +} status_t Camera3Device::Camera3DeviceInjectionMethods::injectionConfigureStreams( camera3::camera_stream_configuration& injectionConfig, - std::vector& injectionBufferSizes) { + const std::vector& injectionBufferSizes) { ATRACE_CALL(); status_t res = NO_ERROR; @@ -326,7 +347,6 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectionConfigureStreams mInjectedCamId.string()); auto rc = parent->mPreparerThread->resume(); - if (rc != OK) { ALOGE("%s: Injection camera %s: Preparer thread failed to resume!", __FUNCTION__, mInjectedCamId.string()); @@ -380,10 +400,18 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::replaceHalInterface( return INVALID_OPERATION; } - if (keepBackup && mBackupHalInterface == nullptr) { - mBackupHalInterface = parent->mInterface; - } else if (!keepBackup) { + if (keepBackup) { + if (mBackupHalInterface == nullptr) { + mBackupHalInterface = parent->mInterface; + } + if (mBackupResultMetadataQueue == nullptr) { + mBackupResultMetadataQueue = std::move(parent->mResultMetadataQueue); + parent->mResultMetadataQueue = std::move(mInjectionResultMetadataQueue); + } + } else { mBackupHalInterface = nullptr; + parent->mResultMetadataQueue = std::move(mBackupResultMetadataQueue); + mBackupResultMetadataQueue = nullptr; } parent->mInterface = newHalInterface; -- GitLab From 93b1079a1ed265c74e321baaa5dc345537413ffc Mon Sep 17 00:00:00 2001 From: Shuzhen Wang Date: Mon, 26 Jul 2021 09:46:31 -0700 Subject: [PATCH 065/694] Camera: Print usage flag as hex, not decimal Hex form is easier to read given the usage flag is a bitmask. Test: Inspect media.camera dumpsys Change-Id: Ieb558c7ff38cef591a44e2bb9ae09dc80edaa72a --- .../camera/libcameraservice/device3/Camera3IOStreamBase.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp b/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp index 0204d491d1..2f4d669d87 100644 --- a/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp +++ b/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp @@ -82,7 +82,7 @@ void Camera3IOStreamBase::dump(int fd, const Vector &args) const { camera_stream::width, camera_stream::height, camera_stream::format, camera_stream::data_space); lines.appendFormat(" Max size: %zu\n", mMaxSize); - lines.appendFormat(" Combined usage: %" PRIu64 ", max HAL buffers: %d\n", + lines.appendFormat(" Combined usage: 0x%" PRIx64 ", max HAL buffers: %d\n", mUsage | consumerUsage, camera_stream::max_buffers); if (strlen(camera_stream::physical_camera_id) > 0) { lines.appendFormat(" Physical camera id: %s\n", camera_stream::physical_camera_id); -- GitLab From 88536dfa674d6abd4fed0bca29241aa3621c3da9 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Mon, 26 Jul 2021 17:30:29 -0700 Subject: [PATCH 066/694] Refactor AudioIoDescriptor The following changes were made: 1. Make the class mostly immutable (except for the 'mPatch' field). 2. Provide constructors for specific use cases. 3. Add 'isInput' field instead of deducing it by patch data. 4. Provide conversion to string for logging. 5. Rename 'audio_io_config_event' to 'audio_io_config_event_t' to conform to other enum type names. Bug: 188932434 Test: m Change-Id: I35e5c83bcb917f60d01ee977eef9b869c3894074 --- media/libaudioclient/AidlConversion.cpp | 53 ++++++----- media/libaudioclient/AudioSystem.cpp | 73 +++++++-------- .../aidl/android/media/AudioIoDescriptor.aidl | 1 + .../include/media/AidlConversion.h | 6 +- .../include/media/AudioIoDescriptor.h | 91 +++++++++++++------ services/audioflinger/AudioFlinger.cpp | 12 +-- services/audioflinger/AudioFlinger.h | 2 +- services/audioflinger/Threads.cpp | 73 +++++---------- services/audioflinger/Threads.h | 18 ++-- 9 files changed, 169 insertions(+), 160 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 2cfb916081..60df8d5d3e 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -289,7 +289,7 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Audio return convertReinterpret(legacy); } -ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event( +ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl) { switch (aidl) { case media::AudioIoConfigEvent::OUTPUT_REGISTERED: @@ -314,8 +314,8 @@ ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_ return unexpected(BAD_VALUE); } -ConversionResult legacy2aidl_audio_io_config_event_AudioIoConfigEvent( - audio_io_config_event legacy) { +ConversionResult legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent( + audio_io_config_event_t legacy) { switch (legacy) { case AUDIO_OUTPUT_REGISTERED: return media::AudioIoConfigEvent::OUTPUT_REGISTERED; @@ -1962,35 +1962,40 @@ ConversionResult legacy2aidl_audio_patch_AudioPatch( ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDescriptor( const media::AudioIoDescriptor& aidl) { - sp legacy(new AudioIoDescriptor()); - legacy->mIoHandle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.ioHandle)); - legacy->mPatch = VALUE_OR_RETURN(aidl2legacy_AudioPatch_audio_patch(aidl.patch)); - legacy->mSamplingRate = VALUE_OR_RETURN(convertIntegral(aidl.samplingRate)); - legacy->mFormat = VALUE_OR_RETURN( + const audio_io_handle_t io_handle = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_io_handle_t(aidl.ioHandle)); + const struct audio_patch patch = VALUE_OR_RETURN( + aidl2legacy_AudioPatch_audio_patch(aidl.patch)); + const bool isInput = aidl.isInput; + const uint32_t sampling_rate = VALUE_OR_RETURN(convertIntegral(aidl.samplingRate)); + const audio_format_t format = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); - legacy->mChannelMask = - VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); - legacy->mFrameCount = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); - legacy->mFrameCountHAL = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); - legacy->mLatency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); - legacy->mPortId = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.portId)); - return legacy; + const audio_channel_mask_t channel_mask = VALUE_OR_RETURN( + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + const size_t frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); + const size_t frame_count_hal = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); + const uint32_t latency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); + const audio_port_handle_t port_id = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_port_handle_t(aidl.portId)); + return sp::make(io_handle, patch, isInput, sampling_rate, format, + channel_mask, frame_count, frame_count_hal, latency, port_id); } ConversionResult legacy2aidl_AudioIoDescriptor_AudioIoDescriptor( const sp& legacy) { media::AudioIoDescriptor aidl; - aidl.ioHandle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy->mIoHandle)); - aidl.patch = VALUE_OR_RETURN(legacy2aidl_audio_patch_AudioPatch(legacy->mPatch)); - aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->mSamplingRate)); + aidl.ioHandle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy->getIoHandle())); + aidl.patch = VALUE_OR_RETURN(legacy2aidl_audio_patch_AudioPatch(legacy->getPatch())); + aidl.isInput = legacy->getIsInput(); + aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->getSamplingRate())); aidl.format = VALUE_OR_RETURN( - legacy2aidl_audio_format_t_AudioFormatDescription(legacy->mFormat)); + legacy2aidl_audio_format_t_AudioFormatDescription(legacy->getFormat())); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->mChannelMask)); - aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->mFrameCount)); - aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->mFrameCountHAL)); - aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->mLatency)); - aidl.portId = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy->mPortId)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->getChannelMask())); + aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCount())); + aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCountHAL())); + aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->getLatency())); + aidl.portId = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy->getPortId())); return aidl; } diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 1d47e3a8ad..b9de92a2c7 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -336,7 +336,7 @@ status_t AudioSystem::getSamplingRate(audio_io_handle_t ioHandle, if (desc == 0) { *samplingRate = af->sampleRate(ioHandle); } else { - *samplingRate = desc->mSamplingRate; + *samplingRate = desc->getSamplingRate(); } if (*samplingRate == 0) { ALOGE("AudioSystem::getSamplingRate failed for ioHandle %d", ioHandle); @@ -371,7 +371,7 @@ status_t AudioSystem::getFrameCount(audio_io_handle_t ioHandle, if (desc == 0) { *frameCount = af->frameCount(ioHandle); } else { - *frameCount = desc->mFrameCount; + *frameCount = desc->getFrameCount(); } if (*frameCount == 0) { ALOGE("AudioSystem::getFrameCount failed for ioHandle %d", ioHandle); @@ -406,7 +406,7 @@ status_t AudioSystem::getLatency(audio_io_handle_t output, if (outputDesc == 0) { *latency = af->latency(output); } else { - *latency = outputDesc->mLatency; + *latency = outputDesc->getLatency(); } ALOGV("getLatency() output %d, latency %d", output, *latency); @@ -494,7 +494,7 @@ status_t AudioSystem::getFrameCountHAL(audio_io_handle_t ioHandle, if (desc == 0) { *frameCount = af->frameCountHAL(ioHandle); } else { - *frameCount = desc->mFrameCountHAL; + *frameCount = desc->getFrameCountHAL(); } if (*frameCount == 0) { ALOGE("AudioSystem::getFrameCountHAL failed for ioHandle %d", ioHandle); @@ -535,15 +535,15 @@ void AudioSystem::AudioFlingerClient::binderDied(const wp& who __unused Status AudioSystem::AudioFlingerClient::ioConfigChanged( media::AudioIoConfigEvent _event, const media::AudioIoDescriptor& _ioDesc) { - audio_io_config_event event = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioIoConfigEvent_audio_io_config_event(_event)); + audio_io_config_event_t event = VALUE_OR_RETURN_BINDER_STATUS( + aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t(_event)); sp ioDesc( VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioIoDescriptor_AudioIoDescriptor(_ioDesc))); ALOGV("ioConfigChanged() event %d", event); - if (ioDesc->mIoHandle == AUDIO_IO_HANDLE_NONE) return Status::ok(); + if (ioDesc->getIoHandle() == AUDIO_IO_HANDLE_NONE) return Status::ok(); audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE; std::vector> callbacksToCall; @@ -556,93 +556,88 @@ Status AudioSystem::AudioFlingerClient::ioConfigChanged( case AUDIO_OUTPUT_REGISTERED: case AUDIO_INPUT_OPENED: case AUDIO_INPUT_REGISTERED: { - sp oldDesc = getIoDescriptor_l(ioDesc->mIoHandle); + sp oldDesc = getIoDescriptor_l(ioDesc->getIoHandle()); if (oldDesc == 0) { - mIoDescriptors.add(ioDesc->mIoHandle, ioDesc); + mIoDescriptors.add(ioDesc->getIoHandle(), ioDesc); } else { deviceId = oldDesc->getDeviceId(); - mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc); + mIoDescriptors.replaceValueFor(ioDesc->getIoHandle(), ioDesc); } if (ioDesc->getDeviceId() != AUDIO_PORT_HANDLE_NONE) { deviceId = ioDesc->getDeviceId(); if (event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED) { - auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle); + auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle()); if (it != mAudioDeviceCallbacks.end()) { callbacks = it->second; } } } - ALOGV("ioConfigChanged() new %s %s %d samplingRate %u, format %#x channel mask %#x " - "frameCount %zu deviceId %d", + ALOGV("ioConfigChanged() new %s %s %s", event == AUDIO_OUTPUT_OPENED || event == AUDIO_OUTPUT_REGISTERED ? "output" : "input", event == AUDIO_OUTPUT_OPENED || event == AUDIO_INPUT_OPENED ? "opened" : "registered", - ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat, - ioDesc->mChannelMask, - ioDesc->mFrameCount, ioDesc->getDeviceId()); + ioDesc->toDebugString().c_str()); } break; case AUDIO_OUTPUT_CLOSED: case AUDIO_INPUT_CLOSED: { - if (getIoDescriptor_l(ioDesc->mIoHandle) == 0) { + if (getIoDescriptor_l(ioDesc->getIoHandle()) == 0) { ALOGW("ioConfigChanged() closing unknown %s %d", - event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle); + event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->getIoHandle()); break; } ALOGV("ioConfigChanged() %s %d closed", - event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->mIoHandle); + event == AUDIO_OUTPUT_CLOSED ? "output" : "input", ioDesc->getIoHandle()); - mIoDescriptors.removeItem(ioDesc->mIoHandle); - mAudioDeviceCallbacks.erase(ioDesc->mIoHandle); + mIoDescriptors.removeItem(ioDesc->getIoHandle()); + mAudioDeviceCallbacks.erase(ioDesc->getIoHandle()); } break; case AUDIO_OUTPUT_CONFIG_CHANGED: case AUDIO_INPUT_CONFIG_CHANGED: { - sp oldDesc = getIoDescriptor_l(ioDesc->mIoHandle); + sp oldDesc = getIoDescriptor_l(ioDesc->getIoHandle()); if (oldDesc == 0) { ALOGW("ioConfigChanged() modifying unknown %s! %d", event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input", - ioDesc->mIoHandle); + ioDesc->getIoHandle()); break; } deviceId = oldDesc->getDeviceId(); - mIoDescriptors.replaceValueFor(ioDesc->mIoHandle, ioDesc); + mIoDescriptors.replaceValueFor(ioDesc->getIoHandle(), ioDesc); if (deviceId != ioDesc->getDeviceId()) { deviceId = ioDesc->getDeviceId(); - auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle); + auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle()); if (it != mAudioDeviceCallbacks.end()) { callbacks = it->second; } } - ALOGV("ioConfigChanged() new config for %s %d samplingRate %u, format %#x " - "channel mask %#x frameCount %zu frameCountHAL %zu deviceId %d", + ALOGV("ioConfigChanged() new config for %s %s", event == AUDIO_OUTPUT_CONFIG_CHANGED ? "output" : "input", - ioDesc->mIoHandle, ioDesc->mSamplingRate, ioDesc->mFormat, - ioDesc->mChannelMask, ioDesc->mFrameCount, ioDesc->mFrameCountHAL, - ioDesc->getDeviceId()); + ioDesc->toDebugString().c_str()); } break; case AUDIO_CLIENT_STARTED: { - sp oldDesc = getIoDescriptor_l(ioDesc->mIoHandle); + sp oldDesc = getIoDescriptor_l(ioDesc->getIoHandle()); if (oldDesc == 0) { - ALOGW("ioConfigChanged() start client on unknown io! %d", ioDesc->mIoHandle); + ALOGW("ioConfigChanged() start client on unknown io! %d", + ioDesc->getIoHandle()); break; } ALOGV("ioConfigChanged() AUDIO_CLIENT_STARTED io %d port %d num callbacks %zu", - ioDesc->mIoHandle, ioDesc->mPortId, mAudioDeviceCallbacks.size()); - oldDesc->mPatch = ioDesc->mPatch; - auto it = mAudioDeviceCallbacks.find(ioDesc->mIoHandle); + ioDesc->getIoHandle(), ioDesc->getPortId(), mAudioDeviceCallbacks.size()); + oldDesc->setPatch(ioDesc->getPatch()); + auto it = mAudioDeviceCallbacks.find(ioDesc->getIoHandle()); if (it != mAudioDeviceCallbacks.end()) { auto cbks = it->second; - auto it2 = cbks.find(ioDesc->mPortId); + auto it2 = cbks.find(ioDesc->getPortId()); if (it2 != cbks.end()) { - callbacks.emplace(ioDesc->mPortId, it2->second); + callbacks.emplace(ioDesc->getPortId(), it2->second); deviceId = oldDesc->getDeviceId(); } } @@ -661,8 +656,8 @@ Status AudioSystem::AudioFlingerClient::ioConfigChanged( // Callbacks must be called without mLock held. May lead to dead lock if calling for // example getRoutedDevice that updates the device and tries to acquire mLock. for (auto cb : callbacksToCall) { - // If callbacksToCall is not empty, it implies ioDesc->mIoHandle and deviceId are valid - cb->onAudioDeviceUpdate(ioDesc->mIoHandle, deviceId); + // If callbacksToCall is not empty, it implies ioDesc->getIoHandle() and deviceId are valid + cb->onAudioDeviceUpdate(ioDesc->getIoHandle(), deviceId); } return Status::ok(); diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index 84f928f973..ea8ec3205f 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -27,6 +27,7 @@ parcelable AudioIoDescriptor { /** Interpreted as audio_io_handle_t. */ int ioHandle; AudioPatch patch; + boolean isInput; int samplingRate; AudioFormatDescription format; AudioChannelMask channelMask; diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 9e606a05c8..e56106a710 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -121,10 +121,10 @@ aidl2legacy_optional_string_view_optional_String16(std::optional> legacy2aidl_optional_String16_optional_string(std::optional legacy); -ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event( +ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl); -ConversionResult legacy2aidl_audio_io_config_event_AudioIoConfigEvent( - audio_io_config_event legacy); +ConversionResult legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent( + audio_io_config_event_t legacy); ConversionResult aidl2legacy_AudioPortRole_audio_port_role_t( media::AudioPortRole aidl); diff --git a/media/libaudioclient/include/media/AudioIoDescriptor.h b/media/libaudioclient/include/media/AudioIoDescriptor.h index 981d33a39a..ef729ed63a 100644 --- a/media/libaudioclient/include/media/AudioIoDescriptor.h +++ b/media/libaudioclient/include/media/AudioIoDescriptor.h @@ -17,9 +17,15 @@ #ifndef ANDROID_AUDIO_IO_DESCRIPTOR_H #define ANDROID_AUDIO_IO_DESCRIPTOR_H +#include +#include + +#include +#include + namespace android { -enum audio_io_config_event { +enum audio_io_config_event_t { AUDIO_OUTPUT_REGISTERED, AUDIO_OUTPUT_OPENED, AUDIO_OUTPUT_CLOSED, @@ -35,39 +41,68 @@ enum audio_io_config_event { // frequent calls through IAudioFlinger class AudioIoDescriptor : public RefBase { public: - AudioIoDescriptor() : - mIoHandle(AUDIO_IO_HANDLE_NONE), - mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(AUDIO_CHANNEL_NONE), - mFrameCount(0), mFrameCountHAL(0), mLatency(0), mPortId(AUDIO_PORT_HANDLE_NONE) - { - memset(&mPatch, 0, sizeof(struct audio_patch)); - } + AudioIoDescriptor() = default; + // For AUDIO_{INPUT|OUTPUT}_CLOSED events. + AudioIoDescriptor(audio_io_handle_t ioHandle) : mIoHandle(ioHandle) {} + // For AUDIO_CLIENT_STARTED events. + AudioIoDescriptor( + audio_io_handle_t ioHandle, const audio_patch& patch, audio_port_handle_t portId) : + mIoHandle(ioHandle), mPatch(patch), mPortId(portId) {} + // For everything else. + AudioIoDescriptor( + audio_io_handle_t ioHandle, const audio_patch& patch, bool isInput, + uint32_t samplingRate, audio_format_t format, audio_channel_mask_t channelMask, + size_t frameCount, size_t frameCountHal, uint32_t latency = 0, + audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) : + mIoHandle(ioHandle), mPatch(patch), mIsInput(isInput), + mSamplingRate(samplingRate), mFormat(format), mChannelMask(channelMask), + mFrameCount(frameCount), mFrameCountHAL(frameCountHal), mLatency(latency), + mPortId(portId) {} - virtual ~AudioIoDescriptor() {} - - audio_port_handle_t getDeviceId() { + audio_io_handle_t getIoHandle() const { return mIoHandle; } + const audio_patch& getPatch() const { return mPatch; } + bool getIsInput() const { return mIsInput; } + uint32_t getSamplingRate() const { return mSamplingRate; } + audio_format_t getFormat() const { return mFormat; } + audio_channel_mask_t getChannelMask() const { return mChannelMask; } + size_t getFrameCount() const { return mFrameCount; } + size_t getFrameCountHAL() const { return mFrameCountHAL; } + uint32_t getLatency() const { return mLatency; } + audio_port_handle_t getPortId() const { return mPortId; } + audio_port_handle_t getDeviceId() const { if (mPatch.num_sources != 0 && mPatch.num_sinks != 0) { - if (mPatch.sources[0].type == AUDIO_PORT_TYPE_MIX) { - // this is an output mix - // FIXME: the API only returns the first device in case of multiple device selection - return mPatch.sinks[0].id; - } else { - // this is an input mix - return mPatch.sources[0].id; - } + // FIXME: the API only returns the first device in case of multiple device selection + return mIsInput ? mPatch.sources[0].id : mPatch.sinks[0].id; } return AUDIO_PORT_HANDLE_NONE; } + void setPatch(const audio_patch& patch) { mPatch = patch; } + + std::string toDebugString() const { + std::ostringstream ss; + ss << mIoHandle << ", samplingRate " << mSamplingRate << ", " + << audio_format_to_string(mFormat) << ", " + << (audio_channel_mask_get_representation(mChannelMask) == + AUDIO_CHANNEL_REPRESENTATION_INDEX ? + audio_channel_index_mask_to_string(mChannelMask) : + (mIsInput ? audio_channel_in_mask_to_string(mChannelMask) : + audio_channel_out_mask_to_string(mChannelMask))) + << ", frameCount " << mFrameCount << ", frameCountHAL " << mFrameCountHAL + << ", deviceId " << getDeviceId(); + return ss.str(); + } - audio_io_handle_t mIoHandle; - struct audio_patch mPatch; - uint32_t mSamplingRate; - audio_format_t mFormat; - audio_channel_mask_t mChannelMask; - size_t mFrameCount; - size_t mFrameCountHAL; - uint32_t mLatency; // only valid for output - audio_port_handle_t mPortId; // valid for event AUDIO_CLIENT_STARTED + private: + const audio_io_handle_t mIoHandle = AUDIO_IO_HANDLE_NONE; + struct audio_patch mPatch = {}; + const bool mIsInput = false; + const uint32_t mSamplingRate = 0; + const audio_format_t mFormat = AUDIO_FORMAT_DEFAULT; + const audio_channel_mask_t mChannelMask = AUDIO_CHANNEL_NONE; + const size_t mFrameCount = 0; + const size_t mFrameCountHAL = 0; + const uint32_t mLatency = 0; + const audio_port_handle_t mPortId = AUDIO_PORT_HANDLE_NONE; }; diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 3b99e02ae3..1e1db3187f 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -1873,13 +1873,13 @@ void AudioFlinger::removeNotificationClient(pid_t pid) } } -void AudioFlinger::ioConfigChanged(audio_io_config_event event, +void AudioFlinger::ioConfigChanged(audio_io_config_event_t event, const sp& ioDesc, pid_t pid) { media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL( - legacy2aidl_audio_io_config_event_AudioIoConfigEvent(event)); + legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event)); Mutex::Autolock _l(mClientLock); size_t size = mNotificationClients.size(); @@ -2752,9 +2752,7 @@ status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output) mMmapThreads.removeItem(output); ALOGD("closing mmapThread %p", mmapThread.get()); } - const sp ioDesc = new AudioIoDescriptor(); - ioDesc->mIoHandle = output; - ioConfigChanged(AUDIO_OUTPUT_CLOSED, ioDesc); + ioConfigChanged(AUDIO_OUTPUT_CLOSED, sp::make(output)); mPatchPanel.notifyStreamClosed(output); } // The thread entity (active unit of execution) is no longer running here, @@ -3012,9 +3010,7 @@ status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input) dumpToThreadLog_l(mmapThread); mMmapThreads.removeItem(input); } - const sp ioDesc = new AudioIoDescriptor(); - ioDesc->mIoHandle = input; - ioConfigChanged(AUDIO_INPUT_CLOSED, ioDesc); + ioConfigChanged(AUDIO_INPUT_CLOSED, sp::make(input)); } // FIXME: calling thread->exit() without mLock held should not be needed anymore now that // we have a different lock for notification client diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index 8fcd6e4c76..d6bf0ae29a 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -750,7 +750,7 @@ using effect_buffer_t = int16_t; // no range check, AudioFlinger::mLock held bool streamMute_l(audio_stream_type_t stream) const { return mStreamTypes[stream].mute; } - void ioConfigChanged(audio_io_config_event event, + void ioConfigChanged(audio_io_config_event_t event, const sp& ioDesc, pid_t pid = 0); diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 7292527a29..9665424192 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -626,7 +626,7 @@ status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp& event) return status; } -void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid, +void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) { Mutex::Autolock _l(mLock); @@ -634,7 +634,7 @@ void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pi } // sendIoConfigEvent_l() must be called with ThreadBase::mLock held -void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid, +void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) { // The audio statistics history is exponentially weighted to forget events @@ -2772,36 +2772,26 @@ status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId return mOutput->stream->selectPresentation(presentationId, programId); } -void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid, +void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) { - sp desc = new AudioIoDescriptor(); ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event); - - desc->mIoHandle = mId; - struct audio_patch patch = mPatch; - if (isMsdDevice()) { - patch = mDownStreamPatch; - } - + sp desc; + const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch; switch (event) { case AUDIO_OUTPUT_OPENED: case AUDIO_OUTPUT_REGISTERED: case AUDIO_OUTPUT_CONFIG_CHANGED: - desc->mPatch = patch; - desc->mChannelMask = mChannelMask; - desc->mSamplingRate = mSampleRate; - desc->mFormat = mFormat; - desc->mFrameCount = mNormalFrameCount; // FIXME see - // AudioFlinger::frameCount(audio_io_handle_t) - desc->mFrameCountHAL = mFrameCount; - desc->mLatency = latency_l(); + desc = sp::make(mId, patch, false /*isInput*/, + mSampleRate, mFormat, mChannelMask, + // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount? + mNormalFrameCount, mFrameCount, latency_l()); break; case AUDIO_CLIENT_STARTED: - desc->mPatch = patch; - desc->mPortId = portId; + desc = sp::make(mId, patch, portId); break; case AUDIO_OUTPUT_CLOSED: default: + desc = sp::make(mId); break; } mAudioFlinger->ioConfigChanged(event, desc, pid); @@ -8784,30 +8774,22 @@ String8 AudioFlinger::RecordThread::getParameters(const String8& keys) return String8(); } -void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid, +void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) { - sp desc = new AudioIoDescriptor(); - - desc->mIoHandle = mId; - + sp desc; switch (event) { case AUDIO_INPUT_OPENED: case AUDIO_INPUT_REGISTERED: case AUDIO_INPUT_CONFIG_CHANGED: - desc->mPatch = mPatch; - desc->mChannelMask = mChannelMask; - desc->mSamplingRate = mSampleRate; - desc->mFormat = mFormat; - desc->mFrameCount = mFrameCount; - desc->mFrameCountHAL = mFrameCount; - desc->mLatency = 0; + desc = sp::make(mId, mPatch, true /*isInput*/, + mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount); break; case AUDIO_CLIENT_STARTED: - desc->mPatch = mPatch; - desc->mPortId = portId; + desc = sp::make(mId, mPatch, portId); break; case AUDIO_INPUT_CLOSED: default: + desc = sp::make(mId); break; } mAudioFlinger->ioConfigChanged(event, desc, pid); @@ -9650,31 +9632,26 @@ String8 AudioFlinger::MmapThread::getParameters(const String8& keys) return String8(); } -void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid, +void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId __unused) { - sp desc = new AudioIoDescriptor(); - - desc->mIoHandle = mId; - + sp desc; + bool isInput = false; switch (event) { case AUDIO_INPUT_OPENED: case AUDIO_INPUT_REGISTERED: case AUDIO_INPUT_CONFIG_CHANGED: + isInput = true; + FALLTHROUGH_INTENDED; case AUDIO_OUTPUT_OPENED: case AUDIO_OUTPUT_REGISTERED: case AUDIO_OUTPUT_CONFIG_CHANGED: - desc->mPatch = mPatch; - desc->mChannelMask = mChannelMask; - desc->mSamplingRate = mSampleRate; - desc->mFormat = mFormat; - desc->mFrameCount = mFrameCount; - desc->mFrameCountHAL = mFrameCount; - desc->mLatency = 0; + desc = sp::make(mId, mPatch, isInput, + mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount); break; - case AUDIO_INPUT_CLOSED: case AUDIO_OUTPUT_CLOSED: default: + desc = sp::make(mId); break; } mAudioFlinger->ioConfigChanged(event, desc, pid); diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h index 3001863074..38e55a301f 100644 --- a/services/audioflinger/Threads.h +++ b/services/audioflinger/Threads.h @@ -113,7 +113,7 @@ public: class IoConfigEventData : public ConfigEventData { public: - IoConfigEventData(audio_io_config_event event, pid_t pid, + IoConfigEventData(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) : mEvent(event), mPid(pid), mPortId(portId) {} @@ -121,14 +121,14 @@ public: snprintf(buffer, size, "- IO event: event %d\n", mEvent); } - const audio_io_config_event mEvent; + const audio_io_config_event_t mEvent; const pid_t mPid; const audio_port_handle_t mPortId; }; class IoConfigEvent : public ConfigEvent { public: - IoConfigEvent(audio_io_config_event event, pid_t pid, audio_port_handle_t portId) : + IoConfigEvent(audio_io_config_event_t event, pid_t pid, audio_port_handle_t portId) : ConfigEvent(CFG_EVENT_IO) { mData = new IoConfigEventData(event, pid, portId); } @@ -332,15 +332,15 @@ public: status_t& status) = 0; virtual status_t setParameters(const String8& keyValuePairs); virtual String8 getParameters(const String8& keys) = 0; - virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0, + virtual void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE) = 0; // sendConfigEvent_l() must be called with ThreadBase::mLock held // Can temporarily release the lock if waiting for a reply from // processConfigEvents_l(). status_t sendConfigEvent_l(sp& event); - void sendIoConfigEvent(audio_io_config_event event, pid_t pid = 0, + void sendIoConfigEvent(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); - void sendIoConfigEvent_l(audio_io_config_event event, pid_t pid = 0, + void sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); void sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp); void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio, bool forApp); @@ -972,7 +972,7 @@ public: { return android_atomic_acquire_load(&mSuspended) > 0; } virtual String8 getParameters(const String8& keys); - virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0, + virtual void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames); // Consider also removing and passing an explicit mMainBuffer initialization @@ -1785,7 +1785,7 @@ public: status_t& status); virtual void cacheParameters_l() {} virtual String8 getParameters(const String8& keys); - virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0, + virtual void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); virtual status_t createAudioPatch_l(const struct audio_patch *patch, audio_patch_handle_t *handle); @@ -1994,7 +1994,7 @@ class MmapThread : public ThreadBase virtual bool checkForNewParameter_l(const String8& keyValuePair, status_t& status); virtual String8 getParameters(const String8& keys); - virtual void ioConfigChanged(audio_io_config_event event, pid_t pid = 0, + virtual void ioConfigChanged(audio_io_config_event_t event, pid_t pid = 0, audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE); void readHalParameters_l(); virtual void cacheParameters_l() {} -- GitLab From 27123556402690891aacf3a52b26de59ff0efbbc Mon Sep 17 00:00:00 2001 From: Dominik Laskowski Date: Tue, 27 Jul 2021 21:20:40 -0700 Subject: [PATCH 067/694] screenrecord: Use ui::LayerStack Bug: 182939859 Test: Build Change-Id: I66f5662fc30da68d15b49bec316027043cba727c --- cmds/screenrecord/screenrecord.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmds/screenrecord/screenrecord.cpp b/cmds/screenrecord/screenrecord.cpp index cd8fe970e8..2e0b678e7c 100644 --- a/cmds/screenrecord/screenrecord.cpp +++ b/cmds/screenrecord/screenrecord.cpp @@ -701,7 +701,7 @@ static status_t recordScreen(const char* fileName) { printf("Display is %dx%d @%.2ffps (orientation=%s), layerStack=%u\n", layerStackSpaceRect.getWidth(), layerStackSpaceRect.getHeight(), displayMode.refreshRate, toCString(displayState.orientation), - displayState.layerStack); + displayState.layerStack.id); fflush(stdout); } -- GitLab From 9dec7011d2907fb50a41ea883b557baf84718b6b Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 21 Jul 2021 10:30:57 -0700 Subject: [PATCH 068/694] Switch the framework AIDL to use AudioChannelLayout 'AudioChannelLayout' is a new type that will be used both by HAL and framework interfaces. This CL changes the framework interfaces to use it instead of 'AudioChannelMask' type which was used to pass legacy 'audio_channel_mask_t' transparently via the AIDL layer. Remove the implementation of 'Parcelable' from AudioProfile and AudioPortConfig in libaudiofoundation because the implementation not used after converting audio fwk interfaces to AIDL, and Parcelable's interface methods do not allow passing in any context. In our case the context is the direction of the I/O ('isInput' flag) which is usually available externally, but absent from the encapsulated data of these classes. Update the audiofoundation_parcelable_test, switch to use of static libs for the framework code so they can run on a device with default system libraries. Bug: 188932434 Test: check audio on device Test: atest audiofoundation_parcelable_test Change-Id: Ie59cdd64f001330ad4b5094264957198809a10a1 --- media/libaudioclient/AidlConversion.cpp | 102 +++++++++--------- media/libaudioclient/Android.bp | 1 - media/libaudioclient/AudioSystem.cpp | 8 +- media/libaudioclient/AudioTrack.cpp | 2 +- media/libaudioclient/IAudioFlinger.cpp | 22 ++-- media/libaudioclient/PolicyAidlConversion.cpp | 10 +- .../aidl/android/media/AudioChannelMask.aidl | 45 -------- .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioGain.aidl | 4 +- .../aidl/android/media/AudioGainConfig.aidl | 4 +- .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 4 +- .../fuzzer/audioflinger_fuzzer.cpp | 10 +- .../include/media/AidlConversion.h | 25 ++--- .../include/media/IAudioFlinger.h | 3 +- .../audio_aidl_legacy_conversion_tests.cpp | 12 +-- media/libaudiofoundation/AudioGain.cpp | 6 +- media/libaudiofoundation/AudioPort.cpp | 33 +++--- media/libaudiofoundation/AudioProfile.cpp | 77 ++++--------- .../DeviceDescriptorBase.cpp | 4 +- .../include/media/AudioPort.h | 8 +- .../include/media/AudioProfile.h | 23 ++-- media/libaudiofoundation/tests/Android.bp | 9 +- .../tests/audiofoundation_parcelable_test.cpp | 21 ++-- services/audioflinger/AudioFlinger.cpp | 17 +-- .../service/AudioPolicyClientImpl.cpp | 14 +-- .../service/AudioPolicyInterfaceImpl.cpp | 6 +- .../service/AudioPolicyService.cpp | 6 +- 31 files changed, 214 insertions(+), 282 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioChannelMask.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 60df8d5d3e..fd6bf28412 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -279,16 +279,6 @@ ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy) { enumToMask_index); } -ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( - media::AudioChannelMask aidl) { - return convertReinterpret(aidl); -} - -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( - audio_channel_mask_t legacy) { - return convertReinterpret(legacy); -} - ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl) { switch (aidl) { @@ -1103,7 +1093,7 @@ std::unordered_map make_ReverseMap(const std::vector>& v) } // namespace ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isOutput) { + const media::AudioChannelLayout& aidl, bool isInput) { using ReverseMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); @@ -1130,7 +1120,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan case Tag::indexMask: return convert(aidl, mIdx, __func__, "index"); case Tag::layoutMask: - return convert(aidl, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + return convert(aidl, isInput ? mIn : mOut, __func__, isInput ? "input" : "output"); case Tag::voiceMask: return convert(aidl, mVoice, __func__, "voice"); } @@ -1139,7 +1129,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan } ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isOutput) { + audio_channel_mask_t legacy, bool isInput) { using DirectMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); @@ -1168,8 +1158,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { return convert(legacy, mIdx, __func__, "index"); } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { - return convert(legacy, isOutput ? mOut : mInAndVoice, __func__, - isOutput ? "output" : "input / voice"); + return convert(legacy, isInput ? mInAndVoice : mOut, __func__, + isInput ? "input / voice" : "output"); } ALOGE("%s: unknown representation %d in audio_channel_mask_t value 0x%x", @@ -1274,9 +1264,9 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi audio_gain_config legacy; legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - legacy.channel_mask = - VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; + legacy.channel_mask = VALUE_OR_RETURN( + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const bool isJoint = bitmaskIsSet(aidl.mode, media::AudioGainMode::JOINT); size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1296,9 +1286,9 @@ ConversionResult legacy2aidl_audio_gain_config_AudioGain media::AudioGainConfig aidl; aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.channelMask = - VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; + aidl.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); const bool isJoint = (legacy.mode & AUDIO_GAIN_MODE_JOINT) != 0; size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1863,9 +1853,11 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::CHANNEL_MASK)) { + const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + aidl.channelMask, isInput)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { legacy.format = VALUE_OR_RETURN( @@ -1894,9 +1886,10 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { - aidl.channelMask = - VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + const bool isInput = VALUE_OR_RETURN( + direction(legacy.role, legacy.type)) == Direction::INPUT; + aidl.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { aidl.format = VALUE_OR_RETURN( @@ -1971,7 +1964,7 @@ ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDes const audio_format_t format = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); const audio_channel_mask_t channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const size_t frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); const size_t frame_count_hal = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); const uint32_t latency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); @@ -1990,8 +1983,8 @@ ConversionResult legacy2aidl_AudioIoDescriptor_AudioIo aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->getSamplingRate())); aidl.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy->getFormat())); - aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->getChannelMask())); + aidl.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + legacy->getChannelMask(), legacy->getIsInput())); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCount())); aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCountHAL())); aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->getLatency())); @@ -2294,7 +2287,7 @@ aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& legacy.version = VALUE_OR_RETURN(convertIntegral(aidl.version)); legacy.size = sizeof(audio_offload_info_t); audio_config_base_t config = VALUE_OR_RETURN( - aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, false /*isInput*/)); legacy.sample_rate = config.sample_rate; legacy.channel_mask = config.channel_mask; legacy.format = config.format; @@ -2323,8 +2316,8 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } aidl.version = VALUE_OR_RETURN(convertIntegral(legacy.version)); aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.config.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + aidl.config.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + legacy.channel_mask, false /*isInput*/)); aidl.config.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.streamType = VALUE_OR_RETURN( @@ -2353,11 +2346,11 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput) { audio_config_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); @@ -2366,11 +2359,11 @@ aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { } ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput) { media::AudioConfig aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); @@ -2379,21 +2372,21 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { } ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl) { +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput) { audio_config_base_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); return legacy; } ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy) { +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput) { media::AudioConfigBase aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); return aidl; } @@ -2723,7 +2716,7 @@ ConversionResult legacy2aidl_AudioPortExt( } ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput) { audio_profile legacy; legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); @@ -2740,7 +2733,9 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { } RETURN_IF_ERROR( convertRange(aidl.channelMasks.begin(), aidl.channelMasks.end(), legacy.channel_masks, - aidl2legacy_AudioChannelMask_audio_channel_mask_t)); + [isInput](const media::AudioChannelLayout& l) { + return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); + })); legacy.num_channel_masks = aidl.channelMasks.size(); legacy.encapsulation_type = VALUE_OR_RETURN( @@ -2749,7 +2744,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { } ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput) { media::AudioProfile aidl; aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); @@ -2767,7 +2762,9 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { RETURN_IF_ERROR( convertRange(legacy.channel_masks, legacy.channel_masks + legacy.num_channel_masks, std::back_inserter(aidl.channelMasks), - legacy2aidl_audio_channel_mask_t_AudioChannelMask)); + [isInput](audio_channel_mask_t m) { + return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); + })); aidl.encapsulationType = VALUE_OR_RETURN( legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( @@ -2779,8 +2776,8 @@ ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + aidl.channelMask, aidl.useInChannelMask)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2791,11 +2788,12 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { } ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy) { +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); + aidl.useInChannelMask = isInput; aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); aidl.maxValue = VALUE_OR_RETURN(convertIntegral(legacy.max_value)); aidl.defaultValue = VALUE_OR_RETURN(convertIntegral(legacy.default_value)); @@ -2816,8 +2814,11 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { if (aidl.profiles.size() > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } + const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; RETURN_IF_ERROR(convertRange(aidl.profiles.begin(), aidl.profiles.end(), legacy.audio_profiles, - aidl2legacy_AudioProfile_audio_profile)); + [isInput](const media::AudioProfile& p) { + return aidl2legacy_AudioProfile_audio_profile(p, isInput); + })); legacy.num_audio_profiles = aidl.profiles.size(); if (aidl.extraAudioDescriptors.size() > std::size(legacy.extra_audio_descriptors)) { @@ -2853,10 +2854,13 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { if (legacy.num_audio_profiles > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } + const bool isInput = VALUE_OR_RETURN(direction(legacy.role, legacy.type)) == Direction::INPUT; RETURN_IF_ERROR( convertRange(legacy.audio_profiles, legacy.audio_profiles + legacy.num_audio_profiles, std::back_inserter(aidl.profiles), - legacy2aidl_audio_profile_AudioProfile)); + [isInput](const audio_profile& p) { + return legacy2aidl_audio_profile_AudioProfile(p, isInput); + })); if (legacy.num_extra_audio_descriptors > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); @@ -2873,7 +2877,9 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { RETURN_IF_ERROR( convertRange(legacy.gains, legacy.gains + legacy.num_gains, std::back_inserter(aidl.gains), - legacy2aidl_audio_gain_AudioGain)); + [isInput](const audio_gain& g) { + return legacy2aidl_audio_gain_AudioGain(g, isInput); + })); aidl.activeConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 64256a1880..63da4d143d 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -304,7 +304,6 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioChannelLayout.aidl", - "aidl/android/media/AudioChannelMask.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", "aidl/android/media/AudioConfigBase.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index b9de92a2c7..2d376b9194 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -1003,7 +1003,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, legacy2aidl_audio_attributes_t_AudioAttributesInternal(*attr)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfig configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(*config)); + legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( @@ -1097,7 +1097,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, int32_t riidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_unique_id_t_int32_t(riid)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*config)); + legacy2aidl_audio_config_base_t_AudioConfigBase(*config, true /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_port_handle_t_int32_t(*selectedDeviceId)); @@ -2431,13 +2431,13 @@ Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( record_client_info_t clientInfoLegacy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_RecordClientInfo_record_client_info_t(clientInfo)); audio_config_base_t clientConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig, true /*isInput*/)); std::vector clientEffectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( clientEffects, aidl2legacy_EffectDescriptor_effect_descriptor_t)); audio_config_base_t deviceConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig, true /*isInput*/)); std::vector effectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( effects, diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index bd9de91ae6..5b7760b0b4 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -171,7 +171,7 @@ bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config, auto result = [&]() -> ConversionResult { media::AudioConfigBase configAidl = VALUE_OR_RETURN( - legacy2aidl_audio_config_base_t_AudioConfigBase(config)); + legacy2aidl_audio_config_base_t_AudioConfigBase(config, false /*isInput*/)); media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); bool retAidl; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 5da56b8feb..5f12f71c36 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -55,7 +55,9 @@ using binder::Status; ConversionResult IAudioFlinger::CreateTrackInput::toAidl() const { media::CreateTrackRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(config)); + // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. + aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( + config, false /*isInput*/)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.sharedBuffer = VALUE_OR_RETURN(legacy2aidl_NullableIMemory_SharedFileRegion(sharedBuffer)); aidl.notificationsPerBuffer = VALUE_OR_RETURN(convertIntegral(notificationsPerBuffer)); @@ -74,7 +76,9 @@ ConversionResult IAudioFlinger::CreateTrackInput::fromAidl(const media::CreateTrackRequest& aidl) { IAudioFlinger::CreateTrackInput legacy; legacy.attr = VALUE_OR_RETURN(aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.config)); + // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. + legacy.config = VALUE_OR_RETURN( + aidl2legacy_AudioConfig_audio_config_t(aidl.config, false /*isInput*/)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.sharedBuffer = VALUE_OR_RETURN(aidl2legacy_NullableSharedFileRegion_IMemory(aidl.sharedBuffer)); legacy.notificationsPerBuffer = VALUE_OR_RETURN( @@ -139,7 +143,8 @@ ConversionResult IAudioFlinger::CreateRecordInput::toAidl() const { media::CreateRecordRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_base_t_AudioConfigBase(config)); + aidl.config = VALUE_OR_RETURN( + legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.riid = VALUE_OR_RETURN(legacy2aidl_audio_unique_id_t_int32_t(riid)); aidl.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -159,7 +164,8 @@ IAudioFlinger::CreateRecordInput::fromAidl( IAudioFlinger::CreateRecordInput legacy; legacy.attr = VALUE_OR_RETURN( aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); + legacy.config = VALUE_OR_RETURN( + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, true /*isInput*/)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.riid = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_unique_id_t(aidl.riid)); legacy.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -412,8 +418,8 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); media::AudioFormatDescription formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(format)); - media::AudioChannelMask channelMaskAidl = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(channelMask)); + media::AudioChannelLayout channelMaskAidl = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(channelMask, true /*isInput*/)); int64_t aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( mDelegate->getInputBufferSize(sampleRateAidl, formatAidl, channelMaskAidl, @@ -939,13 +945,13 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioFormatDescription_audio_format_t(format)); audio_channel_mask_t channelMaskLegacy = VALUE_OR_RETURN_BINDER( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(channelMask, true /*isInput*/)); size_t size = mDelegate->getInputBufferSize(sampleRateLegacy, formatLegacy, channelMaskLegacy); *_aidl_return = VALUE_OR_RETURN_BINDER(convertIntegral(size)); return Status::ok(); diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index d6611d1c94..676bb37406 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -232,7 +232,10 @@ aidl2legacy_AudioMix(const media::AudioMix& aidl) { std::back_inserter(legacy.mCriteria), aidl2legacy_AudioMixMatchCriterion)); legacy.mMixType = VALUE_OR_RETURN(aidl2legacy_AudioMixType_uint32_t(aidl.mixType)); - legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.format)); + // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only + // an output mask is expected here. + legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t( + aidl.format, false /*isInput*/)); legacy.mRouteFlags = VALUE_OR_RETURN( aidl2legacy_AudioMixRouteFlag_uint32_t_mask(aidl.routeFlags)); legacy.mDeviceType = VALUE_OR_RETURN( @@ -252,7 +255,10 @@ legacy2aidl_AudioMix(const AudioMix& legacy) { legacy.mCriteria, legacy2aidl_AudioMixMatchCriterion)); aidl.mixType = VALUE_OR_RETURN(legacy2aidl_uint32_t_AudioMixType(legacy.mMixType)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(legacy.mFormat)); + // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only + // an output mask is expected here. + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( + legacy.mFormat, false /*isInput*/)); aidl.routeFlags = VALUE_OR_RETURN( legacy2aidl_uint32_t_AudioMixRouteFlag_mask(legacy.mRouteFlags)); aidl.device.type = VALUE_OR_RETURN( diff --git a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl deleted file mode 100644 index 1e7e6e5e23..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * AudioChannelMask is an opaque type and its internal layout should not be - * assumed as it may change in the future. - * - * This is a temporary implementation to provide a distinct type (instead of - * 'int') in all the places that need a channel mask. Later the enum will be - * replaced with a type which is more extensible by vendors. - * - * The actual value range of this enum is the same as of - * the 'audio_channel_mask_t' enum. - * - * {@hide} - */ -@Backing(type="int") -enum AudioChannelMask { - /** - * Framework use only, do not constitute a valid channel mask. - */ - INVALID = 0xC0000000, - - NONE = 0, - /** - * Since the current code never uses the values of the SAIDL enum - * directly--it uses the values of the C enum and coerces the type-- - * we don't specify any other values here. - */ -} diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 5fd25d50ac..6996d4276f 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; import android.media.AudioOffloadInfo; @@ -25,7 +25,7 @@ import android.media.AudioOffloadInfo; */ parcelable AudioConfig { int sampleRate; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; AudioFormatDescription format; AudioOffloadInfo offloadInfo; long frameCount; diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index fb20404ad7..e84161bce5 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; /** @@ -24,6 +24,6 @@ import android.media.AudioFormatDescription; */ parcelable AudioConfigBase { int sampleRate; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; AudioFormatDescription format; } diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 58cf1c984c..14e1f5b160 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; /** * {@hide} @@ -27,7 +27,7 @@ parcelable AudioGain { boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; int minValue; int maxValue; int defaultValue; diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl index 67b77a5742..afa3aca3f3 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; /** * {@hide} @@ -31,7 +31,7 @@ parcelable AudioGainConfig { /** * Channels which gain value follows. N/A in joint mode. */ - AudioChannelMask channelMask; + AudioChannelLayout channelMask; /** * Gain values in millibels. diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index ea8ec3205f..efdf99b699 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; import android.media.AudioPatch; @@ -30,7 +30,7 @@ parcelable AudioIoDescriptor { boolean isInput; int samplingRate; AudioFormatDescription format; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; long frameCount; long frameCountHAL; /** Only valid for output. */ diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index c4b572d7f3..be32a69e91 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; @@ -45,7 +45,7 @@ parcelable AudioPortConfig { /** * Channel mask, if applicable. */ - AudioChannelMask channelMask; + AudioChannelLayout channelMask; /** * Format, if applicable. */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 34b8d35d14..9fb8d494e5 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioEncapsulationType; import android.media.AudioFormatDescription; @@ -27,7 +27,7 @@ parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ AudioFormatDescription format; - AudioChannelMask[] channelMasks; + AudioChannelLayout[] channelMasks; int[] samplingRates; boolean isDynamicFormat; boolean isDynamicChannels; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 28233d1366..16f70c133e 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -117,7 +117,7 @@ interface IAudioFlingerService { // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, in AudioFormatDescription format, - AudioChannelMask channelMask); + in AudioChannelLayout channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); int /* audio_io_handle_t */ openDuplicateOutput(int /* audio_io_handle_t */ output1, diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp index 12473fc760..bdd72dd650 100644 --- a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp +++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp @@ -597,7 +597,8 @@ status_t AudioFlingerFuzzer::invokeAudioInputDevice() { media::OpenInputRequest request{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); + request.config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); @@ -654,9 +655,10 @@ status_t AudioFlingerFuzzer::invokeAudioOutputDevice() { media::OpenOutputResponse response{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); - request.mixerConfig = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig)); + request.halConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, false /*isInput*/)); + request.mixerConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig, false /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index e56106a710..2cf127c373 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -99,11 +99,6 @@ ConversionResult legacy2aidl_int32_t_AudioPortConfig ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl); ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy); -ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( - media::AudioChannelMask aidl); -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( - audio_channel_mask_t legacy); - ConversionResult aidl2legacy_int32_t_pid_t(int32_t aidl); ConversionResult legacy2aidl_pid_t_int32_t(pid_t legacy); @@ -137,9 +132,9 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isOutput); + const media::AudioChannelLayout& aidl, bool isInput); ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isOutput); + audio_channel_mask_t legacy, bool isInput); ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl); @@ -233,7 +228,6 @@ ConversionResult legacy2aidl_audio_patch_AudioPatch( ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDescriptor( const media::AudioIoDescriptor& aidl); - ConversionResult legacy2aidl_AudioIoDescriptor_AudioIoDescriptor( const sp& legacy); @@ -278,14 +272,14 @@ ConversionResult legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& legacy); ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl); +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput); ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy); +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput); ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl); +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput); ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy); +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput); ConversionResult> aidl2legacy_SharedFileRegion_IMemory(const media::SharedFileRegion& aidl); @@ -352,14 +346,15 @@ ConversionResult legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy); ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl); +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput); ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy); +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput); ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl); +// The AIDL structure provides a flag for direction indication while the legacy type doesn't. ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy); +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput); ConversionResult aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl); diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 3cc36df92a..8632abb4e7 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -592,7 +592,8 @@ public: getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; Status getInputBufferSize(int32_t sampleRate, const media::AudioFormatDescription& format, - media::AudioChannelMask channelMask, int64_t* _aidl_return) override; + const media::AudioChannelLayout& channelMask, + int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; Status openDuplicateOutput(int32_t output1, int32_t output2, int32_t* _aidl_return) override; diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index b6e597dbfc..7f8af53334 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -172,15 +172,15 @@ TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { make_AFD_Encap, make_AFD_Encap_with_Enc}); } -using ChannelLayoutParam = std::tuple; +using ChannelLayoutParam = std::tuple; class AudioChannelLayoutRoundTripTest : public testing::TestWithParam {}; TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { const auto initial = std::get<0>(GetParam()); - const bool isOutput = std::get<1>(GetParam()); - auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isOutput); + const bool isInput = std::get<1>(GetParam()); + auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isInput); ASSERT_TRUE(conv.ok()); - auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isOutput); + auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isInput); ASSERT_TRUE(convBack.ok()); EXPECT_EQ(initial, convBack.value()); } @@ -189,11 +189,11 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, testing::Combine( testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), make_ACL_ChannelIndex2()), - testing::Values(true, false))); + testing::Values(false, true))); INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, AudioChannelLayoutRoundTripTest, // In legacy constants the voice call is only defined for input. - testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(false))); + testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(true))); class AudioDeviceDescriptionRoundTripTest : public testing::TestWithParam {}; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 5cc2b2f5f2..169899d74b 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -142,7 +142,8 @@ status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + mGain.channel_mask, mUseInChannelMask)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -166,7 +167,8 @@ status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + parcelable.channelMask, parcelable.useInChannelMask)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index 24ecd78397..c70a6c2f8b 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -210,7 +210,8 @@ status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { parcelable->name = mName; parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); - parcelable->profiles = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioProfileVector(mProfiles)); + parcelable->profiles = VALUE_OR_RETURN_STATUS( + legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); parcelable->extraAudioDescriptors = mExtraAudioDescriptors; parcelable->gains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); return OK; @@ -226,7 +227,8 @@ status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { mName = parcelable.name; mType = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortType_audio_port_type_t(parcelable.type)); mRole = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.role)); - mProfiles = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioProfileVector(parcelable.profiles)); + mProfiles = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioProfileVector(parcelable.profiles, useInputChannelMask())); mExtraAudioDescriptors = parcelable.extraAudioDescriptors; mGains = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioGains(parcelable.gains)); return OK; @@ -330,24 +332,19 @@ bool AudioPortConfig::equals(const sp &other) const mGain.ramp_duration_ms == other->mGain.ramp_duration_ms; } -status_t AudioPortConfig::writeToParcel(Parcel *parcel) const { - media::AudioPortConfig parcelable; - return writeToParcelable(&parcelable) - ?: parcelable.writeToParcel(parcel); -} - -status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) const { +status_t AudioPortConfig::writeToParcelable( + media::AudioPortConfig* parcelable, bool isInput) const { parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); parcelable->format = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mChannelMask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mChannelMask, isInput)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); parcelable->gain.index = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.index)); parcelable->gain.mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->gain.channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mGain.channel_mask, isInput)); parcelable->gain.rampDurationMs = VALUE_OR_RETURN_STATUS( convertIntegral(mGain.ramp_duration_ms)); parcelable->gain.values = VALUE_OR_RETURN_STATUS(convertContainer>( @@ -355,24 +352,20 @@ status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) return OK; } -status_t AudioPortConfig::readFromParcel(const Parcel *parcel) { - media::AudioPortConfig parcelable; - return parcelable.readFromParcel(parcel) - ?: readFromParcelable(parcelable); -} - -status_t AudioPortConfig::readFromParcelable(const media::AudioPortConfig& parcelable) { +status_t AudioPortConfig::readFromParcelable( + const media::AudioPortConfig& parcelable, bool isInput) { mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); mFormat = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); mChannelMask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(parcelable.channelMask, isInput)); mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); mGain.index = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.index)); mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.gain.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.gain.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + parcelable.gain.channelMask, isInput)); mGain.ramp_duration_ms = VALUE_OR_RETURN_STATUS( convertIntegral(parcelable.gain.rampDurationMs)); if (parcelable.gain.values.size() > std::size(mGain.values)) { diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index f2bed258b0..47b2d5488e 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -154,20 +154,17 @@ AudioProfile& AudioProfile::operator=(const AudioProfile& other) { return *this; } -status_t AudioProfile::writeToParcel(Parcel *parcel) const { - media::AudioProfile parcelable = VALUE_OR_RETURN_STATUS(toParcelable()); - return parcelable.writeToParcel(parcel); - } - ConversionResult -AudioProfile::toParcelable() const { +AudioProfile::toParcelable(bool isInput) const { media::AudioProfile parcelable; parcelable.name = mName; parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( - convertContainer>( + convertContainer>( mChannelMasks, - legacy2aidl_audio_channel_mask_t_AudioChannelMask)); + [isInput](audio_channel_mask_t m) { + return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); + })); parcelable.samplingRates = VALUE_OR_RETURN( convertContainer>(mSamplingRates, convertIntegral)); @@ -179,24 +176,17 @@ AudioProfile::toParcelable() const { return parcelable; } -status_t AudioProfile::readFromParcel(const Parcel *parcel) { - media::AudioProfile parcelable; - if (status_t status = parcelable.readFromParcel(parcel); status != OK) { - return status; - } - *this = *VALUE_OR_RETURN_STATUS(fromParcelable(parcelable)); - return OK; -} - ConversionResult> -AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { +AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput) { sp legacy = new AudioProfile(); legacy->mName = parcelable.name; legacy->mFormat = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, - aidl2legacy_AudioChannelMask_audio_channel_mask_t)); + [isInput](const media::AudioChannelLayout& l) { + return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); + })); legacy->mSamplingRates = VALUE_OR_RETURN( convertContainer(parcelable.samplingRates, convertIntegral)); @@ -210,13 +200,13 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { } ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl) { - return AudioProfile::fromParcelable(aidl); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput) { + return AudioProfile::fromParcelable(aidl, isInput); } ConversionResult -legacy2aidl_AudioProfile(const sp& legacy) { - return legacy->toParcelable(); +legacy2aidl_AudioProfile(const sp& legacy, bool isInput) { + return legacy->toParcelable(isInput); } ssize_t AudioProfileVector::add(const sp &profile) @@ -330,33 +320,6 @@ void AudioProfileVector::dump(std::string *dst, int spaces) const } } -status_t AudioProfileVector::writeToParcel(Parcel *parcel) const -{ - status_t status = NO_ERROR; - if ((status = parcel->writeVectorSize(*this)) != NO_ERROR) return status; - for (const auto &audioProfile : *this) { - if ((status = parcel->writeParcelable(*audioProfile)) != NO_ERROR) { - break; - } - } - return status; -} - -status_t AudioProfileVector::readFromParcel(const Parcel *parcel) -{ - status_t status = NO_ERROR; - this->clear(); - if ((status = parcel->resizeOutVector(this)) != NO_ERROR) return status; - for (size_t i = 0; i < this->size(); ++i) { - this->at(i) = new AudioProfile(AUDIO_FORMAT_DEFAULT, AUDIO_CHANNEL_NONE, 0 /*sampleRate*/); - if ((status = parcel->readParcelable(this->at(i).get())) != NO_ERROR) { - this->clear(); - break; - } - } - return status; -} - bool AudioProfileVector::equals(const AudioProfileVector& other) const { return std::equal(begin(), end(), other.begin(), other.end(), @@ -366,13 +329,19 @@ bool AudioProfileVector::equals(const AudioProfileVector& other) const } ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl) { - return convertContainer(aidl, aidl2legacy_AudioProfile); +aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput) { + return convertContainer(aidl, + [isInput](const media::AudioProfile& p) { + return aidl2legacy_AudioProfile(p, isInput); + }); } ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy) { - return convertContainer>(legacy, legacy2aidl_AudioProfile); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput) { + return convertContainer>(legacy, + [isInput](const sp& p) { + return legacy2aidl_AudioProfile(p, isInput); + }); } AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp index 5cfea816a2..3cce722225 100644 --- a/media/libaudiofoundation/DeviceDescriptorBase.cpp +++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp @@ -166,7 +166,7 @@ status_t DeviceDescriptorBase::writeToParcel(Parcel *parcel) const status_t DeviceDescriptorBase::writeToParcelable(media::AudioPort* parcelable) const { AudioPort::writeToParcelable(parcelable); - AudioPortConfig::writeToParcelable(&parcelable->activeConfig); + AudioPortConfig::writeToParcelable(&parcelable->activeConfig, useInputChannelMask()); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); media::AudioPortDeviceExt ext; @@ -190,7 +190,7 @@ status_t DeviceDescriptorBase::readFromParcelable(const media::AudioPort& parcel return BAD_VALUE; } status_t status = AudioPort::readFromParcelable(parcelable) - ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig); + ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig, useInputChannelMask()); if (status != OK) { return status; } diff --git a/media/libaudiofoundation/include/media/AudioPort.h b/media/libaudiofoundation/include/media/AudioPort.h index 1cee1c95b2..6e1d032097 100644 --- a/media/libaudiofoundation/include/media/AudioPort.h +++ b/media/libaudiofoundation/include/media/AudioPort.h @@ -130,7 +130,7 @@ private: }; -class AudioPortConfig : public virtual RefBase, public virtual Parcelable +class AudioPortConfig : public virtual RefBase { public: virtual ~AudioPortConfig() = default; @@ -152,10 +152,8 @@ public: bool equals(const sp& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; - status_t writeToParcelable(media::AudioPortConfig* parcelable) const; - status_t readFromParcelable(const media::AudioPortConfig& parcelable); + status_t writeToParcelable(media::AudioPortConfig* parcelable, bool isInput) const; + status_t readFromParcelable(const media::AudioPortConfig& parcelable, bool isInput); protected: unsigned int mSamplingRate = 0u; diff --git a/media/libaudiofoundation/include/media/AudioProfile.h b/media/libaudiofoundation/include/media/AudioProfile.h index 6a36e78bd5..e34a49f32b 100644 --- a/media/libaudiofoundation/include/media/AudioProfile.h +++ b/media/libaudiofoundation/include/media/AudioProfile.h @@ -29,7 +29,7 @@ namespace android { -class AudioProfile final : public RefBase, public Parcelable +class AudioProfile final : public RefBase { public: static sp createFullDynamic(audio_format_t dynamicFormat = AUDIO_FORMAT_DEFAULT); @@ -81,11 +81,9 @@ public: bool equals(const sp& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; - - ConversionResult toParcelable() const; - static ConversionResult> fromParcelable(const media::AudioProfile& parcelable); + ConversionResult toParcelable(bool isInput) const; + static ConversionResult> fromParcelable( + const media::AudioProfile& parcelable, bool isInput); private: @@ -106,11 +104,11 @@ private: // Conversion routines, according to AidlConversion.h conventions. ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput); ConversionResult -legacy2aidl_AudioProfile(const sp& legacy); +legacy2aidl_AudioProfile(const sp& legacy, bool isInput); -class AudioProfileVector : public std::vector>, public Parcelable +class AudioProfileVector : public std::vector> { public: virtual ~AudioProfileVector() = default; @@ -136,18 +134,15 @@ public: virtual void dump(std::string *dst, int spaces) const; bool equals(const AudioProfileVector& other) const; - - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; }; bool operator == (const AudioProfile &left, const AudioProfile &right); // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl); +aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput); ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput); AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, const AudioProfileVector& profiles2); diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp index bb9a5f2ac4..f3cd4468f8 100644 --- a/media/libaudiofoundation/tests/Android.bp +++ b/media/libaudiofoundation/tests/Android.bp @@ -11,12 +11,19 @@ cc_test { name: "audiofoundation_parcelable_test", shared_libs: [ - "libaudiofoundation", + "libbase", "libbinder", "liblog", "libutils", ], + static_libs: [ + "audioclient-types-aidl-cpp", + "libaudioclient_aidl_conversion", + "libaudiofoundation", + "libstagefright_foundation", + ], + header_libs: [ "libaudio_system_headers", ], diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 068b5d86be..2b03a83539 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -86,17 +86,6 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioGain) { ASSERT_TRUE(audioGainsFromParcel.equals(audioGains)); } -TEST(AudioFoundationParcelableTest, ParcelingAudioProfileVector) { - Parcel data; - AudioProfileVector audioProfiles = getAudioProfileVectorForTest(); - - ASSERT_EQ(data.writeParcelable(audioProfiles), NO_ERROR); - data.setDataPosition(0); - AudioProfileVector audioProfilesFromParcel; - ASSERT_EQ(data.readParcelable(&audioProfilesFromParcel), NO_ERROR); - ASSERT_TRUE(audioProfilesFromParcel.equals(audioProfiles)); -} - TEST(AudioFoundationParcelableTest, ParcelingAudioPort) { Parcel data; sp audioPort = new AudioPort( @@ -116,11 +105,15 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioPortConfig) { Parcel data; sp audioPortConfig = new AudioPortConfigTestStub(); audioPortConfig->applyAudioPortConfig(&TEST_AUDIO_PORT_CONFIG); - - ASSERT_EQ(data.writeParcelable(*audioPortConfig), NO_ERROR); + media::AudioPortConfig parcelable{}; + ASSERT_EQ(NO_ERROR, audioPortConfig->writeToParcelable(&parcelable, false /*isInput*/)); + ASSERT_EQ(NO_ERROR, data.writeParcelable(parcelable)); data.setDataPosition(0); + media::AudioPortConfig parcelableFromParcel{}; + ASSERT_EQ(NO_ERROR, data.readParcelable(&parcelableFromParcel)); sp audioPortConfigFromParcel = new AudioPortConfigTestStub(); - ASSERT_EQ(data.readParcelable(audioPortConfigFromParcel.get()), NO_ERROR); + ASSERT_EQ(NO_ERROR, audioPortConfigFromParcel->readFromParcelable( + parcelableFromParcel, false /*isInput*/)); ASSERT_TRUE(audioPortConfigFromParcel->equals(audioPortConfig)); } diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 1e1db3187f..a1fb304e60 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -1876,10 +1876,10 @@ void AudioFlinger::removeNotificationClient(pid_t pid) void AudioFlinger::ioConfigChanged(audio_io_config_event_t event, const sp& ioDesc, pid_t pid) { - media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( - legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL( legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event)); + media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( + legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); Mutex::Autolock _l(mClientLock); size_t size = mNotificationClients.size(); @@ -2610,9 +2610,9 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, audio_module_handle_t module = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_module_handle_t(request.module)); audio_config_t halConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.halConfig)); + aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/)); audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/)); sp device = VALUE_OR_RETURN_STATUS( aidl2legacy_DeviceDescriptorBase(request.device)); audio_output_flags_t flags = VALUE_OR_RETURN_STATUS( @@ -2665,8 +2665,8 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED); } response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output)); - response->config = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(halConfig)); + response->config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/)); response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(latencyMs)); response->flags = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); @@ -2834,7 +2834,7 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, audio_io_handle_t input = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_io_handle_t(request.input)); audio_config_t config = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.config)); + aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/)); sp thread = openInput_l( VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)), @@ -2848,7 +2848,8 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, String8{}); response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); + response->config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); response->device = request.device; if (thread != 0) { diff --git a/services/audiopolicy/service/AudioPolicyClientImpl.cpp b/services/audiopolicy/service/AudioPolicyClientImpl.cpp index 79252d4d03..c8db45bfd9 100644 --- a/services/audiopolicy/service/AudioPolicyClientImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyClientImpl.cpp @@ -56,17 +56,18 @@ status_t AudioPolicyService::AudioPolicyClient::openOutput(audio_module_handle_t media::OpenOutputResponse response; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*halConfig)); - request.mixerConfig = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig)); + request.halConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(*halConfig, false /*isInput*/)); + request.mixerConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig, false /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); status_t status = af->openOutput(request, &response); if (status == OK) { *output = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.output)); - *halConfig = - VALUE_OR_RETURN_STATUS(aidl2legacy_AudioConfig_audio_config_t(response.config)); + *halConfig = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioConfig_audio_config_t(response.config, false /*isInput*/)); *latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(response.latencyMs)); } return status; @@ -135,7 +136,8 @@ status_t AudioPolicyService::AudioPolicyClient::openInput(audio_module_handle_t media::OpenInputRequest request; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(*input)); - request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*config)); + request.config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(*config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index af8a1950cd..4f920b1c38 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -292,7 +292,7 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_stream_type_t stream = AUDIO_STREAM_DEFAULT; audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfig_audio_config_t(configAidl)); + aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/)); audio_output_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_output_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -523,7 +523,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, true /*isInput*/)); audio_input_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_input_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -1433,7 +1433,7 @@ Status AudioPolicyService::isDirectOutputSupported( const media::AudioAttributesInternal& attributesAidl, bool* _aidl_return) { audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, false /*isInput*/)); audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attributesAidl)); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index 3c757b3361..73138932c9 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -446,13 +446,15 @@ void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate( media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo)); media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig)); + legacy2aidl_audio_config_base_t_AudioConfigBase( + *clientConfig, true /*isInput*/)); std::vector clientEffectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( clientEffects, legacy2aidl_effect_descriptor_t_EffectDescriptor)); media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig)); + legacy2aidl_audio_config_base_t_AudioConfigBase( + *deviceConfig, true /*isInput*/)); std::vector effectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( effects, -- GitLab From e028aed5290a98f5e8523ce37595e28aaa838c63 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 28 Jul 2021 10:38:51 -0700 Subject: [PATCH 069/694] Rename AudioGain.useInChannelMask -> isInput This is done for consistency with other data structures and conversion functions. Bug: 188932434 Test: atest audiofoundation_parcelable_test Change-Id: I201d7a814dccf74b327f1fbb420a0a96b7c165d2 --- media/libaudioclient/AidlConversion.cpp | 4 +-- .../aidl/android/media/AudioGain.aidl | 2 +- media/libaudiofoundation/AudioGain.cpp | 32 ++++++++----------- .../include/media/AudioGain.h | 4 +-- .../tests/audiofoundation_parcelable_test.cpp | 2 +- 5 files changed, 19 insertions(+), 25 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index fd6bf28412..4c155fe653 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -2777,7 +2777,7 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, aidl.useInChannelMask)); + aidl.channelMask, aidl.isInput)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2791,7 +2791,7 @@ ConversionResult legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.useInChannelMask = isInput; + aidl.isInput = isInput; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 14e1f5b160..4cfa96e44a 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -23,7 +23,7 @@ import android.media.AudioChannelLayout; */ parcelable AudioGain { int index; - boolean useInChannelMask; + boolean isInput; boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 169899d74b..ea0258a1d1 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -34,10 +34,10 @@ namespace android { -AudioGain::AudioGain(int index, bool useInChannelMask) +AudioGain::AudioGain(int index, bool isInput) { mIndex = index; - mUseInChannelMask = useInChannelMask; + mIsInput = isInput; memset(&mGain, 0, sizeof(struct audio_gain)); } @@ -49,12 +49,9 @@ void AudioGain::getDefaultConfig(struct audio_gain_config *config) if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) { config->values[0] = mGain.default_value; } else { - uint32_t numValues; - if (mUseInChannelMask) { - numValues = audio_channel_count_from_in_mask(mGain.channel_mask); - } else { - numValues = audio_channel_count_from_out_mask(mGain.channel_mask); - } + const uint32_t numValues = mIsInput ? + audio_channel_count_from_in_mask(mGain.channel_mask) : + audio_channel_count_from_out_mask(mGain.channel_mask); for (size_t i = 0; i < numValues; i++) { config->values[i] = mGain.default_value; } @@ -78,12 +75,9 @@ status_t AudioGain::checkConfig(const struct audio_gain_config *config) if ((config->channel_mask & ~mGain.channel_mask) != 0) { return BAD_VALUE; } - uint32_t numValues; - if (mUseInChannelMask) { - numValues = audio_channel_count_from_in_mask(config->channel_mask); - } else { - numValues = audio_channel_count_from_out_mask(config->channel_mask); - } + const uint32_t numValues = mIsInput ? + audio_channel_count_from_in_mask(config->channel_mask) : + audio_channel_count_from_out_mask(config->channel_mask); for (size_t i = 0; i < numValues; i++) { if ((config->values[i] < mGain.min_value) || (config->values[i] > mGain.max_value)) { @@ -116,7 +110,7 @@ void AudioGain::dump(std::string *dst, int spaces, int index) const bool AudioGain::equals(const sp& other) const { return other != nullptr && - mUseInChannelMask == other->mUseInChannelMask && + mIsInput == other->mIsInput && mUseForVolume == other->mUseForVolume && // Compare audio gain mGain.mode == other->mGain.mode && @@ -137,13 +131,13 @@ status_t AudioGain::writeToParcel(android::Parcel *parcel) const { status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->index = VALUE_OR_RETURN_STATUS(convertIntegral(mIndex)); - parcelable->useInChannelMask = mUseInChannelMask; + parcelable->isInput = mIsInput; parcelable->useForVolume = mUseForVolume; parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - mGain.channel_mask, mUseInChannelMask)); + mGain.channel_mask, mIsInput)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -162,13 +156,13 @@ status_t AudioGain::readFromParcel(const android::Parcel *parcel) { status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mIndex = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.index)); - mUseInChannelMask = parcelable.useInChannelMask; + mIsInput = parcelable.isInput; mUseForVolume = parcelable.useForVolume; mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.channelMask, parcelable.useInChannelMask)); + parcelable.channelMask, parcelable.isInput)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/include/media/AudioGain.h b/media/libaudiofoundation/include/media/AudioGain.h index a06b686363..28769d26ba 100644 --- a/media/libaudiofoundation/include/media/AudioGain.h +++ b/media/libaudiofoundation/include/media/AudioGain.h @@ -31,7 +31,7 @@ namespace android { class AudioGain: public RefBase, public Parcelable { public: - AudioGain(int index, bool useInChannelMask); + AudioGain(int index, bool isInput); virtual ~AudioGain() {} void setMode(audio_gain_mode_t mode) { mGain.mode = mode; } @@ -80,7 +80,7 @@ public: private: int mIndex; struct audio_gain mGain; - bool mUseInChannelMask; + bool mIsInput; bool mUseForVolume = false; }; diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 2b03a83539..169698042a 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -53,7 +53,7 @@ public: AudioGains getAudioGainsForTest() { AudioGains audioGains; - sp audioGain = new AudioGain(0 /*index*/, false /*useInChannelMask*/); + sp audioGain = new AudioGain(0 /*index*/, false /*isInput*/); audioGain->setMode(AUDIO_GAIN_MODE_JOINT); audioGain->setChannelMask(AUDIO_CHANNEL_OUT_STEREO); audioGain->setMinValueInMb(-3200); -- GitLab From c3198c345123407b63c9275df40624f7faee47ea Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Wed, 28 Jul 2021 20:59:14 +0000 Subject: [PATCH 070/694] cameraserver: Reduce logspam from checkPermission call failures. In the cases where cameraserver is just checking for permissions (SYSTEM_CAMERA / OPEN_CLOSE_LISTENER) in order to advertise /not advertise certain camera ids, we don't need to log permission failures. Bug: 193256922 Test: check cameraserver logcat for SYSTEM_CAMERA / OPEN_CLOSE_LISTENER permission failures, they're not present when an app doesn't try to use a system camera. Change-Id: I8a7817449391669b4c46b5fb75f137442cc45722 Signed-off-by: Jayant Chowdhary --- services/camera/libcameraservice/CameraService.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp index 7b138a64d2..cc01ab2779 100644 --- a/services/camera/libcameraservice/CameraService.cpp +++ b/services/camera/libcameraservice/CameraService.cpp @@ -613,8 +613,10 @@ void CameraService::onTorchStatusChangedLocked(const String8& cameraId, broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind); } -static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) { - return checkPermission(sSystemCameraPermission, callingPid, callingUid) && +static bool hasPermissionsForSystemCamera(int callingPid, int callingUid, + bool logPermissionFailure = false) { + return checkPermission(sSystemCameraPermission, callingPid, callingUid, + logPermissionFailure) && checkPermission(sCameraPermission, callingPid, callingUid); } @@ -693,8 +695,8 @@ std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) { const std::vector *deviceIds = &mNormalDeviceIdsWithoutSystemCamera; auto callingPid = CameraThreadState::getCallingPid(); auto callingUid = CameraThreadState::getCallingUid(); - if (checkPermission(sSystemCameraPermission, callingPid, callingUid) || - getpid() == callingPid) { + if (checkPermission(sSystemCameraPermission, callingPid, callingUid, + /*logPermissionFailure*/false) || getpid() == callingPid) { deviceIds = &mNormalDeviceIds; } if (cameraIdInt < 0 || cameraIdInt >= static_cast(deviceIds->size())) { @@ -1597,7 +1599,7 @@ bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) // same behavior for system camera devices. if (getCurrentServingCall() != BinderCallType::HWBINDER && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA && - !hasPermissionsForSystemCamera(cPid, cUid)) { + !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) { ALOGW("Rejecting access to system only camera %s, inadequete permissions", cameraId.c_str()); return true; @@ -2336,7 +2338,7 @@ Status CameraService::addListenerHelper(const sp& listen auto clientUid = CameraThreadState::getCallingUid(); auto clientPid = CameraThreadState::getCallingPid(); bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission, - clientPid, clientUid); + clientPid, clientUid, /*logPermissionFailure*/false); Mutex::Autolock lock(mServiceLock); -- GitLab From 94b608f2d9eeeeb0c76ad3d66fb1998aaf8b7033 Mon Sep 17 00:00:00 2001 From: David Stevens Date: Thu, 29 Jul 2021 15:04:14 +0900 Subject: [PATCH 071/694] CCodec: add missing use of input stream usage Add the component's input stream usage flags to two input buffer allocation sites where it was missing. Bug: 194634369, Bug: 194634017 Test: MediaDrmClearkeyTest#testClearKeyPlaybackCenc on ARCVM w/5.10 Test: DashTest#testWidevine23FpsH264Fixed on ARCVM w/5.10 Change-Id: Idc1817789d472b75f2872c5c269efc1264d05b1b --- media/codec2/sfplugin/CCodecBuffers.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/media/codec2/sfplugin/CCodecBuffers.cpp b/media/codec2/sfplugin/CCodecBuffers.cpp index 29cc564349..f846b7e969 100644 --- a/media/codec2/sfplugin/CCodecBuffers.cpp +++ b/media/codec2/sfplugin/CCodecBuffers.cpp @@ -33,7 +33,7 @@ namespace android { namespace { -sp AllocateGraphicBuffer( +sp AllocateInputGraphicBuffer( const std::shared_ptr &pool, const sp &format, uint32_t pixelFormat, @@ -45,9 +45,13 @@ sp AllocateGraphicBuffer( return nullptr; } + int64_t usageValue = 0; + (void)format->findInt64("android._C2MemoryUsage", &usageValue); + C2MemoryUsage fullUsage{usageValue | usage.expected}; + std::shared_ptr block; c2_status_t err = pool->fetchGraphicBlock( - width, height, pixelFormat, usage, &block); + width, height, pixelFormat, fullUsage, &block); if (err != C2_OK) { ALOGD("fetch graphic block failed: %d", err); return nullptr; @@ -884,6 +888,10 @@ sp EncryptedLinearInputBuffers::Alloc( return nullptr; } + int64_t usageValue = 0; + (void)format->findInt64("android._C2MemoryUsage", &usageValue); + usage = C2MemoryUsage(usage.expected | usageValue); + std::shared_ptr block; c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block); if (err != C2_OK || block == nullptr) { @@ -1028,7 +1036,7 @@ std::unique_ptr GraphicInputBuffers::toArrayMode(size_t size) { [pool = mPool, format = mFormat, lbp = mLocalBufferPool, pixelFormat]() -> sp { C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE }; - return AllocateGraphicBuffer( + return AllocateInputGraphicBuffer( pool, format, pixelFormat, usage, lbp); }); return std::move(array); @@ -1039,10 +1047,8 @@ size_t GraphicInputBuffers::numActiveSlots() const { } sp GraphicInputBuffers::createNewBuffer() { - int64_t usageValue = 0; - (void)mFormat->findInt64("android._C2MemoryUsage", &usageValue); - C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE}; - return AllocateGraphicBuffer( + C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE }; + return AllocateInputGraphicBuffer( mPool, mFormat, extractPixelFormat(mFormat), usage, mLocalBufferPool); } -- GitLab From d047631c3c56a37176c079e1b5d1cc07da36a055 Mon Sep 17 00:00:00 2001 From: Cliff Wu Date: Tue, 27 Jul 2021 20:15:55 +0800 Subject: [PATCH 072/694] Fix the crash of deallocate caused by delete array error on storeInjectionConfig() Root cause: Because mInjectionConfig is plain old data, it's not get initialized to 0. In this case, if we use the delete[] method to delete mInjectionConfig.streams, a deallocation crash may occur. Solution: A new vector member variable is added to store the stream of the internal camera, replacing the original new/delete[] method for storing the stream to avoid another deallocation crash caused by uninitialized mInjectionConfig. Bug: 194700088 Test: Manual Change-Id: Ic3d825fce7b6fefea65e7ce27072ed32f275d4bb --- .../libcameraservice/device3/Camera3Device.h | 3 +++ .../device3/Camera3DeviceInjectionMethods.cpp | 18 ++++++------------ 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h index e67777df86..81873aaceb 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.h +++ b/services/camera/libcameraservice/device3/Camera3Device.h @@ -1420,6 +1420,9 @@ class Camera3Device : // Copy the configuration of the internal camera. camera3::camera_stream_configuration mInjectionConfig; + // Copy the streams of the internal camera. + Vector mInjectionStreams; + // Copy the bufferSizes of the output streams of the internal camera. std::vector mInjectionBufferSizes; diff --git a/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp b/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp index 702693496c..4744a6deb7 100644 --- a/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp +++ b/services/camera/libcameraservice/device3/Camera3DeviceInjectionMethods.cpp @@ -193,11 +193,6 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectCamera( status_t Camera3Device::Camera3DeviceInjectionMethods::stopInjection() { status_t res = NO_ERROR; - mIsStreamConfigCompleteButNotInjected = false; - if (mInjectionConfig.streams != nullptr) { - delete [] mInjectionConfig.streams; - mInjectionConfig.streams = nullptr; - } sp parent = mParent.promote(); if (parent == nullptr) { @@ -269,16 +264,12 @@ void Camera3Device::Camera3DeviceInjectionMethods::storeInjectionConfig( const camera3::camera_stream_configuration& injectionConfig, const std::vector& injectionBufferSizes) { mIsStreamConfigCompleteButNotInjected = true; - if (mInjectionConfig.streams != nullptr) { - delete [] mInjectionConfig.streams; - mInjectionConfig.streams = nullptr; - } mInjectionConfig = injectionConfig; - mInjectionConfig.streams = - (android::camera3::camera_stream_t **) new camera_stream_t*[injectionConfig.num_streams]; + mInjectionStreams.clear(); for (size_t i = 0; i < injectionConfig.num_streams; i++) { - mInjectionConfig.streams[i] = injectionConfig.streams[i]; + mInjectionStreams.push_back(injectionConfig.streams[i]); } + mInjectionConfig.streams = mInjectionStreams.editArray(); mInjectionBufferSizes = injectionBufferSizes; } @@ -359,6 +350,9 @@ status_t Camera3Device::Camera3DeviceInjectionMethods::injectionConfigureStreams void Camera3Device::Camera3DeviceInjectionMethods::injectionDisconnectImpl() { ATRACE_CALL(); ALOGI("%s: Injection camera disconnect", __FUNCTION__); + mIsStreamConfigCompleteButNotInjected = false; + mInjectionStreams.clear(); + mInjectionConfig.streams = nullptr; mBackupHalInterface = nullptr; HalInterface* interface = nullptr; -- GitLab From 05399f489aece403775f34cd2c2233243e2d5654 Mon Sep 17 00:00:00 2001 From: Andy Hung Date: Thu, 29 Jul 2021 16:44:41 +0000 Subject: [PATCH 073/694] Revert "Rename AudioGain.useInChannelMask -> isInput" This reverts commit e028aed5290a98f5e8523ce37595e28aaa838c63. Reason for revert: Android Auto regression b/194987848 Change-Id: I80ce258defca1a1c75e8a4c656690bd8cf809331 --- media/libaudioclient/AidlConversion.cpp | 4 +-- .../aidl/android/media/AudioGain.aidl | 2 +- media/libaudiofoundation/AudioGain.cpp | 32 +++++++++++-------- .../include/media/AudioGain.h | 4 +-- .../tests/audiofoundation_parcelable_test.cpp | 2 +- 5 files changed, 25 insertions(+), 19 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 4c155fe653..fd6bf28412 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -2777,7 +2777,7 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, aidl.isInput)); + aidl.channelMask, aidl.useInChannelMask)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2791,7 +2791,7 @@ ConversionResult legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.isInput = isInput; + aidl.useInChannelMask = isInput; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 4cfa96e44a..14e1f5b160 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -23,7 +23,7 @@ import android.media.AudioChannelLayout; */ parcelable AudioGain { int index; - boolean isInput; + boolean useInChannelMask; boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index ea0258a1d1..169899d74b 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -34,10 +34,10 @@ namespace android { -AudioGain::AudioGain(int index, bool isInput) +AudioGain::AudioGain(int index, bool useInChannelMask) { mIndex = index; - mIsInput = isInput; + mUseInChannelMask = useInChannelMask; memset(&mGain, 0, sizeof(struct audio_gain)); } @@ -49,9 +49,12 @@ void AudioGain::getDefaultConfig(struct audio_gain_config *config) if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) { config->values[0] = mGain.default_value; } else { - const uint32_t numValues = mIsInput ? - audio_channel_count_from_in_mask(mGain.channel_mask) : - audio_channel_count_from_out_mask(mGain.channel_mask); + uint32_t numValues; + if (mUseInChannelMask) { + numValues = audio_channel_count_from_in_mask(mGain.channel_mask); + } else { + numValues = audio_channel_count_from_out_mask(mGain.channel_mask); + } for (size_t i = 0; i < numValues; i++) { config->values[i] = mGain.default_value; } @@ -75,9 +78,12 @@ status_t AudioGain::checkConfig(const struct audio_gain_config *config) if ((config->channel_mask & ~mGain.channel_mask) != 0) { return BAD_VALUE; } - const uint32_t numValues = mIsInput ? - audio_channel_count_from_in_mask(config->channel_mask) : - audio_channel_count_from_out_mask(config->channel_mask); + uint32_t numValues; + if (mUseInChannelMask) { + numValues = audio_channel_count_from_in_mask(config->channel_mask); + } else { + numValues = audio_channel_count_from_out_mask(config->channel_mask); + } for (size_t i = 0; i < numValues; i++) { if ((config->values[i] < mGain.min_value) || (config->values[i] > mGain.max_value)) { @@ -110,7 +116,7 @@ void AudioGain::dump(std::string *dst, int spaces, int index) const bool AudioGain::equals(const sp& other) const { return other != nullptr && - mIsInput == other->mIsInput && + mUseInChannelMask == other->mUseInChannelMask && mUseForVolume == other->mUseForVolume && // Compare audio gain mGain.mode == other->mGain.mode && @@ -131,13 +137,13 @@ status_t AudioGain::writeToParcel(android::Parcel *parcel) const { status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->index = VALUE_OR_RETURN_STATUS(convertIntegral(mIndex)); - parcelable->isInput = mIsInput; + parcelable->useInChannelMask = mUseInChannelMask; parcelable->useForVolume = mUseForVolume; parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - mGain.channel_mask, mIsInput)); + mGain.channel_mask, mUseInChannelMask)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -156,13 +162,13 @@ status_t AudioGain::readFromParcel(const android::Parcel *parcel) { status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mIndex = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.index)); - mIsInput = parcelable.isInput; + mUseInChannelMask = parcelable.useInChannelMask; mUseForVolume = parcelable.useForVolume; mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.channelMask, parcelable.isInput)); + parcelable.channelMask, parcelable.useInChannelMask)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/include/media/AudioGain.h b/media/libaudiofoundation/include/media/AudioGain.h index 28769d26ba..a06b686363 100644 --- a/media/libaudiofoundation/include/media/AudioGain.h +++ b/media/libaudiofoundation/include/media/AudioGain.h @@ -31,7 +31,7 @@ namespace android { class AudioGain: public RefBase, public Parcelable { public: - AudioGain(int index, bool isInput); + AudioGain(int index, bool useInChannelMask); virtual ~AudioGain() {} void setMode(audio_gain_mode_t mode) { mGain.mode = mode; } @@ -80,7 +80,7 @@ public: private: int mIndex; struct audio_gain mGain; - bool mIsInput; + bool mUseInChannelMask; bool mUseForVolume = false; }; diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 169698042a..2b03a83539 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -53,7 +53,7 @@ public: AudioGains getAudioGainsForTest() { AudioGains audioGains; - sp audioGain = new AudioGain(0 /*index*/, false /*isInput*/); + sp audioGain = new AudioGain(0 /*index*/, false /*useInChannelMask*/); audioGain->setMode(AUDIO_GAIN_MODE_JOINT); audioGain->setChannelMask(AUDIO_CHANNEL_OUT_STEREO); audioGain->setMinValueInMb(-3200); -- GitLab From b75b624f0a2b9a3e0ae6b89ceb6158e82df71b66 Mon Sep 17 00:00:00 2001 From: Andy Hung Date: Thu, 29 Jul 2021 16:46:14 +0000 Subject: [PATCH 074/694] Revert "Switch the framework AIDL to use AudioChannelLayout" Revert submission 15379650 Reason for revert: Android Auto regression b/194987848 Reverted Changes: Ie59cdd64f:Switch the framework AIDL to use AudioChannelLayou... I35e5c83bc:Refactor AudioIoDescriptor Change-Id: I7ecd9cfa86254d6736662ae752a7f4ef070f9aea --- media/libaudioclient/AidlConversion.cpp | 102 +++++++++--------- media/libaudioclient/Android.bp | 1 + media/libaudioclient/AudioSystem.cpp | 8 +- media/libaudioclient/AudioTrack.cpp | 2 +- media/libaudioclient/IAudioFlinger.cpp | 22 ++-- media/libaudioclient/PolicyAidlConversion.cpp | 10 +- .../aidl/android/media/AudioChannelMask.aidl | 45 ++++++++ .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioGain.aidl | 4 +- .../aidl/android/media/AudioGainConfig.aidl | 4 +- .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 4 +- .../fuzzer/audioflinger_fuzzer.cpp | 10 +- .../include/media/AidlConversion.h | 25 +++-- .../include/media/IAudioFlinger.h | 3 +- .../audio_aidl_legacy_conversion_tests.cpp | 12 +-- media/libaudiofoundation/AudioGain.cpp | 6 +- media/libaudiofoundation/AudioPort.cpp | 33 +++--- media/libaudiofoundation/AudioProfile.cpp | 77 +++++++++---- .../DeviceDescriptorBase.cpp | 4 +- .../include/media/AudioPort.h | 8 +- .../include/media/AudioProfile.h | 23 ++-- media/libaudiofoundation/tests/Android.bp | 9 +- .../tests/audiofoundation_parcelable_test.cpp | 21 ++-- services/audioflinger/AudioFlinger.cpp | 17 ++- .../service/AudioPolicyClientImpl.cpp | 14 ++- .../service/AudioPolicyInterfaceImpl.cpp | 6 +- .../service/AudioPolicyService.cpp | 6 +- 31 files changed, 282 insertions(+), 214 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioChannelMask.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index fd6bf28412..60df8d5d3e 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -279,6 +279,16 @@ ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy) { enumToMask_index); } +ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( + media::AudioChannelMask aidl) { + return convertReinterpret(aidl); +} + +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( + audio_channel_mask_t legacy) { + return convertReinterpret(legacy); +} + ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl) { switch (aidl) { @@ -1093,7 +1103,7 @@ std::unordered_map make_ReverseMap(const std::vector>& v) } // namespace ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isInput) { + const media::AudioChannelLayout& aidl, bool isOutput) { using ReverseMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); @@ -1120,7 +1130,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan case Tag::indexMask: return convert(aidl, mIdx, __func__, "index"); case Tag::layoutMask: - return convert(aidl, isInput ? mIn : mOut, __func__, isInput ? "input" : "output"); + return convert(aidl, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); case Tag::voiceMask: return convert(aidl, mVoice, __func__, "voice"); } @@ -1129,7 +1139,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan } ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isInput) { + audio_channel_mask_t legacy, bool isOutput) { using DirectMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); @@ -1158,8 +1168,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { return convert(legacy, mIdx, __func__, "index"); } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { - return convert(legacy, isInput ? mInAndVoice : mOut, __func__, - isInput ? "input / voice" : "output"); + return convert(legacy, isOutput ? mOut : mInAndVoice, __func__, + isOutput ? "output" : "input / voice"); } ALOGE("%s: unknown representation %d in audio_channel_mask_t value 0x%x", @@ -1264,9 +1274,9 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi audio_gain_config legacy; legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); + legacy.channel_mask = + VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; - legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const bool isJoint = bitmaskIsSet(aidl.mode, media::AudioGainMode::JOINT); size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1286,9 +1296,9 @@ ConversionResult legacy2aidl_audio_gain_config_AudioGain media::AudioGainConfig aidl; aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); + aidl.channelMask = + VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; - aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); const bool isJoint = (legacy.mode & AUDIO_GAIN_MODE_JOINT) != 0; size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1853,11 +1863,9 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::CHANNEL_MASK)) { - const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { legacy.format = VALUE_OR_RETURN( @@ -1886,10 +1894,9 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { - const bool isInput = VALUE_OR_RETURN( - direction(legacy.role, legacy.type)) == Direction::INPUT; - aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); + aidl.channelMask = + VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { aidl.format = VALUE_OR_RETURN( @@ -1964,7 +1971,7 @@ ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDes const audio_format_t format = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); const audio_channel_mask_t channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); const size_t frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); const size_t frame_count_hal = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); const uint32_t latency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); @@ -1983,8 +1990,8 @@ ConversionResult legacy2aidl_AudioIoDescriptor_AudioIo aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->getSamplingRate())); aidl.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy->getFormat())); - aidl.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - legacy->getChannelMask(), legacy->getIsInput())); + aidl.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->getChannelMask())); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCount())); aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCountHAL())); aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->getLatency())); @@ -2287,7 +2294,7 @@ aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& legacy.version = VALUE_OR_RETURN(convertIntegral(aidl.version)); legacy.size = sizeof(audio_offload_info_t); audio_config_base_t config = VALUE_OR_RETURN( - aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, false /*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); legacy.sample_rate = config.sample_rate; legacy.channel_mask = config.channel_mask; legacy.format = config.format; @@ -2316,8 +2323,8 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } aidl.version = VALUE_OR_RETURN(convertIntegral(legacy.version)); aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.config.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - legacy.channel_mask, false /*isInput*/)); + aidl.config.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.config.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.streamType = VALUE_OR_RETURN( @@ -2346,11 +2353,11 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput) { +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { audio_config_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); @@ -2359,11 +2366,11 @@ aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isIn } ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput) { +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { media::AudioConfig aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); @@ -2372,21 +2379,21 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInpu } ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput) { +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl) { audio_config_base_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); return legacy; } ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput) { +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy) { media::AudioConfigBase aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); return aidl; } @@ -2716,7 +2723,7 @@ ConversionResult legacy2aidl_AudioPortExt( } ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput) { +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { audio_profile legacy; legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); @@ -2733,9 +2740,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isI } RETURN_IF_ERROR( convertRange(aidl.channelMasks.begin(), aidl.channelMasks.end(), legacy.channel_masks, - [isInput](const media::AudioChannelLayout& l) { - return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); - })); + aidl2legacy_AudioChannelMask_audio_channel_mask_t)); legacy.num_channel_masks = aidl.channelMasks.size(); legacy.encapsulation_type = VALUE_OR_RETURN( @@ -2744,7 +2749,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isI } ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput) { +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { media::AudioProfile aidl; aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); @@ -2762,9 +2767,7 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput RETURN_IF_ERROR( convertRange(legacy.channel_masks, legacy.channel_masks + legacy.num_channel_masks, std::back_inserter(aidl.channelMasks), - [isInput](audio_channel_mask_t m) { - return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); - })); + legacy2aidl_audio_channel_mask_t_AudioChannelMask)); aidl.encapsulationType = VALUE_OR_RETURN( legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( @@ -2776,8 +2779,8 @@ ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, aidl.useInChannelMask)); + legacy.channel_mask = VALUE_OR_RETURN( + aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2788,12 +2791,11 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { } ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.useInChannelMask = isInput; aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); aidl.maxValue = VALUE_OR_RETURN(convertIntegral(legacy.max_value)); aidl.defaultValue = VALUE_OR_RETURN(convertIntegral(legacy.default_value)); @@ -2814,11 +2816,8 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { if (aidl.profiles.size() > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } - const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; RETURN_IF_ERROR(convertRange(aidl.profiles.begin(), aidl.profiles.end(), legacy.audio_profiles, - [isInput](const media::AudioProfile& p) { - return aidl2legacy_AudioProfile_audio_profile(p, isInput); - })); + aidl2legacy_AudioProfile_audio_profile)); legacy.num_audio_profiles = aidl.profiles.size(); if (aidl.extraAudioDescriptors.size() > std::size(legacy.extra_audio_descriptors)) { @@ -2854,13 +2853,10 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { if (legacy.num_audio_profiles > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } - const bool isInput = VALUE_OR_RETURN(direction(legacy.role, legacy.type)) == Direction::INPUT; RETURN_IF_ERROR( convertRange(legacy.audio_profiles, legacy.audio_profiles + legacy.num_audio_profiles, std::back_inserter(aidl.profiles), - [isInput](const audio_profile& p) { - return legacy2aidl_audio_profile_AudioProfile(p, isInput); - })); + legacy2aidl_audio_profile_AudioProfile)); if (legacy.num_extra_audio_descriptors > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); @@ -2877,9 +2873,7 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { RETURN_IF_ERROR( convertRange(legacy.gains, legacy.gains + legacy.num_gains, std::back_inserter(aidl.gains), - [isInput](const audio_gain& g) { - return legacy2aidl_audio_gain_AudioGain(g, isInput); - })); + legacy2aidl_audio_gain_AudioGain)); aidl.activeConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 63da4d143d..64256a1880 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -304,6 +304,7 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioChannelLayout.aidl", + "aidl/android/media/AudioChannelMask.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", "aidl/android/media/AudioConfigBase.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 2d376b9194..b9de92a2c7 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -1003,7 +1003,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, legacy2aidl_audio_attributes_t_AudioAttributesInternal(*attr)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfig configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/)); + legacy2aidl_audio_config_t_AudioConfig(*config)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( @@ -1097,7 +1097,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, int32_t riidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_unique_id_t_int32_t(riid)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*config, true /*isInput*/)); + legacy2aidl_audio_config_base_t_AudioConfigBase(*config)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_port_handle_t_int32_t(*selectedDeviceId)); @@ -2431,13 +2431,13 @@ Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( record_client_info_t clientInfoLegacy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_RecordClientInfo_record_client_info_t(clientInfo)); audio_config_base_t clientConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig, true /*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig)); std::vector clientEffectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( clientEffects, aidl2legacy_EffectDescriptor_effect_descriptor_t)); audio_config_base_t deviceConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig, true /*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig)); std::vector effectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( effects, diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 5b7760b0b4..bd9de91ae6 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -171,7 +171,7 @@ bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config, auto result = [&]() -> ConversionResult { media::AudioConfigBase configAidl = VALUE_OR_RETURN( - legacy2aidl_audio_config_base_t_AudioConfigBase(config, false /*isInput*/)); + legacy2aidl_audio_config_base_t_AudioConfigBase(config)); media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); bool retAidl; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 5f12f71c36..5da56b8feb 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -55,9 +55,7 @@ using binder::Status; ConversionResult IAudioFlinger::CreateTrackInput::toAidl() const { media::CreateTrackRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. - aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( - config, false /*isInput*/)); + aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(config)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.sharedBuffer = VALUE_OR_RETURN(legacy2aidl_NullableIMemory_SharedFileRegion(sharedBuffer)); aidl.notificationsPerBuffer = VALUE_OR_RETURN(convertIntegral(notificationsPerBuffer)); @@ -76,9 +74,7 @@ ConversionResult IAudioFlinger::CreateTrackInput::fromAidl(const media::CreateTrackRequest& aidl) { IAudioFlinger::CreateTrackInput legacy; legacy.attr = VALUE_OR_RETURN(aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. - legacy.config = VALUE_OR_RETURN( - aidl2legacy_AudioConfig_audio_config_t(aidl.config, false /*isInput*/)); + legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.config)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.sharedBuffer = VALUE_OR_RETURN(aidl2legacy_NullableSharedFileRegion_IMemory(aidl.sharedBuffer)); legacy.notificationsPerBuffer = VALUE_OR_RETURN( @@ -143,8 +139,7 @@ ConversionResult IAudioFlinger::CreateRecordInput::toAidl() const { media::CreateRecordRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - aidl.config = VALUE_OR_RETURN( - legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/)); + aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_base_t_AudioConfigBase(config)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.riid = VALUE_OR_RETURN(legacy2aidl_audio_unique_id_t_int32_t(riid)); aidl.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -164,8 +159,7 @@ IAudioFlinger::CreateRecordInput::fromAidl( IAudioFlinger::CreateRecordInput legacy; legacy.attr = VALUE_OR_RETURN( aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - legacy.config = VALUE_OR_RETURN( - aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, true /*isInput*/)); + legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.riid = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_unique_id_t(aidl.riid)); legacy.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -418,8 +412,8 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); media::AudioFormatDescription formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(format)); - media::AudioChannelLayout channelMaskAidl = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(channelMask, true /*isInput*/)); + media::AudioChannelMask channelMaskAidl = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelMask(channelMask)); int64_t aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( mDelegate->getInputBufferSize(sampleRateAidl, formatAidl, channelMaskAidl, @@ -945,13 +939,13 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioFormatDescription_audio_format_t(format)); audio_channel_mask_t channelMaskLegacy = VALUE_OR_RETURN_BINDER( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(channelMask, true /*isInput*/)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(channelMask)); size_t size = mDelegate->getInputBufferSize(sampleRateLegacy, formatLegacy, channelMaskLegacy); *_aidl_return = VALUE_OR_RETURN_BINDER(convertIntegral(size)); return Status::ok(); diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index 676bb37406..d6611d1c94 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -232,10 +232,7 @@ aidl2legacy_AudioMix(const media::AudioMix& aidl) { std::back_inserter(legacy.mCriteria), aidl2legacy_AudioMixMatchCriterion)); legacy.mMixType = VALUE_OR_RETURN(aidl2legacy_AudioMixType_uint32_t(aidl.mixType)); - // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only - // an output mask is expected here. - legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t( - aidl.format, false /*isInput*/)); + legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.format)); legacy.mRouteFlags = VALUE_OR_RETURN( aidl2legacy_AudioMixRouteFlag_uint32_t_mask(aidl.routeFlags)); legacy.mDeviceType = VALUE_OR_RETURN( @@ -255,10 +252,7 @@ legacy2aidl_AudioMix(const AudioMix& legacy) { legacy.mCriteria, legacy2aidl_AudioMixMatchCriterion)); aidl.mixType = VALUE_OR_RETURN(legacy2aidl_uint32_t_AudioMixType(legacy.mMixType)); - // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only - // an output mask is expected here. - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( - legacy.mFormat, false /*isInput*/)); + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(legacy.mFormat)); aidl.routeFlags = VALUE_OR_RETURN( legacy2aidl_uint32_t_AudioMixRouteFlag_mask(legacy.mRouteFlags)); aidl.device.type = VALUE_OR_RETURN( diff --git a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl new file mode 100644 index 0000000000..1e7e6e5e23 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * AudioChannelMask is an opaque type and its internal layout should not be + * assumed as it may change in the future. + * + * This is a temporary implementation to provide a distinct type (instead of + * 'int') in all the places that need a channel mask. Later the enum will be + * replaced with a type which is more extensible by vendors. + * + * The actual value range of this enum is the same as of + * the 'audio_channel_mask_t' enum. + * + * {@hide} + */ +@Backing(type="int") +enum AudioChannelMask { + /** + * Framework use only, do not constitute a valid channel mask. + */ + INVALID = 0xC0000000, + + NONE = 0, + /** + * Since the current code never uses the values of the SAIDL enum + * directly--it uses the values of the C enum and coerces the type-- + * we don't specify any other values here. + */ +} diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 6996d4276f..5fd25d50ac 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioFormatDescription; import android.media.AudioOffloadInfo; @@ -25,7 +25,7 @@ import android.media.AudioOffloadInfo; */ parcelable AudioConfig { int sampleRate; - AudioChannelLayout channelMask; + AudioChannelMask channelMask; AudioFormatDescription format; AudioOffloadInfo offloadInfo; long frameCount; diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index e84161bce5..fb20404ad7 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioFormatDescription; /** @@ -24,6 +24,6 @@ import android.media.AudioFormatDescription; */ parcelable AudioConfigBase { int sampleRate; - AudioChannelLayout channelMask; + AudioChannelMask channelMask; AudioFormatDescription format; } diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 14e1f5b160..58cf1c984c 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; /** * {@hide} @@ -27,7 +27,7 @@ parcelable AudioGain { boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; - AudioChannelLayout channelMask; + AudioChannelMask channelMask; int minValue; int maxValue; int defaultValue; diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl index afa3aca3f3..67b77a5742 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; /** * {@hide} @@ -31,7 +31,7 @@ parcelable AudioGainConfig { /** * Channels which gain value follows. N/A in joint mode. */ - AudioChannelLayout channelMask; + AudioChannelMask channelMask; /** * Gain values in millibels. diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index efdf99b699..ea8ec3205f 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioFormatDescription; import android.media.AudioPatch; @@ -30,7 +30,7 @@ parcelable AudioIoDescriptor { boolean isInput; int samplingRate; AudioFormatDescription format; - AudioChannelLayout channelMask; + AudioChannelMask channelMask; long frameCount; long frameCountHAL; /** Only valid for output. */ diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index be32a69e91..c4b572d7f3 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; @@ -45,7 +45,7 @@ parcelable AudioPortConfig { /** * Channel mask, if applicable. */ - AudioChannelLayout channelMask; + AudioChannelMask channelMask; /** * Format, if applicable. */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 9fb8d494e5..34b8d35d14 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioEncapsulationType; import android.media.AudioFormatDescription; @@ -27,7 +27,7 @@ parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ AudioFormatDescription format; - AudioChannelLayout[] channelMasks; + AudioChannelMask[] channelMasks; int[] samplingRates; boolean isDynamicFormat; boolean isDynamicChannels; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 16f70c133e..28233d1366 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.AudioChannelMask; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -117,7 +117,7 @@ interface IAudioFlingerService { // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, in AudioFormatDescription format, - in AudioChannelLayout channelMask); + AudioChannelMask channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); int /* audio_io_handle_t */ openDuplicateOutput(int /* audio_io_handle_t */ output1, diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp index bdd72dd650..12473fc760 100644 --- a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp +++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp @@ -597,8 +597,7 @@ status_t AudioFlingerFuzzer::invokeAudioInputDevice() { media::OpenInputRequest request{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - request.config = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); + request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); @@ -655,10 +654,9 @@ status_t AudioFlingerFuzzer::invokeAudioOutputDevice() { media::OpenOutputResponse response{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(config, false /*isInput*/)); - request.mixerConfig = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig, false /*isInput*/)); + request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); + request.mixerConfig = + VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 2cf127c373..e56106a710 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -99,6 +99,11 @@ ConversionResult legacy2aidl_int32_t_AudioPortConfig ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl); ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy); +ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( + media::AudioChannelMask aidl); +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( + audio_channel_mask_t legacy); + ConversionResult aidl2legacy_int32_t_pid_t(int32_t aidl); ConversionResult legacy2aidl_pid_t_int32_t(pid_t legacy); @@ -132,9 +137,9 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isInput); + const media::AudioChannelLayout& aidl, bool isOutput); ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isInput); + audio_channel_mask_t legacy, bool isOutput); ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl); @@ -228,6 +233,7 @@ ConversionResult legacy2aidl_audio_patch_AudioPatch( ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDescriptor( const media::AudioIoDescriptor& aidl); + ConversionResult legacy2aidl_AudioIoDescriptor_AudioIoDescriptor( const sp& legacy); @@ -272,14 +278,14 @@ ConversionResult legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& legacy); ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput); +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl); ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput); +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy); ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput); +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl); ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput); +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy); ConversionResult> aidl2legacy_SharedFileRegion_IMemory(const media::SharedFileRegion& aidl); @@ -346,15 +352,14 @@ ConversionResult legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy); ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput); +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl); ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput); +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy); ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl); -// The AIDL structure provides a flag for direction indication while the legacy type doesn't. ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput); +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy); ConversionResult aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl); diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 8632abb4e7..3cc36df92a 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -592,8 +592,7 @@ public: getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; Status getInputBufferSize(int32_t sampleRate, const media::AudioFormatDescription& format, - const media::AudioChannelLayout& channelMask, - int64_t* _aidl_return) override; + media::AudioChannelMask channelMask, int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; Status openDuplicateOutput(int32_t output1, int32_t output2, int32_t* _aidl_return) override; diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index 7f8af53334..b6e597dbfc 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -172,15 +172,15 @@ TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { make_AFD_Encap, make_AFD_Encap_with_Enc}); } -using ChannelLayoutParam = std::tuple; +using ChannelLayoutParam = std::tuple; class AudioChannelLayoutRoundTripTest : public testing::TestWithParam {}; TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { const auto initial = std::get<0>(GetParam()); - const bool isInput = std::get<1>(GetParam()); - auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isInput); + const bool isOutput = std::get<1>(GetParam()); + auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isOutput); ASSERT_TRUE(conv.ok()); - auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isInput); + auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isOutput); ASSERT_TRUE(convBack.ok()); EXPECT_EQ(initial, convBack.value()); } @@ -189,11 +189,11 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, testing::Combine( testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), make_ACL_ChannelIndex2()), - testing::Values(false, true))); + testing::Values(true, false))); INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, AudioChannelLayoutRoundTripTest, // In legacy constants the voice call is only defined for input. - testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(true))); + testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(false))); class AudioDeviceDescriptionRoundTripTest : public testing::TestWithParam {}; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 169899d74b..5cc2b2f5f2 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -142,8 +142,7 @@ status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - mGain.channel_mask, mUseInChannelMask)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -167,8 +166,7 @@ status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.channelMask, parcelable.useInChannelMask)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index c70a6c2f8b..24ecd78397 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -210,8 +210,7 @@ status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { parcelable->name = mName; parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); - parcelable->profiles = VALUE_OR_RETURN_STATUS( - legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); + parcelable->profiles = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioProfileVector(mProfiles)); parcelable->extraAudioDescriptors = mExtraAudioDescriptors; parcelable->gains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); return OK; @@ -227,8 +226,7 @@ status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { mName = parcelable.name; mType = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortType_audio_port_type_t(parcelable.type)); mRole = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.role)); - mProfiles = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioProfileVector(parcelable.profiles, useInputChannelMask())); + mProfiles = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioProfileVector(parcelable.profiles)); mExtraAudioDescriptors = parcelable.extraAudioDescriptors; mGains = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioGains(parcelable.gains)); return OK; @@ -332,19 +330,24 @@ bool AudioPortConfig::equals(const sp &other) const mGain.ramp_duration_ms == other->mGain.ramp_duration_ms; } -status_t AudioPortConfig::writeToParcelable( - media::AudioPortConfig* parcelable, bool isInput) const { +status_t AudioPortConfig::writeToParcel(Parcel *parcel) const { + media::AudioPortConfig parcelable; + return writeToParcelable(&parcelable) + ?: parcelable.writeToParcel(parcel); +} + +status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) const { parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); parcelable->format = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mChannelMask, isInput)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mChannelMask)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); parcelable->gain.index = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.index)); parcelable->gain.mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->gain.channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mGain.channel_mask, isInput)); + legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); parcelable->gain.rampDurationMs = VALUE_OR_RETURN_STATUS( convertIntegral(mGain.ramp_duration_ms)); parcelable->gain.values = VALUE_OR_RETURN_STATUS(convertContainer>( @@ -352,20 +355,24 @@ status_t AudioPortConfig::writeToParcelable( return OK; } -status_t AudioPortConfig::readFromParcelable( - const media::AudioPortConfig& parcelable, bool isInput) { +status_t AudioPortConfig::readFromParcel(const Parcel *parcel) { + media::AudioPortConfig parcelable; + return parcelable.readFromParcel(parcel) + ?: readFromParcelable(parcelable); +} + +status_t AudioPortConfig::readFromParcelable(const media::AudioPortConfig& parcelable) { mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); mFormat = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); mChannelMask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(parcelable.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); mGain.index = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.index)); mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.gain.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.gain.channelMask, isInput)); + aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.gain.channelMask)); mGain.ramp_duration_ms = VALUE_OR_RETURN_STATUS( convertIntegral(parcelable.gain.rampDurationMs)); if (parcelable.gain.values.size() > std::size(mGain.values)) { diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index 47b2d5488e..f2bed258b0 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -154,17 +154,20 @@ AudioProfile& AudioProfile::operator=(const AudioProfile& other) { return *this; } +status_t AudioProfile::writeToParcel(Parcel *parcel) const { + media::AudioProfile parcelable = VALUE_OR_RETURN_STATUS(toParcelable()); + return parcelable.writeToParcel(parcel); + } + ConversionResult -AudioProfile::toParcelable(bool isInput) const { +AudioProfile::toParcelable() const { media::AudioProfile parcelable; parcelable.name = mName; parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( - convertContainer>( + convertContainer>( mChannelMasks, - [isInput](audio_channel_mask_t m) { - return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); - })); + legacy2aidl_audio_channel_mask_t_AudioChannelMask)); parcelable.samplingRates = VALUE_OR_RETURN( convertContainer>(mSamplingRates, convertIntegral)); @@ -176,17 +179,24 @@ AudioProfile::toParcelable(bool isInput) const { return parcelable; } +status_t AudioProfile::readFromParcel(const Parcel *parcel) { + media::AudioProfile parcelable; + if (status_t status = parcelable.readFromParcel(parcel); status != OK) { + return status; + } + *this = *VALUE_OR_RETURN_STATUS(fromParcelable(parcelable)); + return OK; +} + ConversionResult> -AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput) { +AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { sp legacy = new AudioProfile(); legacy->mName = parcelable.name; legacy->mFormat = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, - [isInput](const media::AudioChannelLayout& l) { - return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); - })); + aidl2legacy_AudioChannelMask_audio_channel_mask_t)); legacy->mSamplingRates = VALUE_OR_RETURN( convertContainer(parcelable.samplingRates, convertIntegral)); @@ -200,13 +210,13 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput } ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput) { - return AudioProfile::fromParcelable(aidl, isInput); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl) { + return AudioProfile::fromParcelable(aidl); } ConversionResult -legacy2aidl_AudioProfile(const sp& legacy, bool isInput) { - return legacy->toParcelable(isInput); +legacy2aidl_AudioProfile(const sp& legacy) { + return legacy->toParcelable(); } ssize_t AudioProfileVector::add(const sp &profile) @@ -320,6 +330,33 @@ void AudioProfileVector::dump(std::string *dst, int spaces) const } } +status_t AudioProfileVector::writeToParcel(Parcel *parcel) const +{ + status_t status = NO_ERROR; + if ((status = parcel->writeVectorSize(*this)) != NO_ERROR) return status; + for (const auto &audioProfile : *this) { + if ((status = parcel->writeParcelable(*audioProfile)) != NO_ERROR) { + break; + } + } + return status; +} + +status_t AudioProfileVector::readFromParcel(const Parcel *parcel) +{ + status_t status = NO_ERROR; + this->clear(); + if ((status = parcel->resizeOutVector(this)) != NO_ERROR) return status; + for (size_t i = 0; i < this->size(); ++i) { + this->at(i) = new AudioProfile(AUDIO_FORMAT_DEFAULT, AUDIO_CHANNEL_NONE, 0 /*sampleRate*/); + if ((status = parcel->readParcelable(this->at(i).get())) != NO_ERROR) { + this->clear(); + break; + } + } + return status; +} + bool AudioProfileVector::equals(const AudioProfileVector& other) const { return std::equal(begin(), end(), other.begin(), other.end(), @@ -329,19 +366,13 @@ bool AudioProfileVector::equals(const AudioProfileVector& other) const } ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput) { - return convertContainer(aidl, - [isInput](const media::AudioProfile& p) { - return aidl2legacy_AudioProfile(p, isInput); - }); +aidl2legacy_AudioProfileVector(const std::vector& aidl) { + return convertContainer(aidl, aidl2legacy_AudioProfile); } ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput) { - return convertContainer>(legacy, - [isInput](const sp& p) { - return legacy2aidl_AudioProfile(p, isInput); - }); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy) { + return convertContainer>(legacy, legacy2aidl_AudioProfile); } AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp index 3cce722225..5cfea816a2 100644 --- a/media/libaudiofoundation/DeviceDescriptorBase.cpp +++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp @@ -166,7 +166,7 @@ status_t DeviceDescriptorBase::writeToParcel(Parcel *parcel) const status_t DeviceDescriptorBase::writeToParcelable(media::AudioPort* parcelable) const { AudioPort::writeToParcelable(parcelable); - AudioPortConfig::writeToParcelable(&parcelable->activeConfig, useInputChannelMask()); + AudioPortConfig::writeToParcelable(&parcelable->activeConfig); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); media::AudioPortDeviceExt ext; @@ -190,7 +190,7 @@ status_t DeviceDescriptorBase::readFromParcelable(const media::AudioPort& parcel return BAD_VALUE; } status_t status = AudioPort::readFromParcelable(parcelable) - ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig, useInputChannelMask()); + ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig); if (status != OK) { return status; } diff --git a/media/libaudiofoundation/include/media/AudioPort.h b/media/libaudiofoundation/include/media/AudioPort.h index 6e1d032097..1cee1c95b2 100644 --- a/media/libaudiofoundation/include/media/AudioPort.h +++ b/media/libaudiofoundation/include/media/AudioPort.h @@ -130,7 +130,7 @@ private: }; -class AudioPortConfig : public virtual RefBase +class AudioPortConfig : public virtual RefBase, public virtual Parcelable { public: virtual ~AudioPortConfig() = default; @@ -152,8 +152,10 @@ public: bool equals(const sp& other) const; - status_t writeToParcelable(media::AudioPortConfig* parcelable, bool isInput) const; - status_t readFromParcelable(const media::AudioPortConfig& parcelable, bool isInput); + status_t writeToParcel(Parcel* parcel) const override; + status_t readFromParcel(const Parcel* parcel) override; + status_t writeToParcelable(media::AudioPortConfig* parcelable) const; + status_t readFromParcelable(const media::AudioPortConfig& parcelable); protected: unsigned int mSamplingRate = 0u; diff --git a/media/libaudiofoundation/include/media/AudioProfile.h b/media/libaudiofoundation/include/media/AudioProfile.h index e34a49f32b..6a36e78bd5 100644 --- a/media/libaudiofoundation/include/media/AudioProfile.h +++ b/media/libaudiofoundation/include/media/AudioProfile.h @@ -29,7 +29,7 @@ namespace android { -class AudioProfile final : public RefBase +class AudioProfile final : public RefBase, public Parcelable { public: static sp createFullDynamic(audio_format_t dynamicFormat = AUDIO_FORMAT_DEFAULT); @@ -81,9 +81,11 @@ public: bool equals(const sp& other) const; - ConversionResult toParcelable(bool isInput) const; - static ConversionResult> fromParcelable( - const media::AudioProfile& parcelable, bool isInput); + status_t writeToParcel(Parcel* parcel) const override; + status_t readFromParcel(const Parcel* parcel) override; + + ConversionResult toParcelable() const; + static ConversionResult> fromParcelable(const media::AudioProfile& parcelable); private: @@ -104,11 +106,11 @@ private: // Conversion routines, according to AidlConversion.h conventions. ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl); ConversionResult -legacy2aidl_AudioProfile(const sp& legacy, bool isInput); +legacy2aidl_AudioProfile(const sp& legacy); -class AudioProfileVector : public std::vector> +class AudioProfileVector : public std::vector>, public Parcelable { public: virtual ~AudioProfileVector() = default; @@ -134,15 +136,18 @@ public: virtual void dump(std::string *dst, int spaces) const; bool equals(const AudioProfileVector& other) const; + + status_t writeToParcel(Parcel* parcel) const override; + status_t readFromParcel(const Parcel* parcel) override; }; bool operator == (const AudioProfile &left, const AudioProfile &right); // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput); +aidl2legacy_AudioProfileVector(const std::vector& aidl); ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy); AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, const AudioProfileVector& profiles2); diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp index f3cd4468f8..bb9a5f2ac4 100644 --- a/media/libaudiofoundation/tests/Android.bp +++ b/media/libaudiofoundation/tests/Android.bp @@ -11,19 +11,12 @@ cc_test { name: "audiofoundation_parcelable_test", shared_libs: [ - "libbase", + "libaudiofoundation", "libbinder", "liblog", "libutils", ], - static_libs: [ - "audioclient-types-aidl-cpp", - "libaudioclient_aidl_conversion", - "libaudiofoundation", - "libstagefright_foundation", - ], - header_libs: [ "libaudio_system_headers", ], diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 2b03a83539..068b5d86be 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -86,6 +86,17 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioGain) { ASSERT_TRUE(audioGainsFromParcel.equals(audioGains)); } +TEST(AudioFoundationParcelableTest, ParcelingAudioProfileVector) { + Parcel data; + AudioProfileVector audioProfiles = getAudioProfileVectorForTest(); + + ASSERT_EQ(data.writeParcelable(audioProfiles), NO_ERROR); + data.setDataPosition(0); + AudioProfileVector audioProfilesFromParcel; + ASSERT_EQ(data.readParcelable(&audioProfilesFromParcel), NO_ERROR); + ASSERT_TRUE(audioProfilesFromParcel.equals(audioProfiles)); +} + TEST(AudioFoundationParcelableTest, ParcelingAudioPort) { Parcel data; sp audioPort = new AudioPort( @@ -105,15 +116,11 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioPortConfig) { Parcel data; sp audioPortConfig = new AudioPortConfigTestStub(); audioPortConfig->applyAudioPortConfig(&TEST_AUDIO_PORT_CONFIG); - media::AudioPortConfig parcelable{}; - ASSERT_EQ(NO_ERROR, audioPortConfig->writeToParcelable(&parcelable, false /*isInput*/)); - ASSERT_EQ(NO_ERROR, data.writeParcelable(parcelable)); + + ASSERT_EQ(data.writeParcelable(*audioPortConfig), NO_ERROR); data.setDataPosition(0); - media::AudioPortConfig parcelableFromParcel{}; - ASSERT_EQ(NO_ERROR, data.readParcelable(&parcelableFromParcel)); sp audioPortConfigFromParcel = new AudioPortConfigTestStub(); - ASSERT_EQ(NO_ERROR, audioPortConfigFromParcel->readFromParcelable( - parcelableFromParcel, false /*isInput*/)); + ASSERT_EQ(data.readParcelable(audioPortConfigFromParcel.get()), NO_ERROR); ASSERT_TRUE(audioPortConfigFromParcel->equals(audioPortConfig)); } diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index a1fb304e60..1e1db3187f 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -1876,10 +1876,10 @@ void AudioFlinger::removeNotificationClient(pid_t pid) void AudioFlinger::ioConfigChanged(audio_io_config_event_t event, const sp& ioDesc, pid_t pid) { - media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL( - legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event)); media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); + media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL( + legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event)); Mutex::Autolock _l(mClientLock); size_t size = mNotificationClients.size(); @@ -2610,9 +2610,9 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, audio_module_handle_t module = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_module_handle_t(request.module)); audio_config_t halConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/)); + aidl2legacy_AudioConfig_audio_config_t(request.halConfig)); audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig)); sp device = VALUE_OR_RETURN_STATUS( aidl2legacy_DeviceDescriptorBase(request.device)); audio_output_flags_t flags = VALUE_OR_RETURN_STATUS( @@ -2665,8 +2665,8 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED); } response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output)); - response->config = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/)); + response->config = + VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(halConfig)); response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(latencyMs)); response->flags = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); @@ -2834,7 +2834,7 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, audio_io_handle_t input = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_io_handle_t(request.input)); audio_config_t config = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/)); + aidl2legacy_AudioConfig_audio_config_t(request.config)); sp thread = openInput_l( VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)), @@ -2848,8 +2848,7 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, String8{}); response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - response->config = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); + response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); response->device = request.device; if (thread != 0) { diff --git a/services/audiopolicy/service/AudioPolicyClientImpl.cpp b/services/audiopolicy/service/AudioPolicyClientImpl.cpp index c8db45bfd9..79252d4d03 100644 --- a/services/audiopolicy/service/AudioPolicyClientImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyClientImpl.cpp @@ -56,18 +56,17 @@ status_t AudioPolicyService::AudioPolicyClient::openOutput(audio_module_handle_t media::OpenOutputResponse response; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(*halConfig, false /*isInput*/)); - request.mixerConfig = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig, false /*isInput*/)); + request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*halConfig)); + request.mixerConfig = + VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); status_t status = af->openOutput(request, &response); if (status == OK) { *output = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.output)); - *halConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(response.config, false /*isInput*/)); + *halConfig = + VALUE_OR_RETURN_STATUS(aidl2legacy_AudioConfig_audio_config_t(response.config)); *latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(response.latencyMs)); } return status; @@ -136,8 +135,7 @@ status_t AudioPolicyService::AudioPolicyClient::openInput(audio_module_handle_t media::OpenInputRequest request; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(*input)); - request.config = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(*config, true /*isInput*/)); + request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*config)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 4f920b1c38..af8a1950cd 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -292,7 +292,7 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_stream_type_t stream = AUDIO_STREAM_DEFAULT; audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/)); + aidl2legacy_AudioConfig_audio_config_t(configAidl)); audio_output_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_output_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -523,7 +523,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, true /*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); audio_input_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_input_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -1433,7 +1433,7 @@ Status AudioPolicyService::isDirectOutputSupported( const media::AudioAttributesInternal& attributesAidl, bool* _aidl_return) { audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, false /*isInput*/)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attributesAidl)); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index 73138932c9..3c757b3361 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -446,15 +446,13 @@ void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate( media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo)); media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase( - *clientConfig, true /*isInput*/)); + legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig)); std::vector clientEffectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( clientEffects, legacy2aidl_effect_descriptor_t_EffectDescriptor)); media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase( - *deviceConfig, true /*isInput*/)); + legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig)); std::vector effectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( effects, -- GitLab From de3fa1818a2f5f615a3b3ff1a58940f03b0ba8fc Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 30 Jul 2021 15:06:42 -0700 Subject: [PATCH 075/694] Revert "Revert "Switch the framework AIDL to use AudioChannelLayout"" This reverts commit b75b624f0a2b9a3e0ae6b89ceb6158e82df71b66. 'AudioChannelLayout' is a new type that will be used both by HAL and framework interfaces. This CL changes the framework interfaces to use it instead of 'AudioChannelMask' type which was used to pass legacy 'audio_channel_mask_t' transparently via the AIDL layer. Remove the implementation of 'Parcelable' from AudioProfile and AudioPortConfig in libaudiofoundation because the implementation not used after converting audio fwk interfaces to AIDL, and Parcelable's interface methods do not allow passing in any context. In our case the context is the direction of the I/O ('isInput' flag) which is usually available externally, but absent from the encapsulated data of these classes. Update the audiofoundation_parcelable_test, switch to use of static libs for the framework code so they can run on a device with default system libraries. Bug: 188932434 Test: check audio on device Test: atest audiofoundation_parcelable_test Test: app-compat/G3Compat/main Change-Id: I95c56040855187464bfbe7fcc7daf27f69fea55b --- media/libaudioclient/AidlConversion.cpp | 102 +++++++++--------- media/libaudioclient/Android.bp | 1 - media/libaudioclient/AudioSystem.cpp | 8 +- media/libaudioclient/AudioTrack.cpp | 2 +- media/libaudioclient/IAudioFlinger.cpp | 22 ++-- media/libaudioclient/PolicyAidlConversion.cpp | 10 +- .../aidl/android/media/AudioChannelMask.aidl | 45 -------- .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../aidl/android/media/AudioGain.aidl | 4 +- .../aidl/android/media/AudioGainConfig.aidl | 4 +- .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 4 +- .../fuzzer/audioflinger_fuzzer.cpp | 10 +- .../include/media/AidlConversion.h | 25 ++--- .../include/media/IAudioFlinger.h | 3 +- .../audio_aidl_legacy_conversion_tests.cpp | 12 +-- media/libaudiofoundation/AudioGain.cpp | 6 +- media/libaudiofoundation/AudioPort.cpp | 33 +++--- media/libaudiofoundation/AudioProfile.cpp | 77 ++++--------- .../DeviceDescriptorBase.cpp | 4 +- .../include/media/AudioPort.h | 8 +- .../include/media/AudioProfile.h | 23 ++-- media/libaudiofoundation/tests/Android.bp | 9 +- .../tests/audiofoundation_parcelable_test.cpp | 21 ++-- services/audioflinger/AudioFlinger.cpp | 17 +-- .../service/AudioPolicyClientImpl.cpp | 14 +-- .../service/AudioPolicyInterfaceImpl.cpp | 6 +- .../service/AudioPolicyService.cpp | 6 +- 31 files changed, 214 insertions(+), 282 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioChannelMask.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 60df8d5d3e..fd6bf28412 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -279,16 +279,6 @@ ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy) { enumToMask_index); } -ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( - media::AudioChannelMask aidl) { - return convertReinterpret(aidl); -} - -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( - audio_channel_mask_t legacy) { - return convertReinterpret(legacy); -} - ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl) { switch (aidl) { @@ -1103,7 +1093,7 @@ std::unordered_map make_ReverseMap(const std::vector>& v) } // namespace ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isOutput) { + const media::AudioChannelLayout& aidl, bool isInput) { using ReverseMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); @@ -1130,7 +1120,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan case Tag::indexMask: return convert(aidl, mIdx, __func__, "index"); case Tag::layoutMask: - return convert(aidl, isOutput ? mOut : mIn, __func__, isOutput ? "output" : "input"); + return convert(aidl, isInput ? mIn : mOut, __func__, isInput ? "input" : "output"); case Tag::voiceMask: return convert(aidl, mVoice, __func__, "voice"); } @@ -1139,7 +1129,7 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan } ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isOutput) { + audio_channel_mask_t legacy, bool isInput) { using DirectMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); @@ -1168,8 +1158,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { return convert(legacy, mIdx, __func__, "index"); } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { - return convert(legacy, isOutput ? mOut : mInAndVoice, __func__, - isOutput ? "output" : "input / voice"); + return convert(legacy, isInput ? mInAndVoice : mOut, __func__, + isInput ? "input / voice" : "output"); } ALOGE("%s: unknown representation %d in audio_channel_mask_t value 0x%x", @@ -1274,9 +1264,9 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi audio_gain_config legacy; legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - legacy.channel_mask = - VALUE_OR_RETURN(aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; + legacy.channel_mask = VALUE_OR_RETURN( + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const bool isJoint = bitmaskIsSet(aidl.mode, media::AudioGainMode::JOINT); size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1296,9 +1286,9 @@ ConversionResult legacy2aidl_audio_gain_config_AudioGain media::AudioGainConfig aidl; aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.channelMask = - VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; + aidl.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); const bool isJoint = (legacy.mode & AUDIO_GAIN_MODE_JOINT) != 0; size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) @@ -1863,9 +1853,11 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::CHANNEL_MASK)) { + const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + aidl.channelMask, isInput)); } if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { legacy.format = VALUE_OR_RETURN( @@ -1894,9 +1886,10 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { - aidl.channelMask = - VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + const bool isInput = VALUE_OR_RETURN( + direction(legacy.role, legacy.type)) == Direction::INPUT; + aidl.channelMask = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { aidl.format = VALUE_OR_RETURN( @@ -1971,7 +1964,7 @@ ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDes const audio_format_t format = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); const audio_channel_mask_t channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const size_t frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); const size_t frame_count_hal = VALUE_OR_RETURN(convertIntegral(aidl.frameCountHAL)); const uint32_t latency = VALUE_OR_RETURN(convertIntegral(aidl.latency)); @@ -1990,8 +1983,8 @@ ConversionResult legacy2aidl_AudioIoDescriptor_AudioIo aidl.samplingRate = VALUE_OR_RETURN(convertIntegral(legacy->getSamplingRate())); aidl.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy->getFormat())); - aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy->getChannelMask())); + aidl.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + legacy->getChannelMask(), legacy->getIsInput())); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCount())); aidl.frameCountHAL = VALUE_OR_RETURN(convertIntegral(legacy->getFrameCountHAL())); aidl.latency = VALUE_OR_RETURN(convertIntegral(legacy->getLatency())); @@ -2294,7 +2287,7 @@ aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& legacy.version = VALUE_OR_RETURN(convertIntegral(aidl.version)); legacy.size = sizeof(audio_offload_info_t); audio_config_base_t config = VALUE_OR_RETURN( - aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, false /*isInput*/)); legacy.sample_rate = config.sample_rate; legacy.channel_mask = config.channel_mask; legacy.format = config.format; @@ -2323,8 +2316,8 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } aidl.version = VALUE_OR_RETURN(convertIntegral(legacy.version)); aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.config.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + aidl.config.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + legacy.channel_mask, false /*isInput*/)); aidl.config.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.streamType = VALUE_OR_RETURN( @@ -2353,11 +2346,11 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput) { audio_config_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); @@ -2366,11 +2359,11 @@ aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl) { } ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput) { media::AudioConfig aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); @@ -2379,21 +2372,21 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy) { } ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl) { +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput) { audio_config_base_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); return legacy; } ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy) { +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput) { media::AudioConfigBase aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); return aidl; } @@ -2723,7 +2716,7 @@ ConversionResult legacy2aidl_AudioPortExt( } ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput) { audio_profile legacy; legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); @@ -2740,7 +2733,9 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { } RETURN_IF_ERROR( convertRange(aidl.channelMasks.begin(), aidl.channelMasks.end(), legacy.channel_masks, - aidl2legacy_AudioChannelMask_audio_channel_mask_t)); + [isInput](const media::AudioChannelLayout& l) { + return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); + })); legacy.num_channel_masks = aidl.channelMasks.size(); legacy.encapsulation_type = VALUE_OR_RETURN( @@ -2749,7 +2744,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl) { } ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput) { media::AudioProfile aidl; aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); @@ -2767,7 +2762,9 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy) { RETURN_IF_ERROR( convertRange(legacy.channel_masks, legacy.channel_masks + legacy.num_channel_masks, std::back_inserter(aidl.channelMasks), - legacy2aidl_audio_channel_mask_t_AudioChannelMask)); + [isInput](audio_channel_mask_t m) { + return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); + })); aidl.encapsulationType = VALUE_OR_RETURN( legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( @@ -2779,8 +2776,8 @@ ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(aidl.channelMask)); + legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + aidl.channelMask, aidl.useInChannelMask)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2791,11 +2788,12 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { } ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy) { +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); + aidl.useInChannelMask = isInput; aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(legacy.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); aidl.maxValue = VALUE_OR_RETURN(convertIntegral(legacy.max_value)); aidl.defaultValue = VALUE_OR_RETURN(convertIntegral(legacy.default_value)); @@ -2816,8 +2814,11 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { if (aidl.profiles.size() > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } + const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; RETURN_IF_ERROR(convertRange(aidl.profiles.begin(), aidl.profiles.end(), legacy.audio_profiles, - aidl2legacy_AudioProfile_audio_profile)); + [isInput](const media::AudioProfile& p) { + return aidl2legacy_AudioProfile_audio_profile(p, isInput); + })); legacy.num_audio_profiles = aidl.profiles.size(); if (aidl.extraAudioDescriptors.size() > std::size(legacy.extra_audio_descriptors)) { @@ -2853,10 +2854,13 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { if (legacy.num_audio_profiles > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } + const bool isInput = VALUE_OR_RETURN(direction(legacy.role, legacy.type)) == Direction::INPUT; RETURN_IF_ERROR( convertRange(legacy.audio_profiles, legacy.audio_profiles + legacy.num_audio_profiles, std::back_inserter(aidl.profiles), - legacy2aidl_audio_profile_AudioProfile)); + [isInput](const audio_profile& p) { + return legacy2aidl_audio_profile_AudioProfile(p, isInput); + })); if (legacy.num_extra_audio_descriptors > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); @@ -2873,7 +2877,9 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { RETURN_IF_ERROR( convertRange(legacy.gains, legacy.gains + legacy.num_gains, std::back_inserter(aidl.gains), - legacy2aidl_audio_gain_AudioGain)); + [isInput](const audio_gain& g) { + return legacy2aidl_audio_gain_AudioGain(g, isInput); + })); aidl.activeConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 64256a1880..63da4d143d 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -304,7 +304,6 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioChannelLayout.aidl", - "aidl/android/media/AudioChannelMask.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", "aidl/android/media/AudioConfigBase.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index b9de92a2c7..2d376b9194 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -1003,7 +1003,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, legacy2aidl_audio_attributes_t_AudioAttributesInternal(*attr)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfig configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_t_AudioConfig(*config)); + legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( @@ -1097,7 +1097,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, int32_t riidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_unique_id_t_int32_t(riid)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); media::AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*config)); + legacy2aidl_audio_config_base_t_AudioConfigBase(*config, true /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_port_handle_t_int32_t(*selectedDeviceId)); @@ -2431,13 +2431,13 @@ Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( record_client_info_t clientInfoLegacy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_RecordClientInfo_record_client_info_t(clientInfo)); audio_config_base_t clientConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(clientConfig, true /*isInput*/)); std::vector clientEffectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( clientEffects, aidl2legacy_EffectDescriptor_effect_descriptor_t)); audio_config_base_t deviceConfigLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(deviceConfig, true /*isInput*/)); std::vector effectsLegacy = VALUE_OR_RETURN_BINDER_STATUS( convertContainer>( effects, diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index bd9de91ae6..5b7760b0b4 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -171,7 +171,7 @@ bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config, auto result = [&]() -> ConversionResult { media::AudioConfigBase configAidl = VALUE_OR_RETURN( - legacy2aidl_audio_config_base_t_AudioConfigBase(config)); + legacy2aidl_audio_config_base_t_AudioConfigBase(config, false /*isInput*/)); media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); bool retAidl; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 5da56b8feb..5f12f71c36 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -55,7 +55,9 @@ using binder::Status; ConversionResult IAudioFlinger::CreateTrackInput::toAidl() const { media::CreateTrackRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(config)); + // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. + aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( + config, false /*isInput*/)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.sharedBuffer = VALUE_OR_RETURN(legacy2aidl_NullableIMemory_SharedFileRegion(sharedBuffer)); aidl.notificationsPerBuffer = VALUE_OR_RETURN(convertIntegral(notificationsPerBuffer)); @@ -74,7 +76,9 @@ ConversionResult IAudioFlinger::CreateTrackInput::fromAidl(const media::CreateTrackRequest& aidl) { IAudioFlinger::CreateTrackInput legacy; legacy.attr = VALUE_OR_RETURN(aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.config)); + // Do not be mislead by 'Input'--this is an input to 'createTrack', which creates output tracks. + legacy.config = VALUE_OR_RETURN( + aidl2legacy_AudioConfig_audio_config_t(aidl.config, false /*isInput*/)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.sharedBuffer = VALUE_OR_RETURN(aidl2legacy_NullableSharedFileRegion_IMemory(aidl.sharedBuffer)); legacy.notificationsPerBuffer = VALUE_OR_RETURN( @@ -139,7 +143,8 @@ ConversionResult IAudioFlinger::CreateRecordInput::toAidl() const { media::CreateRecordRequest aidl; aidl.attr = VALUE_OR_RETURN(legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - aidl.config = VALUE_OR_RETURN(legacy2aidl_audio_config_base_t_AudioConfigBase(config)); + aidl.config = VALUE_OR_RETURN( + legacy2aidl_audio_config_base_t_AudioConfigBase(config, true /*isInput*/)); aidl.clientInfo = VALUE_OR_RETURN(legacy2aidl_AudioClient_AudioClient(clientInfo)); aidl.riid = VALUE_OR_RETURN(legacy2aidl_audio_unique_id_t_int32_t(riid)); aidl.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -159,7 +164,8 @@ IAudioFlinger::CreateRecordInput::fromAidl( IAudioFlinger::CreateRecordInput legacy; legacy.attr = VALUE_OR_RETURN( aidl2legacy_AudioAttributesInternal_audio_attributes_t(aidl.attr)); - legacy.config = VALUE_OR_RETURN(aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config)); + legacy.config = VALUE_OR_RETURN( + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, true /*isInput*/)); legacy.clientInfo = VALUE_OR_RETURN(aidl2legacy_AudioClient_AudioClient(aidl.clientInfo)); legacy.riid = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_unique_id_t(aidl.riid)); legacy.maxSharedAudioHistoryMs = VALUE_OR_RETURN( @@ -412,8 +418,8 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); media::AudioFormatDescription formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(format)); - media::AudioChannelMask channelMaskAidl = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(channelMask)); + media::AudioChannelLayout channelMaskAidl = VALUE_OR_RETURN( + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(channelMask, true /*isInput*/)); int64_t aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( mDelegate->getInputBufferSize(sampleRateAidl, formatAidl, channelMaskAidl, @@ -939,13 +945,13 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioFormatDescription_audio_format_t(format)); audio_channel_mask_t channelMaskLegacy = VALUE_OR_RETURN_BINDER( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(channelMask, true /*isInput*/)); size_t size = mDelegate->getInputBufferSize(sampleRateLegacy, formatLegacy, channelMaskLegacy); *_aidl_return = VALUE_OR_RETURN_BINDER(convertIntegral(size)); return Status::ok(); diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index d6611d1c94..676bb37406 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -232,7 +232,10 @@ aidl2legacy_AudioMix(const media::AudioMix& aidl) { std::back_inserter(legacy.mCriteria), aidl2legacy_AudioMixMatchCriterion)); legacy.mMixType = VALUE_OR_RETURN(aidl2legacy_AudioMixType_uint32_t(aidl.mixType)); - legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t(aidl.format)); + // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only + // an output mask is expected here. + legacy.mFormat = VALUE_OR_RETURN(aidl2legacy_AudioConfig_audio_config_t( + aidl.format, false /*isInput*/)); legacy.mRouteFlags = VALUE_OR_RETURN( aidl2legacy_AudioMixRouteFlag_uint32_t_mask(aidl.routeFlags)); legacy.mDeviceType = VALUE_OR_RETURN( @@ -252,7 +255,10 @@ legacy2aidl_AudioMix(const AudioMix& legacy) { legacy.mCriteria, legacy2aidl_AudioMixMatchCriterion)); aidl.mixType = VALUE_OR_RETURN(legacy2aidl_uint32_t_AudioMixType(legacy.mMixType)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig(legacy.mFormat)); + // See 'convertAudioMixToNative' in 'android_media_AudioSystem.cpp' -- only + // an output mask is expected here. + aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_config_t_AudioConfig( + legacy.mFormat, false /*isInput*/)); aidl.routeFlags = VALUE_OR_RETURN( legacy2aidl_uint32_t_AudioMixRouteFlag_mask(legacy.mRouteFlags)); aidl.device.type = VALUE_OR_RETURN( diff --git a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl b/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl deleted file mode 100644 index 1e7e6e5e23..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioChannelMask.aidl +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * AudioChannelMask is an opaque type and its internal layout should not be - * assumed as it may change in the future. - * - * This is a temporary implementation to provide a distinct type (instead of - * 'int') in all the places that need a channel mask. Later the enum will be - * replaced with a type which is more extensible by vendors. - * - * The actual value range of this enum is the same as of - * the 'audio_channel_mask_t' enum. - * - * {@hide} - */ -@Backing(type="int") -enum AudioChannelMask { - /** - * Framework use only, do not constitute a valid channel mask. - */ - INVALID = 0xC0000000, - - NONE = 0, - /** - * Since the current code never uses the values of the SAIDL enum - * directly--it uses the values of the C enum and coerces the type-- - * we don't specify any other values here. - */ -} diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 5fd25d50ac..6996d4276f 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; import android.media.AudioOffloadInfo; @@ -25,7 +25,7 @@ import android.media.AudioOffloadInfo; */ parcelable AudioConfig { int sampleRate; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; AudioFormatDescription format; AudioOffloadInfo offloadInfo; long frameCount; diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index fb20404ad7..e84161bce5 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; /** @@ -24,6 +24,6 @@ import android.media.AudioFormatDescription; */ parcelable AudioConfigBase { int sampleRate; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; AudioFormatDescription format; } diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 58cf1c984c..14e1f5b160 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; /** * {@hide} @@ -27,7 +27,7 @@ parcelable AudioGain { boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; int minValue; int maxValue; int defaultValue; diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl index 67b77a5742..afa3aca3f3 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; /** * {@hide} @@ -31,7 +31,7 @@ parcelable AudioGainConfig { /** * Channels which gain value follows. N/A in joint mode. */ - AudioChannelMask channelMask; + AudioChannelLayout channelMask; /** * Gain values in millibels. diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index ea8ec3205f..efdf99b699 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioFormatDescription; import android.media.AudioPatch; @@ -30,7 +30,7 @@ parcelable AudioIoDescriptor { boolean isInput; int samplingRate; AudioFormatDescription format; - AudioChannelMask channelMask; + AudioChannelLayout channelMask; long frameCount; long frameCountHAL; /** Only valid for output. */ diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index c4b572d7f3..be32a69e91 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; @@ -45,7 +45,7 @@ parcelable AudioPortConfig { /** * Channel mask, if applicable. */ - AudioChannelMask channelMask; + AudioChannelLayout channelMask; /** * Format, if applicable. */ diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 34b8d35d14..9fb8d494e5 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioEncapsulationType; import android.media.AudioFormatDescription; @@ -27,7 +27,7 @@ parcelable AudioProfile { @utf8InCpp String name; /** The format for an audio profile should only be set when initialized. */ AudioFormatDescription format; - AudioChannelMask[] channelMasks; + AudioChannelLayout[] channelMasks; int[] samplingRates; boolean isDynamicFormat; boolean isDynamicChannels; diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 28233d1366..16f70c133e 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelMask; +import android.media.AudioChannelLayout; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -117,7 +117,7 @@ interface IAudioFlingerService { // FIXME This API assumes a route, and so should be deprecated. long getInputBufferSize(int sampleRate, in AudioFormatDescription format, - AudioChannelMask channelMask); + in AudioChannelLayout channelMask); OpenOutputResponse openOutput(in OpenOutputRequest request); int /* audio_io_handle_t */ openDuplicateOutput(int /* audio_io_handle_t */ output1, diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp index 12473fc760..bdd72dd650 100644 --- a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp +++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp @@ -597,7 +597,8 @@ status_t AudioFlingerFuzzer::invokeAudioInputDevice() { media::OpenInputRequest request{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); + request.config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); @@ -654,9 +655,10 @@ status_t AudioFlingerFuzzer::invokeAudioOutputDevice() { media::OpenOutputResponse response{}; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); - request.mixerConfig = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig)); + request.halConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, false /*isInput*/)); + request.mixerConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_base_t_AudioConfigBase(mixerConfig, false /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index e56106a710..2cf127c373 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -99,11 +99,6 @@ ConversionResult legacy2aidl_int32_t_AudioPortConfig ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl); ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy); -ConversionResult aidl2legacy_AudioChannelMask_audio_channel_mask_t( - media::AudioChannelMask aidl); -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelMask( - audio_channel_mask_t legacy); - ConversionResult aidl2legacy_int32_t_pid_t(int32_t aidl); ConversionResult legacy2aidl_pid_t_int32_t(pid_t legacy); @@ -137,9 +132,9 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isOutput); + const media::AudioChannelLayout& aidl, bool isInput); ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isOutput); + audio_channel_mask_t legacy, bool isInput); ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl); @@ -233,7 +228,6 @@ ConversionResult legacy2aidl_audio_patch_AudioPatch( ConversionResult> aidl2legacy_AudioIoDescriptor_AudioIoDescriptor( const media::AudioIoDescriptor& aidl); - ConversionResult legacy2aidl_AudioIoDescriptor_AudioIoDescriptor( const sp& legacy); @@ -278,14 +272,14 @@ ConversionResult legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& legacy); ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl); +aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput); ConversionResult -legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy); +legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput); ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl); +aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput); ConversionResult -legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy); +legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput); ConversionResult> aidl2legacy_SharedFileRegion_IMemory(const media::SharedFileRegion& aidl); @@ -352,14 +346,15 @@ ConversionResult legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy); ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl); +aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput); ConversionResult -legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy); +legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput); ConversionResult aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl); +// The AIDL structure provides a flag for direction indication while the legacy type doesn't. ConversionResult -legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy); +legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput); ConversionResult aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl); diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 3cc36df92a..8632abb4e7 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -592,7 +592,8 @@ public: getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; Status getInputBufferSize(int32_t sampleRate, const media::AudioFormatDescription& format, - media::AudioChannelMask channelMask, int64_t* _aidl_return) override; + const media::AudioChannelLayout& channelMask, + int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; Status openDuplicateOutput(int32_t output1, int32_t output2, int32_t* _aidl_return) override; diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index b6e597dbfc..7f8af53334 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -172,15 +172,15 @@ TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { make_AFD_Encap, make_AFD_Encap_with_Enc}); } -using ChannelLayoutParam = std::tuple; +using ChannelLayoutParam = std::tuple; class AudioChannelLayoutRoundTripTest : public testing::TestWithParam {}; TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { const auto initial = std::get<0>(GetParam()); - const bool isOutput = std::get<1>(GetParam()); - auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isOutput); + const bool isInput = std::get<1>(GetParam()); + auto conv = aidl2legacy_AudioChannelLayout_audio_channel_mask_t(initial, isInput); ASSERT_TRUE(conv.ok()); - auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isOutput); + auto convBack = legacy2aidl_audio_channel_mask_t_AudioChannelLayout(conv.value(), isInput); ASSERT_TRUE(convBack.ok()); EXPECT_EQ(initial, convBack.value()); } @@ -189,11 +189,11 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, testing::Combine( testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), make_ACL_ChannelIndex2()), - testing::Values(true, false))); + testing::Values(false, true))); INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, AudioChannelLayoutRoundTripTest, // In legacy constants the voice call is only defined for input. - testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(false))); + testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(true))); class AudioDeviceDescriptionRoundTripTest : public testing::TestWithParam {}; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 5cc2b2f5f2..169899d74b 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -142,7 +142,8 @@ status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout( + mGain.channel_mask, mUseInChannelMask)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -166,7 +167,8 @@ status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + parcelable.channelMask, parcelable.useInChannelMask)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index 24ecd78397..c70a6c2f8b 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -210,7 +210,8 @@ status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { parcelable->name = mName; parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); - parcelable->profiles = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioProfileVector(mProfiles)); + parcelable->profiles = VALUE_OR_RETURN_STATUS( + legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); parcelable->extraAudioDescriptors = mExtraAudioDescriptors; parcelable->gains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); return OK; @@ -226,7 +227,8 @@ status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { mName = parcelable.name; mType = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortType_audio_port_type_t(parcelable.type)); mRole = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.role)); - mProfiles = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioProfileVector(parcelable.profiles)); + mProfiles = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioProfileVector(parcelable.profiles, useInputChannelMask())); mExtraAudioDescriptors = parcelable.extraAudioDescriptors; mGains = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioGains(parcelable.gains)); return OK; @@ -330,24 +332,19 @@ bool AudioPortConfig::equals(const sp &other) const mGain.ramp_duration_ms == other->mGain.ramp_duration_ms; } -status_t AudioPortConfig::writeToParcel(Parcel *parcel) const { - media::AudioPortConfig parcelable; - return writeToParcelable(&parcelable) - ?: parcelable.writeToParcel(parcel); -} - -status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) const { +status_t AudioPortConfig::writeToParcelable( + media::AudioPortConfig* parcelable, bool isInput) const { parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); parcelable->format = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mChannelMask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mChannelMask, isInput)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); parcelable->gain.index = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.index)); parcelable->gain.mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->gain.channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelMask(mGain.channel_mask)); + legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mGain.channel_mask, isInput)); parcelable->gain.rampDurationMs = VALUE_OR_RETURN_STATUS( convertIntegral(mGain.ramp_duration_ms)); parcelable->gain.values = VALUE_OR_RETURN_STATUS(convertContainer>( @@ -355,24 +352,20 @@ status_t AudioPortConfig::writeToParcelable(media::AudioPortConfig* parcelable) return OK; } -status_t AudioPortConfig::readFromParcel(const Parcel *parcel) { - media::AudioPortConfig parcelable; - return parcelable.readFromParcel(parcel) - ?: readFromParcelable(parcelable); -} - -status_t AudioPortConfig::readFromParcelable(const media::AudioPortConfig& parcelable) { +status_t AudioPortConfig::readFromParcelable( + const media::AudioPortConfig& parcelable, bool isInput) { mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); mFormat = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); mChannelMask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t(parcelable.channelMask, isInput)); mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); mGain.index = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.index)); mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.gain.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelMask_audio_channel_mask_t(parcelable.gain.channelMask)); + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + parcelable.gain.channelMask, isInput)); mGain.ramp_duration_ms = VALUE_OR_RETURN_STATUS( convertIntegral(parcelable.gain.rampDurationMs)); if (parcelable.gain.values.size() > std::size(mGain.values)) { diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index f2bed258b0..47b2d5488e 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -154,20 +154,17 @@ AudioProfile& AudioProfile::operator=(const AudioProfile& other) { return *this; } -status_t AudioProfile::writeToParcel(Parcel *parcel) const { - media::AudioProfile parcelable = VALUE_OR_RETURN_STATUS(toParcelable()); - return parcelable.writeToParcel(parcel); - } - ConversionResult -AudioProfile::toParcelable() const { +AudioProfile::toParcelable(bool isInput) const { media::AudioProfile parcelable; parcelable.name = mName; parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( - convertContainer>( + convertContainer>( mChannelMasks, - legacy2aidl_audio_channel_mask_t_AudioChannelMask)); + [isInput](audio_channel_mask_t m) { + return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); + })); parcelable.samplingRates = VALUE_OR_RETURN( convertContainer>(mSamplingRates, convertIntegral)); @@ -179,24 +176,17 @@ AudioProfile::toParcelable() const { return parcelable; } -status_t AudioProfile::readFromParcel(const Parcel *parcel) { - media::AudioProfile parcelable; - if (status_t status = parcelable.readFromParcel(parcel); status != OK) { - return status; - } - *this = *VALUE_OR_RETURN_STATUS(fromParcelable(parcelable)); - return OK; -} - ConversionResult> -AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { +AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput) { sp legacy = new AudioProfile(); legacy->mName = parcelable.name; legacy->mFormat = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, - aidl2legacy_AudioChannelMask_audio_channel_mask_t)); + [isInput](const media::AudioChannelLayout& l) { + return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); + })); legacy->mSamplingRates = VALUE_OR_RETURN( convertContainer(parcelable.samplingRates, convertIntegral)); @@ -210,13 +200,13 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable) { } ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl) { - return AudioProfile::fromParcelable(aidl); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput) { + return AudioProfile::fromParcelable(aidl, isInput); } ConversionResult -legacy2aidl_AudioProfile(const sp& legacy) { - return legacy->toParcelable(); +legacy2aidl_AudioProfile(const sp& legacy, bool isInput) { + return legacy->toParcelable(isInput); } ssize_t AudioProfileVector::add(const sp &profile) @@ -330,33 +320,6 @@ void AudioProfileVector::dump(std::string *dst, int spaces) const } } -status_t AudioProfileVector::writeToParcel(Parcel *parcel) const -{ - status_t status = NO_ERROR; - if ((status = parcel->writeVectorSize(*this)) != NO_ERROR) return status; - for (const auto &audioProfile : *this) { - if ((status = parcel->writeParcelable(*audioProfile)) != NO_ERROR) { - break; - } - } - return status; -} - -status_t AudioProfileVector::readFromParcel(const Parcel *parcel) -{ - status_t status = NO_ERROR; - this->clear(); - if ((status = parcel->resizeOutVector(this)) != NO_ERROR) return status; - for (size_t i = 0; i < this->size(); ++i) { - this->at(i) = new AudioProfile(AUDIO_FORMAT_DEFAULT, AUDIO_CHANNEL_NONE, 0 /*sampleRate*/); - if ((status = parcel->readParcelable(this->at(i).get())) != NO_ERROR) { - this->clear(); - break; - } - } - return status; -} - bool AudioProfileVector::equals(const AudioProfileVector& other) const { return std::equal(begin(), end(), other.begin(), other.end(), @@ -366,13 +329,19 @@ bool AudioProfileVector::equals(const AudioProfileVector& other) const } ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl) { - return convertContainer(aidl, aidl2legacy_AudioProfile); +aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput) { + return convertContainer(aidl, + [isInput](const media::AudioProfile& p) { + return aidl2legacy_AudioProfile(p, isInput); + }); } ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy) { - return convertContainer>(legacy, legacy2aidl_AudioProfile); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput) { + return convertContainer>(legacy, + [isInput](const sp& p) { + return legacy2aidl_AudioProfile(p, isInput); + }); } AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp index 5cfea816a2..3cce722225 100644 --- a/media/libaudiofoundation/DeviceDescriptorBase.cpp +++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp @@ -166,7 +166,7 @@ status_t DeviceDescriptorBase::writeToParcel(Parcel *parcel) const status_t DeviceDescriptorBase::writeToParcelable(media::AudioPort* parcelable) const { AudioPort::writeToParcelable(parcelable); - AudioPortConfig::writeToParcelable(&parcelable->activeConfig); + AudioPortConfig::writeToParcelable(&parcelable->activeConfig, useInputChannelMask()); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); media::AudioPortDeviceExt ext; @@ -190,7 +190,7 @@ status_t DeviceDescriptorBase::readFromParcelable(const media::AudioPort& parcel return BAD_VALUE; } status_t status = AudioPort::readFromParcelable(parcelable) - ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig); + ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig, useInputChannelMask()); if (status != OK) { return status; } diff --git a/media/libaudiofoundation/include/media/AudioPort.h b/media/libaudiofoundation/include/media/AudioPort.h index 1cee1c95b2..6e1d032097 100644 --- a/media/libaudiofoundation/include/media/AudioPort.h +++ b/media/libaudiofoundation/include/media/AudioPort.h @@ -130,7 +130,7 @@ private: }; -class AudioPortConfig : public virtual RefBase, public virtual Parcelable +class AudioPortConfig : public virtual RefBase { public: virtual ~AudioPortConfig() = default; @@ -152,10 +152,8 @@ public: bool equals(const sp& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; - status_t writeToParcelable(media::AudioPortConfig* parcelable) const; - status_t readFromParcelable(const media::AudioPortConfig& parcelable); + status_t writeToParcelable(media::AudioPortConfig* parcelable, bool isInput) const; + status_t readFromParcelable(const media::AudioPortConfig& parcelable, bool isInput); protected: unsigned int mSamplingRate = 0u; diff --git a/media/libaudiofoundation/include/media/AudioProfile.h b/media/libaudiofoundation/include/media/AudioProfile.h index 6a36e78bd5..e34a49f32b 100644 --- a/media/libaudiofoundation/include/media/AudioProfile.h +++ b/media/libaudiofoundation/include/media/AudioProfile.h @@ -29,7 +29,7 @@ namespace android { -class AudioProfile final : public RefBase, public Parcelable +class AudioProfile final : public RefBase { public: static sp createFullDynamic(audio_format_t dynamicFormat = AUDIO_FORMAT_DEFAULT); @@ -81,11 +81,9 @@ public: bool equals(const sp& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; - - ConversionResult toParcelable() const; - static ConversionResult> fromParcelable(const media::AudioProfile& parcelable); + ConversionResult toParcelable(bool isInput) const; + static ConversionResult> fromParcelable( + const media::AudioProfile& parcelable, bool isInput); private: @@ -106,11 +104,11 @@ private: // Conversion routines, according to AidlConversion.h conventions. ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl); +aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput); ConversionResult -legacy2aidl_AudioProfile(const sp& legacy); +legacy2aidl_AudioProfile(const sp& legacy, bool isInput); -class AudioProfileVector : public std::vector>, public Parcelable +class AudioProfileVector : public std::vector> { public: virtual ~AudioProfileVector() = default; @@ -136,18 +134,15 @@ public: virtual void dump(std::string *dst, int spaces) const; bool equals(const AudioProfileVector& other) const; - - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; }; bool operator == (const AudioProfile &left, const AudioProfile &right); // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl); +aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput); ConversionResult> -legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy); +legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput); AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, const AudioProfileVector& profiles2); diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp index bb9a5f2ac4..f3cd4468f8 100644 --- a/media/libaudiofoundation/tests/Android.bp +++ b/media/libaudiofoundation/tests/Android.bp @@ -11,12 +11,19 @@ cc_test { name: "audiofoundation_parcelable_test", shared_libs: [ - "libaudiofoundation", + "libbase", "libbinder", "liblog", "libutils", ], + static_libs: [ + "audioclient-types-aidl-cpp", + "libaudioclient_aidl_conversion", + "libaudiofoundation", + "libstagefright_foundation", + ], + header_libs: [ "libaudio_system_headers", ], diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 068b5d86be..2b03a83539 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -86,17 +86,6 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioGain) { ASSERT_TRUE(audioGainsFromParcel.equals(audioGains)); } -TEST(AudioFoundationParcelableTest, ParcelingAudioProfileVector) { - Parcel data; - AudioProfileVector audioProfiles = getAudioProfileVectorForTest(); - - ASSERT_EQ(data.writeParcelable(audioProfiles), NO_ERROR); - data.setDataPosition(0); - AudioProfileVector audioProfilesFromParcel; - ASSERT_EQ(data.readParcelable(&audioProfilesFromParcel), NO_ERROR); - ASSERT_TRUE(audioProfilesFromParcel.equals(audioProfiles)); -} - TEST(AudioFoundationParcelableTest, ParcelingAudioPort) { Parcel data; sp audioPort = new AudioPort( @@ -116,11 +105,15 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioPortConfig) { Parcel data; sp audioPortConfig = new AudioPortConfigTestStub(); audioPortConfig->applyAudioPortConfig(&TEST_AUDIO_PORT_CONFIG); - - ASSERT_EQ(data.writeParcelable(*audioPortConfig), NO_ERROR); + media::AudioPortConfig parcelable{}; + ASSERT_EQ(NO_ERROR, audioPortConfig->writeToParcelable(&parcelable, false /*isInput*/)); + ASSERT_EQ(NO_ERROR, data.writeParcelable(parcelable)); data.setDataPosition(0); + media::AudioPortConfig parcelableFromParcel{}; + ASSERT_EQ(NO_ERROR, data.readParcelable(&parcelableFromParcel)); sp audioPortConfigFromParcel = new AudioPortConfigTestStub(); - ASSERT_EQ(data.readParcelable(audioPortConfigFromParcel.get()), NO_ERROR); + ASSERT_EQ(NO_ERROR, audioPortConfigFromParcel->readFromParcelable( + parcelableFromParcel, false /*isInput*/)); ASSERT_TRUE(audioPortConfigFromParcel->equals(audioPortConfig)); } diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 1e1db3187f..a1fb304e60 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -1876,10 +1876,10 @@ void AudioFlinger::removeNotificationClient(pid_t pid) void AudioFlinger::ioConfigChanged(audio_io_config_event_t event, const sp& ioDesc, pid_t pid) { - media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( - legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); media::AudioIoConfigEvent eventAidl = VALUE_OR_FATAL( legacy2aidl_audio_io_config_event_t_AudioIoConfigEvent(event)); + media::AudioIoDescriptor descAidl = VALUE_OR_FATAL( + legacy2aidl_AudioIoDescriptor_AudioIoDescriptor(ioDesc)); Mutex::Autolock _l(mClientLock); size_t size = mNotificationClients.size(); @@ -2610,9 +2610,9 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, audio_module_handle_t module = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_module_handle_t(request.module)); audio_config_t halConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.halConfig)); + aidl2legacy_AudioConfig_audio_config_t(request.halConfig, false /*isInput*/)); audio_config_base_t mixerConfig = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig)); + aidl2legacy_AudioConfigBase_audio_config_base_t(request.mixerConfig, false/*isInput*/)); sp device = VALUE_OR_RETURN_STATUS( aidl2legacy_DeviceDescriptorBase(request.device)); audio_output_flags_t flags = VALUE_OR_RETURN_STATUS( @@ -2665,8 +2665,8 @@ status_t AudioFlinger::openOutput(const media::OpenOutputRequest& request, mmapThread->ioConfigChanged(AUDIO_OUTPUT_OPENED); } response->output = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output)); - response->config = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(halConfig)); + response->config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(halConfig, false /*isInput*/)); response->latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(latencyMs)); response->flags = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); @@ -2834,7 +2834,7 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, audio_io_handle_t input = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_io_handle_t(request.input)); audio_config_t config = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioConfig_audio_config_t(request.config)); + aidl2legacy_AudioConfig_audio_config_t(request.config, true /*isInput*/)); sp thread = openInput_l( VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_module_handle_t(request.module)), @@ -2848,7 +2848,8 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, String8{}); response->input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(input)); - response->config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(config)); + response->config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); response->device = request.device; if (thread != 0) { diff --git a/services/audiopolicy/service/AudioPolicyClientImpl.cpp b/services/audiopolicy/service/AudioPolicyClientImpl.cpp index 79252d4d03..c8db45bfd9 100644 --- a/services/audiopolicy/service/AudioPolicyClientImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyClientImpl.cpp @@ -56,17 +56,18 @@ status_t AudioPolicyService::AudioPolicyClient::openOutput(audio_module_handle_t media::OpenOutputResponse response; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); - request.halConfig = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*halConfig)); - request.mixerConfig = - VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig)); + request.halConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(*halConfig, false /*isInput*/)); + request.mixerConfig = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_base_t_AudioConfigBase(*mixerConfig, false /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_DeviceDescriptorBase(device)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); status_t status = af->openOutput(request, &response); if (status == OK) { *output = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_io_handle_t(response.output)); - *halConfig = - VALUE_OR_RETURN_STATUS(aidl2legacy_AudioConfig_audio_config_t(response.config)); + *halConfig = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioConfig_audio_config_t(response.config, false /*isInput*/)); *latencyMs = VALUE_OR_RETURN_STATUS(convertIntegral(response.latencyMs)); } return status; @@ -135,7 +136,8 @@ status_t AudioPolicyService::AudioPolicyClient::openInput(audio_module_handle_t media::OpenInputRequest request; request.module = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_module_handle_t_int32_t(module)); request.input = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(*input)); - request.config = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_config_t_AudioConfig(*config)); + request.config = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(*config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index af8a1950cd..4f920b1c38 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -292,7 +292,7 @@ Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_stream_type_t stream = AUDIO_STREAM_DEFAULT; audio_config_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfig_audio_config_t(configAidl)); + aidl2legacy_AudioConfig_audio_config_t(configAidl, false /*isInput*/)); audio_output_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_output_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -523,7 +523,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& audio_session_t session = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_session_t(sessionAidl)); audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, true /*isInput*/)); audio_input_flags_t flags = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_input_flags_t_mask(flagsAidl)); audio_port_handle_t selectedDeviceId = VALUE_OR_RETURN_BINDER_STATUS( @@ -1433,7 +1433,7 @@ Status AudioPolicyService::isDirectOutputSupported( const media::AudioAttributesInternal& attributesAidl, bool* _aidl_return) { audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl)); + aidl2legacy_AudioConfigBase_audio_config_base_t(configAidl, false /*isInput*/)); audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attributesAidl)); RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index 3c757b3361..73138932c9 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -446,13 +446,15 @@ void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate( media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo)); media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*clientConfig)); + legacy2aidl_audio_config_base_t_AudioConfigBase( + *clientConfig, true /*isInput*/)); std::vector clientEffectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( clientEffects, legacy2aidl_effect_descriptor_t_EffectDescriptor)); media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_config_base_t_AudioConfigBase(*deviceConfig)); + legacy2aidl_audio_config_base_t_AudioConfigBase( + *deviceConfig, true /*isInput*/)); std::vector effectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( effects, -- GitLab From 866c77d231ce113fb8693354d1aa64004834cc83 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 30 Jul 2021 15:11:35 -0700 Subject: [PATCH 076/694] Revert "Revert "Rename AudioGain.useInChannelMask -> isInput"" This reverts commit 05399f489aece403775f34cd2c2233243e2d5654. This is done for consistency with other data structures and conversion functions. Bug: 188932434 Test: atest audiofoundation_parcelable_test Change-Id: Ie98f6063625295c6796c49fdb09107d66546814f --- media/libaudioclient/AidlConversion.cpp | 4 +-- .../aidl/android/media/AudioGain.aidl | 2 +- media/libaudiofoundation/AudioGain.cpp | 32 ++++++++----------- .../include/media/AudioGain.h | 4 +-- .../tests/audiofoundation_parcelable_test.cpp | 2 +- 5 files changed, 19 insertions(+), 25 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index fd6bf28412..4c155fe653 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -2777,7 +2777,7 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, aidl.useInChannelMask)); + aidl.channelMask, aidl.isInput)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2791,7 +2791,7 @@ ConversionResult legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { media::AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.useInChannelMask = isInput; + aidl.isInput = isInput; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 14e1f5b160..4cfa96e44a 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -23,7 +23,7 @@ import android.media.AudioChannelLayout; */ parcelable AudioGain { int index; - boolean useInChannelMask; + boolean isInput; boolean useForVolume; /** Bitmask, indexed by AudioGainMode. */ int mode; diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index 169899d74b..ea0258a1d1 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -34,10 +34,10 @@ namespace android { -AudioGain::AudioGain(int index, bool useInChannelMask) +AudioGain::AudioGain(int index, bool isInput) { mIndex = index; - mUseInChannelMask = useInChannelMask; + mIsInput = isInput; memset(&mGain, 0, sizeof(struct audio_gain)); } @@ -49,12 +49,9 @@ void AudioGain::getDefaultConfig(struct audio_gain_config *config) if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) { config->values[0] = mGain.default_value; } else { - uint32_t numValues; - if (mUseInChannelMask) { - numValues = audio_channel_count_from_in_mask(mGain.channel_mask); - } else { - numValues = audio_channel_count_from_out_mask(mGain.channel_mask); - } + const uint32_t numValues = mIsInput ? + audio_channel_count_from_in_mask(mGain.channel_mask) : + audio_channel_count_from_out_mask(mGain.channel_mask); for (size_t i = 0; i < numValues; i++) { config->values[i] = mGain.default_value; } @@ -78,12 +75,9 @@ status_t AudioGain::checkConfig(const struct audio_gain_config *config) if ((config->channel_mask & ~mGain.channel_mask) != 0) { return BAD_VALUE; } - uint32_t numValues; - if (mUseInChannelMask) { - numValues = audio_channel_count_from_in_mask(config->channel_mask); - } else { - numValues = audio_channel_count_from_out_mask(config->channel_mask); - } + const uint32_t numValues = mIsInput ? + audio_channel_count_from_in_mask(config->channel_mask) : + audio_channel_count_from_out_mask(config->channel_mask); for (size_t i = 0; i < numValues; i++) { if ((config->values[i] < mGain.min_value) || (config->values[i] > mGain.max_value)) { @@ -116,7 +110,7 @@ void AudioGain::dump(std::string *dst, int spaces, int index) const bool AudioGain::equals(const sp& other) const { return other != nullptr && - mUseInChannelMask == other->mUseInChannelMask && + mIsInput == other->mIsInput && mUseForVolume == other->mUseForVolume && // Compare audio gain mGain.mode == other->mGain.mode && @@ -137,13 +131,13 @@ status_t AudioGain::writeToParcel(android::Parcel *parcel) const { status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { parcelable->index = VALUE_OR_RETURN_STATUS(convertIntegral(mIndex)); - parcelable->useInChannelMask = mUseInChannelMask; + parcelable->isInput = mIsInput; parcelable->useForVolume = mUseForVolume; parcelable->mode = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - mGain.channel_mask, mUseInChannelMask)); + mGain.channel_mask, mIsInput)); parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); parcelable->defaultValue = VALUE_OR_RETURN_STATUS( @@ -162,13 +156,13 @@ status_t AudioGain::readFromParcel(const android::Parcel *parcel) { status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { mIndex = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.index)); - mUseInChannelMask = parcelable.useInChannelMask; + mIsInput = parcelable.isInput; mUseForVolume = parcelable.useForVolume; mGain.mode = VALUE_OR_RETURN_STATUS( aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); mGain.channel_mask = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.channelMask, parcelable.useInChannelMask)); + parcelable.channelMask, parcelable.isInput)); mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); diff --git a/media/libaudiofoundation/include/media/AudioGain.h b/media/libaudiofoundation/include/media/AudioGain.h index a06b686363..28769d26ba 100644 --- a/media/libaudiofoundation/include/media/AudioGain.h +++ b/media/libaudiofoundation/include/media/AudioGain.h @@ -31,7 +31,7 @@ namespace android { class AudioGain: public RefBase, public Parcelable { public: - AudioGain(int index, bool useInChannelMask); + AudioGain(int index, bool isInput); virtual ~AudioGain() {} void setMode(audio_gain_mode_t mode) { mGain.mode = mode; } @@ -80,7 +80,7 @@ public: private: int mIndex; struct audio_gain mGain; - bool mUseInChannelMask; + bool mIsInput; bool mUseForVolume = false; }; diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 2b03a83539..169698042a 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -53,7 +53,7 @@ public: AudioGains getAudioGainsForTest() { AudioGains audioGains; - sp audioGain = new AudioGain(0 /*index*/, false /*useInChannelMask*/); + sp audioGain = new AudioGain(0 /*index*/, false /*isInput*/); audioGain->setMode(AUDIO_GAIN_MODE_JOINT); audioGain->setChannelMask(AUDIO_CHANNEL_OUT_STEREO); audioGain->setMinValueInMb(-3200); -- GitLab From bbd9db7ce023dcf3e47fc677da669c1d219dd548 Mon Sep 17 00:00:00 2001 From: Edwin Date: Sun, 1 Aug 2021 23:18:56 -0700 Subject: [PATCH 077/694] Update package name change. As part of bug b/171226061 to separate DRM test classes to enable better tracking of test failures through the OWNERs files. The drm tests now reside in android.mediadrm.cts package. The following tests are moved: MediaDrmClearkeyTest, MediaDrmMetricsTest and NativeMediaDrmClearkeyTest Test: atest --test-mapping Bug: 190625926 Change-Id: Ic5778d2989a0a1583cfd36a5cc68c50ec404f7ae --- drm/mediadrm/plugins/TEST_MAPPING | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drm/mediadrm/plugins/TEST_MAPPING b/drm/mediadrm/plugins/TEST_MAPPING index 87becb6112..fd4ef95458 100644 --- a/drm/mediadrm/plugins/TEST_MAPPING +++ b/drm/mediadrm/plugins/TEST_MAPPING @@ -1,19 +1,19 @@ { "presubmit": [ { - "name": "CtsMediaTestCases", + "name": "CtsMediaDrmTestCases", "options" : [ { "include-annotation": "android.platform.test.annotations.Presubmit" }, { - "include-filter": "android.media.cts.MediaDrmClearkeyTest" + "include-filter": "android.mediadrm.cts.MediaDrmClearkeyTest" }, { - "include-filter": "android.media.cts.MediaDrmMetricsTest" + "include-filter": "android.mediadrm.cts.MediaDrmMetricsTest" }, { - "include-filter": "android.media.cts.NativeMediaDrmClearkeyTest" + "include-filter": "android.mediadrm.cts.NativeMediaDrmClearkeyTest" } ] } -- GitLab From 83f407bbac61093c597f5ed14357d6a9bd617200 Mon Sep 17 00:00:00 2001 From: Kensuke Miyagi Date: Fri, 30 Jul 2021 17:38:06 -0700 Subject: [PATCH 078/694] Fix Tuner#shareFrontendFromTuner() Bug: 195154259 Bug: 195331006 Test: android.media.tv.tuner.cts.TunerTest (all 29 tests pass) Change-Id: Ia1618b741b0d5bd2b03ef301d4950e020f9dc9fd --- services/tuner/TunerDemux.cpp | 13 +++++++++++++ services/tuner/TunerDemux.h | 1 + .../aidl/android/media/tv/tuner/ITunerDemux.aidl | 5 +++++ .../aidl/android/media/tv/tuner/ITunerService.aidl | 4 ++-- 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/services/tuner/TunerDemux.cpp b/services/tuner/TunerDemux.cpp index 1122368f6b..99032adf8a 100644 --- a/services/tuner/TunerDemux.cpp +++ b/services/tuner/TunerDemux.cpp @@ -56,6 +56,19 @@ Status TunerDemux::setFrontendDataSource(const std::shared_ptr& return Status::ok(); } +Status TunerDemux::setFrontendDataSourceById(int frontendId) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized"); + return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + } + + Result res = mDemux->setFrontendDataSource(frontendId); + if (res != Result::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return Status::ok(); +} + Status TunerDemux::openFilter( int type, int subType, int bufferSize, const std::shared_ptr& cb, std::shared_ptr* _aidl_return) { diff --git a/services/tuner/TunerDemux.h b/services/tuner/TunerDemux.h index 2a9836bfe6..c2f91f0fa9 100644 --- a/services/tuner/TunerDemux.h +++ b/services/tuner/TunerDemux.h @@ -43,6 +43,7 @@ public: TunerDemux(sp demux, int demuxId); virtual ~TunerDemux(); Status setFrontendDataSource(const shared_ptr& frontend) override; + Status setFrontendDataSourceById(int frontendId) override; Status openFilter( int mainType, int subtype, int bufferSize, const shared_ptr& cb, shared_ptr* _aidl_return) override; diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl index 73b00ae30b..b91b359eb3 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl @@ -35,6 +35,11 @@ interface ITunerDemux { */ void setFrontendDataSource(in ITunerFrontend frontend); + /** + * Set a frontend resource by ID as data input of the demux + */ + void setFrontendDataSourceById(in int frontendId); + /** * Open a new filter in the demux */ diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl index 755b152ff6..44b369c729 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl @@ -43,10 +43,10 @@ interface ITunerService { /** * Retrieve the frontend's information. * - * @param frontendHandle the handle of the frontend granted by TRM. + * @param frontendId the ID of the frontend. * @return the information of the frontend. */ - TunerFrontendInfo getFrontendInfo(in int frontendHandle); + TunerFrontendInfo getFrontendInfo(in int frontendId); /** * Get Dtmb Frontend Capabilities. -- GitLab From 810200089fbd2e30655355303cf8f768f05f38b3 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 3 Aug 2021 14:16:15 -0700 Subject: [PATCH 079/694] Update AIDL<->legacy conversion for AudioChannelLayout Index masks can contain arbitrary bits set, thus the range of valid values is not restricted to AUDIO_CHANNEL_INDEX_MASK_* values from system/audio.h. Bug: 188932434 Bug: 195346865 Test: atest audio_aidl_conversion_tests Test: atest android.media.cts.AudioNativeTest#testInputChannelMasks Change-Id: Ic09c89c996726d9be4563c9d55327bbe9a5b199d --- media/libaudioclient/AidlConversion.cpp | 64 ++++++------------- .../android/media/AudioChannelLayout.aidl | 14 ++-- .../audio_aidl_legacy_conversion_tests.cpp | 9 ++- 3 files changed, 38 insertions(+), 49 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 4c155fe653..b0eb7bdda5 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -396,44 +396,6 @@ using AudioFormatPair = std::pair using AudioFormatPairs = std::vector; } -const detail::AudioChannelPairs& getIndexAudioChannelPairs() { - static const detail::AudioChannelPairs pairs = { -#define DEFINE_INDEX_MASK(n) \ - { \ - AUDIO_CHANNEL_INDEX_MASK_##n, \ - media::AudioChannelLayout::make( \ - media::AudioChannelLayout::INDEX_MASK_##n) \ - } - - DEFINE_INDEX_MASK(1), - DEFINE_INDEX_MASK(2), - DEFINE_INDEX_MASK(3), - DEFINE_INDEX_MASK(4), - DEFINE_INDEX_MASK(5), - DEFINE_INDEX_MASK(6), - DEFINE_INDEX_MASK(7), - DEFINE_INDEX_MASK(8), - DEFINE_INDEX_MASK(9), - DEFINE_INDEX_MASK(10), - DEFINE_INDEX_MASK(11), - DEFINE_INDEX_MASK(12), - DEFINE_INDEX_MASK(13), - DEFINE_INDEX_MASK(14), - DEFINE_INDEX_MASK(15), - DEFINE_INDEX_MASK(16), - DEFINE_INDEX_MASK(17), - DEFINE_INDEX_MASK(18), - DEFINE_INDEX_MASK(19), - DEFINE_INDEX_MASK(20), - DEFINE_INDEX_MASK(21), - DEFINE_INDEX_MASK(22), - DEFINE_INDEX_MASK(23), - DEFINE_INDEX_MASK(24) -#undef DEFINE_INDEX_MASK - }; - return pairs; -} - const detail::AudioChannelPairs& getInAudioChannelPairs() { static const detail::AudioChannelPairs pairs = { #define DEFINE_INPUT_LAYOUT(n) \ @@ -1096,7 +1058,6 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan const media::AudioChannelLayout& aidl, bool isInput) { using ReverseMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; - static const ReverseMap mIdx = make_ReverseMap(getIndexAudioChannelPairs()); static const ReverseMap mIn = make_ReverseMap(getInAudioChannelPairs()); static const ReverseMap mOut = make_ReverseMap(getOutAudioChannelPairs()); static const ReverseMap mVoice = make_ReverseMap(getVoiceAudioChannelPairs()); @@ -1117,8 +1078,19 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan return AUDIO_CHANNEL_NONE; case Tag::invalid: return AUDIO_CHANNEL_INVALID; - case Tag::indexMask: - return convert(aidl, mIdx, __func__, "index"); + case Tag::indexMask: { + // Index masks do not have pre-defined values. + const int bits = aidl.get(); + if (__builtin_popcount(bits) != 0 && + __builtin_popcount(bits) <= AUDIO_CHANNEL_COUNT_MAX) { + return audio_channel_mask_from_representation_and_bits( + AUDIO_CHANNEL_REPRESENTATION_INDEX, bits); + } else { + ALOGE("%s: invalid indexMask value 0x%x in %s", + __func__, bits, aidl.toString().c_str()); + return unexpected(BAD_VALUE); + } + } case Tag::layoutMask: return convert(aidl, isInput ? mIn : mOut, __func__, isInput ? "input" : "output"); case Tag::voiceMask: @@ -1132,7 +1104,6 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud audio_channel_mask_t legacy, bool isInput) { using DirectMap = std::unordered_map; using Tag = media::AudioChannelLayout::Tag; - static const DirectMap mIdx = make_DirectMap(getIndexAudioChannelPairs()); static const DirectMap mInAndVoice = make_DirectMap( getInAudioChannelPairs(), getVoiceAudioChannelPairs()); static const DirectMap mOut = make_DirectMap(getOutAudioChannelPairs()); @@ -1156,7 +1127,14 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud const audio_channel_representation_t repr = audio_channel_mask_get_representation(legacy); if (repr == AUDIO_CHANNEL_REPRESENTATION_INDEX) { - return convert(legacy, mIdx, __func__, "index"); + if (audio_channel_mask_is_valid(legacy)) { + const int indexMask = VALUE_OR_RETURN( + convertIntegral(audio_channel_mask_get_bits(legacy))); + return media::AudioChannelLayout::make(indexMask); + } else { + ALOGE("%s: legacy audio_channel_mask_t value 0x%x is invalid", __func__, legacy); + return unexpected(BAD_VALUE); + } } else if (repr == AUDIO_CHANNEL_REPRESENTATION_POSITION) { return convert(legacy, isInput ? mInAndVoice : mOut, __func__, isInput ? "input / voice" : "output"); diff --git a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl index fdc8184f35..32591055ae 100644 --- a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl +++ b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl @@ -52,9 +52,12 @@ union AudioChannelLayout { */ int invalid = 0; /** - * This variant is used for representing indexed masks. The value - * must be one of the 'INDEX_MASK_*' constants. The 'indexMask' field - * must have at least one bit set. + * This variant is used for representing indexed masks. The mask indicates + * what channels are used. For example, the mask that specifies to use only + * channels 1 and 3 when interacting with a multi-channel device is defined + * as a combination of the 1st and the 3rd bits and thus is equal to 5. See + * also the 'INDEX_MASK_*' constants. The 'indexMask' field must have at + * least one bit set. */ int indexMask; /** @@ -71,7 +74,10 @@ union AudioChannelLayout { int voiceMask; /** - * 'INDEX_MASK_' constants define how many channels are used. + * 'INDEX_MASK_*' constants define how many channels are used. + * The mask constants below are 'canonical' masks. Each 'INDEX_MASK_N' + * constant declares that all N channels are used and arranges + * them starting from the LSB. */ const int INDEX_MASK_1 = (1 << 1) - 1; const int INDEX_MASK_2 = (1 << 2) - 1; diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index 7f8af53334..424b387f42 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -46,6 +46,11 @@ media::AudioChannelLayout make_ACL_ChannelIndex2() { media::AudioChannelLayout::INDEX_MASK_2); } +media::AudioChannelLayout make_ACL_ChannelIndexArbitrary() { + // Use channels 1 and 3. + return media::AudioChannelLayout::make(5); +} + media::AudioChannelLayout make_ACL_VoiceCall() { return media::AudioChannelLayout::make( media::AudioChannelLayout::VOICE_CALL_MONO); @@ -157,7 +162,7 @@ class HashIdentityTest : public ::testing::Test { TEST_F(HashIdentityTest, AudioChannelLayoutHashIdentity) { verifyHashIdentity({ make_ACL_None, make_ACL_Invalid, make_ACL_Stereo, make_ACL_ChannelIndex2, - make_ACL_VoiceCall}); + make_ACL_ChannelIndexArbitrary, make_ACL_VoiceCall}); } TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { @@ -188,7 +193,7 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, AudioChannelLayoutRoundTripTest, testing::Combine( testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), - make_ACL_ChannelIndex2()), + make_ACL_ChannelIndex2(), make_ACL_ChannelIndexArbitrary()), testing::Values(false, true))); INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, AudioChannelLayoutRoundTripTest, -- GitLab From dd1dbe6913768b403fc7c393dc20f4b63b2251a0 Mon Sep 17 00:00:00 2001 From: Jiyong Park Date: Wed, 4 Aug 2021 12:48:04 +0900 Subject: [PATCH 080/694] Remove ndk_platform backend. Use the ndk backend. The ndk_platform backend will soon be deprecated because the ndk backend can serve the same purpose. This is to eliminate the confusion about having two variants (ndk and ndk_platform) for the same ndk backend. Bug: 161456198 Test: m Change-Id: Id16039722fd70d4e2e934a0988f13a768ce833ec --- drm/libmediadrm/Android.bp | 2 +- drm/libmediadrm/fuzzer/Android.bp | 2 +- media/libmedia/Android.bp | 4 ++-- media/libmediaplayerservice/tests/Android.bp | 2 +- media/libmediatranscoding/Android.bp | 4 ++-- media/libmediatranscoding/tests/Android.bp | 2 +- services/mediaresourcemanager/Android.bp | 2 +- services/mediaresourcemanager/test/Android.bp | 2 +- services/mediatranscoding/Android.bp | 4 ++-- services/mediatranscoding/tests/Android.bp | 4 ++-- services/tuner/Android.bp | 10 +++++----- 11 files changed, 19 insertions(+), 19 deletions(-) diff --git a/drm/libmediadrm/Android.bp b/drm/libmediadrm/Android.bp index 0ffe626550..71df58cae8 100644 --- a/drm/libmediadrm/Android.bp +++ b/drm/libmediadrm/Android.bp @@ -66,7 +66,7 @@ cc_library { ], static_libs: [ - "resourcemanager_aidl_interface-ndk_platform", + "resourcemanager_aidl_interface-ndk", ], export_shared_lib_headers: [ diff --git a/drm/libmediadrm/fuzzer/Android.bp b/drm/libmediadrm/fuzzer/Android.bp index 7281066083..49bbad4a8a 100644 --- a/drm/libmediadrm/fuzzer/Android.bp +++ b/drm/libmediadrm/fuzzer/Android.bp @@ -35,7 +35,7 @@ cc_fuzz { static_libs: [ "libmediadrm", "liblog", - "resourcemanager_aidl_interface-ndk_platform", + "resourcemanager_aidl_interface-ndk", ], header_libs: [ "libmedia_headers", diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp index e98d7d858e..9c1b563f6e 100644 --- a/media/libmedia/Android.bp +++ b/media/libmedia/Android.bp @@ -378,12 +378,12 @@ cc_library { ], static_libs: [ - "resourcemanager_aidl_interface-ndk_platform", + "resourcemanager_aidl_interface-ndk", "framework-permission-aidl-cpp", ], export_static_lib_headers: [ - "resourcemanager_aidl_interface-ndk_platform", + "resourcemanager_aidl_interface-ndk", "framework-permission-aidl-cpp", ], diff --git a/media/libmediaplayerservice/tests/Android.bp b/media/libmediaplayerservice/tests/Android.bp index 98626fde12..99202b8fac 100644 --- a/media/libmediaplayerservice/tests/Android.bp +++ b/media/libmediaplayerservice/tests/Android.bp @@ -30,7 +30,7 @@ cc_test { ], static_libs: [ - "resourcemanager_aidl_interface-ndk_platform", + "resourcemanager_aidl_interface-ndk", ], include_dirs: [ diff --git a/media/libmediatranscoding/Android.bp b/media/libmediatranscoding/Android.bp index 042850cf62..937650f83e 100644 --- a/media/libmediatranscoding/Android.bp +++ b/media/libmediatranscoding/Android.bp @@ -106,8 +106,8 @@ cc_library { export_include_dirs: ["include"], static_libs: [ - "mediatranscoding_aidl_interface-ndk_platform", - "resourceobserver_aidl_interface-V1-ndk_platform", + "mediatranscoding_aidl_interface-ndk", + "resourceobserver_aidl_interface-V1-ndk", "libstatslog_media", ], diff --git a/media/libmediatranscoding/tests/Android.bp b/media/libmediatranscoding/tests/Android.bp index 603611af8b..7a6980fcf9 100644 --- a/media/libmediatranscoding/tests/Android.bp +++ b/media/libmediatranscoding/tests/Android.bp @@ -31,7 +31,7 @@ cc_defaults { ], static_libs: [ - "mediatranscoding_aidl_interface-ndk_platform", + "mediatranscoding_aidl_interface-ndk", "libmediatranscoding", ], diff --git a/services/mediaresourcemanager/Android.bp b/services/mediaresourcemanager/Android.bp index f31202b12f..5d80744b9d 100644 --- a/services/mediaresourcemanager/Android.bp +++ b/services/mediaresourcemanager/Android.bp @@ -90,7 +90,7 @@ cc_library { ], static_libs: [ - "resourceobserver_aidl_interface-V1-ndk_platform", + "resourceobserver_aidl_interface-V1-ndk", ], include_dirs: ["frameworks/av/include"], diff --git a/services/mediaresourcemanager/test/Android.bp b/services/mediaresourcemanager/test/Android.bp index ec4ba583c0..618626f646 100644 --- a/services/mediaresourcemanager/test/Android.bp +++ b/services/mediaresourcemanager/test/Android.bp @@ -56,7 +56,7 @@ cc_test { test_suites: ["device-tests"], static_libs: [ "libresourcemanagerservice", - "resourceobserver_aidl_interface-V1-ndk_platform", + "resourceobserver_aidl_interface-V1-ndk", ], shared_libs: [ "libbinder", diff --git a/services/mediatranscoding/Android.bp b/services/mediatranscoding/Android.bp index a9fd14f26e..fa5eb4ea7c 100644 --- a/services/mediatranscoding/Android.bp +++ b/services/mediatranscoding/Android.bp @@ -47,7 +47,7 @@ cc_library { ], static_libs: [ - "mediatranscoding_aidl_interface-ndk_platform", + "mediatranscoding_aidl_interface-ndk", ], cflags: [ @@ -80,7 +80,7 @@ cc_binary { ], static_libs: [ - "mediatranscoding_aidl_interface-ndk_platform", + "mediatranscoding_aidl_interface-ndk", ], cflags: [ diff --git a/services/mediatranscoding/tests/Android.bp b/services/mediatranscoding/tests/Android.bp index cb180ec150..ae13656c72 100644 --- a/services/mediatranscoding/tests/Android.bp +++ b/services/mediatranscoding/tests/Android.bp @@ -34,8 +34,8 @@ cc_defaults { ], static_libs: [ - "mediatranscoding_aidl_interface-ndk_platform", - "resourcemanager_aidl_interface-ndk_platform", + "mediatranscoding_aidl_interface-ndk", + "resourcemanager_aidl_interface-ndk", "libmediatranscodingservice", ], diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp index cd11c881d5..b12afde79a 100644 --- a/services/tuner/Android.bp +++ b/services/tuner/Android.bp @@ -89,13 +89,13 @@ cc_library { "liblog", "libmedia", "libutils", - "tv_tuner_aidl_interface-ndk_platform", - "tv_tuner_resource_manager_aidl_interface-ndk_platform", + "tv_tuner_aidl_interface-ndk", + "tv_tuner_resource_manager_aidl_interface-ndk", "tv_tuner_resource_manager_aidl_interface-cpp", ], static_libs: [ - "android.hardware.common.fmq-V1-ndk_platform", + "android.hardware.common.fmq-V1-ndk", "libaidlcommonsupport", ], @@ -128,12 +128,12 @@ cc_binary { "liblog", "libtunerservice", "libutils", - "tv_tuner_resource_manager_aidl_interface-ndk_platform", + "tv_tuner_resource_manager_aidl_interface-ndk", "tv_tuner_resource_manager_aidl_interface-cpp", ], static_libs: [ - "tv_tuner_aidl_interface-ndk_platform", + "tv_tuner_aidl_interface-ndk", ], init_rc: ["mediatuner.rc"], -- GitLab From e7aa034ba9e4ed14dec3623fa8b90f3c17cb2bad Mon Sep 17 00:00:00 2001 From: Shuzhen Wang Date: Tue, 3 Aug 2021 11:29:47 -0700 Subject: [PATCH 081/694] Camera: Fix onCameraOpened/onCameraClosed callback Add client package id in the CameraStatus interface, so that addListener will return the currently opened cameras if the client has the permission. Bug: 193475498 Test: testCameraManagerListenerCallbacks Change-Id: Ic78b80526c3f55a450caa54e27c3d36265b127b9 --- camera/CameraBase.cpp | 9 +++++++ camera/include/camera/CameraBase.h | 10 ++++++-- .../camera/libcameraservice/CameraService.cpp | 25 ++++++++++++++++++- .../camera/libcameraservice/CameraService.h | 7 ++++++ 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/camera/CameraBase.cpp b/camera/CameraBase.cpp index 03439fdf72..24c9108224 100644 --- a/camera/CameraBase.cpp +++ b/camera/CameraBase.cpp @@ -68,6 +68,9 @@ status_t CameraStatus::writeToParcel(android::Parcel* parcel) const { unavailablePhysicalIds16.push_back(String16(id8)); } res = parcel->writeString16Vector(unavailablePhysicalIds16); + if (res != OK) return res; + + res = parcel->writeString16(String16(clientPackage)); return res; } @@ -86,6 +89,12 @@ status_t CameraStatus::readFromParcel(const android::Parcel* parcel) { for (auto& id16 : unavailablePhysicalIds16) { unavailablePhysicalIds.push_back(String8(id16)); } + + String16 tempClientPackage; + res = parcel->readString16(&tempClientPackage); + if (res != OK) return res; + clientPackage = String8(tempClientPackage); + return res; } diff --git a/camera/include/camera/CameraBase.h b/camera/include/camera/CameraBase.h index e156994798..8e53968633 100644 --- a/camera/include/camera/CameraBase.h +++ b/camera/include/camera/CameraBase.h @@ -85,11 +85,17 @@ struct CameraStatus : public android::Parcelable { */ std::vector unavailablePhysicalIds; + /** + * Client package name if camera is open, otherwise not applicable + */ + String8 clientPackage; + virtual status_t writeToParcel(android::Parcel* parcel) const; virtual status_t readFromParcel(const android::Parcel* parcel); - CameraStatus(String8 id, int32_t s, const std::vector& unavailSubIds) : - cameraId(id), status(s), unavailablePhysicalIds(unavailSubIds) {} + CameraStatus(String8 id, int32_t s, const std::vector& unavailSubIds, + const String8& clientPkg) : cameraId(id), status(s), + unavailablePhysicalIds(unavailSubIds), clientPackage(clientPkg) {} CameraStatus() : status(ICameraServiceListener::STATUS_PRESENT) {} }; diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp index cc01ab2779..c42dbc0120 100644 --- a/services/camera/libcameraservice/CameraService.cpp +++ b/services/camera/libcameraservice/CameraService.cpp @@ -2375,7 +2375,8 @@ Status CameraService::addListenerHelper(const sp& listen Mutex::Autolock lock(mCameraStatesLock); for (auto& i : mCameraStates) { cameraStatuses->emplace_back(i.first, - mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds()); + mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(), + openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty()); } } // Remove the camera statuses that should be hidden from the client, we do @@ -3721,6 +3722,16 @@ bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& phys return count > 0; } +void CameraService::CameraState::setClientPackage(const String8& clientPackage) { + Mutex::Autolock lock(mStatusLock); + mClientPackage = clientPackage; +} + +String8 CameraService::CameraState::getClientPackage() const { + Mutex::Autolock lock(mStatusLock); + return mClientPackage; +} + // ---------------------------------------------------------------------------- // ClientEventListener // ---------------------------------------------------------------------------- @@ -4284,6 +4295,18 @@ void CameraService::updateStatus(StatusInternal status, const String8& cameraId, void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open, const String16& clientPackageName) { + auto state = getCameraState(cameraId); + if (state == nullptr) { + ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__, + cameraId.string()); + return; + } + if (open) { + state->setClientPackage(String8(clientPackageName)); + } else { + state->setClientPackage(String8::empty()); + } + Mutex::Autolock lock(mStatusListenerLock); for (const auto& it : mListenerList) { diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h index ca184a8694..c6a9019909 100644 --- a/services/camera/libcameraservice/CameraService.h +++ b/services/camera/libcameraservice/CameraService.h @@ -631,6 +631,12 @@ private: bool addUnavailablePhysicalId(const String8& physicalId); bool removeUnavailablePhysicalId(const String8& physicalId); + /** + * Set and get client package name. + */ + void setClientPackage(const String8& clientPackage); + String8 getClientPackage() const; + /** * Return the unavailable physical ids for this device. * @@ -643,6 +649,7 @@ private: const int mCost; std::set mConflicting; std::set mUnavailablePhysicalIds; + String8 mClientPackage; mutable Mutex mStatusLock; CameraParameters mShimParams; const SystemCameraKind mSystemCameraKind; -- GitLab From d94fa7406b60e7b02fdf679b3db8d1be998e0740 Mon Sep 17 00:00:00 2001 From: Hongguang Date: Mon, 26 Jul 2021 19:00:18 -0700 Subject: [PATCH 082/694] Use Tuner AIDL HAL data structures in the TunerService. After moving to AIDL HAL, the HAL data structures can be used in TunerService directly, we don't need to define them twice. Bug: 191825295 Test: atest android.media.tv.tuner.cts Change-Id: I0e2c7e950cae11bcfa1792c93b06ed28f4152628 --- services/tuner/Android.bp | 51 +---- services/tuner/aidl/android/media/tv/OWNERS | 2 +- .../android/media/tv/tuner/ITunerDemux.aidl | 8 +- .../media/tv/tuner/ITunerDescrambler.aidl | 6 +- .../android/media/tv/tuner/ITunerDvr.aidl | 4 +- .../media/tv/tuner/ITunerDvrCallback.aidl | 7 +- .../android/media/tv/tuner/ITunerFilter.aidl | 13 +- .../media/tv/tuner/ITunerFilterCallback.aidl | 7 +- .../media/tv/tuner/ITunerFrontend.aidl | 19 +- .../tv/tuner/ITunerFrontendCallback.aidl | 13 +- .../android/media/tv/tuner/ITunerLnb.aidl | 9 +- .../media/tv/tuner/ITunerLnbCallback.aidl | 4 +- .../android/media/tv/tuner/ITunerService.aidl | 21 +- .../tv/tuner/TunerAudioExtraMetaData.aidl | 36 ---- .../tv/tuner/TunerDemuxCapabilities.aidl | 50 ----- .../media/tv/tuner/TunerDemuxIpAddress.aidl | 28 --- .../tv/tuner/TunerDemuxIpAddressSettings.aidl | 34 ---- .../android/media/tv/tuner/TunerDemuxPid.aidl | 28 --- .../media/tv/tuner/TunerDvrSettings.aidl | 34 ---- .../tv/tuner/TunerFilterAlpConfiguration.aidl | 32 --- .../media/tv/tuner/TunerFilterAvSettings.aidl | 29 --- .../tv/tuner/TunerFilterConfiguration.aidl | 40 ---- .../tv/tuner/TunerFilterDownloadEvent.aidl | 40 ---- .../tv/tuner/TunerFilterDownloadSettings.aidl | 26 --- .../media/tv/tuner/TunerFilterEvent.aidl | 54 ----- .../tv/tuner/TunerFilterIpConfiguration.aidl | 31 --- .../tv/tuner/TunerFilterIpPayloadEvent.aidl | 29 --- .../media/tv/tuner/TunerFilterMediaEvent.aidl | 84 -------- .../tuner/TunerFilterMmtpConfiguration.aidl | 30 --- .../tv/tuner/TunerFilterMmtpRecordEvent.aidl | 57 ------ .../tv/tuner/TunerFilterMonitorEvent.aidl | 34 ---- .../tv/tuner/TunerFilterPesDataSettings.aidl | 28 --- .../media/tv/tuner/TunerFilterPesEvent.aidl | 36 ---- .../tv/tuner/TunerFilterRecordSettings.aidl | 32 --- .../tv/tuner/TunerFilterScIndexMask.aidl | 28 --- .../tv/tuner/TunerFilterSectionBits.aidl | 30 --- .../tv/tuner/TunerFilterSectionCondition.aidl | 31 --- .../tv/tuner/TunerFilterSectionEvent.aidl | 44 ----- .../tv/tuner/TunerFilterSectionSettings.aidl | 34 ---- .../tv/tuner/TunerFilterSectionTableInfo.aidl | 28 --- .../media/tv/tuner/TunerFilterSettings.aidl | 44 ----- .../tv/tuner/TunerFilterSharedHandleInfo.aidl | 29 --- .../media/tv/tuner/TunerFilterTemiEvent.aidl | 40 ---- .../tv/tuner/TunerFilterTlvConfiguration.aidl | 32 --- .../tv/tuner/TunerFilterTsConfiguration.aidl | 30 --- .../tv/tuner/TunerFilterTsRecordEvent.aidl | 56 ------ .../TunerFrontendAnalogCapabilities.aidl | 34 ---- .../tv/tuner/TunerFrontendAnalogSettings.aidl | 43 ---- .../tuner/TunerFrontendAtsc3Capabilities.aidl | 54 ----- .../tuner/TunerFrontendAtsc3PlpSettings.aidl | 37 ---- .../tv/tuner/TunerFrontendAtsc3Settings.aidl | 40 ---- .../tuner/TunerFrontendAtscCapabilities.aidl | 29 --- .../tv/tuner/TunerFrontendAtscSettings.aidl | 31 --- .../tuner/TunerFrontendCableCapabilities.aidl | 39 ---- .../tv/tuner/TunerFrontendCableSettings.aidl | 63 ------ .../tv/tuner/TunerFrontendCapabilities.aidl | 85 -------- .../tuner/TunerFrontendDtmbCapabilities.aidl | 36 ---- .../tv/tuner/TunerFrontendDtmbSettings.aidl | 38 ---- .../tuner/TunerFrontendDvbsCapabilities.aidl | 39 ---- .../tv/tuner/TunerFrontendDvbsCodeRate.aidl | 42 ---- .../tv/tuner/TunerFrontendDvbsSettings.aidl | 65 ------ .../tuner/TunerFrontendDvbtCapabilities.aidl | 64 ------ .../tv/tuner/TunerFrontendDvbtSettings.aidl | 75 ------- .../media/tv/tuner/TunerFrontendInfo.aidl | 80 -------- .../TunerFrontendIsdbs3Capabilities.aidl | 34 ---- .../tv/tuner/TunerFrontendIsdbs3Settings.aidl | 44 ----- .../tuner/TunerFrontendIsdbsCapabilities.aidl | 34 ---- .../tv/tuner/TunerFrontendIsdbsSettings.aidl | 44 ----- .../tuner/TunerFrontendIsdbtCapabilities.aidl | 49 ----- .../tv/tuner/TunerFrontendIsdbtSettings.aidl | 41 ---- .../tuner/TunerFrontendScanAtsc3PlpInfo.aidl | 28 --- .../tv/tuner/TunerFrontendScanMessage.aidl | 56 ------ .../media/tv/tuner/TunerFrontendSettings.aidl | 34 ---- .../media/tv/tuner/TunerFrontendStatus.aidl | 187 ------------------ .../TunerFrontendStatusAtsc3PlpInfo.aidl | 39 ---- .../tv/tuner/TunerFrontendUnionSettings.aidl | 55 ------ 76 files changed, 62 insertions(+), 2859 deletions(-) delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerAudioExtraMetaData.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddress.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddressSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerDvrSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterAlpConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterAvSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterIpConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterIpPayloadEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterMediaEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpRecordEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterMonitorEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterPesDataSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterPesEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterRecordSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterScIndexMask.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionBits.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionCondition.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionTableInfo.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterTemiEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterTlvConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterTsConfiguration.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFilterTsRecordEvent.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Capabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3PlpSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Settings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCodeRate.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendInfo.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Capabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Settings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtCapabilities.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanMessage.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl delete mode 100644 services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp index b12afde79a..8a1d45c460 100644 --- a/services/tuner/Android.bp +++ b/services/tuner/Android.bp @@ -7,33 +7,15 @@ package { default_applicable_licenses: ["frameworks_av_license"], } -filegroup { - name: "tv_tuner_aidl", - srcs: [ - "aidl/android/media/tv/tuner/*.aidl", - ], - path: "aidl", -} - -filegroup { - name: "tv_tuner_frontend_info", - srcs: [ - "aidl/android/media/tv/tuner/TunerFrontendInfo.aidl", - "aidl/android/media/tv/tuner/TunerFrontend*Capabilities.aidl", - ], - path: "aidl", -} - aidl_interface { name: "tv_tuner_aidl_interface", unstable: true, local_include_dir: "aidl", - srcs: [ - ":tv_tuner_aidl", - ], + srcs: ["aidl/android/media/tv/tuner/*.aidl"], imports: [ "android.hardware.common-V2", "android.hardware.common.fmq-V1", + "android.hardware.tv.tuner-V1", ], backend: { @@ -49,27 +31,6 @@ aidl_interface { }, } -aidl_interface { - name: "tv_tuner_frontend_info_aidl_interface", - unstable: true, - local_include_dir: "aidl", - srcs: [ - ":tv_tuner_frontend_info", - ], - - backend: { - java: { - enabled: true, - }, - cpp: { - enabled: true, - }, - ndk: { - enabled: true, - }, - }, -} - cc_library { name: "libtunerservice", @@ -78,8 +39,7 @@ cc_library { ], shared_libs: [ - "android.hardware.tv.tuner@1.0", - "android.hardware.tv.tuner@1.1", + "android.hardware.tv.tuner-V1-ndk", "libbase", "libbinder", "libbinder_ndk", @@ -91,7 +51,6 @@ cc_library { "libutils", "tv_tuner_aidl_interface-ndk", "tv_tuner_resource_manager_aidl_interface-ndk", - "tv_tuner_resource_manager_aidl_interface-cpp", ], static_libs: [ @@ -120,8 +79,7 @@ cc_binary { ], shared_libs: [ - "android.hardware.tv.tuner@1.0", - "android.hardware.tv.tuner@1.1", + "android.hardware.tv.tuner-V1-ndk", "libbase", "libbinder", "libfmq", @@ -129,7 +87,6 @@ cc_binary { "libtunerservice", "libutils", "tv_tuner_resource_manager_aidl_interface-ndk", - "tv_tuner_resource_manager_aidl_interface-cpp", ], static_libs: [ diff --git a/services/tuner/aidl/android/media/tv/OWNERS b/services/tuner/aidl/android/media/tv/OWNERS index 0ceb8e86df..bf9fe3408d 100644 --- a/services/tuner/aidl/android/media/tv/OWNERS +++ b/services/tuner/aidl/android/media/tv/OWNERS @@ -1,2 +1,2 @@ -nchalko@google.com +hgchen@google.com quxiangfang@google.com diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl index b91b359eb3..fa326b2e4c 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDemux.aidl @@ -16,6 +16,8 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.DemuxFilterType; +import android.hardware.tv.tuner.DvrType; import android.media.tv.tuner.ITunerDvr; import android.media.tv.tuner.ITunerDvrCallback; import android.media.tv.tuner.ITunerFilter; @@ -43,8 +45,8 @@ interface ITunerDemux { /** * Open a new filter in the demux */ - ITunerFilter openFilter( - in int mainType, in int subtype, in int bufferSize, in ITunerFilterCallback cb); + ITunerFilter openFilter(in DemuxFilterType type, in int bufferSize, + in ITunerFilterCallback cb); /** * Open time filter of the demux. @@ -64,7 +66,7 @@ interface ITunerDemux { /** * Open a DVR (Digital Video Record) instance in the demux. */ - ITunerDvr openDvr(in int dvbType, in int bufferSize, in ITunerDvrCallback cb); + ITunerDvr openDvr(in DvrType dvbType, in int bufferSize, in ITunerDvrCallback cb); /** * Connect Conditional Access Modules (CAM) through Common Interface (CI). diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl index 7370eee736..39d193ce9c 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDescrambler.aidl @@ -16,9 +16,9 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.DemuxPid; import android.media.tv.tuner.ITunerDemux; import android.media.tv.tuner.ITunerFilter; -import android.media.tv.tuner.TunerDemuxPid; /** * Tuner Demux interface handles tuner related operations. @@ -39,12 +39,12 @@ interface ITunerDescrambler { /** * Add packets' PID to the descrambler for descrambling. */ - void addPid(in TunerDemuxPid pid, in ITunerFilter optionalSourceFilter); + void addPid(in DemuxPid pid, in ITunerFilter optionalSourceFilter); /** * Remove packets' PID from the descrambler. */ - void removePid(in TunerDemuxPid pid, in ITunerFilter optionalSourceFilter); + void removePid(in DemuxPid pid, in ITunerFilter optionalSourceFilter); /** * Close a new interface of ITunerDescrambler. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDvr.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDvr.aidl index 8f1601b556..2c01c4ea11 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDvr.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDvr.aidl @@ -18,8 +18,8 @@ package android.media.tv.tuner; import android.hardware.common.fmq.MQDescriptor; import android.hardware.common.fmq.SynchronizedReadWrite; +import android.hardware.tv.tuner.DvrSettings; import android.media.tv.tuner.ITunerFilter; -import android.media.tv.tuner.TunerDvrSettings; /** * Tuner Dvr interface handles tuner related operations. @@ -35,7 +35,7 @@ interface ITunerDvr { /** * Configure the DVR. */ - void configure(in TunerDvrSettings settings); + void configure(in DvrSettings settings); /** * Attach one filter to DVR interface for recording. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerDvrCallback.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerDvrCallback.aidl index e234fe5652..3043d248e7 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerDvrCallback.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerDvrCallback.aidl @@ -16,6 +16,9 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.PlaybackStatus; +import android.hardware.tv.tuner.RecordStatus; + /** * TunerDvrCallback interface handles tuner dvr related callbacks. * @@ -25,10 +28,10 @@ interface ITunerDvrCallback { /** * Notify the client a new status of the demux's record. */ - void onRecordStatus(in int status); + void onRecordStatus(in RecordStatus status); /** * Notify the client a new status of the demux's playback. */ - void onPlaybackStatus(in int status); + void onPlaybackStatus(in PlaybackStatus status); } diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl index 10d4c3b65a..b043fb45f7 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFilter.aidl @@ -19,8 +19,9 @@ package android.media.tv.tuner; import android.hardware.common.fmq.MQDescriptor; import android.hardware.common.fmq.SynchronizedReadWrite; import android.hardware.common.NativeHandle; -import android.media.tv.tuner.TunerFilterConfiguration; -import android.media.tv.tuner.TunerFilterSharedHandleInfo; +import android.hardware.tv.tuner.DemuxFilterSettings; +import android.hardware.tv.tuner.AvStreamType; +import android.hardware.tv.tuner.DemuxFilterMonitorEventType; /** * Tuner Filter interface handles tuner related operations. @@ -46,12 +47,12 @@ interface ITunerFilter { /** * Configure the filter. */ - void configure(in TunerFilterConfiguration config); + void configure(in DemuxFilterSettings settings); /** * Configure the monitor event of the Filter. */ - void configureMonitorEvent(in int monitorEventType); + void configureMonitorEvent(in int monitorEventTypes); /** * Configure the context id of the IP Filter. @@ -61,12 +62,12 @@ interface ITunerFilter { /** * Configure the stream type of the media Filter. */ - void configureAvStreamType(in int avStreamType); + void configureAvStreamType(in AvStreamType avStreamType); /** * Get the a/v shared memory handle */ - TunerFilterSharedHandleInfo getAvSharedHandleInfo(); + long getAvSharedHandle(out NativeHandle avMemory); /** * Release the handle reported by the HAL for AV memory. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl index e7a52a7cd7..6c5304243f 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFilterCallback.aidl @@ -16,7 +16,8 @@ package android.media.tv.tuner; -import android.media.tv.tuner.TunerFilterEvent; +import android.hardware.tv.tuner.DemuxFilterEvent; +import android.hardware.tv.tuner.DemuxFilterStatus; /** * TunerFilterCallback interface handles tuner filter related callbacks. @@ -27,10 +28,10 @@ interface ITunerFilterCallback { /** * Notify the client a new status of a filter. */ - void onFilterStatus(int status); + void onFilterStatus(in DemuxFilterStatus status); /** * Notify the client that a new filter event happened. */ - void onFilterEvent(in TunerFilterEvent[] filterEvent); + void onFilterEvent(in DemuxFilterEvent[] events); } diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl index ef0255acfd..771a6474e4 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontend.aidl @@ -1,5 +1,5 @@ /** - * Copyright 2020, The Android Open Source Project + * Copyright 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,12 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.FrontendScanType; +import android.hardware.tv.tuner.FrontendSettings; +import android.hardware.tv.tuner.FrontendStatus; +import android.hardware.tv.tuner.FrontendStatusType; import android.media.tv.tuner.ITunerFrontendCallback; import android.media.tv.tuner.ITunerLnb; -import android.media.tv.tuner.TunerFrontendSettings; -import android.media.tv.tuner.TunerFrontendStatus; /** * Tuner Frontend interface handles frontend related operations. @@ -39,7 +41,7 @@ interface ITunerFrontend { * * @param settings the settings to tune with. */ - void tune(in TunerFrontendSettings settings); + void tune(in FrontendSettings settings); /** * Stop the previous tuning. @@ -52,7 +54,7 @@ interface ITunerFrontend { * @param settings the settings to scan with. * @param frontendScanType scan with given type. */ - void scan(in TunerFrontendSettings settings, in int frontendScanType); + void scan(in FrontendSettings settings, in FrontendScanType frontendScanType); /** * Stop the previous scanning. @@ -93,12 +95,7 @@ interface ITunerFrontend { /** * Gets the statuses of the frontend. */ - TunerFrontendStatus[] getStatus(in int[] statusTypes); - - /** - * Gets the 1.1 extended statuses of the frontend. - */ - TunerFrontendStatus[] getStatusExtended_1_1(in int[] statusTypes); + FrontendStatus[] getStatus(in FrontendStatusType[] statusTypes); /** * Gets the id of the frontend. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontendCallback.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontendCallback.aidl index c92f5ee6c8..d0ab11d54b 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerFrontendCallback.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerFrontendCallback.aidl @@ -1,5 +1,5 @@ /** - * Copyright 2020, The Android Open Source Project + * Copyright 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ package android.media.tv.tuner; -import android.media.tv.tuner.TunerFrontendScanMessage; +import android.hardware.tv.tuner.FrontendEventType; +import android.hardware.tv.tuner.FrontendScanMessage; +import android.hardware.tv.tuner.FrontendScanMessageType; /** * TunerFrontendCallback interface handles tuner frontend related callbacks. @@ -24,13 +26,14 @@ import android.media.tv.tuner.TunerFrontendScanMessage; * {@hide} */ interface ITunerFrontendCallback { - /** + /** * Notify the client that a new event happened on the frontend. */ - void onEvent(in int frontendEventType); + void onEvent(in FrontendEventType frontendEventType); /** * notify the client of scan messages. */ - void onScanMessage(in int messageType, in TunerFrontendScanMessage message); + void onScanMessage(in FrontendScanMessageType messageType, + in FrontendScanMessage message); } diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerLnb.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerLnb.aidl index d62145e627..79f0761a34 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerLnb.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerLnb.aidl @@ -16,6 +16,9 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.LnbPosition; +import android.hardware.tv.tuner.LnbTone; +import android.hardware.tv.tuner.LnbVoltage; import android.media.tv.tuner.ITunerLnbCallback; /** @@ -32,17 +35,17 @@ interface ITunerLnb { /** * Set the lnb's power voltage. */ - void setVoltage(in int voltage); + void setVoltage(in LnbVoltage voltage); /** * Set the lnb's tone mode. */ - void setTone(in int tone); + void setTone(in LnbTone tone); /** * Select the lnb's position. */ - void setSatellitePosition(in int position); + void setSatellitePosition(in LnbPosition position); /** * Sends DiSEqC (Digital Satellite Equipment Control) message. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerLnbCallback.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerLnbCallback.aidl index 117352f96b..2b6eb5f555 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerLnbCallback.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerLnbCallback.aidl @@ -16,6 +16,8 @@ package android.media.tv.tuner; +import android.hardware.tv.tuner.LnbEventType; + /** * TuneLnbCallback interface handles tuner lnb related callbacks. * @@ -25,7 +27,7 @@ interface ITunerLnbCallback { /** * Notify the client that a new event happened on the Lnb. */ - void onEvent(in int lnbEventType); + void onEvent(in LnbEventType lnbEventType); /** * notify the client of new DiSEqC message. diff --git a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl index 44b369c729..c5733a58d8 100644 --- a/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl +++ b/services/tuner/aidl/android/media/tv/tuner/ITunerService.aidl @@ -1,5 +1,5 @@ /** - * Copyright (c) 2020, The Android Open Source Project + * Copyright (c) 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,12 @@ package android.media.tv.tuner; -import android.hardware.common.fmq.MQDescriptor; -import android.hardware.common.fmq.SynchronizedReadWrite; -import android.hardware.common.fmq.UnsynchronizedWrite; +import android.hardware.tv.tuner.DemuxCapabilities; +import android.hardware.tv.tuner.FrontendInfo; import android.media.tv.tuner.ITunerDemux; import android.media.tv.tuner.ITunerDescrambler; import android.media.tv.tuner.ITunerFrontend; import android.media.tv.tuner.ITunerLnb; -import android.media.tv.tuner.TunerDemuxCapabilities; -import android.media.tv.tuner.TunerFrontendDtmbCapabilities; -import android.media.tv.tuner.TunerFrontendInfo; /** * TunerService interface handles tuner related operations. @@ -33,8 +29,8 @@ import android.media.tv.tuner.TunerFrontendInfo; * {@hide} */ //@VintfStability +@SuppressWarnings(value={"out-array"}) interface ITunerService { - /** * Gets frontend IDs. */ @@ -46,12 +42,7 @@ interface ITunerService { * @param frontendId the ID of the frontend. * @return the information of the frontend. */ - TunerFrontendInfo getFrontendInfo(in int frontendId); - - /** - * Get Dtmb Frontend Capabilities. - */ - TunerFrontendDtmbCapabilities getFrontendDtmbCapabilities(in int id); + FrontendInfo getFrontendInfo(in int frontendId); /** * Open a Tuner Frontend interface. @@ -87,7 +78,7 @@ interface ITunerService { * * @return the demux’s capabilities. */ - TunerDemuxCapabilities getDemuxCaps(); + DemuxCapabilities getDemuxCaps(); /* Open a new interface of ITunerDescrambler given a descramblerHandle. * diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerAudioExtraMetaData.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerAudioExtraMetaData.aidl deleted file mode 100644 index df3374a777..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerAudioExtraMetaData.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Extra Meta Data from AD (Audio Descriptor) according to ETSI TS 101 154 V2.1.1. - * - * {@hide} - */ -parcelable TunerAudioExtraMetaData { - byte adFade; - - byte adPan; - - byte versionTextTag; - - byte adGainCenter; - - byte adGainFront; - - byte adGainSurround; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl deleted file mode 100644 index 71ab151879..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxCapabilities.aidl +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Tuner Demux capabilities interface. - * - * {@hide} - */ -parcelable TunerDemuxCapabilities { - int numDemux; - - int numRecord; - - int numPlayback; - - int numTsFilter; - - int numSectionFilter; - - int numAudioFilter; - - int numVideoFilter; - - int numPesFilter; - - int numPcrFilter; - - int numBytesInSectionFilter; - - int filterCaps; - - int[] linkCaps; - - boolean bTimeFilter; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddress.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddress.aidl deleted file mode 100644 index b65f404f0c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddress.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Demux ip address configure. - * - * {@hide} - */ -parcelable TunerDemuxIpAddress { - boolean isIpV6; - - byte[] addr; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddressSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddressSettings.aidl deleted file mode 100644 index b2443888ff..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxIpAddressSettings.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerDemuxIpAddress; - -/** - * Filter Settings for an Ip filter. - * - * {@hide} - */ -parcelable TunerDemuxIpAddressSettings { - TunerDemuxIpAddress srcIpAddress; - - TunerDemuxIpAddress dstIpAddress; - - char srcPort; - - char dstPort; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl deleted file mode 100644 index 8b238b6b95..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerDemuxPid.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Demux PID interface. - * - * {@hide} - */ -union TunerDemuxPid { - char tPid; - - char mmtpPid; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerDvrSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerDvrSettings.aidl deleted file mode 100644 index 4ec4d75791..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerDvrSettings.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Dvr Settings interface. - * - * {@hide} - */ -parcelable TunerDvrSettings { - int statusMask; - - int lowThreshold; - - int highThreshold; - - int dataFormat; - - int packetSize; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterAlpConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterAlpConfiguration.aidl deleted file mode 100644 index 4c9e3afb13..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterAlpConfiguration.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSettings; - -/** - * Filter Settings for an ALP filter. - * - * {@hide} - */ -parcelable TunerFilterAlpConfiguration { - byte packetType; - - byte lengthType; - - TunerFilterSettings filterSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterAvSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterAvSettings.aidl deleted file mode 100644 index 6bf88f0e2b..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterAvSettings.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Settings for a Video and Audio. - * - * {@hide} - */ -parcelable TunerFilterAvSettings { - /** - * true if the filter output goes to decoder directly in pass through mode. - */ - boolean isPassthrough; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterConfiguration.aidl deleted file mode 100644 index 808cfd1b76..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterConfiguration.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterAlpConfiguration; -import android.media.tv.tuner.TunerFilterIpConfiguration; -import android.media.tv.tuner.TunerFilterMmtpConfiguration; -import android.media.tv.tuner.TunerFilterTlvConfiguration; -import android.media.tv.tuner.TunerFilterTsConfiguration; - -/** - * Filter configuration. - * - * {@hide} - */ -union TunerFilterConfiguration { - TunerFilterTsConfiguration ts; - - TunerFilterMmtpConfiguration mmtp; - - TunerFilterIpConfiguration ip; - - TunerFilterTlvConfiguration tlv; - - TunerFilterAlpConfiguration alp; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadEvent.aidl deleted file mode 100644 index b971dd35ac..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadEvent.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for Download data. - * - * {@hide} - */ -parcelable TunerFilterDownloadEvent { - int itemId; - - /** - * MPU sequence number of filtered data (only for MMTP) - */ - int mpuSequenceNumber; - - int itemFragmentIndex; - - int lastItemFragmentIndex; - - /** - * Data size in bytes of filtered data - */ - char dataLength; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadSettings.aidl deleted file mode 100644 index 417a5fe104..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterDownloadSettings.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Settings for downloading. - * - * {@hide} - */ -parcelable TunerFilterDownloadSettings { - int downloadId; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterEvent.aidl deleted file mode 100644 index 130551067e..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterEvent.aidl +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterDownloadEvent; -import android.media.tv.tuner.TunerFilterIpPayloadEvent; -import android.media.tv.tuner.TunerFilterMediaEvent; -import android.media.tv.tuner.TunerFilterMmtpRecordEvent; -import android.media.tv.tuner.TunerFilterMonitorEvent; -import android.media.tv.tuner.TunerFilterPesEvent; -import android.media.tv.tuner.TunerFilterSectionEvent; -import android.media.tv.tuner.TunerFilterTemiEvent; -import android.media.tv.tuner.TunerFilterTsRecordEvent; - -/** - * Filter events. - * - * {@hide} - */ -union TunerFilterEvent { - TunerFilterMediaEvent media; - - TunerFilterSectionEvent section; - - TunerFilterPesEvent pes; - - TunerFilterTsRecordEvent tsRecord; - - TunerFilterMmtpRecordEvent mmtpRecord; - - TunerFilterDownloadEvent download; - - TunerFilterIpPayloadEvent ipPayload; - - TunerFilterTemiEvent temi; - - TunerFilterMonitorEvent monitor; - - int startId; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpConfiguration.aidl deleted file mode 100644 index 8b4d889d9c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpConfiguration.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerDemuxIpAddressSettings; -import android.media.tv.tuner.TunerFilterSettings; - -/** - * Filter Settings for a ip filter. - * - * {@hide} - */ -parcelable TunerFilterIpConfiguration { - TunerDemuxIpAddressSettings ipAddr; - - TunerFilterSettings filterSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpPayloadEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpPayloadEvent.aidl deleted file mode 100644 index d5bda93c65..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterIpPayloadEvent.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for IP payload data. - * - * {@hide} - */ -parcelable TunerFilterIpPayloadEvent { - /** - * Data size in bytes of ip data - */ - char dataLength; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMediaEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterMediaEvent.aidl deleted file mode 100644 index c3dbce9b5f..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMediaEvent.aidl +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.hardware.common.NativeHandle; -import android.media.tv.tuner.TunerAudioExtraMetaData; - -/** - * Filter Event for Audio or Video Filter. - * - * {@hide} - */ -parcelable TunerFilterMediaEvent { - char streamId; - - /** - * true if PTS is present in PES header. - */ - boolean isPtsPresent; - - /** - * Presentation Time Stamp for audio or video frame. It based on 90KHz has - * the same format as PTS (Presentation Time Stamp). - */ - long pts; - - /** - * Data size in bytes of audio or video frame - */ - int dataLength; - - /** - * The offset in the memory block which is shared among multiple - * MediaEvents. - */ - int offset; - - /** - * A handle associated to the memory where audio or video data stays. - */ - NativeHandle avMemory; - - /** - * True if the avMemory is in secure area, and isn't mappable. - */ - boolean isSecureMemory; - - /** - * An Id is used by HAL to provide additional information for AV data. - * For secure audio, it's the audio handle used by Audio Track. - */ - long avDataId; - - /** - * MPU sequence number of filtered data (only for MMTP) - */ - int mpuSequenceNumber; - - boolean isPesPrivateData; - - /** - * If TunerAudioExtraMetaData field is valid or not - */ - boolean isAudioExtraMetaData; - - /** - * Only valid when isAudioExtraMetaData is true - */ - TunerAudioExtraMetaData audio; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpConfiguration.aidl deleted file mode 100644 index 162ca8ee3e..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpConfiguration.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSettings; - -/** - * Filter Settings for an mmtp filter. - * - * {@hide} - */ -parcelable TunerFilterMmtpConfiguration { - char mmtpPid; - - TunerFilterSettings filterSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpRecordEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpRecordEvent.aidl deleted file mode 100644 index b8871cf546..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMmtpRecordEvent.aidl +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for an MMTP Record Filter. - * - * {@hide} - */ -parcelable TunerFilterMmtpRecordEvent { - int scHevcIndexMask; - - /** - * Byte number from beginning of the filter's output - */ - long byteNumber; - - /** - * If the current event contains extended information or not - */ - boolean isExtended; - - /** - * The Presentation Time Stamp(PTS) for the audio or video frame. It is based on 90KHz - * and has the same format as the PTS in ISO/IEC 13818-1. - */ - long pts; - - /** - * MPU sequence number of the filtered data. This is only used for MMTP. - */ - int mpuSequenceNumber; - - /** - * Specifies the address of the first macroblock in the slice defined in ITU-T Rec. H.264. - */ - int firstMbInSlice; - - /** - * TS index mask. - */ - int tsIndexMask; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMonitorEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterMonitorEvent.aidl deleted file mode 100644 index 31ab5e68cb..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterMonitorEvent.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter monitor events. - * - * {@hide} - */ -union TunerFilterMonitorEvent { - /** - * New scrambling status. - */ - int scramblingStatus; - - /** - * New cid for the IP filter. - */ - int cid; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesDataSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesDataSettings.aidl deleted file mode 100644 index 312f314d71..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesDataSettings.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Settings for Pes Data. - * - * {@hide} - */ -parcelable TunerFilterPesDataSettings { - char streamId; - - boolean isRaw; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesEvent.aidl deleted file mode 100644 index dc1ecc610c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterPesEvent.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for PES Filter. - * - * {@hide} - */ -parcelable TunerFilterPesEvent { - char streamId; - - /** - * Data size in bytes of PES data - */ - char dataLength; - - /** - * MPU sequence number of filtered data - */ - int mpuSequenceNumber; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterRecordSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterRecordSettings.aidl deleted file mode 100644 index 29be6245d7..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterRecordSettings.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterScIndexMask; - -/** - * Filter Settings for recording. - * - * {@hide} - */ -parcelable TunerFilterRecordSettings { - int tsIndexMask; - - int scIndexType; - - TunerFilterScIndexMask scIndexMask; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterScIndexMask.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterScIndexMask.aidl deleted file mode 100644 index ed37fcef93..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterScIndexMask.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter SC Index Mask - * - * {@hide} - */ -union TunerFilterScIndexMask { - int sc; - - int scHevc; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionBits.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionBits.aidl deleted file mode 100644 index dd4f84299b..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionBits.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Bits settings of a section Filter. - * - * {@hide} - */ -parcelable TunerFilterSectionBits { - byte[] filter; - - byte[] mask; - - byte[] mode; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionCondition.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionCondition.aidl deleted file mode 100644 index 00aabe44a5..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionCondition.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSectionBits; -import android.media.tv.tuner.TunerFilterSectionTableInfo; - -/** - * Section filter condition settings. - * - * {@hide} - */ -union TunerFilterSectionCondition { - TunerFilterSectionBits sectionBits; - - TunerFilterSectionTableInfo tableInfo; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionEvent.aidl deleted file mode 100644 index 5f20926148..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionEvent.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for Section Filter. - * - * {@hide} - */ -parcelable TunerFilterSectionEvent { - /** - * Table ID of filtered data - */ - char tableId; - - /** - * Version number of filtered data - */ - char version; - - /** - * Section number of filtered data - */ - char sectionNum; - - /** - * Data size in bytes of filtered data - */ - char dataLength; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionSettings.aidl deleted file mode 100644 index 22129b615a..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionSettings.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSectionCondition; - -/** - * Filter Settings for a section filter. - * - * {@hide} - */ -parcelable TunerFilterSectionSettings { - TunerFilterSectionCondition condition; - - boolean isCheckCrc; - - boolean isRepeat; - - boolean isRaw; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionTableInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionTableInfo.aidl deleted file mode 100644 index cc78c9d356..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSectionTableInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Table info settings of a section Filter. - * - * {@hide} - */ -parcelable TunerFilterSectionTableInfo { - char tableId; - - char version; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSettings.aidl deleted file mode 100644 index eb7eaa598c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSettings.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterAvSettings; -import android.media.tv.tuner.TunerFilterDownloadSettings; -import android.media.tv.tuner.TunerFilterPesDataSettings; -import android.media.tv.tuner.TunerFilterRecordSettings; -import android.media.tv.tuner.TunerFilterSectionSettings; - -/** - * Filter Settings. - * - * {@hide} - */ -union TunerFilterSettings { - boolean nothing; - - TunerFilterAvSettings av; - - TunerFilterSectionSettings section; - - TunerFilterPesDataSettings pesData; - - TunerFilterRecordSettings record; - - TunerFilterDownloadSettings download; - - boolean isPassthrough; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl deleted file mode 100644 index 122dfc35ef..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterSharedHandleInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.hardware.common.NativeHandle; - -/** - * Filter Shared Handle Information. - * - * {@hide} - */ -parcelable TunerFilterSharedHandleInfo { - NativeHandle handle; - long size; -} \ No newline at end of file diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTemiEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterTemiEvent.aidl deleted file mode 100644 index 4c4e9930a7..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTemiEvent.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Filter Event for Timed External Media Information (TEMI) data. - * - * {@hide} - */ -parcelable TunerFilterTemiEvent { - /** - * Presentation Time Stamp for audio or video frame. It based on 90KHz has - * the same format as PTS (Presentation Time Stamp) in ISO/IEC 13818-1. - */ - long pts; - - /** - * TEMI Descriptor Tag - */ - byte descrTag; - - /** - * TEMI Descriptor - */ - byte[] descrData; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTlvConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterTlvConfiguration.aidl deleted file mode 100644 index 0b237b4d7d..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTlvConfiguration.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSettings; - -/** - * Filter Settings for a tlv filter. - * - * {@hide} - */ -parcelable TunerFilterTlvConfiguration { - byte packetType; - - boolean isCompressedIpPacket; - - TunerFilterSettings filterSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsConfiguration.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsConfiguration.aidl deleted file mode 100644 index 2e386e62f9..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsConfiguration.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterSettings; - -/** - * Filter Settings for a TS filter. - * - * {@hide} - */ -parcelable TunerFilterTsConfiguration { - char tpid; - - TunerFilterSettings filterSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsRecordEvent.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsRecordEvent.aidl deleted file mode 100644 index c52a749d2f..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFilterTsRecordEvent.aidl +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFilterScIndexMask; - -/** - * Filter Event for TS Record Filter. - * - * {@hide} - */ -parcelable TunerFilterTsRecordEvent { - char pid; - - int tsIndexMask; - - /** - * Indexes of record output - */ - TunerFilterScIndexMask scIndexMask; - - /** - * Byte number from beginning of the filter's output - */ - long byteNumber; - - /** - * If the current event contains extended information or not - */ - boolean isExtended; - - /** - * The Presentation Time Stamp(PTS) for the audio or video frame. It is based on 90KHz - * and has the same format as the PTS in ISO/IEC 13818-1. - */ - long pts; - - /** - * Specifies the address of the first macroblock in the slice defined in ITU-T Rec. H.264. - */ - int firstMbInSlice; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogCapabilities.aidl deleted file mode 100644 index 74bf04e9b0..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogCapabilities.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Analog Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendAnalogCapabilities { - /** - * Signal Type capability - */ - int typeCap; - - /** - * Standard Interchange Format (SIF) capability - */ - int sifStandardCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl deleted file mode 100644 index 40cd8c9e7a..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAnalogSettings.aidl +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Analog Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendAnalogSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int signalType; - - /** - * Standard Interchange Format (SIF) setting - */ - int sifStandard; - - /** - * Fields after isExtended are only valid when isExtended is true - */ - boolean isExtended; - - int aftFlag; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Capabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Capabilities.aidl deleted file mode 100644 index 6c9be77f94..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Capabilities.aidl +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * ATSC3 Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendAtsc3Capabilities { - /** - * Bandwidth capability - */ - int bandwidthCap; - - /** - * Modulation capability - */ - int modulationCap; - - /** - * TimeInterleaveMode capability - */ - int timeInterleaveModeCap; - - /** - * CodeRate capability - */ - int codeRateCap; - - /** - * FEC capability - */ - int fecCap; - - /** - * Demodulator Output Format capability - */ - int demodOutputFormatCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3PlpSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3PlpSettings.aidl deleted file mode 100644 index b29e1f7d4c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3PlpSettings.aidl +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Atsc3 Frontend Physical Layer Pipe Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendAtsc3PlpSettings { - int plpId; - - int modulation; - - int interleaveMode; - - int codeRate; - - /** - * Forward Error Correction Type. - */ - int fec; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Settings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Settings.aidl deleted file mode 100644 index 32fb8c7627..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtsc3Settings.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendAtsc3PlpSettings; - -/** - * Atsc3 Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendAtsc3Settings { - /** - * Signal frequency in Hertz - */ - int frequency; - - /** - * Bandwidth of tuning band. - */ - int bandwidth; - - int demodOutputFormat; - - TunerFrontendAtsc3PlpSettings[] plpSettings; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscCapabilities.aidl deleted file mode 100644 index 2b6c2fc60c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscCapabilities.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * ATSC Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendAtscCapabilities { - /** - * Modulation capability - */ - int modulationCap; -} \ No newline at end of file diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscSettings.aidl deleted file mode 100644 index c7a8c079ec..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendAtscSettings.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Atsc Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendAtscSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int modulation; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl deleted file mode 100644 index b880c60ee8..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableCapabilities.aidl +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Cable(DVBC) Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendCableCapabilities { - /** - * Modulation capability - */ - int modulationCap; - - /** - * Code Rate capability - */ - long codeRateCap; // inner FEC will converge to codeRate - - /** - * Annex capability - */ - int annexCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl deleted file mode 100644 index b9bcf29428..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCableSettings.aidl +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Cable Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendCableSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int modulation; - - /** - * Inner Forward Error Correction type as specified in ETSI EN 300 468 V1.15.1 - * and ETSI EN 302 307-2 V1.1.1. - */ - long innerFec; - - /** - * Symbols per second - */ - int symbolRate; - - /** - * Outer Forward Error Correction (FEC) Type. - */ - int outerFec; - - int annex; - - /** - * Spectral Inversion Type. - */ - int spectralInversion; - - /** - * Fields after isExtended are only valid when isExtended is true - */ - boolean isExtended; - - int interleaveMode; - - int bandwidth; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCapabilities.aidl deleted file mode 100644 index 19f31f1bae..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendCapabilities.aidl +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendAnalogCapabilities; -import android.media.tv.tuner.TunerFrontendAtscCapabilities; -import android.media.tv.tuner.TunerFrontendAtsc3Capabilities; -import android.media.tv.tuner.TunerFrontendCableCapabilities; -import android.media.tv.tuner.TunerFrontendDvbsCapabilities; -import android.media.tv.tuner.TunerFrontendDvbtCapabilities; -import android.media.tv.tuner.TunerFrontendIsdbsCapabilities; -import android.media.tv.tuner.TunerFrontendIsdbs3Capabilities; -import android.media.tv.tuner.TunerFrontendIsdbtCapabilities; - -/** - * Frontend Capabilities interface. - * - * Use a group of vectors as the workaround for Union structure that is not fully supported - * in AIDL currently. - * - * Client may use FrontendInfo.type as the discriminar to check the corresponding vector. If - * the vector is not null, it contains valid value. - * - * {@hide} - */ -union TunerFrontendCapabilities { - /** - * Analog Frontend Capabilities - */ - TunerFrontendAnalogCapabilities analogCaps; - - /** - * ATSC Frontend Capabilities - */ - TunerFrontendAtscCapabilities atscCaps; - - /** - * ATSC3 Frontend Capabilities - */ - TunerFrontendAtsc3Capabilities atsc3Caps; - - /** - * Cable Frontend Capabilities - */ - TunerFrontendCableCapabilities cableCaps; - - /** - * DVBS Frontend Capabilities - */ - TunerFrontendDvbsCapabilities dvbsCaps; - - /** - * DVBT Frontend Capabilities - */ - TunerFrontendDvbtCapabilities dvbtCaps; - - /** - * ISDB-S Frontend Capabilities - */ - TunerFrontendIsdbsCapabilities isdbsCaps; - - /** - * ISDB-S3 Frontend Capabilities - */ - TunerFrontendIsdbs3Capabilities isdbs3Caps; - - /** - * ISDB-T Frontend Capabilities - */ - TunerFrontendIsdbtCapabilities isdbtCaps; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl deleted file mode 100644 index e8e493377a..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbCapabilities.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * DTMB Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendDtmbCapabilities { - int transmissionModeCap; - - int bandwidthCap; - - int modulationCap; - - int codeRateCap; - - int guardIntervalCap; - - int interleaveModeCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl deleted file mode 100644 index 45e7ff9cbb..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDtmbSettings.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * DTMB Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendDtmbSettings { - int frequency; - - int transmissionMode; - - int bandwidth; - - int modulation; - - int codeRate; - - int guardInterval; - - int interleaveMode; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCapabilities.aidl deleted file mode 100644 index 5e4322c392..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCapabilities.aidl +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * DVBS Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendDvbsCapabilities { - /** - * Modulation capability - */ - int modulationCap; - - /** - * Code Rate capability - */ - long codeRateCap; // inner FEC will converge to codeRate - - /** - * Sub standards capability - */ - int standard; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCodeRate.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCodeRate.aidl deleted file mode 100644 index 59b7de371e..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsCodeRate.aidl +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Dvbs Frontend CodeRate interface. - * - * {@hide} - */ -parcelable TunerFrontendDvbsCodeRate { - /** - * Inner Forward Error Correction type as specified in ETSI EN 300 468 V1.15.1 - * and ETSI EN 302 307-2 V1.1.1. - */ - long fec; - - boolean isLinear; - - /** - * true if enable short frame - */ - boolean isShortFrames; - - /** - * bits number in 1000 symbol. 0 if use the default. - */ - int bitsPer1000Symbol; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl deleted file mode 100644 index ec3e4b9943..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbsSettings.aidl +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendDvbsCodeRate; - -/** - * Dvbs Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendDvbsSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int modulation; - - TunerFrontendDvbsCodeRate codeRate; - - int symbolRate; - - /** - * Roll off type. - */ - int rolloff; - - /** - * Pilot mode. - */ - int pilot; - - int inputStreamId; - - int standard; - - /** - * Vcm mode. - */ - int vcm; - - /** - * Fields after isExtended are only valid when isExtended is true - */ - boolean isExtended; - - int scanType; - - boolean isDiseqcRxMessage; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtCapabilities.aidl deleted file mode 100644 index 73f16dd394..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtCapabilities.aidl +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * DVBT Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendDvbtCapabilities { - /** - * Transmission Mode capability - */ - int transmissionModeCap; - - /** - * Bandwidth capability - */ - int bandwidthCap; - - /** - * Constellation capability - */ - int constellationCap; - - /** - * Code Rate capability - */ - int codeRateCap; - - /** - * Hierarchy Type capability - */ - int hierarchyCap; - - /** - * Guard Interval capability - */ - int guardIntervalCap; - - /** - * T2 Support capability - */ - boolean isT2Supported; - - /** - * Miso Support capability - */ - boolean isMisoSupported; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl deleted file mode 100644 index 14c942a162..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendDvbtSettings.aidl +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Dvbt Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendDvbtSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int transmissionMode; - - int bandwidth; - - int constellation; - - int hierarchy; - - /** - * Code Rate for High Priority level - */ - int hpCodeRate; - - /** - * Code Rate for Low Priority level - */ - int lpCodeRate; - - int guardInterval; - - boolean isHighPriority; - - int standard; - - boolean isMiso; - - /** - * Physical Layer Pipe (PLP) mode - */ - int plpMode; - - /** - * Physical Layer Pipe (PLP) Id - */ - int plpId; - - /** - * Physical Layer Pipe (PLP) Group Id - */ - int plpGroupId; - - /** - * Fields after isExtended are only valid when isExtended is true - */ - boolean isExtended; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendInfo.aidl deleted file mode 100644 index 4bccd5675c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendInfo.aidl +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendCapabilities; - -/** - * FrontendInfo interface that carries tuner frontend information. - * - *

This is used to update the TunerResourceManager and pass Frontend - * information from HAL to the client side. - * - * {@hide} - */ -parcelable TunerFrontendInfo { - /** - * Frontend Handle - */ - int handle; - - /** - * Frontend Type - */ - int type; - - /** - * Minimum Frequency in Hertz - */ - int minFrequency; - - /** - * Maximum Frequency in Hertz - */ - int maxFrequency; - - /** - * Minimum symbols per second - */ - int minSymbolRate; - - /** - * Maximum symbols per second - */ - int maxSymbolRate; - - /** - * Range in Hertz - */ - int acquireRange; - - /** - * Frontends are assigned with the same exclusiveGroupId if they can't - * function at same time. For instance, they share same hardware module. - */ - int exclusiveGroupId; - - /** - * A list of supported status types which client can inquiry - */ - int[] statusCaps; - - /** - * Frontend Capabilities - */ - TunerFrontendCapabilities caps; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Capabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Capabilities.aidl deleted file mode 100644 index 84dd67aed4..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Capabilities.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * ISDB-S3 Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbs3Capabilities { - /** - * Modulation capability - */ - int modulationCap; - - /** - * Code Rate capability - */ - int codeRateCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Settings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Settings.aidl deleted file mode 100644 index 9a11fd578f..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbs3Settings.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Isdbs3 Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbs3Settings { - /** - * Signal frequency in Hertz - */ - int frequency; - - char streamId; - - int streamIdType; - - int modulation; - - int codeRate; - - /** - * Symbols per second - */ - int symbolRate; - - int rolloff; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsCapabilities.aidl deleted file mode 100644 index 15dfdf7ef0..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsCapabilities.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * ISDB-S Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbsCapabilities { - /** - * Modulation capability - */ - int modulationCap; - - /** - * Code Rate capability - */ - int codeRateCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsSettings.aidl deleted file mode 100644 index dff9f4ad52..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbsSettings.aidl +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Isdbs Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbsSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - char streamId; - - int streamIdType; - - int modulation; - - int codeRate; - - /** - * Symbols per second - */ - int symbolRate; - - int rolloff; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtCapabilities.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtCapabilities.aidl deleted file mode 100644 index c9295d8b1c..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtCapabilities.aidl +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * ISDB-T Frontend Capabilities interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbtCapabilities { - /** - * ISDB-T Mode capability - */ - int modeCap; - - /** - * Bandwidth capability - */ - int bandwidthCap; - - /** - * Modulation capability - */ - int modulationCap; - - /** - * Code Rate capability - */ - int codeRateCap; - - /** - * Guard Interval capability - */ - int guardIntervalCap; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtSettings.aidl deleted file mode 100644 index 191f3a6874..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendIsdbtSettings.aidl +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Isdbt Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendIsdbtSettings { - /** - * Signal frequency in Hertz - */ - int frequency; - - int modulation; - - int bandwidth; - - int mode; - - int codeRate; - - int guardInterval; - - int serviceAreaId; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl deleted file mode 100644 index 1b8fcbbfa4..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanAtsc3PlpInfo.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Atsc3 Frontend Physical Layer Pipe Info. - * - * {@hide} - */ -parcelable TunerFrontendScanAtsc3PlpInfo { - byte plpId; - - boolean llsFlag; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanMessage.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanMessage.aidl deleted file mode 100644 index 9921ca1d3a..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendScanMessage.aidl +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendScanAtsc3PlpInfo; - -/** - * Tuner Frontend Scan Message interface. - * - * {@hide} - */ -union TunerFrontendScanMessage { - boolean isLocked; - - boolean isEnd; - - byte progressPercent; - - int[] frequencies; - - int[] symbolRates; - - int hierarchy; - - int analogType; - - byte[] plpIds; - - byte[] groupIds; - - char[] inputStreamIds; - - int std; - - TunerFrontendScanAtsc3PlpInfo[] atsc3PlpInfos; - - int modulation; - - int annex; - - boolean isHighPriority; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl deleted file mode 100644 index 70a5f3ef95..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendSettings.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendUnionSettings; - -/** - * Frontend Settings interface. - * - * {@hide} - */ -parcelable TunerFrontendSettings { - TunerFrontendUnionSettings settings; - - boolean isExtended; - - int endFrequency; - - int inversion; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl deleted file mode 100644 index 2b3c01bd86..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatus.aidl +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendStatusAtsc3PlpInfo; - -/** - * Tuner Frontend Status interface. - * - * {@hide} - */ -union TunerFrontendStatus { - /** - * Lock status for Demod in True/False. - */ - boolean isDemodLocked; - - /** - * SNR value measured by 0.001 dB. - */ - int snr; - - /** - * The number of error bits per 1 billion bits. - */ - int ber; - - /** - * The number of error packages per 1 billion packages. - */ - int per; - - /** - * The number of error bits per 1 billion bits before FEC. - */ - int preBer; - - /** - * Signal Quality in percent. - */ - int signalQuality; - - /** - * Signal Strength measured by 0.001 dBm. - */ - int signalStrength; - - /** - * Symbols per second - */ - int symbolRate; - - long innerFec; - - /** - * Check frontend type to decide the hidl type value - */ - int modulation; - - int inversion; - - int lnbVoltage; - - byte plpId; - - boolean isEWBS; - - /** - * AGC value is normalized from 0 to 255. - */ - byte agc; - - boolean isLnaOn; - - boolean[] isLayerError; - - /** - * MER value measured by 0.001 dB - */ - int mer; - - /** - * Frequency difference in Hertz. - */ - int freqOffset; - - int hierarchy; - - boolean isRfLocked; - - /** - * A list of PLP status for tuned PLPs for ATSC3 frontend. - */ - TunerFrontendStatusAtsc3PlpInfo[] plpInfo; - - // 1.1 Extension Starting - - /** - * Extended modulation status. Check frontend type to decide the hidl type value. - */ - int[] modulations; - - /** - * Extended bit error ratio status. - */ - int[] bers; - - /** - * Extended code rate status. - */ - long[] codeRates; - - /** - * Extended bandwidth status. Check frontend type to decide the hidl type value. - */ - int bandwidth; - - /** - * Extended guard interval status. Check frontend type to decide the hidl type value. - */ - int interval; - - /** - * Extended transmission mode status. Check frontend type to decide the hidl type value. - */ - int transmissionMode; - - /** - * Uncorrectable Error Counts of the frontend's Physical Layer Pipe (PLP) - * since the last tune operation. - */ - int uec; - - /** - * The current DVB-T2 system id status. - */ - char systemId; - - /** - * Frontend Interleaving Modes. Check frontend type to decide the hidl type value. - */ - int[] interleaving; - - /** - * Segments in ISDB-T Specification of all the channels. - */ - byte[] isdbtSegment; - - /** - * Transport Stream Data Rate in BPS of the current channel. - */ - int[] tsDataRate; - - /** - * Roll Off Type status of the frontend. Check frontend type to decide the hidl type value. - */ - int rollOff; - - /** - * If the frontend currently supports MISO or not. - */ - boolean isMiso; - - /** - * If the frontend code rate is linear or not. - */ - boolean isLinear; - - /** - * If short frames are enabled or not. - */ - boolean isShortFrames; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl deleted file mode 100644 index 4116c34809..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendStatusAtsc3PlpInfo.aidl +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 2021, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -/** - * Atsc3 Frontend Physical Layer Pipe Info in Frontend status. - * - * {@hide} - */ -parcelable TunerFrontendStatusAtsc3PlpInfo { - /** - * PLP Id value. - */ - byte plpId; - - /** - * Demod Lock/Unlock status of this particular PLP. - */ - boolean isLocked; - - /** - * Uncorrectable Error Counts (UEC) of this particular PLP since last tune operation. - */ - int uec; -} diff --git a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl b/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl deleted file mode 100644 index c362c2ad7b..0000000000 --- a/services/tuner/aidl/android/media/tv/tuner/TunerFrontendUnionSettings.aidl +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2020, The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media.tv.tuner; - -import android.media.tv.tuner.TunerFrontendAnalogSettings; -import android.media.tv.tuner.TunerFrontendAtscSettings; -import android.media.tv.tuner.TunerFrontendAtsc3Settings; -import android.media.tv.tuner.TunerFrontendCableSettings; -import android.media.tv.tuner.TunerFrontendDtmbSettings; -import android.media.tv.tuner.TunerFrontendDvbsSettings; -import android.media.tv.tuner.TunerFrontendDvbtSettings; -import android.media.tv.tuner.TunerFrontendIsdbsSettings; -import android.media.tv.tuner.TunerFrontendIsdbs3Settings; -import android.media.tv.tuner.TunerFrontendIsdbtSettings; - -/** - * Frontend Settings Union interface. - * - * {@hide} - */ -union TunerFrontendUnionSettings { - TunerFrontendAnalogSettings analog; - - TunerFrontendAtscSettings atsc; - - TunerFrontendAtsc3Settings atsc3; - - TunerFrontendCableSettings cable; - - TunerFrontendDvbsSettings dvbs; - - TunerFrontendDvbtSettings dvbt; - - TunerFrontendIsdbsSettings isdbs; - - TunerFrontendIsdbs3Settings isdbs3; - - TunerFrontendIsdbtSettings isdbt; - - TunerFrontendDtmbSettings dtmb; -} -- GitLab From d063b6d7d4a8beba008d4143694e50f4b07e7313 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Fri, 6 Aug 2021 16:58:10 +0100 Subject: [PATCH 083/694] Remove unused MyTransmitter class I suspect this class was left here with the purpose of debugging RTSP. Lacking references and documentation, this is effectively dead code. For future RTSP testing, developers should favor unit testing or a mock RTSP server for end-to-end integration debugging. Test: Manually built the tree. Change-Id: Ib103e6d257f0694b8dc6b5e9da2b5eaac9d74a7e --- media/libstagefright/rtsp/MyTransmitter.h | 984 ---------------------- 1 file changed, 984 deletions(-) delete mode 100644 media/libstagefright/rtsp/MyTransmitter.h diff --git a/media/libstagefright/rtsp/MyTransmitter.h b/media/libstagefright/rtsp/MyTransmitter.h deleted file mode 100644 index bf44aff288..0000000000 --- a/media/libstagefright/rtsp/MyTransmitter.h +++ /dev/null @@ -1,984 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MY_TRANSMITTER_H_ - -#define MY_TRANSMITTER_H_ - -#include "ARTPConnection.h" - -#include -#include - -#include - -#include -#include -#include - -#ifdef ANDROID -#include "VideoSource.h" -#include -#include -#include -#include -#endif - -namespace android { - -#define TRACK_SUFFIX "trackid=1" -#define PT 96 -#define PT_STR "96" - -#define USERNAME "bcast" -#define PASSWORD "test" - -static int uniformRand(int limit) { - return ((double)rand() * limit) / RAND_MAX; -} - -static bool GetAttribute(const char *s, const char *key, AString *value) { - value->clear(); - - size_t keyLen = strlen(key); - - for (;;) { - const char *colonPos = strchr(s, ';'); - - size_t len = - (colonPos == NULL) ? strlen(s) : colonPos - s; - - if (len >= keyLen + 1 && s[keyLen] == '=' && !strncmp(s, key, keyLen)) { - value->setTo(&s[keyLen + 1], len - keyLen - 1); - return true; - } - - if (colonPos == NULL) { - return false; - } - - s = colonPos + 1; - } -} - -struct MyTransmitter : public AHandler { - MyTransmitter(const char *url, const sp &looper) - : mServerURL(url), - mLooper(looper), - mConn(new ARTSPConnection), - mConnected(false), - mAuthType(NONE), - mRTPSocket(-1), - mRTCPSocket(-1), - mSourceID(rand()), - mSeqNo(uniformRand(65536)), - mRTPTimeBase(rand()), - mNumSamplesSent(0), - mNumRTPSent(0), - mNumRTPOctetsSent(0), - mLastRTPTime(0), - mLastNTPTime(0) { - mStreamURL = mServerURL; - mStreamURL.append("/bazong.sdp"); - - mTrackURL = mStreamURL; - mTrackURL.append("/"); - mTrackURL.append(TRACK_SUFFIX); - - mLooper->registerHandler(this); - mLooper->registerHandler(mConn); - - sp reply = new AMessage('conn', this); - mConn->connect(mServerURL.c_str(), reply); - -#ifdef ANDROID - int width = 640; - int height = 480; - - sp source = new VideoSource(width, height); - - sp encMeta = new AMessage; - encMeta->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC); - encMeta->setInt32("width", width); - encMeta->setInt32("height", height); - encMeta->setInt32("frame-rate", 30); - encMeta->setInt32("bitrate", 256000); - encMeta->setInt32("i-frame-interval", 10); - - sp encLooper = new ALooper; - encLooper->setName("rtsp_transmitter"); - encLooper->start(); - - mEncoder = MediaCodecSource::Create(encLooper, encMeta, source); - - mEncoder->start(); - - MediaBuffer *buffer; - CHECK_EQ(mEncoder->read(&buffer), (status_t)OK); - CHECK(buffer != NULL); - - makeH264SPropParamSets(buffer); - - buffer->release(); - buffer = NULL; -#endif - } - - uint64_t ntpTime() { - struct timeval tv; - gettimeofday(&tv, NULL); - - uint64_t nowUs = tv.tv_sec * 1000000ll + tv.tv_usec; - - nowUs += ((70ll * 365 + 17) * 24) * 60 * 60 * 1000000ll; - - uint64_t hi = nowUs / 1000000ll; - uint64_t lo = ((1ll << 32) * (nowUs % 1000000ll)) / 1000000ll; - - return (hi << 32) | lo; - } - - void issueAnnounce() { - AString sdp; - sdp = "v=0\r\n"; - - sdp.append("o=- "); - - uint64_t ntp = ntpTime(); - sdp.append(ntp); - sdp.append(" "); - sdp.append(ntp); - sdp.append(" IN IP4 127.0.0.0\r\n"); - - sdp.append( - "s=Sample\r\n" - "i=Playing around with ANNOUNCE\r\n" - "c=IN IP4 "); - - struct in_addr addr; - addr.s_addr = htonl(mServerIP); - - sdp.append(inet_ntoa(addr)); - - sdp.append( - "\r\n" - "t=0 0\r\n" - "a=range:npt=now-\r\n"); - -#ifdef ANDROID - sp meta = mEncoder->getFormat(); - int32_t width, height; - CHECK(meta->findInt32(kKeyWidth, &width)); - CHECK(meta->findInt32(kKeyHeight, &height)); - - sdp.append( - "m=video 0 RTP/AVP " PT_STR "\r\n" - "b=AS 320000\r\n" - "a=rtpmap:" PT_STR " H264/90000\r\n"); - - sdp.append("a=cliprect 0,0,"); - sdp.append(height); - sdp.append(","); - sdp.append(width); - sdp.append("\r\n"); - - sdp.append( - "a=framesize:" PT_STR " "); - sdp.append(width); - sdp.append("-"); - sdp.append(height); - sdp.append("\r\n"); - - sdp.append( - "a=fmtp:" PT_STR " profile-level-id=42C015;sprop-parameter-sets="); - - sdp.append(mSeqParamSet); - sdp.append(","); - sdp.append(mPicParamSet); - sdp.append(";packetization-mode=1\r\n"); -#else - sdp.append( - "m=audio 0 RTP/AVP " PT_STR "\r\n" - "a=rtpmap:" PT_STR " L8/8000/1\r\n"); -#endif - - sdp.append("a=control:" TRACK_SUFFIX "\r\n"); - - AString request; - request.append("ANNOUNCE "); - request.append(mStreamURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "ANNOUNCE", mStreamURL.c_str()); - - request.append("Content-Type: application/sdp\r\n"); - request.append("Content-Length: "); - request.append(sdp.size()); - request.append("\r\n"); - - request.append("\r\n"); - request.append(sdp); - - sp reply = new AMessage('anno', this); - mConn->sendRequest(request.c_str(), reply); - } - - void H(const AString &s, AString *out) { - out->clear(); - - MD5_CTX m; - MD5_Init(&m); - MD5_Update(&m, s.c_str(), s.size()); - - uint8_t key[16]; - MD5_Final(key, &m); - - for (size_t i = 0; i < 16; ++i) { - char nibble = key[i] >> 4; - if (nibble <= 9) { - nibble += '0'; - } else { - nibble += 'a' - 10; - } - out->append(&nibble, 1); - - nibble = key[i] & 0x0f; - if (nibble <= 9) { - nibble += '0'; - } else { - nibble += 'a' - 10; - } - out->append(&nibble, 1); - } - } - - void authenticate(const sp &response) { - ssize_t i = response->mHeaders.indexOfKey("www-authenticate"); - CHECK_GE(i, 0); - - AString value = response->mHeaders.valueAt(i); - - if (!strncmp(value.c_str(), "Basic", 5)) { - mAuthType = BASIC; - } else { - CHECK(!strncmp(value.c_str(), "Digest", 6)); - mAuthType = DIGEST; - - i = value.find("nonce="); - CHECK_GE(i, 0); - CHECK_EQ(value.c_str()[i + 6], '\"'); - ssize_t j = value.find("\"", i + 7); - CHECK_GE(j, 0); - - mNonce.setTo(value, i + 7, j - i - 7); - } - - issueAnnounce(); - } - - void addAuthentication( - AString *request, const char *method, const char *url) { - if (mAuthType == NONE) { - return; - } - - if (mAuthType == BASIC) { - request->append("Authorization: Basic YmNhc3Q6dGVzdAo=\r\n"); - return; - } - - CHECK_EQ((int)mAuthType, (int)DIGEST); - - AString A1; - A1.append(USERNAME); - A1.append(":"); - A1.append("Streaming Server"); - A1.append(":"); - A1.append(PASSWORD); - - AString A2; - A2.append(method); - A2.append(":"); - A2.append(url); - - AString HA1, HA2; - H(A1, &HA1); - H(A2, &HA2); - - AString tmp; - tmp.append(HA1); - tmp.append(":"); - tmp.append(mNonce); - tmp.append(":"); - tmp.append(HA2); - - AString digest; - H(tmp, &digest); - - request->append("Authorization: Digest "); - request->append("nonce=\""); - request->append(mNonce); - request->append("\", "); - request->append("username=\"" USERNAME "\", "); - request->append("uri=\""); - request->append(url); - request->append("\", "); - request->append("response=\""); - request->append(digest); - request->append("\""); - request->append("\r\n"); - } - - virtual void onMessageReceived(const sp &msg) { - switch (msg->what()) { - case 'conn': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "connection request completed with result " - << result << " (" << strerror(-result) << ")"; - - if (result != OK) { - (new AMessage('quit', this))->post(); - break; - } - - mConnected = true; - - CHECK(msg->findInt32("server-ip", (int32_t *)&mServerIP)); - - issueAnnounce(); - break; - } - - case 'anno': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "ANNOUNCE completed with result " - << result << " (" << strerror(-result) << ")"; - - sp obj; - CHECK(msg->findObject("response", &obj)); - sp response; - - if (result == OK) { - response = static_cast(obj.get()); - CHECK(response != NULL); - - if (response->mStatusCode == 401) { - if (mAuthType != NONE) { - LOG(INFO) << "FAILED to authenticate"; - (new AMessage('quit', this))->post(); - break; - } - - authenticate(response); - break; - } - } - - if (result != OK || response->mStatusCode != 200) { - (new AMessage('quit', this))->post(); - break; - } - - unsigned rtpPort; - ARTPConnection::MakePortPair(&mRTPSocket, &mRTCPSocket, &rtpPort); - - // (new AMessage('poll', this))->post(); - - AString request; - request.append("SETUP "); - request.append(mTrackURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "SETUP", mTrackURL.c_str()); - - request.append("Transport: RTP/AVP;unicast;client_port="); - request.append(rtpPort); - request.append("-"); - request.append(rtpPort + 1); - request.append(";mode=record\r\n"); - request.append("\r\n"); - - sp reply = new AMessage('setu', this); - mConn->sendRequest(request.c_str(), reply); - break; - } - -#if 0 - case 'poll': - { - fd_set rs; - FD_ZERO(&rs); - FD_SET(mRTCPSocket, &rs); - - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = 0; - - int res = select(mRTCPSocket + 1, &rs, NULL, NULL, &tv); - - if (res == 1) { - sp buffer = new ABuffer(65536); - ssize_t n = recv(mRTCPSocket, buffer->data(), buffer->size(), 0); - - if (n <= 0) { - LOG(ERROR) << "recv returned " << n; - } else { - LOG(INFO) << "recv returned " << n << " bytes of data."; - - hexdump(buffer->data(), n); - } - } - - msg->post(50000); - break; - } -#endif - - case 'setu': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "SETUP completed with result " - << result << " (" << strerror(-result) << ")"; - - sp obj; - CHECK(msg->findObject("response", &obj)); - sp response; - - if (result == OK) { - response = static_cast(obj.get()); - CHECK(response != NULL); - } - - if (result != OK || response->mStatusCode != 200) { - (new AMessage('quit', this))->post(); - break; - } - - ssize_t i = response->mHeaders.indexOfKey("session"); - CHECK_GE(i, 0); - mSessionID = response->mHeaders.valueAt(i); - i = mSessionID.find(";"); - if (i >= 0) { - // Remove options, i.e. ";timeout=90" - mSessionID.erase(i, mSessionID.size() - i); - } - - i = response->mHeaders.indexOfKey("transport"); - CHECK_GE(i, 0); - AString transport = response->mHeaders.valueAt(i); - - LOG(INFO) << "transport = '" << transport << "'"; - - AString value; - CHECK(GetAttribute(transport.c_str(), "server_port", &value)); - - unsigned rtpPort, rtcpPort; - CHECK_EQ(sscanf(value.c_str(), "%u-%u", &rtpPort, &rtcpPort), 2); - - CHECK(GetAttribute(transport.c_str(), "source", &value)); - - memset(mRemoteAddr.sin_zero, 0, sizeof(mRemoteAddr.sin_zero)); - mRemoteAddr.sin_family = AF_INET; - mRemoteAddr.sin_addr.s_addr = inet_addr(value.c_str()); - mRemoteAddr.sin_port = htons(rtpPort); - - mRemoteRTCPAddr = mRemoteAddr; - mRemoteRTCPAddr.sin_port = htons(rtpPort + 1); - - CHECK_EQ(0, connect(mRTPSocket, - (const struct sockaddr *)&mRemoteAddr, - sizeof(mRemoteAddr))); - - CHECK_EQ(0, connect(mRTCPSocket, - (const struct sockaddr *)&mRemoteRTCPAddr, - sizeof(mRemoteRTCPAddr))); - - uint32_t x = ntohl(mRemoteAddr.sin_addr.s_addr); - LOG(INFO) << "sending data to " - << (x >> 24) - << "." - << ((x >> 16) & 0xff) - << "." - << ((x >> 8) & 0xff) - << "." - << (x & 0xff) - << ":" - << rtpPort; - - AString request; - request.append("RECORD "); - request.append(mStreamURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "RECORD", mStreamURL.c_str()); - - request.append("Session: "); - request.append(mSessionID); - request.append("\r\n"); - request.append("\r\n"); - - sp reply = new AMessage('reco', this); - mConn->sendRequest(request.c_str(), reply); - break; - } - - case 'reco': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "RECORD completed with result " - << result << " (" << strerror(-result) << ")"; - - sp obj; - CHECK(msg->findObject("response", &obj)); - sp response; - - if (result == OK) { - response = static_cast(obj.get()); - CHECK(response != NULL); - } - - if (result != OK) { - (new AMessage('quit', this))->post(); - break; - } - - (new AMessage('more', this))->post(); - (new AMessage('sr ', this))->post(); - (new AMessage('aliv', this))->post(30000000ll); - break; - } - - case 'aliv': - { - if (!mConnected) { - break; - } - - AString request; - request.append("OPTIONS "); - request.append(mStreamURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "RECORD", mStreamURL.c_str()); - - request.append("Session: "); - request.append(mSessionID); - request.append("\r\n"); - request.append("\r\n"); - - sp reply = new AMessage('opts', this); - mConn->sendRequest(request.c_str(), reply); - break; - } - - case 'opts': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "OPTIONS completed with result " - << result << " (" << strerror(-result) << ")"; - - if (!mConnected) { - break; - } - - (new AMessage('aliv', this))->post(30000000ll); - break; - } - - case 'more': - { - if (!mConnected) { - break; - } - - sp buffer = new ABuffer(65536); - uint8_t *data = buffer->data(); - data[0] = 0x80; - data[1] = (1 << 7) | PT; // M-bit - data[2] = (mSeqNo >> 8) & 0xff; - data[3] = mSeqNo & 0xff; - data[8] = mSourceID >> 24; - data[9] = (mSourceID >> 16) & 0xff; - data[10] = (mSourceID >> 8) & 0xff; - data[11] = mSourceID & 0xff; - -#ifdef ANDROID - MediaBuffer *mediaBuf = NULL; - for (;;) { - CHECK_EQ(mEncoder->read(&mediaBuf), (status_t)OK); - if (mediaBuf->range_length() > 0) { - break; - } - mediaBuf->release(); - mediaBuf = NULL; - } - - int64_t timeUs; - CHECK(mediaBuf->meta_data()->findInt64(kKeyTime, &timeUs)); - - uint32_t rtpTime = mRTPTimeBase + (timeUs * 9 / 100ll); - - const uint8_t *mediaData = - (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset(); - - CHECK(!memcmp("\x00\x00\x00\x01", mediaData, 4)); - - CHECK_LE(mediaBuf->range_length() - 4 + 12, buffer->size()); - - memcpy(&data[12], - mediaData + 4, mediaBuf->range_length() - 4); - - buffer->setRange(0, mediaBuf->range_length() - 4 + 12); - - mediaBuf->release(); - mediaBuf = NULL; -#else - uint32_t rtpTime = mRTPTimeBase + mNumRTPSent * 128; - memset(&data[12], 0, 128); - buffer->setRange(0, 12 + 128); -#endif - - data[4] = rtpTime >> 24; - data[5] = (rtpTime >> 16) & 0xff; - data[6] = (rtpTime >> 8) & 0xff; - data[7] = rtpTime & 0xff; - - ssize_t n = send( - mRTPSocket, data, buffer->size(), 0); - if (n < 0) { - LOG(ERROR) << "send failed (" << strerror(errno) << ")"; - } - CHECK_EQ(n, (ssize_t)buffer->size()); - - ++mSeqNo; - - ++mNumRTPSent; - mNumRTPOctetsSent += buffer->size() - 12; - - mLastRTPTime = rtpTime; - mLastNTPTime = ntpTime(); - -#ifdef ANDROID - if (mNumRTPSent < 60 * 25) { // 60 secs worth - msg->post(40000); -#else - if (mNumRTPOctetsSent < 8000 * 60) { - msg->post(1000000ll * 128 / 8000); -#endif - } else { - LOG(INFO) << "That's enough, pausing."; - - AString request; - request.append("PAUSE "); - request.append(mStreamURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "PAUSE", mStreamURL.c_str()); - - request.append("Session: "); - request.append(mSessionID); - request.append("\r\n"); - request.append("\r\n"); - - sp reply = new AMessage('paus', this); - mConn->sendRequest(request.c_str(), reply); - } - break; - } - - case 'sr ': - { - if (!mConnected) { - break; - } - - sp buffer = new ABuffer(65536); - buffer->setRange(0, 0); - - addSR(buffer); - addSDES(buffer); - - uint8_t *data = buffer->data(); - ssize_t n = send( - mRTCPSocket, data, buffer->size(), 0); - CHECK_EQ(n, (ssize_t)buffer->size()); - - msg->post(3000000); - break; - } - - case 'paus': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "PAUSE completed with result " - << result << " (" << strerror(-result) << ")"; - - sp obj; - CHECK(msg->findObject("response", &obj)); - sp response; - - AString request; - request.append("TEARDOWN "); - request.append(mStreamURL); - request.append(" RTSP/1.0\r\n"); - - addAuthentication(&request, "TEARDOWN", mStreamURL.c_str()); - - request.append("Session: "); - request.append(mSessionID); - request.append("\r\n"); - request.append("\r\n"); - - sp reply = new AMessage('tear', this); - mConn->sendRequest(request.c_str(), reply); - break; - } - - case 'tear': - { - int32_t result; - CHECK(msg->findInt32("result", &result)); - - LOG(INFO) << "TEARDOWN completed with result " - << result << " (" << strerror(-result) << ")"; - - sp obj; - CHECK(msg->findObject("response", &obj)); - sp response; - - if (result == OK) { - response = static_cast(obj.get()); - CHECK(response != NULL); - } - - (new AMessage('quit', this))->post(); - break; - } - - case 'disc': - { - LOG(INFO) << "disconnect completed"; - - mConnected = false; - (new AMessage('quit', this))->post(); - break; - } - - case 'quit': - { - if (mConnected) { - mConn->disconnect(new AMessage('disc', this)); - break; - } - - if (mRTPSocket >= 0) { - close(mRTPSocket); - mRTPSocket = -1; - } - - if (mRTCPSocket >= 0) { - close(mRTCPSocket); - mRTCPSocket = -1; - } - -#ifdef ANDROID - mEncoder->stop(); - mEncoder.clear(); -#endif - - mLooper->stop(); - break; - } - - default: - TRESPASS(); - } - } - -protected: - virtual ~MyTransmitter() { - } - -private: - enum AuthType { - NONE, - BASIC, - DIGEST - }; - - AString mServerURL; - AString mTrackURL; - AString mStreamURL; - - sp mLooper; - sp mConn; - bool mConnected; - uint32_t mServerIP; - AuthType mAuthType; - AString mNonce; - AString mSessionID; - int mRTPSocket, mRTCPSocket; - uint32_t mSourceID; - uint32_t mSeqNo; - uint32_t mRTPTimeBase; - struct sockaddr_in mRemoteAddr; - struct sockaddr_in mRemoteRTCPAddr; - size_t mNumSamplesSent; - uint32_t mNumRTPSent; - uint32_t mNumRTPOctetsSent; - uint32_t mLastRTPTime; - uint64_t mLastNTPTime; - -#ifdef ANDROID - sp mEncoder; - AString mSeqParamSet; - AString mPicParamSet; - - void makeH264SPropParamSets(MediaBuffer *buffer) { - static const char kStartCode[] = "\x00\x00\x00\x01"; - - const uint8_t *data = - (const uint8_t *)buffer->data() + buffer->range_offset(); - size_t size = buffer->range_length(); - - CHECK_GE(size, 0u); - CHECK(!memcmp(kStartCode, data, 4)); - - data += 4; - size -= 4; - - size_t startCodePos = 0; - while (startCodePos + 3 < size - && memcmp(kStartCode, &data[startCodePos], 4)) { - ++startCodePos; - } - - CHECK_LT(startCodePos + 3, size); - - encodeBase64(data, startCodePos, &mSeqParamSet); - - encodeBase64(&data[startCodePos + 4], size - startCodePos - 4, - &mPicParamSet); - } -#endif - - void addSR(const sp &buffer) { - uint8_t *data = buffer->data() + buffer->size(); - - data[0] = 0x80 | 0; - data[1] = 200; // SR - data[2] = 0; - data[3] = 6; - data[4] = mSourceID >> 24; - data[5] = (mSourceID >> 16) & 0xff; - data[6] = (mSourceID >> 8) & 0xff; - data[7] = mSourceID & 0xff; - - data[8] = mLastNTPTime >> (64 - 8); - data[9] = (mLastNTPTime >> (64 - 16)) & 0xff; - data[10] = (mLastNTPTime >> (64 - 24)) & 0xff; - data[11] = (mLastNTPTime >> 32) & 0xff; - data[12] = (mLastNTPTime >> 24) & 0xff; - data[13] = (mLastNTPTime >> 16) & 0xff; - data[14] = (mLastNTPTime >> 8) & 0xff; - data[15] = mLastNTPTime & 0xff; - - data[16] = (mLastRTPTime >> 24) & 0xff; - data[17] = (mLastRTPTime >> 16) & 0xff; - data[18] = (mLastRTPTime >> 8) & 0xff; - data[19] = mLastRTPTime & 0xff; - - data[20] = mNumRTPSent >> 24; - data[21] = (mNumRTPSent >> 16) & 0xff; - data[22] = (mNumRTPSent >> 8) & 0xff; - data[23] = mNumRTPSent & 0xff; - - data[24] = mNumRTPOctetsSent >> 24; - data[25] = (mNumRTPOctetsSent >> 16) & 0xff; - data[26] = (mNumRTPOctetsSent >> 8) & 0xff; - data[27] = mNumRTPOctetsSent & 0xff; - - buffer->setRange(buffer->offset(), buffer->size() + 28); - } - - void addSDES(const sp &buffer) { - uint8_t *data = buffer->data() + buffer->size(); - data[0] = 0x80 | 1; - data[1] = 202; // SDES - data[4] = mSourceID >> 24; - data[5] = (mSourceID >> 16) & 0xff; - data[6] = (mSourceID >> 8) & 0xff; - data[7] = mSourceID & 0xff; - - size_t offset = 8; - - data[offset++] = 1; // CNAME - - static const char *kCNAME = "andih@laptop"; - data[offset++] = strlen(kCNAME); - - memcpy(&data[offset], kCNAME, strlen(kCNAME)); - offset += strlen(kCNAME); - - data[offset++] = 7; // NOTE - - static const char *kNOTE = "Hell's frozen over."; - data[offset++] = strlen(kNOTE); - - memcpy(&data[offset], kNOTE, strlen(kNOTE)); - offset += strlen(kNOTE); - - data[offset++] = 0; - - if ((offset % 4) > 0) { - size_t count = 4 - (offset % 4); - switch (count) { - case 3: - data[offset++] = 0; - case 2: - data[offset++] = 0; - case 1: - data[offset++] = 0; - } - } - - size_t numWords = (offset / 4) - 1; - data[2] = numWords >> 8; - data[3] = numWords & 0xff; - - buffer->setRange(buffer->offset(), buffer->size() + offset); - } - - DISALLOW_EVIL_CONSTRUCTORS(MyTransmitter); -}; - -} // namespace android - -#endif // MY_TRANSMITTER_H_ -- GitLab From eae68393bdbcda0644d253b97526d6a63ab64498 Mon Sep 17 00:00:00 2001 From: Hongguang Date: Tue, 27 Jul 2021 20:56:23 -0700 Subject: [PATCH 084/694] New TunerService implemented by AIDL HAL. TODO: add backward HIDL HAL support to separate files. Bug: 191825295 Test: atest android.media.tv.tuner.cts Change-Id: I8400fd75080971ee897e1e2dc35e2bab45ec1659 --- services/tuner/.clang-format | 33 + services/tuner/OWNERS | 2 +- services/tuner/TunerDemux.cpp | 237 +++--- services/tuner/TunerDemux.h | 62 +- services/tuner/TunerDescrambler.cpp | 112 ++- services/tuner/TunerDescrambler.h | 45 +- services/tuner/TunerDvr.cpp | 207 ++--- services/tuner/TunerDvr.h | 86 +- services/tuner/TunerFilter.cpp | 902 +++------------------ services/tuner/TunerFilter.h | 206 ++--- services/tuner/TunerFrontend.cpp | 1091 +++----------------------- services/tuner/TunerFrontend.h | 113 ++- services/tuner/TunerLnb.cpp | 131 ++-- services/tuner/TunerLnb.h | 55 +- services/tuner/TunerService.cpp | 533 ++++--------- services/tuner/TunerService.h | 128 ++- services/tuner/TunerTimeFilter.cpp | 100 ++- services/tuner/TunerTimeFilter.h | 35 +- services/tuner/main_tunerservice.cpp | 19 +- 19 files changed, 1015 insertions(+), 3082 deletions(-) create mode 100644 services/tuner/.clang-format diff --git a/services/tuner/.clang-format b/services/tuner/.clang-format new file mode 100644 index 0000000000..f14cc88254 --- /dev/null +++ b/services/tuner/.clang-format @@ -0,0 +1,33 @@ +--- +BasedOnStyle: Google +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: true +BinPackArguments: true +BinPackParameters: true +CommentPragmas: NOLINT:.* +ContinuationIndentWidth: 8 +DerivePointerAlignment: false +IndentWidth: 4 +PointerAlignment: Left +TabWidth: 4 + +# Deviations from the above file: +# "Don't indent the section label" +AccessModifierOffset: -4 +# "Each line of text in your code should be at most 100 columns long." +ColumnLimit: 100 +# "Constructor initializer lists can be all on one line or with subsequent +# lines indented eight spaces.". clang-format does not support having the colon +# on the same line as the constructor function name, so this is the best +# approximation of that rule, which makes all entries in the list (except the +# first one) have an eight space indentation. +ConstructorInitializerIndentWidth: 6 +# There is nothing in go/droidcppstyle about case labels, but there seems to be +# more code that does not indent the case labels in frameworks/base. +IndentCaseLabels: false +# There have been some bugs in which subsequent formatting operations introduce +# weird comment jumps. +ReflowComments: false +# Android does support C++11 now. +Standard: Cpp11 \ No newline at end of file diff --git a/services/tuner/OWNERS b/services/tuner/OWNERS index 0ceb8e86df..bf9fe3408d 100644 --- a/services/tuner/OWNERS +++ b/services/tuner/OWNERS @@ -1,2 +1,2 @@ -nchalko@google.com +hgchen@google.com quxiangfang@google.com diff --git a/services/tuner/TunerDemux.cpp b/services/tuner/TunerDemux.cpp index 99032adf8a..34efe01613 100644 --- a/services/tuner/TunerDemux.cpp +++ b/services/tuner/TunerDemux.cpp @@ -16,23 +16,32 @@ #define LOG_TAG "TunerDemux" -#include "TunerDvr.h" #include "TunerDemux.h" + +#include +#include +#include +#include +#include +#include + +#include "TunerDvr.h" #include "TunerTimeFilter.h" -using ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxIpFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxTlvFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; -using ::android::hardware::tv::tuner::V1_0::DvrType; -using ::android::hardware::tv::tuner::V1_0::Result; +using ::aidl::android::hardware::tv::tuner::IDvr; +using ::aidl::android::hardware::tv::tuner::IDvrCallback; +using ::aidl::android::hardware::tv::tuner::IFilter; +using ::aidl::android::hardware::tv::tuner::IFilterCallback; +using ::aidl::android::hardware::tv::tuner::ITimeFilter; +using ::aidl::android::hardware::tv::tuner::Result; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerDemux::TunerDemux(sp demux, int id) { +TunerDemux::TunerDemux(shared_ptr demux, int id) { mDemux = demux; mDemuxId = id; } @@ -41,205 +50,141 @@ TunerDemux::~TunerDemux() { mDemux = nullptr; } -Status TunerDemux::setFrontendDataSource(const std::shared_ptr& frontend) { +::ndk::ScopedAStatus TunerDemux::setFrontendDataSource( + const shared_ptr& in_frontend) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } int frontendId; - frontend->getFrontendId(&frontendId); - Result res = mDemux->setFrontendDataSource(frontendId); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + in_frontend->getFrontendId(&frontendId); + + return mDemux->setFrontendDataSource(frontendId); } -Status TunerDemux::setFrontendDataSourceById(int frontendId) { +::ndk::ScopedAStatus TunerDemux::setFrontendDataSourceById(int frontendId) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDemux->setFrontendDataSource(frontendId); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDemux->setFrontendDataSource(frontendId); } -Status TunerDemux::openFilter( - int type, int subType, int bufferSize, const std::shared_ptr& cb, - std::shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerDemux::openFilter(const DemuxFilterType& in_type, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) { if (mDemux == nullptr) { - ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + ALOGE("IDemux is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - DemuxFilterMainType mainType = static_cast(type); - DemuxFilterType filterType { - .mainType = mainType, - }; - - switch(mainType) { - case DemuxFilterMainType::TS: - filterType.subType.tsFilterType(static_cast(subType)); - break; - case DemuxFilterMainType::MMTP: - filterType.subType.mmtpFilterType(static_cast(subType)); - break; - case DemuxFilterMainType::IP: - filterType.subType.ipFilterType(static_cast(subType)); - break; - case DemuxFilterMainType::TLV: - filterType.subType.tlvFilterType(static_cast(subType)); - break; - case DemuxFilterMainType::ALP: - filterType.subType.alpFilterType(static_cast(subType)); - break; - } - Result status; - sp filterSp; - sp cbSp = new TunerFilter::FilterCallback(cb); - mDemux->openFilter(filterType, bufferSize, cbSp, - [&](Result r, const sp& filter) { - filterSp = filter; - status = r; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + shared_ptr filter; + shared_ptr cb = ::ndk::SharedRefBase::make(in_cb); + auto status = mDemux->openFilter(in_type, in_bufferSize, cb, &filter); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(filter, in_type); } - *_aidl_return = ::ndk::SharedRefBase::make(filterSp, type, subType); - return Status::ok(); + return status; } -Status TunerDemux::openTimeFilter(shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerDemux::openTimeFilter(shared_ptr* _aidl_return) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - sp filterSp; - mDemux->openTimeFilter([&](Result r, const sp& filter) { - filterSp = filter; - status = r; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + shared_ptr filter; + auto status = mDemux->openTimeFilter(&filter); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(filter); } - *_aidl_return = ::ndk::SharedRefBase::make(filterSp); - return Status::ok(); + return status; } -Status TunerDemux::getAvSyncHwId(const shared_ptr& tunerFilter, int* _aidl_return) { +::ndk::ScopedAStatus TunerDemux::getAvSyncHwId(const shared_ptr& tunerFilter, + int32_t* _aidl_return) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - uint32_t avSyncHwId; - Result res; - sp halFilter = static_cast(tunerFilter.get())->getHalFilter(); - mDemux->getAvSyncHwId(halFilter, - [&](Result r, uint32_t id) { - res = r; - avSyncHwId = id; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - - *_aidl_return = (int)avSyncHwId; - return Status::ok(); + shared_ptr halFilter = (static_cast(tunerFilter.get()))->getHalFilter(); + return mDemux->getAvSyncHwId(halFilter, _aidl_return); } -Status TunerDemux::getAvSyncTime(int avSyncHwId, int64_t* _aidl_return) { +::ndk::ScopedAStatus TunerDemux::getAvSyncTime(int32_t avSyncHwId, int64_t* _aidl_return) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - uint64_t time; - Result res; - mDemux->getAvSyncTime(static_cast(avSyncHwId), - [&](Result r, uint64_t ts) { - res = r; - time = ts; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - - *_aidl_return = (int64_t)time; - return Status::ok(); + return mDemux->getAvSyncTime(avSyncHwId, _aidl_return); } -Status TunerDemux::openDvr(int dvrType, int bufferSize, const shared_ptr& cb, - shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerDemux::openDvr(DvrType in_dvbType, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res; - sp callback = new TunerDvr::DvrCallback(cb); - sp hidlDvr; - mDemux->openDvr(static_cast(dvrType), bufferSize, callback, - [&](Result r, const sp& dvr) { - hidlDvr = dvr; - res = r; - }); - if (res != Result::SUCCESS) { - *_aidl_return = NULL; - return Status::fromServiceSpecificError(static_cast(res)); + shared_ptr callback = ::ndk::SharedRefBase::make(in_cb); + shared_ptr halDvr; + auto res = mDemux->openDvr(in_dvbType, in_bufferSize, callback, &halDvr); + if (res.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(halDvr, in_dvbType); } - *_aidl_return = ::ndk::SharedRefBase::make(hidlDvr, dvrType); - return Status::ok(); + return res; } -Status TunerDemux::connectCiCam(int ciCamId) { +::ndk::ScopedAStatus TunerDemux::connectCiCam(int32_t ciCamId) { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDemux->connectCiCam(static_cast(ciCamId)); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDemux->connectCiCam(ciCamId); } -Status TunerDemux::disconnectCiCam() { +::ndk::ScopedAStatus TunerDemux::disconnectCiCam() { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDemux->disconnectCiCam(); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDemux->disconnectCiCam(); } -Status TunerDemux::close() { +::ndk::ScopedAStatus TunerDemux::close() { if (mDemux == nullptr) { ALOGE("IDemux is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDemux->close(); - mDemux = NULL; + auto res = mDemux->close(); + mDemux = nullptr; - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return res; } + +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerDemux.h b/services/tuner/TunerDemux.h index c2f91f0fa9..cdb3aa08c8 100644 --- a/services/tuner/TunerDemux.h +++ b/services/tuner/TunerDemux.h @@ -17,53 +17,55 @@ #ifndef ANDROID_MEDIA_TUNERDEMUX_H #define ANDROID_MEDIA_TUNERDEMUX_H +#include #include -#include -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::media::tv::tuner::BnTunerDemux; -using ::aidl::android::media::tv::tuner::ITunerDvr; -using ::aidl::android::media::tv::tuner::ITunerDvrCallback; -using ::aidl::android::media::tv::tuner::ITunerFilter; -using ::aidl::android::media::tv::tuner::ITunerFilterCallback; -using ::aidl::android::media::tv::tuner::ITunerFrontend; -using ::aidl::android::media::tv::tuner::ITunerTimeFilter; -using ::android::hardware::tv::tuner::V1_0::IDemux; -using ::android::hardware::tv::tuner::V1_0::IDvr; -using ::android::hardware::tv::tuner::V1_0::IDvrCallback; -using ::android::hardware::tv::tuner::V1_0::ITimeFilter; +using ::aidl::android::hardware::tv::tuner::DemuxFilterType; +using ::aidl::android::hardware::tv::tuner::DvrType; +using ::aidl::android::hardware::tv::tuner::IDemux; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { class TunerDemux : public BnTunerDemux { public: - TunerDemux(sp demux, int demuxId); + TunerDemux(shared_ptr demux, int demuxId); virtual ~TunerDemux(); - Status setFrontendDataSource(const shared_ptr& frontend) override; - Status setFrontendDataSourceById(int frontendId) override; - Status openFilter( - int mainType, int subtype, int bufferSize, const shared_ptr& cb, - shared_ptr* _aidl_return) override; - Status openTimeFilter(shared_ptr* _aidl_return) override; - Status getAvSyncHwId(const shared_ptr& tunerFilter, int* _aidl_return) override; - Status getAvSyncTime(int avSyncHwId, int64_t* _aidl_return) override; - Status openDvr( - int dvbType, int bufferSize, const shared_ptr& cb, - shared_ptr* _aidl_return) override; - Status connectCiCam(int ciCamId) override; - Status disconnectCiCam() override; - Status close() override; + + ::ndk::ScopedAStatus setFrontendDataSource( + const shared_ptr& in_frontend) override; + ::ndk::ScopedAStatus setFrontendDataSourceById(int frontendId) override; + ::ndk::ScopedAStatus openFilter(const DemuxFilterType& in_type, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openTimeFilter(shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getAvSyncHwId(const shared_ptr& in_tunerFilter, + int32_t* _aidl_return) override; + ::ndk::ScopedAStatus getAvSyncTime(int32_t in_avSyncHwId, int64_t* _aidl_return) override; + ::ndk::ScopedAStatus openDvr(DvrType in_dvbType, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus connectCiCam(int32_t in_ciCamId) override; + ::ndk::ScopedAStatus disconnectCiCam() override; + ::ndk::ScopedAStatus close() override; int getId() { return mDemuxId; } private: - sp mDemux; + shared_ptr mDemux; int mDemuxId; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERDEMUX_H diff --git a/services/tuner/TunerDescrambler.cpp b/services/tuner/TunerDescrambler.cpp index b7ae1674c0..8e2d6c76cb 100644 --- a/services/tuner/TunerDescrambler.cpp +++ b/services/tuner/TunerDescrambler.cpp @@ -16,17 +16,26 @@ #define LOG_TAG "TunerDescrambler" -#include "TunerFilter.h" -#include "TunerDemux.h" #include "TunerDescrambler.h" -using ::android::hardware::tv::tuner::V1_0::Result; +#include +#include + +#include "TunerDemux.h" +#include "TunerFilter.h" + +using ::aidl::android::hardware::tv::tuner::IFilter; +using ::aidl::android::hardware::tv::tuner::Result; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerDescrambler::TunerDescrambler(sp descrambler) { +TunerDescrambler::TunerDescrambler(shared_ptr descrambler) { mDescrambler = descrambler; } @@ -34,91 +43,74 @@ TunerDescrambler::~TunerDescrambler() { mDescrambler = nullptr; } -Status TunerDescrambler::setDemuxSource(const std::shared_ptr& demux) { +::ndk::ScopedAStatus TunerDescrambler::setDemuxSource( + const shared_ptr& in_tunerDemux) { if (mDescrambler == nullptr) { ALOGE("IDescrambler is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDescrambler->setDemuxSource(static_cast(demux.get())->getId()); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDescrambler->setDemuxSource((static_cast(in_tunerDemux.get()))->getId()); } -Status TunerDescrambler::setKeyToken(const vector& keyToken) { +::ndk::ScopedAStatus TunerDescrambler::setKeyToken(const vector& in_keyToken) { if (mDescrambler == nullptr) { ALOGE("IDescrambler is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDescrambler->setKeyToken(keyToken); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDescrambler->setKeyToken(in_keyToken); } -Status TunerDescrambler::addPid(const TunerDemuxPid& pid, - const shared_ptr& optionalSourceFilter) { +::ndk::ScopedAStatus TunerDescrambler::addPid( + const DemuxPid& in_pid, const shared_ptr& in_optionalSourceFilter) { if (mDescrambler == nullptr) { ALOGE("IDescrambler is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - sp halFilter = (optionalSourceFilter == NULL) - ? NULL : static_cast(optionalSourceFilter.get())->getHalFilter(); - Result res = mDescrambler->addPid(getHidlDemuxPid(pid), halFilter); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + shared_ptr halFilter = + (in_optionalSourceFilter == nullptr) + ? nullptr + : static_cast(in_optionalSourceFilter.get())->getHalFilter(); + + return mDescrambler->addPid(in_pid, halFilter); } -Status TunerDescrambler::removePid(const TunerDemuxPid& pid, - const shared_ptr& optionalSourceFilter) { +::ndk::ScopedAStatus TunerDescrambler::removePid( + const DemuxPid& in_pid, const shared_ptr& in_optionalSourceFilter) { if (mDescrambler == nullptr) { ALOGE("IDescrambler is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - sp halFilter = (optionalSourceFilter == NULL) - ? NULL : static_cast(optionalSourceFilter.get())->getHalFilter(); - Result res = mDescrambler->removePid(getHidlDemuxPid(pid), halFilter); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + shared_ptr halFilter = + (in_optionalSourceFilter == nullptr) + ? nullptr + : static_cast(in_optionalSourceFilter.get())->getHalFilter(); + + return mDescrambler->removePid(in_pid, halFilter); } -Status TunerDescrambler::close() { +::ndk::ScopedAStatus TunerDescrambler::close() { if (mDescrambler == nullptr) { ALOGE("IDescrambler is not initialized."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDescrambler->close(); - mDescrambler = NULL; + auto res = mDescrambler->close(); + mDescrambler = nullptr; - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return res; } -DemuxPid TunerDescrambler::getHidlDemuxPid(const TunerDemuxPid& pid) { - DemuxPid hidlPid; - switch (pid.getTag()) { - case TunerDemuxPid::tPid: { - hidlPid.tPid((uint16_t)pid.get()); - break; - } - case TunerDemuxPid::mmtpPid: { - hidlPid.mmtpPid((uint16_t)pid.get()); - break; - } - } - return hidlPid; -} +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerDescrambler.h b/services/tuner/TunerDescrambler.h index 1970fb71a5..b1d5fb96a5 100644 --- a/services/tuner/TunerDescrambler.h +++ b/services/tuner/TunerDescrambler.h @@ -17,38 +17,43 @@ #ifndef ANDROID_MEDIA_TUNERDESCRAMBLER_H #define ANDROID_MEDIA_TUNERDESCRAMBLER_H +#include #include -#include -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::media::tv::tuner::BnTunerDescrambler; -using ::aidl::android::media::tv::tuner::ITunerDemux; -using ::aidl::android::media::tv::tuner::ITunerFilter; -using ::aidl::android::media::tv::tuner::TunerDemuxPid; -using ::android::hardware::tv::tuner::V1_0::DemuxPid; -using ::android::hardware::tv::tuner::V1_0::IDescrambler; +using ::aidl::android::hardware::tv::tuner::DemuxPid; +using ::aidl::android::hardware::tv::tuner::IDescrambler; +using namespace std; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { class TunerDescrambler : public BnTunerDescrambler { public: - TunerDescrambler(sp descrambler); + TunerDescrambler(shared_ptr descrambler); virtual ~TunerDescrambler(); - Status setDemuxSource(const shared_ptr& demux) override; - Status setKeyToken(const vector& keyToken) override; - Status addPid(const TunerDemuxPid& pid, - const shared_ptr& optionalSourceFilter) override; - Status removePid(const TunerDemuxPid& pid, - const shared_ptr& optionalSourceFilter) override; - Status close() override; -private: - DemuxPid getHidlDemuxPid(const TunerDemuxPid& pid); + ::ndk::ScopedAStatus setDemuxSource(const shared_ptr& in_tunerDemux) override; + ::ndk::ScopedAStatus setKeyToken(const vector& in_keyToken) override; + ::ndk::ScopedAStatus addPid(const DemuxPid& in_pid, + const shared_ptr& in_optionalSourceFilter) override; + ::ndk::ScopedAStatus removePid( + const DemuxPid& in_pid, + const shared_ptr& in_optionalSourceFilter) override; + ::ndk::ScopedAStatus close() override; - sp mDescrambler; +private: + shared_ptr mDescrambler; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERDESCRAMBLER_H diff --git a/services/tuner/TunerDvr.cpp b/services/tuner/TunerDvr.cpp index db4e07be93..fb03b06e44 100644 --- a/services/tuner/TunerDvr.cpp +++ b/services/tuner/TunerDvr.cpp @@ -16,194 +16,151 @@ #define LOG_TAG "TunerDvr" -#include #include "TunerDvr.h" + +#include + #include "TunerFilter.h" -using ::android::hardware::tv::tuner::V1_0::DataFormat; -using ::android::hardware::tv::tuner::V1_0::Result; +using ::aidl::android::hardware::tv::tuner::Result; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerDvr::TunerDvr(sp dvr, int type) { +TunerDvr::TunerDvr(shared_ptr dvr, DvrType type) { mDvr = dvr; - mType = static_cast(type); + mType = type; } TunerDvr::~TunerDvr() { - mDvr = NULL; + mDvr = nullptr; } -Status TunerDvr::getQueueDesc(AidlMQDesc* _aidl_return) { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::getQueueDesc(AidlMQDesc* _aidl_return) { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - MQDesc dvrMQDesc; - Result res; - mDvr->getQueueDesc([&](Result r, const MQDesc& desc) { - dvrMQDesc = desc; - res = r; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - AidlMQDesc aidlMQDesc; - unsafeHidlToAidlMQDescriptor( - dvrMQDesc, &aidlMQDesc); - *_aidl_return = move(aidlMQDesc); - return Status::ok(); + return mDvr->getQueueDesc(_aidl_return); } -Status TunerDvr::configure(const TunerDvrSettings& settings) { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::configure(const DvrSettings& in_settings) { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDvr->configure(getHidlDvrSettingsFromAidl(settings)); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDvr->configure(in_settings); } -Status TunerDvr::attachFilter(const shared_ptr& filter) { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::attachFilter(const shared_ptr& in_filter) { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - ITunerFilter* tunerFilter = filter.get(); - sp hidlFilter = static_cast(tunerFilter)->getHalFilter(); - if (hidlFilter == NULL) { - return Status::fromServiceSpecificError(static_cast(Result::INVALID_ARGUMENT)); + if (in_filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - Result res = mDvr->attachFilter(hidlFilter); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + shared_ptr halFilter = (static_cast(in_filter.get()))->getHalFilter(); + if (halFilter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - return Status::ok(); + + return mDvr->attachFilter(halFilter); } -Status TunerDvr::detachFilter(const shared_ptr& filter) { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::detachFilter(const shared_ptr& in_filter) { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - ITunerFilter* tunerFilter = filter.get(); - sp hidlFilter = static_cast(tunerFilter)->getHalFilter(); - if (hidlFilter == NULL) { - return Status::fromServiceSpecificError(static_cast(Result::INVALID_ARGUMENT)); + if (in_filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - Result res = mDvr->detachFilter(hidlFilter); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + shared_ptr halFilter = (static_cast(in_filter.get()))->getHalFilter(); + if (halFilter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - return Status::ok(); + + return mDvr->detachFilter(halFilter); } -Status TunerDvr::start() { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::start() { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDvr->start(); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDvr->start(); } -Status TunerDvr::stop() { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::stop() { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDvr->stop(); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDvr->stop(); } -Status TunerDvr::flush() { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::flush() { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDvr->flush(); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mDvr->flush(); } -Status TunerDvr::close() { - if (mDvr == NULL) { +::ndk::ScopedAStatus TunerDvr::close() { + if (mDvr == nullptr) { ALOGE("IDvr is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mDvr->close(); - mDvr = NULL; - - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); -} + auto status = mDvr->close(); + mDvr = nullptr; -DvrSettings TunerDvr::getHidlDvrSettingsFromAidl(TunerDvrSettings settings) { - DvrSettings s; - switch (mType) { - case DvrType::PLAYBACK: { - s.playback({ - .statusMask = static_cast(settings.statusMask), - .lowThreshold = static_cast(settings.lowThreshold), - .highThreshold = static_cast(settings.highThreshold), - .dataFormat = static_cast(settings.dataFormat), - .packetSize = static_cast(settings.packetSize), - }); - return s; - } - case DvrType::RECORD: { - s.record({ - .statusMask = static_cast(settings.statusMask), - .lowThreshold = static_cast(settings.lowThreshold), - .highThreshold = static_cast(settings.highThreshold), - .dataFormat = static_cast(settings.dataFormat), - .packetSize = static_cast(settings.packetSize), - }); - return s; - } - default: - break; - } - return s; + return status; } /////////////// IDvrCallback /////////////////////// - -Return TunerDvr::DvrCallback::onRecordStatus(const RecordStatus status) { - if (mTunerDvrCallback != NULL) { - mTunerDvrCallback->onRecordStatus(static_cast(status)); +::ndk::ScopedAStatus TunerDvr::DvrCallback::onRecordStatus(const RecordStatus status) { + if (mTunerDvrCallback != nullptr) { + mTunerDvrCallback->onRecordStatus(status); } - return Void(); + return ndk::ScopedAStatus::ok(); } -Return TunerDvr::DvrCallback::onPlaybackStatus(const PlaybackStatus status) { - if (mTunerDvrCallback != NULL) { - mTunerDvrCallback->onPlaybackStatus(static_cast(status)); +::ndk::ScopedAStatus TunerDvr::DvrCallback::onPlaybackStatus(const PlaybackStatus status) { + if (mTunerDvrCallback != nullptr) { + mTunerDvrCallback->onPlaybackStatus(status); } - return Void(); + return ndk::ScopedAStatus::ok(); } + +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerDvr.h b/services/tuner/TunerDvr.h index a508e99e60..1854d088fb 100644 --- a/services/tuner/TunerDvr.h +++ b/services/tuner/TunerDvr.h @@ -17,81 +17,71 @@ #ifndef ANDROID_MEDIA_TUNERDVR_H #define ANDROID_MEDIA_TUNERDVR_H +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include "TunerFilter.h" -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::hardware::common::fmq::GrantorDescriptor; using ::aidl::android::hardware::common::fmq::MQDescriptor; using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite; -using ::aidl::android::media::tv::tuner::BnTunerDvr; -using ::aidl::android::media::tv::tuner::ITunerDvrCallback; -using ::aidl::android::media::tv::tuner::ITunerFilter; -using ::aidl::android::media::tv::tuner::TunerDvrSettings; - -using ::android::hardware::MQDescriptorSync; -using ::android::hardware::MessageQueue; -using ::android::hardware::Return; -using ::android::hardware::Void; - -using ::android::hardware::tv::tuner::V1_0::DvrSettings; -using ::android::hardware::tv::tuner::V1_0::DvrType; -using ::android::hardware::tv::tuner::V1_0::IDvr; -using ::android::hardware::tv::tuner::V1_0::IDvrCallback; -using ::android::hardware::tv::tuner::V1_0::PlaybackStatus; -using ::android::hardware::tv::tuner::V1_0::RecordStatus; +using ::aidl::android::hardware::tv::tuner::BnDvrCallback; +using ::aidl::android::hardware::tv::tuner::DvrSettings; +using ::aidl::android::hardware::tv::tuner::DvrType; +using ::aidl::android::hardware::tv::tuner::IDvr; +using ::aidl::android::hardware::tv::tuner::PlaybackStatus; +using ::aidl::android::hardware::tv::tuner::RecordStatus; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -using MQDesc = MQDescriptorSync; using AidlMQDesc = MQDescriptor; class TunerDvr : public BnTunerDvr { public: - TunerDvr(sp dvr, int type); + TunerDvr(shared_ptr dvr, DvrType type); ~TunerDvr(); - Status getQueueDesc(AidlMQDesc* _aidl_return) override; + ::ndk::ScopedAStatus getQueueDesc(AidlMQDesc* _aidl_return) override; + ::ndk::ScopedAStatus configure(const DvrSettings& in_settings) override; + ::ndk::ScopedAStatus attachFilter(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus detachFilter(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus start() override; + ::ndk::ScopedAStatus stop() override; + ::ndk::ScopedAStatus flush() override; + ::ndk::ScopedAStatus close() override; - Status configure(const TunerDvrSettings& settings) override; - - Status attachFilter(const shared_ptr& filter) override; - - Status detachFilter(const shared_ptr& filter) override; - - Status start() override; - - Status stop() override; - - Status flush() override; - - Status close() override; - - struct DvrCallback : public IDvrCallback { + struct DvrCallback : public BnDvrCallback { DvrCallback(const shared_ptr tunerDvrCallback) - : mTunerDvrCallback(tunerDvrCallback) {}; + : mTunerDvrCallback(tunerDvrCallback){}; - virtual Return onRecordStatus(const RecordStatus status); - virtual Return onPlaybackStatus(const PlaybackStatus status); + ::ndk::ScopedAStatus onRecordStatus(const RecordStatus status) override; + ::ndk::ScopedAStatus onPlaybackStatus(const PlaybackStatus status) override; - private: - shared_ptr mTunerDvrCallback; + private: + shared_ptr mTunerDvrCallback; }; private: - DvrSettings getHidlDvrSettingsFromAidl(TunerDvrSettings settings); - - sp mDvr; + shared_ptr mDvr; DvrType mType; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERDVR_H diff --git a/services/tuner/TunerFilter.cpp b/services/tuner/TunerFilter.cpp index 039fd3114a..005445a578 100644 --- a/services/tuner/TunerFilter.cpp +++ b/services/tuner/TunerFilter.cpp @@ -18,893 +18,205 @@ #include "TunerFilter.h" -using ::aidl::android::media::tv::tuner::TunerFilterSectionCondition; - -using ::android::hardware::hidl_handle; -using ::android::hardware::tv::tuner::V1_0::DemuxAlpLengthType; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; -using ::android::hardware::tv::tuner::V1_0::DemuxIpAddress; -using ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxMmtpPid; -using ::android::hardware::tv::tuner::V1_0::DemuxRecordScIndexType; -using ::android::hardware::tv::tuner::V1_0::DemuxStreamId; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; -using ::android::hardware::tv::tuner::V1_0::Result; -using ::android::hardware::tv::tuner::V1_1::AudioStreamType; -using ::android::hardware::tv::tuner::V1_1::Constant; -using ::android::hardware::tv::tuner::V1_1::VideoStreamType; +#include +using ::aidl::android::hardware::tv::tuner::Result; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { using namespace std; -TunerFilter::TunerFilter( - sp filter, int mainType, int subType) { - mFilter = filter; - mFilter_1_1 = ::android::hardware::tv::tuner::V1_1::IFilter::castFrom(filter); - mMainType = mainType; - mSubType = subType; -} +TunerFilter::TunerFilter(shared_ptr filter, DemuxFilterType type) + : mFilter(filter), mType(type) {} TunerFilter::~TunerFilter() { mFilter = nullptr; - mFilter_1_1 = nullptr; } -Status TunerFilter::getQueueDesc(AidlMQDesc* _aidl_return) { - if (mFilter == NULL) { +::ndk::ScopedAStatus TunerFilter::getQueueDesc(AidlMQDesc* _aidl_return) { + if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - MQDesc filterMQDesc; - Result res; - mFilter->getQueueDesc([&](Result r, const MQDesc& desc) { - filterMQDesc = desc; - res = r; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - AidlMQDesc aidlMQDesc; - unsafeHidlToAidlMQDescriptor( - filterMQDesc, &aidlMQDesc); - *_aidl_return = move(aidlMQDesc); - return Status::ok(); + return mFilter->getQueueDesc(_aidl_return); } -Status TunerFilter::getId(int32_t* _aidl_return) { +::ndk::ScopedAStatus TunerFilter::getId(int32_t* _aidl_return) { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res; - mFilter->getId([&](Result r, uint32_t filterId) { - res = r; - mId = filterId; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + auto status = mFilter->getId(&mId); + if (status.isOk()) { + *_aidl_return = mId; } - *_aidl_return = mId; - return Status::ok(); + return status; } -Status TunerFilter::getId64Bit(int64_t* _aidl_return) { - if (mFilter_1_1 == nullptr) { - ALOGE("IFilter_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result res; - mFilter_1_1->getId64Bit([&](Result r, uint64_t filterId) { - res = r; - mId64Bit = filterId; - }); - if (res != Result::SUCCESS) { - return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); - } - *_aidl_return = mId64Bit; - return Status::ok(); -} - -Status TunerFilter::configure(const TunerFilterConfiguration& config) { +::ndk::ScopedAStatus TunerFilter::getId64Bit(int64_t* _aidl_return) { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - DemuxFilterSettings settings; - switch (config.getTag()) { - case TunerFilterConfiguration::ts: { - getHidlTsSettings(config, settings); - break; - } - case TunerFilterConfiguration::mmtp: { - getHidlMmtpSettings(config, settings); - break; - } - case TunerFilterConfiguration::ip: { - getHidlIpSettings(config, settings); - break; - } - case TunerFilterConfiguration::tlv: { - getHidlTlvSettings(config, settings); - break; - } - case TunerFilterConfiguration::alp: { - getHidlAlpSettings(config, settings); - break; - } - } - - Result res = mFilter->configure(settings); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); -} - -Status TunerFilter::configureMonitorEvent(int monitorEventType) { - if (mFilter_1_1 == nullptr) { - ALOGE("IFilter_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result res = mFilter_1_1->configureMonitorEvent(monitorEventType); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); -} - -Status TunerFilter::configureIpFilterContextId(int cid) { - if (mFilter_1_1 == nullptr) { - ALOGE("IFilter_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mFilter_1_1->configureIpCid(cid); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + auto status = mFilter->getId64Bit(&mId64Bit); + if (status.isOk()) { + *_aidl_return = mId64Bit; } - return Status::ok(); + return status; } -Status TunerFilter::configureAvStreamType(int avStreamType) { - if (mFilter_1_1 == nullptr) { - ALOGE("IFilter_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - AvStreamType type; - if (!getHidlAvStreamType(avStreamType, type)) { - return Status::fromServiceSpecificError(static_cast(Result::INVALID_STATE)); - } - - Result res = mFilter_1_1->configureAvStreamType(type); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); -} - -Status TunerFilter::setDataSource(const shared_ptr& filter) { +::ndk::ScopedAStatus TunerFilter::configure(const DemuxFilterSettings& in_settings) { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - ITunerFilter* tunerFilter = filter.get(); - sp hidlFilter = static_cast(tunerFilter)->getHalFilter(); - Result res = mFilter->setDataSource(hidlFilter); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::ok(); -} -void TunerFilter::getHidlTsSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings) { - auto tsConf = config.get(); - DemuxTsFilterSettings ts{ - .tpid = static_cast(tsConf.tpid), - }; - - TunerFilterSettings tunerSettings = tsConf.filterSettings; - switch (tunerSettings.getTag()) { - case TunerFilterSettings::av: { - ts.filterSettings.av(getAvSettings(tunerSettings)); - break; - } - case TunerFilterSettings::section: { - ts.filterSettings.section(getSectionSettings(tunerSettings)); - break; - } - case TunerFilterSettings::pesData: { - ts.filterSettings.pesData(getPesDataSettings(tunerSettings)); - break; - } - case TunerFilterSettings::record: { - ts.filterSettings.record(getRecordSettings(tunerSettings)); - break; - } - default: { - ts.filterSettings.noinit(); - break; - } - } - settings.ts(ts); + return mFilter->configure(in_settings); } -void TunerFilter::getHidlMmtpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings) { - auto mmtpConf = config.get(); - DemuxMmtpFilterSettings mmtp{ - .mmtpPid = static_cast(mmtpConf.mmtpPid), - }; - - TunerFilterSettings tunerSettings = mmtpConf.filterSettings; - switch (tunerSettings.getTag()) { - case TunerFilterSettings::av: { - mmtp.filterSettings.av(getAvSettings(tunerSettings)); - break; - } - case TunerFilterSettings::section: { - mmtp.filterSettings.section(getSectionSettings(tunerSettings)); - break; - } - case TunerFilterSettings::pesData: { - mmtp.filterSettings.pesData(getPesDataSettings(tunerSettings)); - break; - } - case TunerFilterSettings::record: { - mmtp.filterSettings.record(getRecordSettings(tunerSettings)); - break; - } - case TunerFilterSettings::download: { - mmtp.filterSettings.download(getDownloadSettings(tunerSettings)); - break; - } - default: { - mmtp.filterSettings.noinit(); - break; - } +::ndk::ScopedAStatus TunerFilter::configureMonitorEvent(int32_t monitorEventType) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - settings.mmtp(mmtp); -} -void TunerFilter::getHidlIpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings) { - auto ipConf = config.get(); - DemuxIpAddress ipAddr{ - .srcPort = static_cast(ipConf.ipAddr.srcPort), - .dstPort = static_cast(ipConf.ipAddr.dstPort), - }; - - ipConf.ipAddr.srcIpAddress.isIpV6 - ? ipAddr.srcIpAddress.v6(getIpV6Address(ipConf.ipAddr.srcIpAddress)) - : ipAddr.srcIpAddress.v4(getIpV4Address(ipConf.ipAddr.srcIpAddress)); - ipConf.ipAddr.dstIpAddress.isIpV6 - ? ipAddr.dstIpAddress.v6(getIpV6Address(ipConf.ipAddr.dstIpAddress)) - : ipAddr.dstIpAddress.v4(getIpV4Address(ipConf.ipAddr.dstIpAddress)); - DemuxIpFilterSettings ip{ - .ipAddr = ipAddr, - }; - - TunerFilterSettings tunerSettings = ipConf.filterSettings; - switch (tunerSettings.getTag()) { - case TunerFilterSettings::section: { - ip.filterSettings.section(getSectionSettings(tunerSettings)); - break; - } - case TunerFilterSettings::isPassthrough: { - ip.filterSettings.bPassthrough(tunerSettings.isPassthrough); - break; - } - default: { - ip.filterSettings.noinit(); - break; - } - } - settings.ip(ip); + return mFilter->configureMonitorEvent(monitorEventType); } -hidl_array TunerFilter::getIpV6Address(TunerDemuxIpAddress addr) { - hidl_array ip; - if (addr.addr.size() != IP_V6_LENGTH) { - return ip; - } - copy(addr.addr.begin(), addr.addr.end(), ip.data()); - return ip; -} - -hidl_array TunerFilter::getIpV4Address(TunerDemuxIpAddress addr) { - hidl_array ip; - if (addr.addr.size() != IP_V4_LENGTH) { - return ip; +::ndk::ScopedAStatus TunerFilter::configureIpFilterContextId(int32_t cid) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - copy(addr.addr.begin(), addr.addr.end(), ip.data()); - return ip; -} -void TunerFilter::getHidlTlvSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings) { - auto tlvConf = config.get(); - DemuxTlvFilterSettings tlv{ - .packetType = static_cast(tlvConf.packetType), - .isCompressedIpPacket = tlvConf.isCompressedIpPacket, - }; - - TunerFilterSettings tunerSettings = tlvConf.filterSettings; - switch (tunerSettings.getTag()) { - case TunerFilterSettings::section: { - tlv.filterSettings.section(getSectionSettings(tunerSettings)); - break; - } - case TunerFilterSettings::isPassthrough: { - tlv.filterSettings.bPassthrough(tunerSettings.isPassthrough); - break; - } - default: { - tlv.filterSettings.noinit(); - break; - } - } - settings.tlv(tlv); + return mFilter->configureIpCid(cid); } -void TunerFilter::getHidlAlpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings) { - auto alpConf = config.get(); - DemuxAlpFilterSettings alp{ - .packetType = static_cast(alpConf.packetType), - .lengthType = static_cast(alpConf.lengthType), - }; - - TunerFilterSettings tunerSettings = alpConf.filterSettings; - switch (tunerSettings.getTag()) { - case TunerFilterSettings::section: { - alp.filterSettings.section(getSectionSettings(tunerSettings)); - break; - } - default: { - alp.filterSettings.noinit(); - break; - } +::ndk::ScopedAStatus TunerFilter::configureAvStreamType(const AvStreamType& in_avStreamType) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - settings.alp(alp); -} -DemuxFilterAvSettings TunerFilter::getAvSettings(const TunerFilterSettings& settings) { - DemuxFilterAvSettings av { - .isPassthrough = settings.get().isPassthrough, - }; - return av; + return mFilter->configureAvStreamType(in_avStreamType); } -DemuxFilterSectionSettings TunerFilter::getSectionSettings(const TunerFilterSettings& settings) { - auto s = settings.get(); - DemuxFilterSectionSettings section{ - .isCheckCrc = s.isCheckCrc, - .isRepeat = s.isRepeat, - .isRaw = s.isRaw, - }; - - switch (s.condition.getTag()) { - case TunerFilterSectionCondition::sectionBits: { - auto sectionBits = s.condition.get(); - vector filter(sectionBits.filter.begin(), sectionBits.filter.end()); - vector mask(sectionBits.mask.begin(), sectionBits.mask.end()); - vector mode(sectionBits.mode.begin(), sectionBits.mode.end()); - section.condition.sectionBits({ - .filter = filter, - .mask = mask, - .mode = mode, - }); - break; - } - case TunerFilterSectionCondition::tableInfo: { - auto tableInfo = s.condition.get(); - section.condition.tableInfo({ - .tableId = static_cast(tableInfo.tableId), - .version = static_cast(tableInfo.version), - }); - break; - } - default: { - break; - } +::ndk::ScopedAStatus TunerFilter::setDataSource(const shared_ptr& filter) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return section; -} - -DemuxFilterPesDataSettings TunerFilter::getPesDataSettings(const TunerFilterSettings& settings) { - DemuxFilterPesDataSettings pes{ - .streamId = static_cast( - settings.get().streamId), - .isRaw = settings.get().isRaw, - }; - return pes; -} -DemuxFilterRecordSettings TunerFilter::getRecordSettings(const TunerFilterSettings& settings) { - auto r = settings.get(); - DemuxFilterRecordSettings record{ - .tsIndexMask = static_cast(r.tsIndexMask), - .scIndexType = static_cast(r.scIndexType), - }; - - switch (r.scIndexMask.getTag()) { - case TunerFilterScIndexMask::sc: { - record.scIndexMask.sc(static_cast( - r.scIndexMask.get())); - break; - } - case TunerFilterScIndexMask::scHevc: { - record.scIndexMask.scHevc(static_cast( - r.scIndexMask.get())); - break; - } + if (filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - return record; -} -DemuxFilterDownloadSettings TunerFilter::getDownloadSettings(const TunerFilterSettings& settings) { - DemuxFilterDownloadSettings download { - .downloadId = static_cast( - settings.get().downloadId), - }; - return download; + shared_ptr halFilter = static_cast(filter.get())->getHalFilter(); + return mFilter->setDataSource(halFilter); } -Status TunerFilter::getAvSharedHandleInfo(TunerFilterSharedHandleInfo* _aidl_return) { - if (mFilter_1_1 == nullptr) { - ALOGE("IFilter_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); +::ndk::ScopedAStatus TunerFilter::getAvSharedHandle(NativeHandle* out_avMemory, + int64_t* _aidl_return) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res; - mFilter_1_1->getAvSharedHandle([&](Result r, hidl_handle avMemory, uint64_t avMemSize) { - res = r; - if (res == Result::SUCCESS) { - TunerFilterSharedHandleInfo info{ - .handle = dupToAidl(avMemory), - .size = static_cast(avMemSize), - }; - *_aidl_return = move(info); - } else { - _aidl_return = NULL; - } - }); - - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mFilter->getAvSharedHandle(out_avMemory, _aidl_return); } -Status TunerFilter::releaseAvHandle( - const ::aidl::android::hardware::common::NativeHandle& handle, int64_t avDataId) { +::ndk::ScopedAStatus TunerFilter::releaseAvHandle(const NativeHandle& in_handle, + int64_t in_avDataId) { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mFilter->releaseAvHandle(hidl_handle(makeFromAidl(handle)), avDataId); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return mFilter->releaseAvHandle(in_handle, in_avDataId); } -Status TunerFilter::start() { +::ndk::ScopedAStatus TunerFilter::start() { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mFilter->start(); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + + return mFilter->start(); } -Status TunerFilter::stop() { +::ndk::ScopedAStatus TunerFilter::stop() { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - Result res = mFilter->stop(); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::ok(); + + return mFilter->stop(); } -Status TunerFilter::flush() { +::ndk::ScopedAStatus TunerFilter::flush() { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - Result res = mFilter->flush(); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::ok(); + + return mFilter->flush(); } -Status TunerFilter::close() { +::ndk::ScopedAStatus TunerFilter::close() { if (mFilter == nullptr) { ALOGE("IFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mFilter->close(); - mFilter = NULL; - mFilter_1_1 = NULL; + auto res = mFilter->close(); + mFilter = nullptr; - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return res; } -sp TunerFilter::getHalFilter() { +shared_ptr TunerFilter::getHalFilter() { return mFilter; } -bool TunerFilter::isAudioFilter() { - return (mMainType == (int)DemuxFilterMainType::TS - && mSubType == (int)DemuxTsFilterType::AUDIO) - || (mMainType == (int)DemuxFilterMainType::MMTP - && mSubType == (int)DemuxMmtpFilterType::AUDIO); -} - -bool TunerFilter::isVideoFilter() { - return (mMainType == (int)DemuxFilterMainType::TS - && mSubType == (int)DemuxTsFilterType::VIDEO) - || (mMainType == (int)DemuxFilterMainType::MMTP - && mSubType == (int)DemuxMmtpFilterType::VIDEO); -} - -bool TunerFilter::getHidlAvStreamType(int avStreamType, AvStreamType& type) { - if (isAudioFilter()) { - type.audio(static_cast(avStreamType)); - return true; - } - - if (isVideoFilter()) { - type.video(static_cast(avStreamType)); - return true; - } - - return false; -} - /////////////// FilterCallback /////////////////////// - -Return TunerFilter::FilterCallback::onFilterStatus(DemuxFilterStatus status) { - if (mTunerFilterCallback != NULL) { - mTunerFilterCallback->onFilterStatus((int)status); +::ndk::ScopedAStatus TunerFilter::FilterCallback::onFilterStatus(DemuxFilterStatus status) { + if (mTunerFilterCallback != nullptr) { + mTunerFilterCallback->onFilterStatus(status); } - return Void(); -} - -Return TunerFilter::FilterCallback::onFilterEvent(const DemuxFilterEvent& filterEvent) { - vector emptyEventsExt; - DemuxFilterEventExt emptyFilterEventExt { - .events = emptyEventsExt, - }; - onFilterEvent_1_1(filterEvent, emptyFilterEventExt); - return Void(); + return ::ndk::ScopedAStatus::ok(); } -Return TunerFilter::FilterCallback::onFilterEvent_1_1(const DemuxFilterEvent& filterEvent, - const DemuxFilterEventExt& filterEventExt) { - if (mTunerFilterCallback != NULL) { - vector events = filterEvent.events; - vector eventsExt = filterEventExt.events; - vector tunerEvent; - - getAidlFilterEvent(events, eventsExt, tunerEvent); - mTunerFilterCallback->onFilterEvent(tunerEvent); +::ndk::ScopedAStatus TunerFilter::FilterCallback::onFilterEvent( + const vector& events) { + if (mTunerFilterCallback != nullptr) { + mTunerFilterCallback->onFilterEvent(events); } - return Void(); + return ::ndk::ScopedAStatus::ok(); } -/////////////// FilterCallback Helper Methods /////////////////////// - -void TunerFilter::FilterCallback::getAidlFilterEvent(vector& events, - vector& eventsExt, - vector& tunerEvent) { - if (events.empty() && !eventsExt.empty()) { - auto eventExt = eventsExt[0]; - switch (eventExt.getDiscriminator()) { - case DemuxFilterEventExt::Event::hidl_discriminator::monitorEvent: { - getMonitorEvent(eventsExt, tunerEvent); - return; - } - case DemuxFilterEventExt::Event::hidl_discriminator::startId: { - getRestartEvent(eventsExt, tunerEvent); - return; - } - default: { - break; - } - } - return; - } - - if (!events.empty()) { - auto event = events[0]; - switch (event.getDiscriminator()) { - case DemuxFilterEvent::Event::hidl_discriminator::media: { - getMediaEvent(events, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::section: { - getSectionEvent(events, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::pes: { - getPesEvent(events, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::tsRecord: { - getTsRecordEvent(events, eventsExt, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::mmtpRecord: { - getMmtpRecordEvent(events, eventsExt, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::download: { - getDownloadEvent(events, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::ipPayload: { - getIpPayloadEvent(events, tunerEvent); - break; - } - case DemuxFilterEvent::Event::hidl_discriminator::temi: { - getTemiEvent(events, tunerEvent); - break; - } - default: { - break; - } - } - } -} - -void TunerFilter::FilterCallback::getMediaEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterMediaEvent mediaEvent = e.media(); - TunerFilterMediaEvent tunerMedia; - - tunerMedia.streamId = static_cast(mediaEvent.streamId); - tunerMedia.isPtsPresent = mediaEvent.isPtsPresent; - tunerMedia.pts = static_cast(mediaEvent.pts); - tunerMedia.dataLength = static_cast(mediaEvent.dataLength); - tunerMedia.offset = static_cast(mediaEvent.offset); - tunerMedia.isSecureMemory = mediaEvent.isSecureMemory; - tunerMedia.avDataId = static_cast(mediaEvent.avDataId); - tunerMedia.mpuSequenceNumber = static_cast(mediaEvent.mpuSequenceNumber); - tunerMedia.isPesPrivateData = mediaEvent.isPesPrivateData; - - if (mediaEvent.extraMetaData.getDiscriminator() == - DemuxFilterMediaEvent::ExtraMetaData::hidl_discriminator::audio) { - tunerMedia.isAudioExtraMetaData = true; - tunerMedia.audio = { - .adFade = static_cast( - mediaEvent.extraMetaData.audio().adFade), - .adPan = static_cast( - mediaEvent.extraMetaData.audio().adPan), - .versionTextTag = static_cast( - mediaEvent.extraMetaData.audio().versionTextTag), - .adGainCenter = static_cast( - mediaEvent.extraMetaData.audio().adGainCenter), - .adGainFront = static_cast( - mediaEvent.extraMetaData.audio().adGainFront), - .adGainSurround = static_cast( - mediaEvent.extraMetaData.audio().adGainSurround), - }; - } else { - tunerMedia.isAudioExtraMetaData = false; - } - - if (mediaEvent.avMemory.getNativeHandle() != nullptr) { - tunerMedia.avMemory = dupToAidl(mediaEvent.avMemory.getNativeHandle()); - } - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerMedia)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getSectionEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterSectionEvent sectionEvent = e.section(); - TunerFilterSectionEvent tunerSection; - - tunerSection.tableId = static_cast(sectionEvent.tableId); - tunerSection.version = static_cast(sectionEvent.version); - tunerSection.sectionNum = static_cast(sectionEvent.sectionNum); - tunerSection.dataLength = static_cast(sectionEvent.dataLength); - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerSection)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getPesEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterPesEvent pesEvent = e.pes(); - TunerFilterPesEvent tunerPes; - - tunerPes.streamId = static_cast(pesEvent.streamId); - tunerPes.dataLength = static_cast(pesEvent.dataLength); - tunerPes.mpuSequenceNumber = static_cast(pesEvent.mpuSequenceNumber); - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerPes)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getTsRecordEvent(vector& events, - vector& eventsExt, vector& res) { - for (int i = 0; i < events.size(); i++) { - TunerFilterTsRecordEvent tunerTsRecord; - DemuxFilterTsRecordEvent tsRecordEvent = events[i].tsRecord(); - - TunerFilterScIndexMask scIndexMask; - if (tsRecordEvent.scIndexMask.getDiscriminator() - == DemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::sc) { - scIndexMask.set( - static_cast(tsRecordEvent.scIndexMask.sc())); - } else if (tsRecordEvent.scIndexMask.getDiscriminator() - == DemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::scHevc) { - scIndexMask.set( - static_cast(tsRecordEvent.scIndexMask.scHevc())); - } - - if (tsRecordEvent.pid.getDiscriminator() == DemuxPid::hidl_discriminator::tPid) { - tunerTsRecord.pid = static_cast(tsRecordEvent.pid.tPid()); - } else { - tunerTsRecord.pid = static_cast(Constant::INVALID_TS_PID); - } - - tunerTsRecord.scIndexMask = scIndexMask; - tunerTsRecord.tsIndexMask = static_cast(tsRecordEvent.tsIndexMask); - tunerTsRecord.byteNumber = static_cast(tsRecordEvent.byteNumber); - - if (eventsExt.size() > i && eventsExt[i].getDiscriminator() == - DemuxFilterEventExt::Event::hidl_discriminator::tsRecord) { - tunerTsRecord.isExtended = true; - tunerTsRecord.pts = static_cast(eventsExt[i].tsRecord().pts); - tunerTsRecord.firstMbInSlice = static_cast(eventsExt[i].tsRecord().firstMbInSlice); - } else { - tunerTsRecord.isExtended = false; - } - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerTsRecord)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getMmtpRecordEvent(vector& events, - vector& eventsExt, vector& res) { - for (int i = 0; i < events.size(); i++) { - TunerFilterMmtpRecordEvent tunerMmtpRecord; - DemuxFilterMmtpRecordEvent mmtpRecordEvent = events[i].mmtpRecord(); - - tunerMmtpRecord.scHevcIndexMask = static_cast(mmtpRecordEvent.scHevcIndexMask); - tunerMmtpRecord.byteNumber = static_cast(mmtpRecordEvent.byteNumber); - - if (eventsExt.size() > i && eventsExt[i].getDiscriminator() == - DemuxFilterEventExt::Event::hidl_discriminator::mmtpRecord) { - tunerMmtpRecord.isExtended = true; - tunerMmtpRecord.pts = static_cast(eventsExt[i].mmtpRecord().pts); - tunerMmtpRecord.mpuSequenceNumber = - static_cast(eventsExt[i].mmtpRecord().mpuSequenceNumber); - tunerMmtpRecord.firstMbInSlice = - static_cast(eventsExt[i].mmtpRecord().firstMbInSlice); - tunerMmtpRecord.tsIndexMask = static_cast(eventsExt[i].mmtpRecord().tsIndexMask); - } else { - tunerMmtpRecord.isExtended = false; - } - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerMmtpRecord)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getDownloadEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterDownloadEvent downloadEvent = e.download(); - TunerFilterDownloadEvent tunerDownload; - - tunerDownload.itemId = static_cast(downloadEvent.itemId); - tunerDownload.itemFragmentIndex = static_cast(downloadEvent.itemFragmentIndex); - tunerDownload.mpuSequenceNumber = static_cast(downloadEvent.mpuSequenceNumber); - tunerDownload.lastItemFragmentIndex = static_cast(downloadEvent.lastItemFragmentIndex); - tunerDownload.dataLength = static_cast(downloadEvent.dataLength); - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerDownload)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getIpPayloadEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterIpPayloadEvent ipPayloadEvent = e.ipPayload(); - TunerFilterIpPayloadEvent tunerIpPayload; - - tunerIpPayload.dataLength = static_cast(ipPayloadEvent.dataLength); - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerIpPayload)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getTemiEvent( - vector& events, vector& res) { - for (DemuxFilterEvent::Event e : events) { - DemuxFilterTemiEvent temiEvent = e.temi(); - TunerFilterTemiEvent tunerTemi; - - tunerTemi.pts = static_cast(temiEvent.pts); - tunerTemi.descrTag = static_cast(temiEvent.descrTag); - vector descrData = temiEvent.descrData; - tunerTemi.descrData.resize(descrData.size()); - copy(descrData.begin(), descrData.end(), tunerTemi.descrData.begin()); - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerTemi)); - res.push_back(move(tunerEvent)); - } -} - -void TunerFilter::FilterCallback::getMonitorEvent( - vector& eventsExt, vector& res) { - DemuxFilterMonitorEvent monitorEvent = eventsExt[0].monitorEvent(); - TunerFilterMonitorEvent tunerMonitor; - - switch (monitorEvent.getDiscriminator()) { - case DemuxFilterMonitorEvent::hidl_discriminator::scramblingStatus: { - tunerMonitor.set( - static_cast(monitorEvent.scramblingStatus())); - break; - } - case DemuxFilterMonitorEvent::hidl_discriminator::cid: { - tunerMonitor.set(static_cast(monitorEvent.cid())); - break; - } - } - - TunerFilterEvent tunerEvent; - tunerEvent.set(move(tunerMonitor)); - res.push_back(move(tunerEvent)); -} - -void TunerFilter::FilterCallback::getRestartEvent( - vector& eventsExt, vector& res) { - TunerFilterEvent tunerEvent; - tunerEvent.set(static_cast(eventsExt[0].startId())); - res.push_back(move(tunerEvent)); -} +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerFilter.h b/services/tuner/TunerFilter.h index ff4728c010..86d178c62f 100644 --- a/services/tuner/TunerFilter.h +++ b/services/tuner/TunerFilter.h @@ -17,176 +17,90 @@ #ifndef ANDROID_MEDIA_TUNERFILTER_H #define ANDROID_MEDIA_TUNERFILTER_H +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include #include -#include -#include -using Status = ::ndk::ScopedAStatus; +using ::aidl::android::hardware::common::NativeHandle; using ::aidl::android::hardware::common::fmq::MQDescriptor; using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite; +using ::aidl::android::hardware::tv::tuner::AvStreamType; +using ::aidl::android::hardware::tv::tuner::BnFilterCallback; +using ::aidl::android::hardware::tv::tuner::DemuxFilterEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterStatus; +using ::aidl::android::hardware::tv::tuner::DemuxFilterType; +using ::aidl::android::hardware::tv::tuner::IFilter; using ::aidl::android::media::tv::tuner::BnTunerFilter; -using ::aidl::android::media::tv::tuner::ITunerFilterCallback; -using ::aidl::android::media::tv::tuner::TunerDemuxIpAddress; -using ::aidl::android::media::tv::tuner::TunerFilterConfiguration; -using ::aidl::android::media::tv::tuner::TunerFilterDownloadEvent; -using ::aidl::android::media::tv::tuner::TunerFilterIpPayloadEvent; -using ::aidl::android::media::tv::tuner::TunerFilterEvent; -using ::aidl::android::media::tv::tuner::TunerFilterMediaEvent; -using ::aidl::android::media::tv::tuner::TunerFilterMmtpRecordEvent; -using ::aidl::android::media::tv::tuner::TunerFilterMonitorEvent; -using ::aidl::android::media::tv::tuner::TunerFilterPesEvent; -using ::aidl::android::media::tv::tuner::TunerFilterScIndexMask; -using ::aidl::android::media::tv::tuner::TunerFilterSectionEvent; -using ::aidl::android::media::tv::tuner::TunerFilterSharedHandleInfo; -using ::aidl::android::media::tv::tuner::TunerFilterSettings; -using ::aidl::android::media::tv::tuner::TunerFilterTemiEvent; -using ::aidl::android::media::tv::tuner::TunerFilterTsRecordEvent; -using ::android::hardware::MQDescriptorSync; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_array; -using ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterIpPayloadEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMediaEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMmtpRecordEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterPesDataSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterPesEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterRecordSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterTemiEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterTsRecordEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxIpFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxTlvFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxPid; -using ::android::hardware::tv::tuner::V1_0::IFilter; -using ::android::hardware::tv::tuner::V1_1::AvStreamType; -using ::android::hardware::tv::tuner::V1_1::DemuxFilterEventExt; -using ::android::hardware::tv::tuner::V1_1::DemuxFilterMonitorEvent; -using ::android::hardware::tv::tuner::V1_1::DemuxFilterTsRecordEventExt; -using ::android::hardware::tv::tuner::V1_1::IFilterCallback; +using namespace std; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -using MQDesc = MQDescriptorSync; using AidlMQDesc = MQDescriptor; -const static int IP_V4_LENGTH = 4; -const static int IP_V6_LENGTH = 16; - class TunerFilter : public BnTunerFilter { public: - TunerFilter(sp filter, int mainType, int subTyp); + TunerFilter(shared_ptr filter, DemuxFilterType type); virtual ~TunerFilter(); - Status getId(int32_t* _aidl_return) override; - Status getId64Bit(int64_t* _aidl_return) override; - Status getQueueDesc(AidlMQDesc* _aidl_return) override; - Status configure(const TunerFilterConfiguration& config) override; - Status configureMonitorEvent(int monitorEventType) override; - Status configureIpFilterContextId(int cid) override; - Status configureAvStreamType(int avStreamType) override; - Status getAvSharedHandleInfo(TunerFilterSharedHandleInfo* _aidl_return) override; - Status releaseAvHandle(const ::aidl::android::hardware::common::NativeHandle& handle, - int64_t avDataId) override; - Status setDataSource(const std::shared_ptr& filter) override; - Status start() override; - Status stop() override; - Status flush() override; - Status close() override; - sp getHalFilter(); - - struct FilterCallback : public IFilterCallback { - FilterCallback(const std::shared_ptr tunerFilterCallback) - : mTunerFilterCallback(tunerFilterCallback) {}; - - virtual Return onFilterEvent(const DemuxFilterEvent& filterEvent); - virtual Return onFilterEvent_1_1(const DemuxFilterEvent& filterEvent, - const DemuxFilterEventExt& filterEventExt); - virtual Return onFilterStatus(DemuxFilterStatus status); - - void getAidlFilterEvent(std::vector& events, - std::vector& eventsExt, - std::vector& tunerEvent); - - void getMediaEvent( - std::vector& events, std::vector& res); - void getSectionEvent( - std::vector& events, std::vector& res); - void getPesEvent( - std::vector& events, std::vector& res); - void getTsRecordEvent( - std::vector& events, - std::vector& eventsExt, - std::vector& res); - void getMmtpRecordEvent( - std::vector& events, - std::vector& eventsExt, - std::vector& res); - void getDownloadEvent( - std::vector& events, std::vector& res); - void getIpPayloadEvent( - std::vector& events, std::vector& res); - void getTemiEvent( - std::vector& events, std::vector& res); - void getMonitorEvent( - std::vector& eventsExt, - std::vector& res); - void getRestartEvent( - std::vector& eventsExt, - std::vector& res); - - std::shared_ptr mTunerFilterCallback; + + ::ndk::ScopedAStatus getId(int32_t* _aidl_return) override; + ::ndk::ScopedAStatus getId64Bit(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus getQueueDesc(AidlMQDesc* _aidl_return) override; + ::ndk::ScopedAStatus configure(const DemuxFilterSettings& in_settings) override; + ::ndk::ScopedAStatus configureMonitorEvent(int32_t in_monitorEventTypes) override; + ::ndk::ScopedAStatus configureIpFilterContextId(int32_t in_cid) override; + ::ndk::ScopedAStatus configureAvStreamType(const AvStreamType& in_avStreamType) override; + ::ndk::ScopedAStatus getAvSharedHandle(NativeHandle* out_avMemory, + int64_t* _aidl_return) override; + ::ndk::ScopedAStatus releaseAvHandle(const NativeHandle& in_handle, + int64_t in_avDataId) override; + ::ndk::ScopedAStatus setDataSource(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus start() override; + ::ndk::ScopedAStatus stop() override; + ::ndk::ScopedAStatus flush() override; + ::ndk::ScopedAStatus close() override; + + shared_ptr getHalFilter(); + + class FilterCallback : public BnFilterCallback { + public: + FilterCallback(const shared_ptr tunerFilterCallback) + : mTunerFilterCallback(tunerFilterCallback){}; + + ::ndk::ScopedAStatus onFilterEvent(const vector& events) override; + ::ndk::ScopedAStatus onFilterStatus(DemuxFilterStatus status) override; + + private: + shared_ptr mTunerFilterCallback; }; private: - DemuxFilterAvSettings getAvSettings(const TunerFilterSettings& settings); - DemuxFilterSectionSettings getSectionSettings(const TunerFilterSettings& settings); - DemuxFilterPesDataSettings getPesDataSettings(const TunerFilterSettings& settings); - DemuxFilterRecordSettings getRecordSettings(const TunerFilterSettings& settings); - DemuxFilterDownloadSettings getDownloadSettings(const TunerFilterSettings& settings); - bool isAudioFilter(); bool isVideoFilter(); - bool getHidlAvStreamType(int avStreamType, AvStreamType& type); - - void getHidlTsSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings); - void getHidlMmtpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings); - void getHidlIpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings); - void getHidlTlvSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings); - void getHidlAlpSettings( - const TunerFilterConfiguration& config, DemuxFilterSettings& settings); - - hidl_array getIpV4Address(TunerDemuxIpAddress addr); - hidl_array getIpV6Address(TunerDemuxIpAddress addr); - - sp mFilter; - sp<::android::hardware::tv::tuner::V1_1::IFilter> mFilter_1_1; + + shared_ptr mFilter; int32_t mId; int64_t mId64Bit; - int mMainType; - int mSubType; + DemuxFilterType mType; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERFILTER_H diff --git a/services/tuner/TunerFrontend.cpp b/services/tuner/TunerFrontend.cpp index 74b5519c89..e86e8e122e 100644 --- a/services/tuner/TunerFrontend.cpp +++ b/services/tuner/TunerFrontend.cpp @@ -1,5 +1,5 @@ /** - * Copyright 2020, The Android Open Source Project + * Copyright 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,1081 +14,186 @@ * limitations under the License. */ +//#define LOG_NDEBUG 0 #define LOG_TAG "TunerFrontend" #include "TunerFrontend.h" + +#include + #include "TunerLnb.h" -using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3PlpSettings; -using ::aidl::android::media::tv::tuner::TunerFrontendScanAtsc3PlpInfo; -using ::aidl::android::media::tv::tuner::TunerFrontendStatusAtsc3PlpInfo; -using ::aidl::android::media::tv::tuner::TunerFrontendUnionSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendAnalogSifStandard; -using ::android::hardware::tv::tuner::V1_0::FrontendAnalogType; -using ::android::hardware::tv::tuner::V1_0::FrontendAtscModulation; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Bandwidth; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3CodeRate; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3DemodOutputFormat; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Fec; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Modulation; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3TimeInterleaveMode; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbcAnnex; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbcModulation; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbcOuterFec; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbcSpectralInversion; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsModulation; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsPilot; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsRolloff; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsStandard; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsVcmMode; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtBandwidth; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtCoderate; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtConstellation; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtGuardInterval; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtHierarchy; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtPlpMode; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtStandard; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbtTransmissionMode; -using ::android::hardware::tv::tuner::V1_0::FrontendInnerFec; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Coderate; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Modulation; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Rolloff; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Settings; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbsCoderate; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbsModulation; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbsRolloff; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbsSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbsStreamIdType; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtBandwidth; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtCoderate; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtGuardInterval; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtMode; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtModulation; -using ::android::hardware::tv::tuner::V1_0::FrontendIsdbtSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendModulationStatus; -using ::android::hardware::tv::tuner::V1_0::FrontendScanAtsc3PlpInfo; -using ::android::hardware::tv::tuner::V1_0::FrontendScanType; -using ::android::hardware::tv::tuner::V1_0::FrontendStatusType; -using ::android::hardware::tv::tuner::V1_0::Result; -using ::android::hardware::tv::tuner::V1_1::FrontendAnalogAftFlag; -using ::android::hardware::tv::tuner::V1_1::FrontendBandwidth; -using ::android::hardware::tv::tuner::V1_1::FrontendCableTimeInterleaveMode; -using ::android::hardware::tv::tuner::V1_1::FrontendDvbcBandwidth; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbBandwidth; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbCodeRate; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbGuardInterval; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbModulation; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbTimeInterleaveMode; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbTransmissionMode; -using ::android::hardware::tv::tuner::V1_1::FrontendDvbsScanType; -using ::android::hardware::tv::tuner::V1_1::FrontendGuardInterval; -using ::android::hardware::tv::tuner::V1_1::FrontendInterleaveMode; -using ::android::hardware::tv::tuner::V1_1::FrontendModulation; -using ::android::hardware::tv::tuner::V1_1::FrontendRollOff; -using ::android::hardware::tv::tuner::V1_1::FrontendTransmissionMode; -using ::android::hardware::tv::tuner::V1_1::FrontendSpectralInversion; -using ::android::hardware::tv::tuner::V1_1::FrontendStatusTypeExt1_1; +using ::aidl::android::hardware::tv::tuner::Result; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerFrontend::TunerFrontend(sp frontend, int id) { +TunerFrontend::TunerFrontend(shared_ptr frontend, int id) { mFrontend = frontend; - mFrontend_1_1 = ::android::hardware::tv::tuner::V1_1::IFrontend::castFrom(mFrontend); mId = id; } TunerFrontend::~TunerFrontend() { - mFrontend = NULL; - mFrontend_1_1 = NULL; + mFrontend = nullptr; mId = -1; } -Status TunerFrontend::setCallback( +::ndk::ScopedAStatus TunerFrontend::setCallback( const shared_ptr& tunerFrontendCallback) { - if (mFrontend == NULL) { + if (mFrontend == nullptr) { ALOGE("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - if (tunerFrontendCallback == NULL) { - return Status::fromServiceSpecificError(static_cast(Result::INVALID_ARGUMENT)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - sp frontendCallback = new FrontendCallback(tunerFrontendCallback); - Result status = mFrontend->setCallback(frontendCallback); - if (status == Result::SUCCESS) { - return Status::ok(); + if (tunerFrontendCallback == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - return Status::fromServiceSpecificError(static_cast(status)); + shared_ptr frontendCallback = + ::ndk::SharedRefBase::make(tunerFrontendCallback); + return mFrontend->setCallback(frontendCallback); } -Status TunerFrontend::tune(const TunerFrontendSettings& settings) { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::tune(const FrontendSettings& settings) { + if (mFrontend == nullptr) { ALOGE("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result status; - FrontendSettings frontendSettings = getHidlFrontendSettings(settings); - if (settings.isExtended) { - if (mFrontend_1_1 == NULL) { - ALOGE("IFrontend_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - FrontendSettingsExt1_1 frontendSettingsExt = getHidlFrontendSettingsExt(settings); - status = mFrontend_1_1->tune_1_1(frontendSettings, frontendSettingsExt); - } else { - status = mFrontend->tune(frontendSettings); - } - - if (status == Result::SUCCESS) { - return Status::ok(); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->tune(settings); } -Status TunerFrontend::stopTune() { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::stopTune() { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mFrontend->stopTune(); - if (status == Result::SUCCESS) { - return Status::ok(); - } - - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->stopTune(); } -Status TunerFrontend::scan(const TunerFrontendSettings& settings, int frontendScanType) { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::scan(const FrontendSettings& settings, + FrontendScanType frontendScanType) { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result status; - FrontendSettings frontendSettings = getHidlFrontendSettings(settings); - if (settings.isExtended) { - if (mFrontend_1_1 == NULL) { - ALOGE("IFrontend_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - FrontendSettingsExt1_1 frontendSettingsExt = getHidlFrontendSettingsExt(settings); - status = mFrontend_1_1->scan_1_1(frontendSettings, - static_cast(frontendScanType), frontendSettingsExt); - } else { - status = mFrontend->scan( - frontendSettings, static_cast(frontendScanType)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - if (status == Result::SUCCESS) { - return Status::ok(); - } - - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->scan(settings, frontendScanType); } -Status TunerFrontend::stopScan() { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::stopScan() { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result status = mFrontend->stopScan(); - if (status == Result::SUCCESS) { - return Status::ok(); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->stopScan(); } -Status TunerFrontend::setLnb(const shared_ptr& lnb) { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::setLnb(const shared_ptr& lnb) { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mFrontend->setLnb(static_cast(lnb.get())->getId()); - if (status == Result::SUCCESS) { - return Status::ok(); + if (lnb == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->setLnb(static_cast(lnb.get())->getId()); } -Status TunerFrontend::setLna(bool bEnable) { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::setLna(bool bEnable) { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mFrontend->setLna(bEnable); - if (status == Result::SUCCESS) { - return Status::ok(); - } - - return Status::fromServiceSpecificError(static_cast(status)); -} - -Status TunerFrontend::linkCiCamToFrontend(int ciCamId, int32_t* _aidl_return) { - if (mFrontend_1_1 == NULL) { - ALOGD("IFrontend_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - int ltsId; - Result status; - mFrontend_1_1->linkCiCam(static_cast(ciCamId), - [&](Result r, uint32_t id) { - status = r; - ltsId = id; - }); - - if (status == Result::SUCCESS) { - *_aidl_return = ltsId; - return Status::ok(); - } - - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->setLna(bEnable); } -Status TunerFrontend::unlinkCiCamToFrontend(int ciCamId) { - if (mFrontend_1_1 == NULL) { - ALOGD("IFrontend_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result status = mFrontend_1_1->unlinkCiCam(ciCamId); - if (status == Result::SUCCESS) { - return Status::ok(); +::ndk::ScopedAStatus TunerFrontend::linkCiCamToFrontend(int32_t ciCamId, int32_t* _aidl_return) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - return Status::fromServiceSpecificError(static_cast(status)); + return mFrontend->linkCiCam(ciCamId, _aidl_return); } -Status TunerFrontend::close() { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::unlinkCiCamToFrontend(int32_t ciCamId) { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mFrontend->close(); - mFrontend = NULL; - mFrontend_1_1 = NULL; - - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mFrontend->unlinkCiCam(ciCamId); } -Status TunerFrontend::getStatus(const vector& statusTypes, - vector* _aidl_return) { - if (mFrontend == NULL) { +::ndk::ScopedAStatus TunerFrontend::close() { + if (mFrontend == nullptr) { ALOGD("IFrontend is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result res; - vector status; - vector types; - for (auto s : statusTypes) { - types.push_back(static_cast(s)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - mFrontend->getStatus(types, [&](Result r, const hidl_vec& s) { - res = r; - status = s; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } + auto res = mFrontend->close(); + mFrontend = nullptr; - getAidlFrontendStatus(status, *_aidl_return); - return Status::ok(); + return res; } -Status TunerFrontend::getStatusExtended_1_1(const vector& statusTypes, - vector* _aidl_return) { - if (mFrontend_1_1 == NULL) { - ALOGD("IFrontend_1_1 is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); - } - - Result res; - vector status; - vector types; - for (auto s : statusTypes) { - types.push_back(static_cast(s)); - } - - mFrontend_1_1->getStatusExt1_1(types, [&](Result r, const hidl_vec& s) { - res = r; - status = s; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); +::ndk::ScopedAStatus TunerFrontend::getStatus(const vector& in_statusTypes, + vector* _aidl_return) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - getAidlFrontendStatusExt(status, *_aidl_return); - return Status::ok(); + return mFrontend->getStatus(in_statusTypes, _aidl_return); } -Status TunerFrontend::getFrontendId(int* _aidl_return) { +::ndk::ScopedAStatus TunerFrontend::getFrontendId(int32_t* _aidl_return) { *_aidl_return = mId; - return Status::ok(); + return ::ndk::ScopedAStatus::ok(); } /////////////// FrontendCallback /////////////////////// - -Return TunerFrontend::FrontendCallback::onEvent(FrontendEventType frontendEventType) { - ALOGD("FrontendCallback::onEvent, type=%d", frontendEventType); - mTunerFrontendCallback->onEvent((int)frontendEventType); - return Void(); -} - -Return TunerFrontend::FrontendCallback::onScanMessage( - FrontendScanMessageType type, const FrontendScanMessage& message) { - ALOGD("FrontendCallback::onScanMessage, type=%d", type); - TunerFrontendScanMessage scanMessage; - switch(type) { - case FrontendScanMessageType::LOCKED: { - scanMessage.set(message.isLocked()); - break; - } - case FrontendScanMessageType::END: { - scanMessage.set(message.isEnd()); - break; - } - case FrontendScanMessageType::PROGRESS_PERCENT: { - scanMessage.set(message.progressPercent()); - break; - } - case FrontendScanMessageType::FREQUENCY: { - auto f = message.frequencies(); - vector frequencies(begin(f), end(f)); - scanMessage.set(frequencies); - break; - } - case FrontendScanMessageType::SYMBOL_RATE: { - auto s = message.symbolRates(); - vector symbolRates(begin(s), end(s)); - scanMessage.set(symbolRates); - break; - } - case FrontendScanMessageType::HIERARCHY: { - scanMessage.set((int)message.hierarchy()); - break; - } - case FrontendScanMessageType::ANALOG_TYPE: { - scanMessage.set((int)message.analogType()); - break; - } - case FrontendScanMessageType::PLP_IDS: { - auto p = message.plpIds(); - vector plpIds(begin(p), end(p)); - scanMessage.set(plpIds); - break; - } - case FrontendScanMessageType::GROUP_IDS: { - auto g = message.groupIds(); - vector groupIds(begin(g), end(g)); - scanMessage.set(groupIds); - break; - } - case FrontendScanMessageType::INPUT_STREAM_IDS: { - auto i = message.inputStreamIds(); - vector streamIds(begin(i), end(i)); - scanMessage.set(streamIds); - break; - } - case FrontendScanMessageType::STANDARD: { - FrontendScanMessage::Standard std = message.std(); - int standard; - if (std.getDiscriminator() == FrontendScanMessage::Standard::hidl_discriminator::sStd) { - standard = (int) std.sStd(); - } else if (std.getDiscriminator() == - FrontendScanMessage::Standard::hidl_discriminator::tStd) { - standard = (int) std.tStd(); - } else if (std.getDiscriminator() == - FrontendScanMessage::Standard::hidl_discriminator::sifStd) { - standard = (int) std.sifStd(); - } - scanMessage.set(standard); - break; - } - case FrontendScanMessageType::ATSC3_PLP_INFO: { - vector plpInfos = message.atsc3PlpInfos(); - vector tunerPlpInfos; - for (int i = 0; i < plpInfos.size(); i++) { - auto info = plpInfos[i]; - int8_t plpId = (int8_t) info.plpId; - bool lls = (bool) info.bLlsFlag; - TunerFrontendScanAtsc3PlpInfo plpInfo{ - .plpId = plpId, - .llsFlag = lls, - }; - tunerPlpInfos.push_back(plpInfo); - } - scanMessage.set(tunerPlpInfos); - break; - } - default: - break; - } - mTunerFrontendCallback->onScanMessage((int)type, scanMessage); - return Void(); -} - -Return TunerFrontend::FrontendCallback::onScanMessageExt1_1( - FrontendScanMessageTypeExt1_1 type, const FrontendScanMessageExt1_1& message) { - ALOGD("onScanMessageExt1_1::onScanMessage, type=%d", type); - TunerFrontendScanMessage scanMessage; - switch(type) { - case FrontendScanMessageTypeExt1_1::MODULATION: { - FrontendModulation m = message.modulation(); - int modulation; - switch (m.getDiscriminator()) { - case FrontendModulation::hidl_discriminator::dvbc: - modulation = (int) m.dvbc(); - break; - case FrontendModulation::hidl_discriminator::dvbt: - modulation = (int) m.dvbt(); - break; - case FrontendModulation::hidl_discriminator::dvbs: - modulation = (int) m.dvbs(); - break; - case FrontendModulation::hidl_discriminator::isdbs: - modulation = (int) m.isdbs(); - break; - case FrontendModulation::hidl_discriminator::isdbs3: - modulation = (int) m.isdbs3(); - break; - case FrontendModulation::hidl_discriminator::isdbt: - modulation = (int) m.isdbt(); - break; - case FrontendModulation::hidl_discriminator::atsc: - modulation = (int) m.atsc(); - break; - case FrontendModulation::hidl_discriminator::atsc3: - modulation = (int) m.atsc3(); - break; - case FrontendModulation::hidl_discriminator::dtmb: - modulation = (int) m.dtmb(); - break; - } - scanMessage.set(modulation); - break; - } - case FrontendScanMessageTypeExt1_1::DVBC_ANNEX: { - scanMessage.set((int)message.annex()); - break; - } - case FrontendScanMessageTypeExt1_1::HIGH_PRIORITY: { - scanMessage.set(message.isHighPriority()); - break; - } - default: - break; - } - mTunerFrontendCallback->onScanMessage((int)type, scanMessage); - return Void(); -} - -/////////////// TunerFrontend Helper Methods /////////////////////// - -void TunerFrontend::getAidlFrontendStatus( - vector& hidlStatus, vector& aidlStatus) { - for (FrontendStatus s : hidlStatus) { - TunerFrontendStatus status; - switch (s.getDiscriminator()) { - case FrontendStatus::hidl_discriminator::isDemodLocked: { - status.set(s.isDemodLocked()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::snr: { - status.set((int)s.snr()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::ber: { - status.set((int)s.ber()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::per: { - status.set((int)s.per()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::preBer: { - status.set((int)s.preBer()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::signalQuality: { - status.set((int)s.signalQuality()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::signalStrength: { - status.set((int)s.signalStrength()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::symbolRate: { - status.set((int)s.symbolRate()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::innerFec: { - status.set((long)s.innerFec()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::modulation: { - switch (s.modulation().getDiscriminator()) { - case FrontendModulationStatus::hidl_discriminator::dvbc: - status.set((int)s.modulation().dvbc()); - aidlStatus.push_back(status); - break; - case FrontendModulationStatus::hidl_discriminator::dvbs: - status.set((int)s.modulation().dvbs()); - aidlStatus.push_back(status); - break; - case FrontendModulationStatus::hidl_discriminator::isdbs: - status.set((int)s.modulation().isdbs()); - aidlStatus.push_back(status); - break; - case FrontendModulationStatus::hidl_discriminator::isdbs3: - status.set((int)s.modulation().isdbs3()); - aidlStatus.push_back(status); - break; - case FrontendModulationStatus::hidl_discriminator::isdbt: - status.set((int)s.modulation().isdbt()); - aidlStatus.push_back(status); - break; - } - break; - } - case FrontendStatus::hidl_discriminator::inversion: { - status.set((int)s.inversion()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::lnbVoltage: { - status.set((int)s.lnbVoltage()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::plpId: { - status.set((int8_t)s.plpId()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::isEWBS: { - status.set(s.isEWBS()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::agc: { - status.set((int8_t)s.agc()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::isLnaOn: { - status.set(s.isLnaOn()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::isLayerError: { - vector e(s.isLayerError().begin(), s.isLayerError().end()); - status.set(e); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::mer: { - status.set((int)s.mer()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::freqOffset: { - status.set((int)s.freqOffset()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::hierarchy: { - status.set((int)s.hierarchy()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::isRfLocked: { - status.set(s.isRfLocked()); - aidlStatus.push_back(status); - break; - } - case FrontendStatus::hidl_discriminator::plpInfo: { - vector info; - for (auto i : s.plpInfo()) { - info.push_back({ - .plpId = (int8_t)i.plpId, - .isLocked = i.isLocked, - .uec = (int)i.uec, - }); - } - status.set(info); - aidlStatus.push_back(status); - break; - } - } - } -} - -void TunerFrontend::getAidlFrontendStatusExt( - vector& hidlStatus, vector& aidlStatus) { - for (FrontendStatusExt1_1 s : hidlStatus) { - TunerFrontendStatus status; - switch (s.getDiscriminator()) { - case FrontendStatusExt1_1::hidl_discriminator::modulations: { - vector aidlMod; - for (auto m : s.modulations()) { - switch (m.getDiscriminator()) { - case FrontendModulation::hidl_discriminator::dvbc: - aidlMod.push_back((int)m.dvbc()); - break; - case FrontendModulation::hidl_discriminator::dvbs: - aidlMod.push_back((int)m.dvbs()); - break; - case FrontendModulation::hidl_discriminator::dvbt: - aidlMod.push_back((int)m.dvbt()); - break; - case FrontendModulation::hidl_discriminator::isdbs: - aidlMod.push_back((int)m.isdbs()); - break; - case FrontendModulation::hidl_discriminator::isdbs3: - aidlMod.push_back((int)m.isdbs3()); - break; - case FrontendModulation::hidl_discriminator::isdbt: - aidlMod.push_back((int)m.isdbt()); - break; - case FrontendModulation::hidl_discriminator::atsc: - aidlMod.push_back((int)m.atsc()); - break; - case FrontendModulation::hidl_discriminator::atsc3: - aidlMod.push_back((int)m.atsc3()); - break; - case FrontendModulation::hidl_discriminator::dtmb: - aidlMod.push_back((int)m.dtmb()); - break; - } - } - status.set(aidlMod); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::bers: { - vector b(s.bers().begin(), s.bers().end()); - status.set(b); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::codeRates: { - vector codeRates; - for (auto c : s.codeRates()) { - codeRates.push_back((long)c); - } - status.set(codeRates); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::bandwidth: { - switch (s.bandwidth().getDiscriminator()) { - case FrontendBandwidth::hidl_discriminator::atsc3: - status.set((int)s.bandwidth().atsc3()); - break; - case FrontendBandwidth::hidl_discriminator::dvbc: - status.set((int)s.bandwidth().dvbc()); - break; - case FrontendBandwidth::hidl_discriminator::dvbt: - status.set((int)s.bandwidth().dvbt()); - break; - case FrontendBandwidth::hidl_discriminator::isdbt: - status.set((int)s.bandwidth().isdbt()); - break; - case FrontendBandwidth::hidl_discriminator::dtmb: - status.set((int)s.bandwidth().dtmb()); - break; - } - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::interval: { - switch (s.interval().getDiscriminator()) { - case FrontendGuardInterval::hidl_discriminator::dvbt: - status.set((int)s.interval().dvbt()); - break; - case FrontendGuardInterval::hidl_discriminator::isdbt: - status.set((int)s.interval().isdbt()); - break; - case FrontendGuardInterval::hidl_discriminator::dtmb: - status.set((int)s.interval().dtmb()); - break; - } - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::transmissionMode: { - switch (s.transmissionMode().getDiscriminator()) { - case FrontendTransmissionMode::hidl_discriminator::dvbt: - status.set( - (int)s.transmissionMode().dvbt()); - break; - case FrontendTransmissionMode::hidl_discriminator::isdbt: - status.set( - (int)s.transmissionMode().isdbt()); - break; - case FrontendTransmissionMode::hidl_discriminator::dtmb: - status.set( - (int)s.transmissionMode().dtmb()); - break; - } - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::uec: { - status.set((int)s.uec()); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::systemId: { - status.set((char16_t)s.systemId()); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::interleaving: { - vector aidlInter; - for (auto i : s.interleaving()) { - switch (i.getDiscriminator()) { - case FrontendInterleaveMode::hidl_discriminator::atsc3: - aidlInter.push_back((int)i.atsc3()); - break; - case FrontendInterleaveMode::hidl_discriminator::dvbc: - aidlInter.push_back((int)i.dvbc()); - break; - case FrontendInterleaveMode::hidl_discriminator::dtmb: - aidlInter.push_back((int)i.dtmb()); - break; - } - } - status.set(aidlInter); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::isdbtSegment: { - auto seg = s.isdbtSegment(); - vector i(seg.begin(), seg.end()); - status.set(i); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::tsDataRate: { - vector ts(s.tsDataRate().begin(), s.tsDataRate().end()); - status.set(ts); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::rollOff: { - switch (s.rollOff().getDiscriminator()) { - case FrontendRollOff::hidl_discriminator::dvbs: - status.set((int)s.rollOff().dvbs()); - break; - case FrontendRollOff::hidl_discriminator::isdbs: - status.set((int)s.rollOff().isdbs()); - break; - case FrontendRollOff::hidl_discriminator::isdbs3: - status.set((int)s.rollOff().isdbs3()); - break; - } - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::isMiso: { - status.set(s.isMiso()); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::isLinear: { - status.set(s.isLinear()); - aidlStatus.push_back(status); - break; - } - case FrontendStatusExt1_1::hidl_discriminator::isShortFrames: { - status.set(s.isShortFrames()); - aidlStatus.push_back(status); - break; - } - } +::ndk::ScopedAStatus TunerFrontend::FrontendCallback::onEvent(FrontendEventType frontendEventType) { + ALOGV("FrontendCallback::onEvent, type=%d", frontendEventType); + if (mTunerFrontendCallback != nullptr) { + mTunerFrontendCallback->onEvent(frontendEventType); } + return ndk::ScopedAStatus::ok(); } -hidl_vec TunerFrontend::getAtsc3PlpSettings( - const TunerFrontendAtsc3Settings& settings) { - int len = settings.plpSettings.size(); - hidl_vec plps = hidl_vec(len); - // parse PLP settings - for (int i = 0; i < len; i++) { - uint8_t plpId = static_cast(settings.plpSettings[i].plpId); - FrontendAtsc3Modulation modulation = - static_cast(settings.plpSettings[i].modulation); - FrontendAtsc3TimeInterleaveMode interleaveMode = - static_cast( - settings.plpSettings[i].interleaveMode); - FrontendAtsc3CodeRate codeRate = - static_cast(settings.plpSettings[i].codeRate); - FrontendAtsc3Fec fec = - static_cast(settings.plpSettings[i].fec); - FrontendAtsc3PlpSettings frontendAtsc3PlpSettings { - .plpId = plpId, - .modulation = modulation, - .interleaveMode = interleaveMode, - .codeRate = codeRate, - .fec = fec, - }; - plps[i] = frontendAtsc3PlpSettings; - } - return plps; -} - -FrontendDvbsCodeRate TunerFrontend::getDvbsCodeRate(const TunerFrontendDvbsCodeRate& codeRate) { - FrontendInnerFec innerFec = static_cast(codeRate.fec); - bool isLinear = codeRate.isLinear; - bool isShortFrames = codeRate.isShortFrames; - uint32_t bitsPer1000Symbol = static_cast(codeRate.bitsPer1000Symbol); - FrontendDvbsCodeRate coderate { - .fec = innerFec, - .isLinear = isLinear, - .isShortFrames = isShortFrames, - .bitsPer1000Symbol = bitsPer1000Symbol, - }; - return coderate; -} - -FrontendSettings TunerFrontend::getHidlFrontendSettings(const TunerFrontendSettings& aidlSettings) { - auto settings = aidlSettings.settings; - FrontendSettings frontendSettings; - - switch (settings.getTag()) { - case TunerFrontendUnionSettings::analog: { - auto analog = settings.get(); - frontendSettings.analog({ - .frequency = static_cast(analog.frequency), - .type = static_cast(analog.signalType), - .sifStandard = static_cast(analog.sifStandard), - }); - break; - } - case TunerFrontendUnionSettings::atsc: { - auto atsc = settings.get(); - frontendSettings.atsc({ - .frequency = static_cast(atsc.frequency), - .modulation = static_cast(atsc.modulation), - }); - break; - } - case TunerFrontendUnionSettings::atsc3: { - auto atsc3 = settings.get(); - frontendSettings.atsc3({ - .frequency = static_cast(atsc3.frequency), - .bandwidth = static_cast(atsc3.bandwidth), - .demodOutputFormat = static_cast( - atsc3.demodOutputFormat), - .plpSettings = getAtsc3PlpSettings(atsc3), - }); - break; - } - case TunerFrontendUnionSettings::cable: { - auto dvbc = settings.get(); - frontendSettings.dvbc({ - .frequency = static_cast(dvbc.frequency), - .modulation = static_cast(dvbc.modulation), - .fec = static_cast(dvbc.innerFec), - .symbolRate = static_cast(dvbc.symbolRate), - .outerFec = static_cast(dvbc.outerFec), - .annex = static_cast(dvbc.annex), - .spectralInversion = static_cast( - dvbc.spectralInversion), - }); - break; - } - case TunerFrontendUnionSettings::dvbs: { - auto dvbs = settings.get(); - frontendSettings.dvbs({ - .frequency = static_cast(dvbs.frequency), - .modulation = static_cast(dvbs.modulation), - .coderate = getDvbsCodeRate(dvbs.codeRate), - .symbolRate = static_cast(dvbs.symbolRate), - .rolloff = static_cast(dvbs.rolloff), - .pilot = static_cast(dvbs.pilot), - .inputStreamId = static_cast(dvbs.inputStreamId), - .standard = static_cast(dvbs.standard), - .vcmMode = static_cast(dvbs.vcm), - }); - break; - } - case TunerFrontendUnionSettings::dvbt: { - auto dvbt = settings.get(); - frontendSettings.dvbt({ - .frequency = static_cast(dvbt.frequency), - .transmissionMode = static_cast( - dvbt.transmissionMode), - .bandwidth = static_cast(dvbt.bandwidth), - .constellation = static_cast(dvbt.constellation), - .hierarchy = static_cast(dvbt.hierarchy), - .hpCoderate = static_cast(dvbt.hpCodeRate), - .lpCoderate = static_cast(dvbt.lpCodeRate), - .guardInterval = static_cast(dvbt.guardInterval), - .isHighPriority = dvbt.isHighPriority, - .standard = static_cast(dvbt.standard), - .isMiso = dvbt.isMiso, - .plpMode = static_cast(dvbt.plpMode), - .plpId = static_cast(dvbt.plpId), - .plpGroupId = static_cast(dvbt.plpGroupId), - }); - break; - } - case TunerFrontendUnionSettings::isdbs: { - auto isdbs = settings.get(); - frontendSettings.isdbs({ - .frequency = static_cast(isdbs.frequency), - .streamId = static_cast(isdbs.streamId), - .streamIdType = static_cast(isdbs.streamIdType), - .modulation = static_cast(isdbs.modulation), - .coderate = static_cast(isdbs.codeRate), - .symbolRate = static_cast(isdbs.symbolRate), - .rolloff = static_cast(isdbs.rolloff), - }); - break; - } - case TunerFrontendUnionSettings::isdbs3: { - auto isdbs3 = settings.get(); - frontendSettings.isdbs3({ - .frequency = static_cast(isdbs3.frequency), - .streamId = static_cast(isdbs3.streamId), - .streamIdType = static_cast(isdbs3.streamIdType), - .modulation = static_cast(isdbs3.modulation), - .coderate = static_cast(isdbs3.codeRate), - .symbolRate = static_cast(isdbs3.symbolRate), - .rolloff = static_cast(isdbs3.rolloff), - }); - break; - } - case TunerFrontendUnionSettings::isdbt: { - auto isdbt = settings.get(); - frontendSettings.isdbt({ - .frequency = static_cast(isdbt.frequency), - .modulation = static_cast(isdbt.modulation), - .bandwidth = static_cast(isdbt.bandwidth), - .mode = static_cast(isdbt.mode), - .coderate = static_cast(isdbt.codeRate), - .guardInterval = static_cast(isdbt.guardInterval), - .serviceAreaId = static_cast(isdbt.serviceAreaId), - }); - break; - } - default: - break; +::ndk::ScopedAStatus TunerFrontend::FrontendCallback::onScanMessage( + FrontendScanMessageType type, const FrontendScanMessage& message) { + ALOGV("FrontendCallback::onScanMessage, type=%d", type); + if (mTunerFrontendCallback != nullptr) { + mTunerFrontendCallback->onScanMessage(type, message); } - - return frontendSettings; + return ndk::ScopedAStatus::ok(); } -FrontendSettingsExt1_1 TunerFrontend::getHidlFrontendSettingsExt( - const TunerFrontendSettings& aidlSettings) { - FrontendSettingsExt1_1 frontendSettingsExt{ - .endFrequency = static_cast(aidlSettings.endFrequency), - .inversion = static_cast(aidlSettings.inversion), - }; - - auto settings = aidlSettings.settings; - switch (settings.getTag()) { - case TunerFrontendUnionSettings::analog: { - auto analog = settings.get(); - if (analog.isExtended) { - frontendSettingsExt.settingExt.analog({ - .aftFlag = static_cast(analog.aftFlag), - }); - } else { - frontendSettingsExt.settingExt.noinit(); - } - break; - } - case TunerFrontendUnionSettings::cable: { - auto dvbc = settings.get(); - if (dvbc.isExtended) { - frontendSettingsExt.settingExt.dvbc({ - .interleaveMode = static_cast( - dvbc.interleaveMode), - .bandwidth = static_cast( - dvbc.bandwidth), - }); - } else { - frontendSettingsExt.settingExt.noinit(); - } - break; - } - case TunerFrontendUnionSettings::dvbs: { - auto dvbs = settings.get(); - if (dvbs.isExtended) { - frontendSettingsExt.settingExt.dvbs({ - .scanType = static_cast(dvbs.scanType), - .isDiseqcRxMessage = dvbs.isDiseqcRxMessage, - }); - } else { - frontendSettingsExt.settingExt.noinit(); - } - break; - } - case TunerFrontendUnionSettings::dvbt: { - auto dvbt = settings.get(); - if (dvbt.isExtended) { - frontendSettingsExt.settingExt.dvbt({ - .constellation = - static_cast( - dvbt.constellation), - .transmissionMode = - static_cast( - dvbt.transmissionMode), - }); - } else { - frontendSettingsExt.settingExt.noinit(); - } - break; - } - case TunerFrontendUnionSettings::dtmb: { - auto dtmb = settings.get(); - frontendSettingsExt.settingExt.dtmb({ - .frequency = static_cast(dtmb.frequency), - .transmissionMode = static_cast( - dtmb.transmissionMode), - .bandwidth = static_cast(dtmb.bandwidth), - .modulation = static_cast(dtmb.modulation), - .codeRate = static_cast(dtmb.codeRate), - .guardInterval = static_cast(dtmb.guardInterval), - .interleaveMode = static_cast(dtmb.interleaveMode), - }); - break; - } - default: - frontendSettingsExt.settingExt.noinit(); - break; - } - - return frontendSettingsExt; -} +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerFrontend.h b/services/tuner/TunerFrontend.h index 22fd509c6f..41069411ce 100644 --- a/services/tuner/TunerFrontend.h +++ b/services/tuner/TunerFrontend.h @@ -1,5 +1,5 @@ /** - * Copyright 2020, The Android Open Source Project + * Copyright 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,95 +17,74 @@ #ifndef ANDROID_MEDIA_TUNERFRONTEND_H #define ANDROID_MEDIA_TUNERFRONTEND_H +#include +#include +#include #include -#include -#include -#include #include #include -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::media::tv::tuner::BnTunerFrontend; -using ::aidl::android::media::tv::tuner::ITunerFrontendCallback; -using ::aidl::android::media::tv::tuner::ITunerLnb; -using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3Settings; -using ::aidl::android::media::tv::tuner::TunerFrontendDvbsCodeRate; -using ::aidl::android::media::tv::tuner::TunerFrontendScanMessage; -using ::aidl::android::media::tv::tuner::TunerFrontendSettings; -using ::aidl::android::media::tv::tuner::TunerFrontendStatus; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_vec; -using ::android::hardware::tv::tuner::V1_0::FrontendAtsc3PlpSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendDvbsCodeRate; -using ::android::hardware::tv::tuner::V1_0::FrontendEventType; -using ::android::hardware::tv::tuner::V1_0::FrontendId; -using ::android::hardware::tv::tuner::V1_0::FrontendScanMessage; -using ::android::hardware::tv::tuner::V1_0::FrontendScanMessageType; -using ::android::hardware::tv::tuner::V1_0::FrontendSettings; -using ::android::hardware::tv::tuner::V1_0::FrontendStatus; -using ::android::hardware::tv::tuner::V1_0::IFrontend; -using ::android::hardware::tv::tuner::V1_1::IFrontendCallback; -using ::android::hardware::tv::tuner::V1_1::FrontendScanMessageExt1_1; -using ::android::hardware::tv::tuner::V1_1::FrontendScanMessageTypeExt1_1; -using ::android::hardware::tv::tuner::V1_1::FrontendSettingsExt1_1; -using ::android::hardware::tv::tuner::V1_1::FrontendStatusExt1_1; +using ::aidl::android::hardware::tv::tuner::BnFrontendCallback; +using ::aidl::android::hardware::tv::tuner::FrontendEventType; +using ::aidl::android::hardware::tv::tuner::FrontendScanMessage; +using ::aidl::android::hardware::tv::tuner::FrontendScanMessageType; +using ::aidl::android::hardware::tv::tuner::FrontendScanType; +using ::aidl::android::hardware::tv::tuner::FrontendSettings; +using ::aidl::android::hardware::tv::tuner::FrontendStatus; +using ::aidl::android::hardware::tv::tuner::FrontendStatusType; +using ::aidl::android::hardware::tv::tuner::IFrontend; +using ::aidl::android::hardware::tv::tuner::IFrontendCallback; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { class TunerFrontend : public BnTunerFrontend { public: - TunerFrontend(sp frontend, int id); + TunerFrontend(shared_ptr frontend, int id); virtual ~TunerFrontend(); - Status setCallback( - const shared_ptr& tunerFrontendCallback) override; - Status tune(const TunerFrontendSettings& settings) override; - Status stopTune() override; - Status scan(const TunerFrontendSettings& settings, int frontendScanType) override; - Status stopScan() override; - Status setLnb(const shared_ptr& lnb) override; - Status setLna(bool bEnable) override; - Status linkCiCamToFrontend(int ciCamId, int32_t* _aidl_return) override; - Status unlinkCiCamToFrontend(int ciCamId) override; - Status close() override; - Status getStatus(const vector& statusTypes, - vector* _aidl_return) override; - Status getStatusExtended_1_1(const vector& statusTypes, - vector* _aidl_return) override; - Status getFrontendId(int* _aidl_return) override; - struct FrontendCallback : public IFrontendCallback { + ::ndk::ScopedAStatus setCallback( + const shared_ptr& in_tunerFrontendCallback) override; + ::ndk::ScopedAStatus tune(const FrontendSettings& in_settings) override; + ::ndk::ScopedAStatus stopTune() override; + ::ndk::ScopedAStatus scan(const FrontendSettings& in_settings, + FrontendScanType in_frontendScanType) override; + ::ndk::ScopedAStatus stopScan() override; + ::ndk::ScopedAStatus setLnb(const shared_ptr& in_lnb) override; + ::ndk::ScopedAStatus setLna(bool in_bEnable) override; + ::ndk::ScopedAStatus linkCiCamToFrontend(int32_t in_ciCamId, int32_t* _aidl_return) override; + ::ndk::ScopedAStatus unlinkCiCamToFrontend(int32_t in_ciCamId) override; + ::ndk::ScopedAStatus close() override; + ::ndk::ScopedAStatus getStatus(const vector& in_statusTypes, + vector* _aidl_return) override; + ::ndk::ScopedAStatus getFrontendId(int32_t* _aidl_return) override; + + struct FrontendCallback : public BnFrontendCallback { FrontendCallback(const shared_ptr tunerFrontendCallback) - : mTunerFrontendCallback(tunerFrontendCallback) {}; + : mTunerFrontendCallback(tunerFrontendCallback){}; - virtual Return onEvent(FrontendEventType frontendEventType); - virtual Return onScanMessage( - FrontendScanMessageType type, const FrontendScanMessage& message); - virtual Return onScanMessageExt1_1( - FrontendScanMessageTypeExt1_1 type, const FrontendScanMessageExt1_1& message); + ::ndk::ScopedAStatus onEvent(FrontendEventType frontendEventType) override; + ::ndk::ScopedAStatus onScanMessage(FrontendScanMessageType type, + const FrontendScanMessage& message) override; shared_ptr mTunerFrontendCallback; }; private: - hidl_vec getAtsc3PlpSettings( - const TunerFrontendAtsc3Settings& settings); - FrontendDvbsCodeRate getDvbsCodeRate(const TunerFrontendDvbsCodeRate& codeRate); - FrontendSettings getHidlFrontendSettings(const TunerFrontendSettings& aidlSettings); - FrontendSettingsExt1_1 getHidlFrontendSettingsExt(const TunerFrontendSettings& aidlSettings); - void getAidlFrontendStatus( - vector& hidlStatus, vector& aidlStatus); - void getAidlFrontendStatusExt( - vector& hidlStatus, vector& aidlStatus); - int mId; - sp mFrontend; - sp<::android::hardware::tv::tuner::V1_1::IFrontend> mFrontend_1_1; + shared_ptr mFrontend; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERFRONTEND_H diff --git a/services/tuner/TunerLnb.cpp b/services/tuner/TunerLnb.cpp index 77248d4e81..1e143c349d 100644 --- a/services/tuner/TunerLnb.cpp +++ b/services/tuner/TunerLnb.cpp @@ -18,123 +18,116 @@ #include "TunerLnb.h" -using ::android::hardware::tv::tuner::V1_0::LnbPosition; -using ::android::hardware::tv::tuner::V1_0::LnbTone; -using ::android::hardware::tv::tuner::V1_0::LnbVoltage; -using ::android::hardware::tv::tuner::V1_0::Result; +#include +#include +using ::aidl::android::hardware::tv::tuner::ILnbCallback; +using ::aidl::android::hardware::tv::tuner::Result; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerLnb::TunerLnb(sp lnb, int id) { +TunerLnb::TunerLnb(shared_ptr lnb, int id) { mLnb = lnb; mId = id; } TunerLnb::~TunerLnb() { - mLnb = NULL; + mLnb = nullptr; mId = -1; } -Status TunerLnb::setCallback( - const shared_ptr& tunerLnbCallback) { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::setCallback( + const shared_ptr& in_tunerLnbCallback) { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - if (tunerLnbCallback == NULL) { - return Status::fromServiceSpecificError(static_cast(Result::INVALID_ARGUMENT)); + if (in_tunerLnbCallback == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); } - sp lnbCallback = new LnbCallback(tunerLnbCallback); - Result status = mLnb->setCallback(lnbCallback); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + shared_ptr lnbCallback = + ::ndk::SharedRefBase::make(in_tunerLnbCallback); + return mLnb->setCallback(lnbCallback); } -Status TunerLnb::setVoltage(int voltage) { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::setVoltage(LnbVoltage in_voltage) { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mLnb->setVoltage(static_cast(voltage)); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mLnb->setVoltage(in_voltage); } -Status TunerLnb::setTone(int tone) { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::setTone(LnbTone in_tone) { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mLnb->setTone(static_cast(tone)); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mLnb->setTone(in_tone); } -Status TunerLnb::setSatellitePosition(int position) { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::setSatellitePosition(LnbPosition in_position) { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mLnb->setSatellitePosition(static_cast(position)); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mLnb->setSatellitePosition(in_position); } -Status TunerLnb::sendDiseqcMessage(const vector& diseqcMessage) { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::sendDiseqcMessage(const vector& in_diseqcMessage) { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mLnb->sendDiseqcMessage(diseqcMessage); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mLnb->sendDiseqcMessage(in_diseqcMessage); } -Status TunerLnb::close() { - if (mLnb == NULL) { +::ndk::ScopedAStatus TunerLnb::close() { + if (mLnb == nullptr) { ALOGE("ILnb is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mLnb->close(); - mLnb = NULL; + auto res = mLnb->close(); + mLnb = nullptr; - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return res; } /////////////// ILnbCallback /////////////////////// - -Return TunerLnb::LnbCallback::onEvent(const LnbEventType lnbEventType) { - if (mTunerLnbCallback != NULL) { - mTunerLnbCallback->onEvent((int)lnbEventType); +::ndk::ScopedAStatus TunerLnb::LnbCallback::onEvent(const LnbEventType lnbEventType) { + if (mTunerLnbCallback != nullptr) { + mTunerLnbCallback->onEvent(lnbEventType); } - return Void(); + return ndk::ScopedAStatus::ok(); } -Return TunerLnb::LnbCallback::onDiseqcMessage(const hidl_vec& diseqcMessage) { - if (mTunerLnbCallback != NULL && diseqcMessage != NULL) { - vector msg(begin(diseqcMessage), end(diseqcMessage)); - mTunerLnbCallback->onDiseqcMessage(msg); +::ndk::ScopedAStatus TunerLnb::LnbCallback::onDiseqcMessage(const vector& diseqcMessage) { + if (mTunerLnbCallback != nullptr) { + mTunerLnbCallback->onDiseqcMessage(diseqcMessage); } - return Void(); + return ndk::ScopedAStatus::ok(); } + +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerLnb.h b/services/tuner/TunerLnb.h index 500d072d36..37efdf8cd3 100644 --- a/services/tuner/TunerLnb.h +++ b/services/tuner/TunerLnb.h @@ -17,55 +17,62 @@ #ifndef ANDROID_MEDIA_TUNERFLNB_H #define ANDROID_MEDIA_TUNERFLNB_H +#include +#include #include -#include -#include #include #include -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::media::tv::tuner::BnTunerLnb; -using ::aidl::android::media::tv::tuner::ITunerLnbCallback; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_vec; -using ::android::hardware::tv::tuner::V1_0::ILnb; -using ::android::hardware::tv::tuner::V1_0::ILnbCallback; -using ::android::hardware::tv::tuner::V1_0::LnbEventType; +using ::aidl::android::hardware::tv::tuner::BnLnbCallback; +using ::aidl::android::hardware::tv::tuner::ILnb; +using ::aidl::android::hardware::tv::tuner::LnbEventType; +using ::aidl::android::hardware::tv::tuner::LnbPosition; +using ::aidl::android::hardware::tv::tuner::LnbTone; +using ::aidl::android::hardware::tv::tuner::LnbVoltage; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { class TunerLnb : public BnTunerLnb { public: - TunerLnb(sp lnb, int id); + TunerLnb(shared_ptr lnb, int id); virtual ~TunerLnb(); - Status setCallback(const shared_ptr& tunerLnbCallback) override; - Status setVoltage(int voltage) override; - Status setTone(int tone) override; - Status setSatellitePosition(int position) override; - Status sendDiseqcMessage(const vector& diseqcMessage) override; - Status close() override; + + ::ndk::ScopedAStatus setCallback( + const shared_ptr& in_tunerLnbCallback) override; + ::ndk::ScopedAStatus setVoltage(LnbVoltage in_voltage) override; + ::ndk::ScopedAStatus setTone(LnbTone in_tone) override; + ::ndk::ScopedAStatus setSatellitePosition(LnbPosition in_position) override; + ::ndk::ScopedAStatus sendDiseqcMessage(const vector& in_diseqcMessage) override; + ::ndk::ScopedAStatus close() override; int getId() { return mId; } - struct LnbCallback : public ILnbCallback { + struct LnbCallback : public BnLnbCallback { LnbCallback(const shared_ptr tunerLnbCallback) - : mTunerLnbCallback(tunerLnbCallback) {}; + : mTunerLnbCallback(tunerLnbCallback){}; - virtual Return onEvent(const LnbEventType lnbEventType); - virtual Return onDiseqcMessage(const hidl_vec& diseqcMessage); + ::ndk::ScopedAStatus onEvent(const LnbEventType lnbEventType) override; + ::ndk::ScopedAStatus onDiseqcMessage(const vector& diseqcMessage) override; shared_ptr mTunerLnbCallback; }; private: int mId; - sp mLnb; + shared_ptr mLnb; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERFLNB_H diff --git a/services/tuner/TunerService.cpp b/services/tuner/TunerService.cpp index 5b4129a4ce..0703700a2d 100644 --- a/services/tuner/TunerService.cpp +++ b/services/tuner/TunerService.cpp @@ -1,5 +1,5 @@ /** - * Copyright (c) 2020, The Android Open Source Project + * Copyright (c) 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,60 +14,63 @@ * limitations under the License. */ +//#define LOG_NDEBUG 0 #define LOG_TAG "TunerService" +#include "TunerService.h" + +#include +#include +#include +#include +#include +#include #include #include #include #include -#include "TunerService.h" -#include "TunerFrontend.h" -#include "TunerLnb.h" + #include "TunerDemux.h" #include "TunerDescrambler.h" +#include "TunerFrontend.h" +#include "TunerLnb.h" -using ::aidl::android::media::tv::tuner::TunerFrontendAnalogCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendAtsc3Capabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendAtscCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendCableCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendDvbsCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendDvbtCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendIsdbs3Capabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendIsdbsCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendIsdbtCapabilities; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; -using ::android::hardware::tv::tuner::V1_0::FrontendId; -using ::android::hardware::tv::tuner::V1_0::FrontendType; -using ::android::hardware::tv::tuner::V1_0::IFrontend; -using ::android::hardware::tv::tuner::V1_0::ILnb; -using ::android::hardware::tv::tuner::V1_0::LnbId; -using ::android::hardware::tv::tuner::V1_0::Result; -using ::android::hardware::tv::tuner::V1_1::FrontendDtmbCapabilities; - +using ::aidl::android::hardware::tv::tuner::IDemux; +using ::aidl::android::hardware::tv::tuner::IDescrambler; +using ::aidl::android::hardware::tv::tuner::IFrontend; +using ::aidl::android::hardware::tv::tuner::Result; +using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; +using ::android::defaultServiceManager; +using ::android::IBinder; +using ::android::interface_cast; +using ::android::IServiceManager; +using ::android::sp; +using ::android::String16; +using ::android::binder::Status; +using ::android::content::pm::IPackageManagerNative; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { TunerService::TunerService() { sp serviceMgr = defaultServiceManager(); - sp packageMgr; + sp packageMgr; if (serviceMgr.get() == nullptr) { ALOGE("%s: Cannot find service manager", __func__); return; } else { sp binder = serviceMgr->waitForService(String16("package_native")); - packageMgr = interface_cast(binder); + packageMgr = interface_cast(binder); } - bool hasFeature = false; if (packageMgr != nullptr) { - binder::Status status = packageMgr->hasSystemFeature(FEATURE_TUNER, 0, &hasFeature); + bool hasFeature = false; + Status status = packageMgr->hasSystemFeature(FEATURE_TUNER, 0, &hasFeature); if (!status.isOk()) { - ALOGE("%s: hasSystemFeature failed: %s", - __func__, status.exceptionMessage().c_str()); + ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str()); return; } if (!hasFeature) { @@ -93,231 +96,149 @@ binder_status_t TunerService::instantiate() { } bool TunerService::hasITuner() { - ALOGD("hasITuner"); + ALOGV("hasITuner"); if (mTuner != nullptr) { return true; } - mTuner = ITuner::getService(); - if (mTuner == nullptr) { - ALOGE("Failed to get ITuner service"); - return false; - } - mTunerVersion = TUNER_HAL_VERSION_1_0; - mTuner_1_1 = ::android::hardware::tv::tuner::V1_1::ITuner::castFrom(mTuner); - if (mTuner_1_1 != nullptr) { - mTunerVersion = TUNER_HAL_VERSION_1_1; + const string statsServiceName = string() + ITuner::descriptor + "/default"; + if (AServiceManager_isDeclared(statsServiceName.c_str())) { + ::ndk::SpAIBinder binder(AServiceManager_waitForService(statsServiceName.c_str())); + mTuner = ITuner::fromBinder(binder); } else { - ALOGE("Failed to get ITuner_1_1 service"); + mTuner = nullptr; + ALOGE("Failed to get Tuner HAL Service"); + return false; } - return true; -} -bool TunerService::hasITuner_1_1() { - ALOGD("hasITuner_1_1"); - hasITuner(); - return (mTunerVersion == TUNER_HAL_VERSION_1_1); -} - -Status TunerService::openDemux( - int /* demuxHandle */, std::shared_ptr* _aidl_return) { - ALOGD("openDemux"); - if (!hasITuner()) { - return Status::fromServiceSpecificError(static_cast(Result::NOT_INITIALIZED)); - } - Result res; - uint32_t id; - sp demuxSp = nullptr; - shared_ptr tunerDemux = nullptr; - mTuner->openDemux([&](Result r, uint32_t demuxId, const sp& demux) { - demuxSp = demux; - id = demuxId; - res = r; - ALOGD("open demux, id = %d", demuxId); - }); - if (res == Result::SUCCESS) { - tunerDemux = ::ndk::SharedRefBase::make(demuxSp, id); - *_aidl_return = tunerDemux->ref(); - return Status::ok(); - } + mTunerVersion = TUNER_HAL_VERSION_2_0; + // TODO: Enable this after Tuner HAL is frozen. + // if (mTuner->getInterfaceVersion(&mTunerVersion).isOk()) { + // // Tuner AIDL HAL version 1 will be Tuner HAL 2.0 + // mTunerVersion = (mTunerVersion + 1) << 16; + //} - ALOGW("open demux failed, res = %d", res); - return Status::fromServiceSpecificError(static_cast(res)); + return true; } -Status TunerService::getDemuxCaps(TunerDemuxCapabilities* _aidl_return) { - ALOGD("getDemuxCaps"); +::ndk::ScopedAStatus TunerService::openDemux(int32_t /* in_demuxHandle */, + shared_ptr* _aidl_return) { + ALOGV("openDemux"); if (!hasITuner()) { - return Status::fromServiceSpecificError(static_cast(Result::NOT_INITIALIZED)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res; - DemuxCapabilities caps; - mTuner->getDemuxCaps([&](Result r, const DemuxCapabilities& demuxCaps) { - caps = demuxCaps; - res = r; - }); - if (res == Result::SUCCESS) { - *_aidl_return = getAidlDemuxCaps(caps); - return Status::ok(); + vector id; + shared_ptr demux; + auto status = mTuner->openDemux(&id, &demux); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(demux, id[0]); } - ALOGW("Get demux caps failed, res = %d", res); - return Status::fromServiceSpecificError(static_cast(res)); + return status; } -Status TunerService::getFrontendIds(vector* ids) { +::ndk::ScopedAStatus TunerService::getDemuxCaps(DemuxCapabilities* _aidl_return) { + ALOGV("getDemuxCaps"); if (!hasITuner()) { - return Status::fromServiceSpecificError( - static_cast(Result::NOT_INITIALIZED)); - } - hidl_vec feIds; - Result res = getHidlFrontendIds(feIds); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - ids->resize(feIds.size()); - copy(feIds.begin(), feIds.end(), ids->begin()); - return Status::ok(); + return mTuner->getDemuxCaps(_aidl_return); } -Status TunerService::getFrontendInfo(int32_t id, TunerFrontendInfo* _aidl_return) { +::ndk::ScopedAStatus TunerService::getFrontendIds(vector* ids) { if (!hasITuner()) { - ALOGE("ITuner service is not init."); return ::ndk::ScopedAStatus::fromServiceSpecificError( static_cast(Result::UNAVAILABLE)); } - FrontendInfo info; - Result res = getHidlFrontendInfo(id, info); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - - TunerFrontendInfo tunerInfo = convertToAidlFrontendInfo(info); - *_aidl_return = tunerInfo; - return Status::ok(); + return mTuner->getFrontendIds(ids); } -Status TunerService::getFrontendDtmbCapabilities( - int32_t id, TunerFrontendDtmbCapabilities* _aidl_return) { - if (!hasITuner_1_1()) { - ALOGE("ITuner_1_1 service is not init."); +::ndk::ScopedAStatus TunerService::getFrontendInfo(int32_t id, FrontendInfo* _aidl_return) { + if (!hasITuner()) { + ALOGE("ITuner service is not init."); return ::ndk::ScopedAStatus::fromServiceSpecificError( static_cast(Result::UNAVAILABLE)); } - Result res; - FrontendDtmbCapabilities dtmbCaps; - mTuner_1_1->getFrontendDtmbCapabilities(id, - [&](Result r, const FrontendDtmbCapabilities& caps) { - dtmbCaps = caps; - res = r; - }); - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - - TunerFrontendDtmbCapabilities aidlDtmbCaps{ - .transmissionModeCap = (int)dtmbCaps.transmissionModeCap, - .bandwidthCap = (int)dtmbCaps.bandwidthCap, - .modulationCap = (int)dtmbCaps.modulationCap, - .codeRateCap = (int)dtmbCaps.codeRateCap, - .guardIntervalCap = (int)dtmbCaps.guardIntervalCap, - .interleaveModeCap = (int)dtmbCaps.interleaveModeCap, - }; - - *_aidl_return = aidlDtmbCaps; - return Status::ok(); + return mTuner->getFrontendInfo(id, _aidl_return); } -Status TunerService::openFrontend( - int32_t frontendHandle, shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerService::openFrontend(int32_t frontendHandle, + shared_ptr* _aidl_return) { if (!hasITuner()) { ALOGE("ITuner service is not init."); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - sp frontend; int id = getResourceIdFromHandle(frontendHandle, FRONTEND); - mTuner->openFrontendById(id, [&](Result result, const sp& fe) { - frontend = fe; - status = result; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + shared_ptr frontend; + auto status = mTuner->openFrontendById(id, &frontend); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(frontend, id); } - *_aidl_return = ::ndk::SharedRefBase::make(frontend, id); - return Status::ok(); + + return status; } -Status TunerService::openLnb(int lnbHandle, shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerService::openLnb(int lnbHandle, shared_ptr* _aidl_return) { if (!hasITuner()) { ALOGD("get ITuner failed"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - sp lnb; + shared_ptr lnb; int id = getResourceIdFromHandle(lnbHandle, LNB); - mTuner->openLnbById(id, [&](Result result, const sp& lnbSp){ - lnb = lnbSp; - status = result; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + auto status = mTuner->openLnbById(id, &lnb); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(lnb, id); } - *_aidl_return = ::ndk::SharedRefBase::make(lnb, id); - return Status::ok(); + return status; } -Status TunerService::openLnbByName(const string& lnbName, shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerService::openLnbByName(const string& lnbName, + shared_ptr* _aidl_return) { if (!hasITuner()) { ALOGE("get ITuner failed"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - int lnbId; - Result status; - sp lnb; - mTuner->openLnbByName(lnbName, [&](Result r, LnbId id, const sp& lnbSp) { - status = r; - lnb = lnbSp; - lnbId = (int)id; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + vector id; + shared_ptr lnb; + auto status = mTuner->openLnbByName(lnbName, &id, &lnb); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(lnb, id[0]); } - *_aidl_return = ::ndk::SharedRefBase::make(lnb, lnbId); - return Status::ok(); + return ::ndk::ScopedAStatus::ok(); } -Status TunerService::openDescrambler(int32_t /*descramblerHandle*/, - std::shared_ptr* _aidl_return) { +::ndk::ScopedAStatus TunerService::openDescrambler(int32_t /*descramblerHandle*/, + shared_ptr* _aidl_return) { if (!hasITuner()) { ALOGD("get ITuner failed"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - sp descrambler; - //int id = getResourceIdFromHandle(descramblerHandle, DESCRAMBLER); - mTuner->openDescrambler([&](Result r, const sp& descramblerSp) { - status = r; - descrambler = descramblerSp; - }); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); + shared_ptr descrambler; + // int id = getResourceIdFromHandle(descramblerHandle, DESCRAMBLER); + auto status = mTuner->openDescrambler(&descrambler); + if (status.isOk()) { + *_aidl_return = ::ndk::SharedRefBase::make(descrambler); } - *_aidl_return = ::ndk::SharedRefBase::make(descrambler); - return Status::ok(); + return status; } void TunerService::updateTunerResources() { - if (!hasITuner() || mTunerResourceManager == NULL) { + if (!hasITuner() || mTunerResourceManager == nullptr) { ALOGE("Failed to updateTunerResources"); return; } @@ -327,29 +248,30 @@ void TunerService::updateTunerResources() { // TODO: update Demux, Descrambler. } -Status TunerService::getTunerHalVersion(int* _aidl_return) { +::ndk::ScopedAStatus TunerService::getTunerHalVersion(int* _aidl_return) { hasITuner(); *_aidl_return = mTunerVersion; - return Status::ok(); + return ::ndk::ScopedAStatus::ok(); } void TunerService::updateFrontendResources() { - hidl_vec ids; - Result res = getHidlFrontendIds(ids); - if (res != Result::SUCCESS) { + vector ids; + auto status = mTuner->getFrontendIds(&ids); + if (!status.isOk()) { return; } + vector infos; for (int i = 0; i < ids.size(); i++) { FrontendInfo frontendInfo; - Result res = getHidlFrontendInfo((int)ids[i], frontendInfo); - if (res != Result::SUCCESS) { + auto res = mTuner->getFrontendInfo(ids[i], &frontendInfo); + if (!res.isOk()) { continue; } TunerFrontendInfo tunerFrontendInfo{ - .handle = getResourceHandleFromId((int)ids[i], FRONTEND), - .type = static_cast(frontendInfo.type), - .exclusiveGroupId = static_cast(frontendInfo.exclusiveGroupId), + .handle = getResourceHandleFromId((int)ids[i], FRONTEND), + .type = static_cast(frontendInfo.type), + .exclusiveGroupId = frontendInfo.exclusiveGroupId, }; infos.push_back(tunerFrontendInfo); } @@ -357,26 +279,21 @@ void TunerService::updateFrontendResources() { } void TunerService::updateLnbResources() { - vector handles = getLnbHandles(); + vector handles = getLnbHandles(); if (handles.size() == 0) { return; } mTunerResourceManager->setLnbInfoList(handles); } -vector TunerService::getLnbHandles() { - vector lnbHandles; - if (mTuner != NULL) { - Result res; - vector lnbIds; - mTuner->getLnbIds([&](Result r, const hardware::hidl_vec& ids) { - lnbIds = ids; - res = r; - }); - if (res != Result::SUCCESS || lnbIds.size() == 0) { - } else { +vector TunerService::getLnbHandles() { + vector lnbHandles; + if (mTuner != nullptr) { + vector lnbIds; + auto res = mTuner->getLnbIds(&lnbIds); + if (res.isOk()) { for (int i = 0; i < lnbIds.size(); i++) { - lnbHandles.push_back(getResourceHandleFromId((int)lnbIds[i], LNB)); + lnbHandles.push_back(getResourceHandleFromId(lnbIds[i], LNB)); } } } @@ -384,186 +301,8 @@ vector TunerService::getLnbHandles() { return lnbHandles; } -Result TunerService::getHidlFrontendIds(hidl_vec& ids) { - if (mTuner == NULL) { - return Result::NOT_INITIALIZED; - } - Result res; - mTuner->getFrontendIds([&](Result r, const hidl_vec& frontendIds) { - ids = frontendIds; - res = r; - }); - return res; -} - -Result TunerService::getHidlFrontendInfo(int id, FrontendInfo& info) { - if (mTuner == NULL) { - return Result::NOT_INITIALIZED; - } - Result res; - mTuner->getFrontendInfo(id, [&](Result r, const FrontendInfo& feInfo) { - info = feInfo; - res = r; - }); - return res; -} - -TunerDemuxCapabilities TunerService::getAidlDemuxCaps(DemuxCapabilities caps) { - TunerDemuxCapabilities aidlCaps{ - .numDemux = (int)caps.numDemux, - .numRecord = (int)caps.numRecord, - .numPlayback = (int)caps.numPlayback, - .numTsFilter = (int)caps.numTsFilter, - .numSectionFilter = (int)caps.numSectionFilter, - .numAudioFilter = (int)caps.numAudioFilter, - .numVideoFilter = (int)caps.numVideoFilter, - .numPesFilter = (int)caps.numPesFilter, - .numPcrFilter = (int)caps.numPcrFilter, - .numBytesInSectionFilter = (int)caps.numBytesInSectionFilter, - .filterCaps = (int)caps.filterCaps, - .bTimeFilter = caps.bTimeFilter, - }; - aidlCaps.linkCaps.resize(caps.linkCaps.size()); - copy(caps.linkCaps.begin(), caps.linkCaps.end(), aidlCaps.linkCaps.begin()); - return aidlCaps; -} - -TunerFrontendInfo TunerService::convertToAidlFrontendInfo(FrontendInfo halInfo) { - TunerFrontendInfo info{ - .type = (int)halInfo.type, - .minFrequency = (int)halInfo.minFrequency, - .maxFrequency = (int)halInfo.maxFrequency, - .minSymbolRate = (int)halInfo.minSymbolRate, - .maxSymbolRate = (int)halInfo.maxSymbolRate, - .acquireRange = (int)halInfo.acquireRange, - .exclusiveGroupId = (int)halInfo.exclusiveGroupId, - }; - for (int i = 0; i < halInfo.statusCaps.size(); i++) { - info.statusCaps.push_back((int)halInfo.statusCaps[i]); - } - - TunerFrontendCapabilities caps; - switch (halInfo.type) { - case FrontendType::ANALOG: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::analogCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendAnalogCapabilities analogCaps{ - .typeCap = (int)halInfo.frontendCaps.analogCaps().typeCap, - .sifStandardCap = (int)halInfo.frontendCaps.analogCaps().sifStandardCap, - }; - caps.set(analogCaps); - } - break; - } - case FrontendType::ATSC: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::atscCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendAtscCapabilities atscCaps{ - .modulationCap = (int)halInfo.frontendCaps.atscCaps().modulationCap, - }; - caps.set(atscCaps); - } - break; - } - case FrontendType::ATSC3: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::atsc3Caps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendAtsc3Capabilities atsc3Caps{ - .bandwidthCap = (int)halInfo.frontendCaps.atsc3Caps().bandwidthCap, - .modulationCap = (int)halInfo.frontendCaps.atsc3Caps().modulationCap, - .timeInterleaveModeCap = - (int)halInfo.frontendCaps.atsc3Caps().timeInterleaveModeCap, - .codeRateCap = (int)halInfo.frontendCaps.atsc3Caps().codeRateCap, - .demodOutputFormatCap - = (int)halInfo.frontendCaps.atsc3Caps().demodOutputFormatCap, - .fecCap = (int)halInfo.frontendCaps.atsc3Caps().fecCap, - }; - caps.set(atsc3Caps); - } - break; - } - case FrontendType::DVBC: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::dvbcCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendCableCapabilities cableCaps{ - .modulationCap = (int)halInfo.frontendCaps.dvbcCaps().modulationCap, - .codeRateCap = (int64_t)halInfo.frontendCaps.dvbcCaps().fecCap, - .annexCap = (int)halInfo.frontendCaps.dvbcCaps().annexCap, - }; - caps.set(cableCaps); - } - break; - } - case FrontendType::DVBS: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::dvbsCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendDvbsCapabilities dvbsCaps{ - .modulationCap = (int)halInfo.frontendCaps.dvbsCaps().modulationCap, - .codeRateCap = (long)halInfo.frontendCaps.dvbsCaps().innerfecCap, - .standard = (int)halInfo.frontendCaps.dvbsCaps().standard, - }; - caps.set(dvbsCaps); - } - break; - } - case FrontendType::DVBT: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::dvbtCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendDvbtCapabilities dvbtCaps{ - .transmissionModeCap = (int)halInfo.frontendCaps.dvbtCaps().transmissionModeCap, - .bandwidthCap = (int)halInfo.frontendCaps.dvbtCaps().bandwidthCap, - .constellationCap = (int)halInfo.frontendCaps.dvbtCaps().constellationCap, - .codeRateCap = (int)halInfo.frontendCaps.dvbtCaps().coderateCap, - .hierarchyCap = (int)halInfo.frontendCaps.dvbtCaps().hierarchyCap, - .guardIntervalCap = (int)halInfo.frontendCaps.dvbtCaps().guardIntervalCap, - .isT2Supported = (bool)halInfo.frontendCaps.dvbtCaps().isT2Supported, - .isMisoSupported = (bool)halInfo.frontendCaps.dvbtCaps().isMisoSupported, - }; - caps.set(dvbtCaps); - } - break; - } - case FrontendType::ISDBS: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::isdbsCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendIsdbsCapabilities isdbsCaps{ - .modulationCap = (int)halInfo.frontendCaps.isdbsCaps().modulationCap, - .codeRateCap = (int)halInfo.frontendCaps.isdbsCaps().coderateCap, - }; - caps.set(isdbsCaps); - } - break; - } - case FrontendType::ISDBS3: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::isdbs3Caps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendIsdbs3Capabilities isdbs3Caps{ - .modulationCap = (int)halInfo.frontendCaps.isdbs3Caps().modulationCap, - .codeRateCap = (int)halInfo.frontendCaps.isdbs3Caps().coderateCap, - }; - caps.set(isdbs3Caps); - } - break; - } - case FrontendType::ISDBT: { - if (FrontendInfo::FrontendCapabilities::hidl_discriminator::isdbtCaps - == halInfo.frontendCaps.getDiscriminator()) { - TunerFrontendIsdbtCapabilities isdbtCaps{ - .modeCap = (int)halInfo.frontendCaps.isdbtCaps().modeCap, - .bandwidthCap = (int)halInfo.frontendCaps.isdbtCaps().bandwidthCap, - .modulationCap = (int)halInfo.frontendCaps.isdbtCaps().modulationCap, - .codeRateCap = (int)halInfo.frontendCaps.isdbtCaps().coderateCap, - .guardIntervalCap = (int)halInfo.frontendCaps.isdbtCaps().guardIntervalCap, - }; - caps.set(isdbtCaps); - } - break; - } - default: - break; - } - - info.caps = caps; - return info; -} -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/TunerService.h b/services/tuner/TunerService.h index f8e2ee609b..164bef8d93 100644 --- a/services/tuner/TunerService.h +++ b/services/tuner/TunerService.h @@ -1,5 +1,5 @@ /** - * Copyright (c) 2020, The Android Open Source Project + * Copyright (c) 2021, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,61 +17,33 @@ #ifndef ANDROID_MEDIA_TUNERSERVICE_H #define ANDROID_MEDIA_TUNERSERVICE_H -#include +#include +#include +#include +#include #include -#include -#include -#include -#include - -using ::aidl::android::hardware::common::fmq::GrantorDescriptor; -using ::aidl::android::hardware::common::fmq::MQDescriptor; -using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite; -using ::aidl::android::media::tv::tuner::BnTunerService; -using ::aidl::android::media::tv::tuner::ITunerDemux; -using ::aidl::android::media::tv::tuner::ITunerDescrambler; -using ::aidl::android::media::tv::tuner::ITunerFrontend; -using ::aidl::android::media::tv::tuner::ITunerLnb; -using ::aidl::android::media::tv::tuner::TunerDemuxCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendDtmbCapabilities; -using ::aidl::android::media::tv::tuner::TunerFrontendInfo; -using ::aidl::android::media::tv::tunerresourcemanager::ITunerResourceManager; +#include -using ::android::hardware::details::logError; -using ::android::hardware::hidl_vec; -using ::android::hardware::kSynchronizedReadWrite; -using ::android::hardware::EventFlag; -using ::android::hardware::MessageQueue; -using ::android::hardware::MQDescriptorSync; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::tv::tuner::V1_0::DemuxCapabilities; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; -using ::android::hardware::tv::tuner::V1_0::DemuxFilterType; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings; -using ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; -using ::android::hardware::tv::tuner::V1_0::FrontendId; -using ::android::hardware::tv::tuner::V1_0::FrontendInfo; -using ::android::hardware::tv::tuner::V1_0::IDemux; -using ::android::hardware::tv::tuner::V1_0::IDescrambler; -using ::android::hardware::tv::tuner::V1_0::IFilter; -using ::android::hardware::tv::tuner::V1_0::IFilterCallback; -using ::android::hardware::tv::tuner::V1_0::ITuner; -using ::android::hardware::tv::tuner::V1_0::Result; - -using Status = ::ndk::ScopedAStatus; +using ::aidl::android::hardware::tv::tuner::BnFilterCallback; +using ::aidl::android::hardware::tv::tuner::DemuxCapabilities; +using ::aidl::android::hardware::tv::tuner::DemuxFilterEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterStatus; +using ::aidl::android::hardware::tv::tuner::FrontendInfo; +using ::aidl::android::hardware::tv::tuner::ITuner; +using ::aidl::android::media::tv::tunerresourcemanager::ITunerResourceManager; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { const static int TUNER_HAL_VERSION_UNKNOWN = 0; const static int TUNER_HAL_VERSION_1_0 = 1 << 16; const static int TUNER_HAL_VERSION_1_1 = (1 << 16) | 1; +const static int TUNER_HAL_VERSION_2_0 = 2 << 16; // System Feature defined in PackageManager static const ::android::String16 FEATURE_TUNER(::android::String16("android.hardware.tv.tuner")); @@ -82,40 +54,40 @@ typedef enum { DESCRAMBLER, } TunerResourceType; -struct FilterCallback : public IFilterCallback { +struct FilterCallback : public BnFilterCallback { ~FilterCallback() {} - Return onFilterEvent(const DemuxFilterEvent&) { - return Void(); + virtual ::ndk::ScopedAStatus onFilterEvent( + const vector& /* events */) override { + return ::ndk::ScopedAStatus::ok(); } - Return onFilterStatus(const DemuxFilterStatus) { - return Void(); + + virtual ::ndk::ScopedAStatus onFilterStatus(const DemuxFilterStatus /*status*/) override { + return ::ndk::ScopedAStatus::ok(); } }; class TunerService : public BnTunerService { - typedef AidlMessageQueue AidlMessageQueue; - typedef MessageQueue HidlMessageQueue; - typedef MQDescriptor AidlMQDesc; - public: static char const *getServiceName() { return "media.tuner"; } static binder_status_t instantiate(); TunerService(); virtual ~TunerService(); - Status getFrontendIds(vector* ids) override; - Status getFrontendInfo(int32_t id, TunerFrontendInfo* _aidl_return) override; - Status getFrontendDtmbCapabilities( - int32_t id, TunerFrontendDtmbCapabilities* _aidl_return) override; - Status openFrontend( - int32_t frontendHandle, shared_ptr* _aidl_return) override; - Status openLnb(int lnbHandle, shared_ptr* _aidl_return) override; - Status openLnbByName(const string& lnbName, shared_ptr* _aidl_return) override; - Status openDemux(int32_t demuxHandle, std::shared_ptr* _aidl_return) override; - Status getDemuxCaps(TunerDemuxCapabilities* _aidl_return) override; - Status openDescrambler(int32_t descramblerHandle, - std::shared_ptr* _aidl_return) override; - Status getTunerHalVersion(int* _aidl_return) override; + ::ndk::ScopedAStatus getFrontendIds(vector* out_ids) override; + ::ndk::ScopedAStatus getFrontendInfo(int32_t in_frontendHandle, + FrontendInfo* _aidl_return) override; + ::ndk::ScopedAStatus openFrontend(int32_t in_frontendHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openLnb(int32_t in_lnbHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openLnbByName(const string& in_lnbName, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openDemux(int32_t in_demuxHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getDemuxCaps(DemuxCapabilities* _aidl_return) override; + ::ndk::ScopedAStatus openDescrambler(int32_t in_descramblerHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getTunerHalVersion(int32_t* _aidl_return) override; // TODO: create a map between resource id and handles. static int getResourceIdFromHandle(int resourceHandle, int /*type*/) { @@ -131,27 +103,21 @@ public: private: bool hasITuner(); - bool hasITuner_1_1(); void updateTunerResources(); - void updateFrontendResources(); void updateLnbResources(); - Result getHidlFrontendIds(hidl_vec& ids); - Result getHidlFrontendInfo(int id, FrontendInfo& info); - vector getLnbHandles(); - - TunerDemuxCapabilities getAidlDemuxCaps(DemuxCapabilities caps); - TunerFrontendInfo convertToAidlFrontendInfo(FrontendInfo halInfo); - - sp mTuner; - sp<::android::hardware::tv::tuner::V1_1::ITuner> mTuner_1_1; + vector getLnbHandles(); + shared_ptr mTuner; shared_ptr mTunerResourceManager; int mResourceRequestCount = 0; - int mTunerVersion = TUNER_HAL_VERSION_UNKNOWN; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERSERVICE_H diff --git a/services/tuner/TunerTimeFilter.cpp b/services/tuner/TunerTimeFilter.cpp index ea9da30b88..73cd6b482c 100644 --- a/services/tuner/TunerTimeFilter.cpp +++ b/services/tuner/TunerTimeFilter.cpp @@ -18,97 +18,91 @@ #include "TunerTimeFilter.h" -using ::android::hardware::tv::tuner::V1_0::Result; -using ::android::hardware::tv::tuner::V1_1::Constant64Bit; +#include +#include +using ::aidl::android::hardware::tv::tuner::Constant64Bit; +using ::aidl::android::hardware::tv::tuner::Result; + +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { -TunerTimeFilter::TunerTimeFilter(sp timeFilter) { +TunerTimeFilter::TunerTimeFilter(shared_ptr timeFilter) { mTimeFilter = timeFilter; } TunerTimeFilter::~TunerTimeFilter() { - mTimeFilter = NULL; + mTimeFilter = nullptr; } -Status TunerTimeFilter::setTimeStamp(int64_t timeStamp) { - if (mTimeFilter == NULL) { +::ndk::ScopedAStatus TunerTimeFilter::setTimeStamp(int64_t timeStamp) { + if (mTimeFilter == nullptr) { ALOGE("ITimeFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mTimeFilter->setTimeStamp(timeStamp); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mTimeFilter->setTimeStamp(timeStamp); } -Status TunerTimeFilter::clearTimeStamp() { - if (mTimeFilter == NULL) { +::ndk::ScopedAStatus TunerTimeFilter::clearTimeStamp() { + if (mTimeFilter == nullptr) { ALOGE("ITimeFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status = mTimeFilter->clearTimeStamp(); - if (status != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(status)); - } - return Status::ok(); + return mTimeFilter->clearTimeStamp(); } -Status TunerTimeFilter::getSourceTime(int64_t* _aidl_return) { - if (mTimeFilter == NULL) { +::ndk::ScopedAStatus TunerTimeFilter::getSourceTime(int64_t* _aidl_return) { + if (mTimeFilter == nullptr) { *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; ALOGE("ITimeFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - mTimeFilter->getSourceTime( - [&](Result r, uint64_t t) { - status = r; - *_aidl_return = t; - }); - if (status != Result::SUCCESS) { + auto status = mTimeFilter->getSourceTime(_aidl_return); + if (!status.isOk()) { *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; - return Status::fromServiceSpecificError(static_cast(status)); } - return Status::ok(); + return status; } -Status TunerTimeFilter::getTimeStamp(int64_t* _aidl_return) { - if (mTimeFilter == NULL) { +::ndk::ScopedAStatus TunerTimeFilter::getTimeStamp(int64_t* _aidl_return) { + if (mTimeFilter == nullptr) { *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; ALOGE("ITimeFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result status; - mTimeFilter->getTimeStamp( - [&](Result r, uint64_t t) { - status = r; - *_aidl_return = t; - }); - if (status != Result::SUCCESS) { + auto status = mTimeFilter->getTimeStamp(_aidl_return); + if (!status.isOk()) { *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; - return Status::fromServiceSpecificError(static_cast(status)); } - return Status::ok(); + return status; } -Status TunerTimeFilter::close() { - if (mTimeFilter == NULL) { +::ndk::ScopedAStatus TunerTimeFilter::close() { + if (mTimeFilter == nullptr) { ALOGE("ITimeFilter is not initialized"); - return Status::fromServiceSpecificError(static_cast(Result::UNAVAILABLE)); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); } - Result res = mTimeFilter->close(); - mTimeFilter = NULL; + auto status = mTimeFilter->close(); + mTimeFilter = nullptr; - if (res != Result::SUCCESS) { - return Status::fromServiceSpecificError(static_cast(res)); - } - return Status::ok(); + return status; } + +} // namespace tuner +} // namespace tv +} // namespace media } // namespace android +} // namespace aidl diff --git a/services/tuner/TunerTimeFilter.h b/services/tuner/TunerTimeFilter.h index d67531915c..c111694698 100644 --- a/services/tuner/TunerTimeFilter.h +++ b/services/tuner/TunerTimeFilter.h @@ -17,38 +17,41 @@ #ifndef ANDROID_MEDIA_TUNERFTIMEFILTER_H #define ANDROID_MEDIA_TUNERFTIMEFILTER_H +#include #include -#include -#include #include #include -using Status = ::ndk::ScopedAStatus; -using ::aidl::android::media::tv::tuner::BnTunerTimeFilter; -using ::android::hardware::Return; -using ::android::hardware::Void; -using ::android::hardware::hidl_vec; -using ::android::hardware::tv::tuner::V1_0::ITimeFilter; +using ::aidl::android::hardware::tv::tuner::ITimeFilter; using namespace std; +namespace aidl { namespace android { +namespace media { +namespace tv { +namespace tuner { class TunerTimeFilter : public BnTunerTimeFilter { public: - TunerTimeFilter(sp timeFilter); + TunerTimeFilter(shared_ptr timeFilter); virtual ~TunerTimeFilter(); - Status setTimeStamp(int64_t timeStamp) override; - Status clearTimeStamp() override; - Status getSourceTime(int64_t* _aidl_return) override; - Status getTimeStamp(int64_t* _aidl_return) override; - Status close() override; + + ::ndk::ScopedAStatus setTimeStamp(int64_t in_timeStamp) override; + ::ndk::ScopedAStatus clearTimeStamp() override; + ::ndk::ScopedAStatus getSourceTime(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus getTimeStamp(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus close() override; private: - sp mTimeFilter; + shared_ptr mTimeFilter; }; -} // namespace android +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl #endif // ANDROID_MEDIA_TUNERFTIMEFILTER_H diff --git a/services/tuner/main_tunerservice.cpp b/services/tuner/main_tunerservice.cpp index 586a0e2eac..bda2f71371 100644 --- a/services/tuner/main_tunerservice.cpp +++ b/services/tuner/main_tunerservice.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,30 +14,27 @@ * limitations under the License. */ -#include +#include #include #include -#include -#include +#include #include "TunerService.h" +using ::aidl::android::media::tv::tuner::TunerService; + using namespace android; -int main(int argc __unused, char** argv) { +int main() { ALOGD("Tuner service starting"); - strcpy(argv[0], "media.tuner"); sp proc(ProcessState::self()); sp sm = defaultServiceManager(); - ALOGD("ServiceManager: %p", sm.get()); binder_status_t status = TunerService::instantiate(); - if (status != STATUS_OK) { - ALOGD("Failed to add tuner service as AIDL interface"); - return -1; - } + CHECK(status == STATUS_OK); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); + return EXIT_FAILURE; // should not reached } -- GitLab From 7be8c90ad79d45f41b85addebee44e7a8f27c410 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Fri, 6 Aug 2021 22:37:54 +0000 Subject: [PATCH 085/694] Remove confusing A2DP check for fast mixer From a dumpsys of audioflinger, it seems that bluetooth a2dp is using fast mixer. However, from inspecting the code, it seems like this is not the case. After adding log statements, I noticed that outDeviceTypes() always returns nothing in this block. It seems that the statement is not fully ready by the time that this block is called. Later on, outDeviceTypes() seems to work fine but not here. The BT audio HAL should no longer be bursty because of two changes 1. In the Qualcomm and newer HALs, the offload path has been added so the DSP can encode the data instead. This path is not bursty. 2. When offloading is not implemented, the Bluetooth a2dp hal is used. In system/bt, audio_a2dp_hw has been replaced by audio_bluetooth_hw and this HAL is not bursty. This means that using FastMixer for BT is good and the only "fix" needed here is to remove this confusing code. I will do a sweep for other instances of outDeviceTypes() in a future cl. Bug: 195790812 Test: Tested on Bramble with various headsets and offloading turned on/off Change-Id: I773028ba3b79fa6f7fc4244177b24751d373d38d --- services/audioflinger/Threads.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 9665424192..d5394d95f0 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -4569,12 +4569,7 @@ AudioFlinger::MixerThread::MixerThread(const sp& audioFlinger, Aud break; case FastMixer_Static: case FastMixer_Dynamic: - // FastMixer was designed to operate with a HAL that pulls at a regular rate, - // where the period is less than an experimentally determined threshold that can be - // scheduled reliably with CFS. However, the BT A2DP HAL is - // bursty (does not pull at a regular rate) and so cannot operate with FastMixer. - initFastMixer = mFrameCount < mNormalFrameCount - && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty(); + initFastMixer = mFrameCount < mNormalFrameCount; break; } ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount, -- GitLab From e801c20fa4ea00b9c5a6b3669ce6ad1c5a657f11 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Mon, 9 Aug 2021 19:41:08 +0000 Subject: [PATCH 086/694] Add missing include for AString in StagefrightRecorder.h Bug: 189053744 Change-Id: I4eb8271c31cf802cb3df40e21b16e7d111e27d6d Test: manually built. --- media/libmediaplayerservice/StagefrightRecorder.h | 1 + 1 file changed, 1 insertion(+) diff --git a/media/libmediaplayerservice/StagefrightRecorder.h b/media/libmediaplayerservice/StagefrightRecorder.h index d6de47f3cd..d7785da3af 100644 --- a/media/libmediaplayerservice/StagefrightRecorder.h +++ b/media/libmediaplayerservice/StagefrightRecorder.h @@ -26,6 +26,7 @@ #include #include +#include #include namespace android { -- GitLab From 06db0a3f6874cc7d46238b367592361d49fb4280 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Tue, 10 Aug 2021 19:05:34 +0000 Subject: [PATCH 087/694] Add some info about monopipe depth Log the size of the playback and record threads' monopipes Bug: 196060611 Bug: 196071180 Test: adb shell dumpsys media.audio_flinger Change-Id: Ica0d07ca8379842fe2136de330ec123de33b66ed --- .../include/media/nbaio/AudioStreamOutSink.h | 4 --- services/audioflinger/Threads.cpp | 26 +++++++++++++++++++ services/audioflinger/Threads.h | 1 + 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/media/libnbaio/include/media/nbaio/AudioStreamOutSink.h b/media/libnbaio/include/media/nbaio/AudioStreamOutSink.h index 348b4f8273..635f67f010 100644 --- a/media/libnbaio/include/media/nbaio/AudioStreamOutSink.h +++ b/media/libnbaio/include/media/nbaio/AudioStreamOutSink.h @@ -42,10 +42,6 @@ public: //virtual size_t framesUnderrun() const; //virtual size_t underruns() const; - // This is an over-estimate, and could dupe the caller into making a blocking write() - // FIXME Use an audio HAL API to query the buffer emptying status when it's available. - virtual ssize_t availableToWrite() { return mStreamBufferSizeBytes / mFrameSize; } - virtual ssize_t write(const void *buffer, size_t count); virtual status_t getTimestamp(ExtendedTimestamp ×tamp); diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 9665424192..6a6181cd37 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -644,6 +644,7 @@ void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event mIoJitterMs.reset(); mLatencyMs.reset(); mProcessTimeMs.reset(); + mMonopipePipeDepthStats.reset(); mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS); sp configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId); @@ -988,6 +989,12 @@ void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector& args _ isOutput() ? "write" : "read", mLatencyMs.toString().c_str()); } + + if (mMonopipePipeDepthStats.getN() > 0) { + dprintf(fd, " Monopipe %s pipe depth stats: %s\n", + isOutput() ? "write" : "read", + mMonopipePipeDepthStats.toString().c_str()); + } } void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector& args) @@ -1917,6 +1924,12 @@ void AudioFlinger::ThreadBase::sendStatistics(bool force) item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean()); item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev()); } + if (mMonopipePipeDepthStats.getN() > 0) { + item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean", + mMonopipePipeDepthStats.getMean()); + item->setDouble(MM_PREFIX "monopipePipeDepthStats.std", + mMonopipePipeDepthStats.getStdDev()); + } item->selfrecord(); } @@ -3972,6 +3985,18 @@ bool AudioFlinger::PlaybackThread::threadLoop() Mutex::Autolock _l(mLock); mIoJitterMs.add(jitterMs); mProcessTimeMs.add(processMs); + + if (mPipeSink.get() != nullptr) { + // Using the Monopipe availableToWrite, we estimate the current + // buffer size. + MonoPipe* monoPipe = static_cast(mPipeSink.get()); + const ssize_t + availableToWrite = mPipeSink->availableToWrite(); + const size_t pipeFrames = monoPipe->maxFrames(); + const size_t + remainingFrames = pipeFrames - max(availableToWrite, 0); + mMonopipePipeDepthStats.add(remainingFrames); + } } // write blocked detection @@ -7588,6 +7613,7 @@ reacquire_wakelock: const ssize_t availableToRead = mPipeSource->availableToRead(); if (availableToRead >= 0) { + mMonopipePipeDepthStats.add(availableToRead); // PipeSource is the primary clock. It is up to the AudioRecord client to keep up. LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2, "more frames to read than fifo size, %zd > %zu", diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h index 38e55a301f..9cf457a7e5 100644 --- a/services/audioflinger/Threads.h +++ b/services/audioflinger/Threads.h @@ -684,6 +684,7 @@ protected: audio_utils::Statistics mIoJitterMs{0.995 /* alpha */}; audio_utils::Statistics mProcessTimeMs{0.995 /* alpha */}; audio_utils::Statistics mLatencyMs{0.995 /* alpha */}; + audio_utils::Statistics mMonopipePipeDepthStats{0.999 /* alpha */}; // Save the last count when we delivered statistics to mediametrics. int64_t mLastRecordedTimestampVerifierN = 0; -- GitLab From f3d98cdfc2ede1a247733de9588b77c8c81acea5 Mon Sep 17 00:00:00 2001 From: Colin Cross Date: Tue, 10 Aug 2021 13:56:45 -0700 Subject: [PATCH 088/694] Add android:exported tag These are now required to be explicitly specified for apps targetting API 31. Bug: 195988762 Test: make Change-Id: If1d8974150e14421a977674af7f0b0230af0e0be --- .../SampleVideoEncoder/app/src/main/AndroidManifest.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/media/tests/SampleVideoEncoder/app/src/main/AndroidManifest.xml b/media/tests/SampleVideoEncoder/app/src/main/AndroidManifest.xml index b17541d4a3..75d73bf9d7 100644 --- a/media/tests/SampleVideoEncoder/app/src/main/AndroidManifest.xml +++ b/media/tests/SampleVideoEncoder/app/src/main/AndroidManifest.xml @@ -30,7 +30,8 @@ android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> - + @@ -42,4 +43,4 @@ android:targetPackage="com.android.media.samplevideoencoder" android:label="SampleVideoEncoder Test"/> - \ No newline at end of file + -- GitLab From c6e64010f806688c413c39241583b3c2dd9ba082 Mon Sep 17 00:00:00 2001 From: Rucha Katakwar Date: Thu, 12 Aug 2021 06:32:42 +0000 Subject: [PATCH 089/694] Camera: Fix for HWAddressSanitizer tag mismatch. In ACameraManager when binderDied is executed, iteration happens over the mDeviceStatusMap to get the cameraId. This same map gets modified in onStatusChangedLocked and also sometimes deleting the cameraId entry if the new status is NOT_PRESENT. This causes crash while accessing memory just deleted. This change creates a list of cameraId which is then used during the iteration in binderDied. bug: 194808760 Test: 1.Run NativeCameraDeviceTest#testCameraDeviceOpenAndClose and kill cameraserver process to trigger binderDied.Verified the logs that cameraId is passed to onStatusChangedLock. 2.Camera cts test suite currently in progress on device. Change-Id: Ib885941e0d0ca7c25d2172f6e1314bb7bef451b7 --- camera/ndk/impl/ACameraManager.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/camera/ndk/impl/ACameraManager.cpp b/camera/ndk/impl/ACameraManager.cpp index 95ef2b2af1..5892f1ad0f 100644 --- a/camera/ndk/impl/ACameraManager.cpp +++ b/camera/ndk/impl/ACameraManager.cpp @@ -189,8 +189,12 @@ void CameraManagerGlobal::DeathNotifier::binderDied(const wp&) sp cm = mCameraManager.promote(); if (cm != nullptr) { AutoMutex lock(cm->mLock); + std::vector cameraIdList; for (auto& pair : cm->mDeviceStatusMap) { - const String8 &cameraId = pair.first; + cameraIdList.push_back(pair.first); + } + + for (String8 cameraId : cameraIdList) { cm->onStatusChangedLocked( CameraServiceListener::STATUS_NOT_PRESENT, cameraId); } -- GitLab From 4c7bb7dd30c34fbfc05b2511d109d6e53b663771 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Thu, 12 Aug 2021 18:50:13 +0000 Subject: [PATCH 090/694] Change a verbose message to debug Changing an error message to debug for better logging Bug: 195393472 Test: mma Change-Id: I6b3b08e1393c56e7e9bcbb6b846f3a36f135dbe6 --- services/audioflinger/Threads.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 6a6181cd37..29d014f00c 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -2286,7 +2286,7 @@ sp AudioFlinger::PlaybackThread::createTrac "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu", frameCount, mFrameCount); } else { - ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu " + ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu " "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x " "sampleRate=%u mSampleRate=%u " "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x", -- GitLab From c121cd192e62d6f662b771c9115816b71a84797a Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Fri, 13 Aug 2021 17:51:40 +0000 Subject: [PATCH 091/694] Reduce an log to verbose In AudioFlinger, we added more info to a specific failure case. This cl removes an unnecessary log in AudioTrack to keep logs to a minimum. Bug: 194956750 Test: mma Change-Id: If6b61e667710f709a42e39652de914df6048f380 --- media/libaudioclient/AudioTrack.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 5b7760b0b4..1149790412 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -1797,7 +1797,7 @@ status_t AudioTrack::createTrack_l() mAwaitBoost = true; } } else { - ALOGD("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", + ALOGV("%s(%d): AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu -> %zu", __func__, mPortId, mReqFrameCount, mFrameCount); } } -- GitLab From cd277cd3be600318a88632cfbb2ad9dd213e49f5 Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Wed, 11 Aug 2021 15:48:40 -0700 Subject: [PATCH 092/694] cameraserver: Add stream id to capture request tag monitoring. Bug: 196264836 Test: adb shell dumpsys media.camera -m "android.control.zoomRatio" shows stream ids for each capture request. Change-Id: I1990fb572b733597f72064c4377f062da8fea021 Signed-off-by: Jayant Chowdhary --- .../device3/Camera3Device.cpp | 18 +++++-- .../libcameraservice/device3/Camera3Device.h | 3 +- .../device3/Camera3OutputUtils.cpp | 2 +- .../libcameraservice/utils/TagMonitor.cpp | 53 ++++++++++++++----- .../libcameraservice/utils/TagMonitor.h | 18 +++++-- 5 files changed, 73 insertions(+), 21 deletions(-) diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp index fc17f4f48d..7c3c6b78e6 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.cpp +++ b/services/camera/libcameraservice/device3/Camera3Device.cpp @@ -3083,10 +3083,11 @@ CameraMetadata Camera3Device::getLatestRequestLocked() { void Camera3Device::monitorMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, - const std::unordered_map& physicalMetadata) { + const std::unordered_map& physicalMetadata, + const std::set &outputStreamIds, int32_t inputStreamId) { mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata, - physicalMetadata); + physicalMetadata, outputStreamIds, inputStreamId); } /** @@ -4589,9 +4590,20 @@ void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) { sp parent = mParent.promote(); if (parent != NULL) { + std::set outputStreamIds; + for (size_t i = 0; i < halRequest.num_output_buffers; i++) { + const camera_stream_buffer_t *src = halRequest.output_buffers + i; + int32_t streamId = Camera3Stream::cast(src->stream)->getId(); + outputStreamIds.emplace(streamId); + } + int32_t inputStreamId = -1; + if (halRequest.input_buffer != nullptr) { + inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId(); + } + parent->monitorMetadata(TagMonitor::REQUEST, halRequest.frame_number, - 0, mLatestRequest, mLatestPhysicalRequest); + 0, mLatestRequest, mLatestPhysicalRequest, outputStreamIds, inputStreamId); } } diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h index 1fe72f191e..c0dc6f85c1 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.h +++ b/services/camera/libcameraservice/device3/Camera3Device.h @@ -1249,7 +1249,8 @@ class Camera3Device : void monitorMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, - const std::unordered_map& physicalMetadata); + const std::unordered_map& physicalMetadata, + const std::set &outputStreamIds, int32_t inputStreamId); metadata_vendor_id_t mVendorTagId; diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp index 9f225d0c82..ef51adaf50 100644 --- a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp +++ b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp @@ -368,7 +368,7 @@ void sendCaptureResult( } states.tagMonitor.monitorMetadata(TagMonitor::RESULT, frameNumber, sensorTimestamp, captureResult.mMetadata, - monitoredPhysicalMetadata); + monitoredPhysicalMetadata, std::set()); insertResultLocked(states, &captureResult, frameNumber); } diff --git a/services/camera/libcameraservice/utils/TagMonitor.cpp b/services/camera/libcameraservice/utils/TagMonitor.cpp index 262f962c74..53a92e968a 100644 --- a/services/camera/libcameraservice/utils/TagMonitor.cpp +++ b/services/camera/libcameraservice/utils/TagMonitor.cpp @@ -112,11 +112,14 @@ void TagMonitor::disableMonitoring() { mLastMonitoredResultValues.clear(); mLastMonitoredPhysicalRequestKeys.clear(); mLastMonitoredPhysicalResultKeys.clear(); + mLastStreamIds.clear(); + mLastInputStreamId = -1; } void TagMonitor::monitorMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, - const std::unordered_map& physicalMetadata) { + const std::unordered_map& physicalMetadata, + const std::set &outputStreamIds, int32_t inputStreamId) { if (!mMonitoringEnabled) return; std::lock_guard lock(mMonitorMutex); @@ -127,16 +130,19 @@ void TagMonitor::monitorMetadata(eventSource source, int64_t frameNumber, nsecs_ std::string emptyId; for (auto tag : mMonitoredTagList) { - monitorSingleMetadata(source, frameNumber, timestamp, emptyId, tag, metadata); + monitorSingleMetadata(source, frameNumber, timestamp, emptyId, tag, metadata, + outputStreamIds, inputStreamId); for (auto& m : physicalMetadata) { - monitorSingleMetadata(source, frameNumber, timestamp, m.first, tag, m.second); + monitorSingleMetadata(source, frameNumber, timestamp, m.first, tag, m.second, + outputStreamIds, inputStreamId); } } } void TagMonitor::monitorSingleMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, - const std::string& cameraId, uint32_t tag, const CameraMetadata& metadata) { + const std::string& cameraId, uint32_t tag, const CameraMetadata& metadata, + const std::set &outputStreamIds, int32_t inputStreamId) { CameraMetadata &lastValues = (source == REQUEST) ? (cameraId.empty() ? mLastMonitoredRequestValues : @@ -177,13 +183,21 @@ void TagMonitor::monitorSingleMetadata(eventSource source, int64_t frameNumber, // No last entry, so always consider to be different isDifferent = true; } - + // Also monitor when the stream ids change, this helps visually see what + // monitored metadata values are for capture requests with different + // stream ids. + if (inputStreamId != mLastInputStreamId || outputStreamIds != mLastStreamIds) { + mLastInputStreamId = inputStreamId; + mLastStreamIds = outputStreamIds; + isDifferent = true; + } if (isDifferent) { ALOGV("%s: Tag %s changed", __FUNCTION__, get_local_camera_metadata_tag_name_vendor_id( tag, mVendorTagId)); lastValues.update(entry); - mMonitoringEvents.emplace(source, frameNumber, timestamp, entry, cameraId); + mMonitoringEvents.emplace(source, frameNumber, timestamp, entry, cameraId, + outputStreamIds, inputStreamId); } } else if (lastEntry.count > 0) { // Value has been removed @@ -195,7 +209,10 @@ void TagMonitor::monitorSingleMetadata(eventSource source, int64_t frameNumber, entry.type = get_local_camera_metadata_tag_type_vendor_id(tag, mVendorTagId); entry.count = 0; - mMonitoringEvents.emplace(source, frameNumber, timestamp, entry, cameraId); + mLastInputStreamId = inputStreamId; + mLastStreamIds = outputStreamIds; + mMonitoringEvents.emplace(source, frameNumber, timestamp, entry, cameraId, outputStreamIds, + inputStreamId); } } @@ -232,7 +249,7 @@ void TagMonitor::dumpMonitoredMetadata(int fd) { } else { printData(fd, event.newData.data(), event.tag, event.type, event.newData.size() / camera_metadata_type_size[event.type], - indentation + 18); + indentation + 18, event.outputStreamIds, event.inputStreamId); } } } @@ -244,7 +261,8 @@ void TagMonitor::dumpMonitoredMetadata(int fd) { #define CAMERA_METADATA_ENUM_STRING_MAX_SIZE 29 void TagMonitor::printData(int fd, const uint8_t *data_ptr, uint32_t tag, - int type, int count, int indentation) { + int type, int count, int indentation, const std::set &outputStreamIds, + int32_t inputStreamId) { static int values_per_line[NUM_TYPES] = { [TYPE_BYTE] = 16, [TYPE_INT32] = 8, @@ -319,20 +337,31 @@ void TagMonitor::printData(int fd, const uint8_t *data_ptr, uint32_t tag, dprintf(fd, "??? "); } } - dprintf(fd, "]\n"); + dprintf(fd, "] "); + if (outputStreamIds.size() > 0) { + dprintf(fd, "output stream ids: "); + for (const auto &id : outputStreamIds) { + dprintf(fd, " %d ", id); + } + } + if (inputStreamId != -1) { + dprintf(fd, "input stream id: %d", inputStreamId); + } + dprintf(fd, "\n"); } } template TagMonitor::MonitorEvent::MonitorEvent(eventSource src, uint32_t frameNumber, nsecs_t timestamp, - const T &value, const std::string& cameraId) : + const T &value, const std::string& cameraId, const std::set &outputStreamIds, + int32_t inputStreamId) : source(src), frameNumber(frameNumber), timestamp(timestamp), tag(value.tag), type(value.type), newData(value.data.u8, value.data.u8 + camera_metadata_type_size[value.type] * value.count), - cameraId(cameraId) { + cameraId(cameraId), outputStreamIds(outputStreamIds), inputStreamId(inputStreamId) { } TagMonitor::MonitorEvent::~MonitorEvent() { diff --git a/services/camera/libcameraservice/utils/TagMonitor.h b/services/camera/libcameraservice/utils/TagMonitor.h index 413f502020..dfc424ea66 100644 --- a/services/camera/libcameraservice/utils/TagMonitor.h +++ b/services/camera/libcameraservice/utils/TagMonitor.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -66,7 +67,8 @@ class TagMonitor { // Scan through the metadata and update the monitoring information void monitorMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, - const std::unordered_map& physicalMetadata); + const std::unordered_map& physicalMetadata, + const std::set &outputStreamIds, int32_t inputStreamId = -1); // Dump current event log to the provided fd void dumpMonitoredMetadata(int fd); @@ -74,11 +76,13 @@ class TagMonitor { private: static void printData(int fd, const uint8_t *data_ptr, uint32_t tag, - int type, int count, int indentation); + int type, int count, int indentation, const std::set &outputStreamIds, + int32_t inputStreamId); void monitorSingleMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const std::string& cameraId, uint32_t tag, - const CameraMetadata& metadata); + const CameraMetadata& metadata, const std::set &outputStreamIds, + int32_t inputStreamId); std::atomic mMonitoringEnabled; std::mutex mMonitorMutex; @@ -93,6 +97,9 @@ class TagMonitor { std::unordered_map mLastMonitoredPhysicalRequestKeys; std::unordered_map mLastMonitoredPhysicalResultKeys; + int32_t mLastInputStreamId = -1; + std::set mLastStreamIds; + /** * A monitoring event * Stores a new metadata field value and the timestamp at which it changed. @@ -101,7 +108,8 @@ class TagMonitor { struct MonitorEvent { template MonitorEvent(eventSource src, uint32_t frameNumber, nsecs_t timestamp, - const T &newValue, const std::string& cameraId); + const T &newValue, const std::string& cameraId, + const std::set &outputStreamIds, int32_t inputStreamId); ~MonitorEvent(); eventSource source; @@ -111,6 +119,8 @@ class TagMonitor { uint8_t type; std::vector newData; std::string cameraId; + std::set outputStreamIds; + int32_t inputStreamId = 1; }; // A ring buffer for tracking the last kMaxMonitorEvents metadata changes -- GitLab From b00edc3878939d6bdb0c1460790891675e42f12f Mon Sep 17 00:00:00 2001 From: jiabin Date: Mon, 16 Aug 2021 16:27:54 +0000 Subject: [PATCH 093/694] Add format conversion in AudioRecord. In audio flinger, it is required that the client's format matches the hardware format to get fast mode. However, format conversion is not a time consuming operation. In that case, adding format conversion in AudioRecord can help the client get fast mode if only format is different from the hardware one. This can help improve latency. Test: atest AudioRecordTest, capture audio in fast/non-fast mode Bug: 79156275 Bug: 188843084 Change-Id: I1baaa9a6054bb84412c31a159c6d25ee498822cf --- media/libaudioclient/AudioRecord.cpp | 36 ++++++++++++++----- media/libaudioclient/IAudioFlinger.cpp | 4 +++ .../android/media/CreateRecordResponse.aidl | 2 ++ .../include/media/AudioRecord.h | 7 ++++ .../include/media/IAudioFlinger.h | 1 + services/audioflinger/AudioFlinger.cpp | 14 ++++++++ services/audioflinger/Threads.cpp | 3 +- 7 files changed, 57 insertions(+), 10 deletions(-) diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp index a02a373193..d3c5231595 100644 --- a/media/libaudioclient/AudioRecord.cpp +++ b/media/libaudioclient/AudioRecord.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -858,6 +859,10 @@ status_t AudioRecord::createRecord_l(const Modulo &epoch) mRoutedDeviceId = output.selectedDeviceId; mSessionId = output.sessionId; mSampleRate = output.sampleRate; + mServerConfig = output.serverConfig; + mServerFrameSize = audio_bytes_per_frame( + audio_channel_count_from_in_mask(mServerConfig.channel_mask), mServerConfig.format); + mServerSampleSize = audio_bytes_per_sample(mServerConfig.format); if (output.cblk == 0) { ALOGE("%s(%d): Could not get control block", __func__, mPortId); @@ -921,6 +926,10 @@ status_t AudioRecord::createRecord_l(const Modulo &epoch) mNotificationFramesReq, output.notificationFrameCount, output.frameCount); } mNotificationFramesAct = (uint32_t)output.notificationFrameCount; + if (mServerConfig.format != mFormat && mCbf != nullptr) { + mFormatConversionBufRaw = std::make_unique(mNotificationFramesAct * mFrameSize); + mFormatConversionBuffer.raw = mFormatConversionBufRaw.get(); + } //mInput != input includes the case where mInput == AUDIO_IO_HANDLE_NONE for first creation if (mDeviceCallback != 0) { @@ -947,7 +956,7 @@ status_t AudioRecord::createRecord_l(const Modulo &epoch) } // update proxy - mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mFrameSize); + mProxy = new AudioRecordClientProxy(cblk, buffers, mFrameCount, mServerFrameSize); mProxy->setEpoch(epoch); mProxy->setMinimum(mNotificationFramesAct); @@ -1077,7 +1086,7 @@ status_t AudioRecord::obtainBuffer(Buffer* audioBuffer, const struct timespec *r } while ((status == DEAD_OBJECT) && (tryCounter-- > 0)); audioBuffer->frameCount = buffer.mFrameCount; - audioBuffer->size = buffer.mFrameCount * mFrameSize; + audioBuffer->size = buffer.mFrameCount * mServerFrameSize; audioBuffer->raw = buffer.mRaw; audioBuffer->sequence = oldSequence; if (nonContig != NULL) { @@ -1090,7 +1099,7 @@ void AudioRecord::releaseBuffer(const Buffer* audioBuffer) { // FIXME add error checking on mode, by adding an internal version - size_t stepCount = audioBuffer->size / mFrameSize; + size_t stepCount = audioBuffer->frameCount; if (stepCount == 0) { return; } @@ -1152,8 +1161,9 @@ ssize_t AudioRecord::read(void* buffer, size_t userSize, bool blocking) return ssize_t(err); } - size_t bytesRead = audioBuffer.size; - memcpy(buffer, audioBuffer.i8, bytesRead); + size_t bytesRead = audioBuffer.frameCount * mFrameSize; + memcpy_by_audio_format(buffer, mFormat, audioBuffer.raw, mServerConfig.format, + audioBuffer.size / mServerSampleSize); buffer = ((char *) buffer) + bytesRead; userSize -= bytesRead; read += bytesRead; @@ -1350,9 +1360,19 @@ nsecs_t AudioRecord::processAudioBuffer() } } - size_t reqSize = audioBuffer.size; - mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer); - size_t readSize = audioBuffer.size; + Buffer* buffer = &audioBuffer; + if (mServerConfig.format != mFormat) { + buffer = &mFormatConversionBuffer; + buffer->frameCount = audioBuffer.frameCount; + buffer->size = buffer->frameCount * mFrameSize; + buffer->sequence = audioBuffer.sequence; + memcpy_by_audio_format(buffer->raw, mFormat, audioBuffer.raw, + mServerConfig.format, audioBuffer.size / mServerSampleSize); + } + + size_t reqSize = buffer->size; + mCbf(EVENT_MORE_DATA, mUserData, buffer); + size_t readSize = buffer->size; // Validate on returned size if (ssize_t(readSize) < 0 || readSize > reqSize) { diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 5f12f71c36..6d2ec9352f 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -195,6 +195,8 @@ IAudioFlinger::CreateRecordOutput::toAidl() const { aidl.buffers = VALUE_OR_RETURN(legacy2aidl_NullableIMemory_SharedFileRegion(buffers)); aidl.portId = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(portId)); aidl.audioRecord = audioRecord; + aidl.serverConfig = VALUE_OR_RETURN( + legacy2aidl_audio_config_base_t_AudioConfigBase(serverConfig, true /*isInput*/)); return aidl; } @@ -215,6 +217,8 @@ IAudioFlinger::CreateRecordOutput::fromAidl( legacy.buffers = VALUE_OR_RETURN(aidl2legacy_NullableSharedFileRegion_IMemory(aidl.buffers)); legacy.portId = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.portId)); legacy.audioRecord = aidl.audioRecord; + legacy.serverConfig = VALUE_OR_RETURN( + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.serverConfig, true /*isInput*/)); return legacy; } diff --git a/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl b/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl index d78b3fcd2b..61195d096a 100644 --- a/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl +++ b/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl @@ -16,6 +16,7 @@ package android.media; +import android.media.AudioConfigBase; import android.media.IAudioRecord; import android.media.SharedFileRegion; @@ -43,4 +44,5 @@ parcelable CreateRecordResponse { int portId; /** The newly created record. */ @nullable IAudioRecord audioRecord; + AudioConfigBase serverConfig; } diff --git a/media/libaudioclient/include/media/AudioRecord.h b/media/libaudioclient/include/media/AudioRecord.h index f17ee3a507..a32c595916 100644 --- a/media/libaudioclient/include/media/AudioRecord.h +++ b/media/libaudioclient/include/media/AudioRecord.h @@ -760,6 +760,13 @@ private: bool mTimestampRetrogradePositionReported = false; // reduce log spam bool mTimestampRetrogradeTimeReported = false; // reduce log spam + // Format conversion. Maybe needed for adding fast tracks whose format is different from server. + audio_config_base_t mServerConfig; + size_t mServerFrameSize; + size_t mServerSampleSize; + std::unique_ptr mFormatConversionBufRaw; + Buffer mFormatConversionBuffer; + private: class DeathNotifier : public IBinder::DeathRecipient { public: diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 8632abb4e7..a2ce145e74 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -166,6 +166,7 @@ public: sp buffers; audio_port_handle_t portId; sp audioRecord; + audio_config_base_t serverConfig; ConversionResult toAidl() const; static ConversionResult diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index a1fb304e60..445de02ebe 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -2142,6 +2142,20 @@ status_t AudioFlinger::createRecord(const media::CreateRecordRequest& _input, goto Exit; } + if (recordTrack->isFastTrack()) { + output.serverConfig = { + thread->sampleRate(), + thread->channelMask(), + thread->format() + }; + } else { + output.serverConfig = { + recordTrack->sampleRate(), + recordTrack->channelMask(), + recordTrack->format() + }; + } + // Check if one effect chain was awaiting for an AudioRecord to be created on this // session and move it to this thread. sp chain = getOrphanEffectChain_l(sessionId); diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp index 9665424192..a07b9b1b15 100644 --- a/services/audioflinger/Threads.cpp +++ b/services/audioflinger/Threads.cpp @@ -8016,6 +8016,7 @@ sp AudioFlinger::RecordThread::createRe if ( // we formerly checked for a callback handler (non-0 tid), // but that is no longer required for TRANSFER_OBTAIN mode + // No need to match hardware format, format conversion will be done in client side. // // Frame count is not specified (0), or is less than or equal the pipe depth. // It is OK to provide a higher capacity than requested. @@ -8023,8 +8024,6 @@ sp AudioFlinger::RecordThread::createRe (frameCount <= mPipeFramesP2) && // PCM data audio_is_linear_pcm(format) && - // hardware format - (format == mFormat) && // hardware channel mask (channelMask == mChannelMask) && // hardware sample rate -- GitLab From ee1871384aeb9ad785a9b1dcecae578439ee5207 Mon Sep 17 00:00:00 2001 From: Neelkamal Semwal Date: Wed, 14 Jul 2021 09:50:52 +0530 Subject: [PATCH 094/694] mp3dec: Ignore integer overflow in pvmp3_st_intensity Test: poc in bug description Test: atest Mp3DecoderTest -- --enable-module-dynamic-download=true Test: atest VtsHalMediaC2V1_0TargetAudioDecTest Bug: 170373840 Change-Id: I7f1614bf418f5b1df25846316099110d87ce91b8 --- media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp b/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp index 4338c4380d..c04f7f3c72 100644 --- a/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp +++ b/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp @@ -219,6 +219,9 @@ void pvmp3_st_mid_side(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS], ; FUNCTION CODE ----------------------------------------------------------------------------*/ +#if __has_attribute(no_sanitize) +__attribute__((no_sanitize("integer"))) +#endif void pvmp3_st_intensity(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS], int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS], int32 is_pos, -- GitLab From c30b4c3078b2c7bb9cf924eb32d1ad3217aa4a4a Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Wed, 18 Aug 2021 11:43:16 -0700 Subject: [PATCH 095/694] TagMonitor: don't allocate a set of stream ids if monitoring is not enabled. Bug: 196264836 Test: adb shell dumpsys media.camera -m "android.control.zoomRatio" shows stream ids requests/ Change-Id: I1e722235724f25114fa30d77a6d6486c6d6b638c Signed-off-by: Jayant Chowdhary --- .../device3/Camera3Device.cpp | 14 ++--- .../libcameraservice/device3/Camera3Device.h | 3 +- .../device3/Camera3OutputUtils.cpp | 2 +- .../device3/Camera3OutputUtils.h | 60 ------------------- .../device3/InFlightRequest.h | 60 +++++++++++++++++++ .../libcameraservice/utils/TagMonitor.cpp | 21 +++++-- .../libcameraservice/utils/TagMonitor.h | 17 +++--- 7 files changed, 92 insertions(+), 85 deletions(-) diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp index 7c3c6b78e6..368c39c260 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.cpp +++ b/services/camera/libcameraservice/device3/Camera3Device.cpp @@ -3084,10 +3084,11 @@ CameraMetadata Camera3Device::getLatestRequestLocked() { void Camera3Device::monitorMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, const std::unordered_map& physicalMetadata, - const std::set &outputStreamIds, int32_t inputStreamId) { + const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers, + int32_t inputStreamId) { mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata, - physicalMetadata, outputStreamIds, inputStreamId); + physicalMetadata, outputBuffers, numOutputBuffers, inputStreamId); } /** @@ -4590,12 +4591,6 @@ void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) { sp parent = mParent.promote(); if (parent != NULL) { - std::set outputStreamIds; - for (size_t i = 0; i < halRequest.num_output_buffers; i++) { - const camera_stream_buffer_t *src = halRequest.output_buffers + i; - int32_t streamId = Camera3Stream::cast(src->stream)->getId(); - outputStreamIds.emplace(streamId); - } int32_t inputStreamId = -1; if (halRequest.input_buffer != nullptr) { inputStreamId = Camera3Stream::cast(halRequest.input_buffer->stream)->getId(); @@ -4603,7 +4598,8 @@ void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) { parent->monitorMetadata(TagMonitor::REQUEST, halRequest.frame_number, - 0, mLatestRequest, mLatestPhysicalRequest, outputStreamIds, inputStreamId); + 0, mLatestRequest, mLatestPhysicalRequest, halRequest.output_buffers, + halRequest.num_output_buffers, inputStreamId); } } diff --git a/services/camera/libcameraservice/device3/Camera3Device.h b/services/camera/libcameraservice/device3/Camera3Device.h index c0dc6f85c1..ffc239bf01 100644 --- a/services/camera/libcameraservice/device3/Camera3Device.h +++ b/services/camera/libcameraservice/device3/Camera3Device.h @@ -1250,7 +1250,8 @@ class Camera3Device : void monitorMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, const std::unordered_map& physicalMetadata, - const std::set &outputStreamIds, int32_t inputStreamId); + const camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers, + int32_t inputStreamId); metadata_vendor_id_t mVendorTagId; diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp index ef51adaf50..9f225d0c82 100644 --- a/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp +++ b/services/camera/libcameraservice/device3/Camera3OutputUtils.cpp @@ -368,7 +368,7 @@ void sendCaptureResult( } states.tagMonitor.monitorMetadata(TagMonitor::RESULT, frameNumber, sensorTimestamp, captureResult.mMetadata, - monitoredPhysicalMetadata, std::set()); + monitoredPhysicalMetadata); insertResultLocked(states, &captureResult, frameNumber); } diff --git a/services/camera/libcameraservice/device3/Camera3OutputUtils.h b/services/camera/libcameraservice/device3/Camera3OutputUtils.h index 142889a1b3..3f54ac58aa 100644 --- a/services/camera/libcameraservice/device3/Camera3OutputUtils.h +++ b/services/camera/libcameraservice/device3/Camera3OutputUtils.h @@ -42,66 +42,6 @@ using ResultMetadataQueue = hardware::MessageQueue #include #include +#include namespace android { @@ -119,7 +120,8 @@ void TagMonitor::disableMonitoring() { void TagMonitor::monitorMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, const std::unordered_map& physicalMetadata, - const std::set &outputStreamIds, int32_t inputStreamId) { + const camera3::camera_stream_buffer_t *outputBuffers, uint32_t numOutputBuffers, + int32_t inputStreamId) { if (!mMonitoringEnabled) return; std::lock_guard lock(mMonitorMutex); @@ -127,7 +129,12 @@ void TagMonitor::monitorMetadata(eventSource source, int64_t frameNumber, nsecs_ if (timestamp == 0) { timestamp = systemTime(SYSTEM_TIME_BOOTTIME); } - + std::unordered_set outputStreamIds; + for (size_t i = 0; i < numOutputBuffers; i++) { + const camera3::camera_stream_buffer_t *src = outputBuffers + i; + int32_t streamId = camera3::Camera3Stream::cast(src->stream)->getId(); + outputStreamIds.emplace(streamId); + } std::string emptyId; for (auto tag : mMonitoredTagList) { monitorSingleMetadata(source, frameNumber, timestamp, emptyId, tag, metadata, @@ -142,7 +149,7 @@ void TagMonitor::monitorMetadata(eventSource source, int64_t frameNumber, nsecs_ void TagMonitor::monitorSingleMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, const std::string& cameraId, uint32_t tag, const CameraMetadata& metadata, - const std::set &outputStreamIds, int32_t inputStreamId) { + const std::unordered_set &outputStreamIds, int32_t inputStreamId) { CameraMetadata &lastValues = (source == REQUEST) ? (cameraId.empty() ? mLastMonitoredRequestValues : @@ -186,7 +193,8 @@ void TagMonitor::monitorSingleMetadata(eventSource source, int64_t frameNumber, // Also monitor when the stream ids change, this helps visually see what // monitored metadata values are for capture requests with different // stream ids. - if (inputStreamId != mLastInputStreamId || outputStreamIds != mLastStreamIds) { + if (source == REQUEST && + (inputStreamId != mLastInputStreamId || outputStreamIds != mLastStreamIds)) { mLastInputStreamId = inputStreamId; mLastStreamIds = outputStreamIds; isDifferent = true; @@ -261,7 +269,7 @@ void TagMonitor::dumpMonitoredMetadata(int fd) { #define CAMERA_METADATA_ENUM_STRING_MAX_SIZE 29 void TagMonitor::printData(int fd, const uint8_t *data_ptr, uint32_t tag, - int type, int count, int indentation, const std::set &outputStreamIds, + int type, int count, int indentation, const std::unordered_set &outputStreamIds, int32_t inputStreamId) { static int values_per_line[NUM_TYPES] = { [TYPE_BYTE] = 16, @@ -353,7 +361,8 @@ void TagMonitor::printData(int fd, const uint8_t *data_ptr, uint32_t tag, template TagMonitor::MonitorEvent::MonitorEvent(eventSource src, uint32_t frameNumber, nsecs_t timestamp, - const T &value, const std::string& cameraId, const std::set &outputStreamIds, + const T &value, const std::string& cameraId, + const std::unordered_set &outputStreamIds, int32_t inputStreamId) : source(src), frameNumber(frameNumber), diff --git a/services/camera/libcameraservice/utils/TagMonitor.h b/services/camera/libcameraservice/utils/TagMonitor.h index dfc424ea66..f6df4b79f8 100644 --- a/services/camera/libcameraservice/utils/TagMonitor.h +++ b/services/camera/libcameraservice/utils/TagMonitor.h @@ -20,7 +20,6 @@ #include #include #include -#include #include #include @@ -31,6 +30,7 @@ #include #include #include +#include namespace android { @@ -68,7 +68,8 @@ class TagMonitor { void monitorMetadata(eventSource source, int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata, const std::unordered_map& physicalMetadata, - const std::set &outputStreamIds, int32_t inputStreamId = -1); + const camera3::camera_stream_buffer_t *outputBuffers = nullptr, + uint32_t numOutputBuffers = 0, int32_t inputStreamId = -1); // Dump current event log to the provided fd void dumpMonitoredMetadata(int fd); @@ -76,12 +77,12 @@ class TagMonitor { private: static void printData(int fd, const uint8_t *data_ptr, uint32_t tag, - int type, int count, int indentation, const std::set &outputStreamIds, - int32_t inputStreamId); + int type, int count, int indentation, + const std::unordered_set &outputStreamIds, int32_t inputStreamId); void monitorSingleMetadata(TagMonitor::eventSource source, int64_t frameNumber, nsecs_t timestamp, const std::string& cameraId, uint32_t tag, - const CameraMetadata& metadata, const std::set &outputStreamIds, + const CameraMetadata& metadata, const std::unordered_set &outputStreamIds, int32_t inputStreamId); std::atomic mMonitoringEnabled; @@ -98,7 +99,7 @@ class TagMonitor { std::unordered_map mLastMonitoredPhysicalResultKeys; int32_t mLastInputStreamId = -1; - std::set mLastStreamIds; + std::unordered_set mLastStreamIds; /** * A monitoring event @@ -109,7 +110,7 @@ class TagMonitor { template MonitorEvent(eventSource src, uint32_t frameNumber, nsecs_t timestamp, const T &newValue, const std::string& cameraId, - const std::set &outputStreamIds, int32_t inputStreamId); + const std::unordered_set &outputStreamIds, int32_t inputStreamId); ~MonitorEvent(); eventSource source; @@ -119,7 +120,7 @@ class TagMonitor { uint8_t type; std::vector newData; std::string cameraId; - std::set outputStreamIds; + std::unordered_set outputStreamIds; int32_t inputStreamId = 1; }; -- GitLab From 1d9c0ec299d03f5d83df8442cfacb308c9cfa538 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Wed, 18 Aug 2021 21:45:08 -0700 Subject: [PATCH 096/694] Document why we ignore overflows in pvmp3_st_intensity Bug: 170373840 Test: poc in bug description Test: atest Mp3DecoderTest -- --enable-module-dynamic-download=true Test: atest VtsHalMediaC2V1_0TargetAudioDecTest Change-Id: I8fa1dcfb2161e2ff4427e06ae2a23e0bb08c3d83 --- media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp b/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp index c04f7f3c72..b3ecc7701e 100644 --- a/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp +++ b/media/codecs/mp3dec/src/pvmp3_stereo_proc.cpp @@ -219,6 +219,7 @@ void pvmp3_st_mid_side(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS], ; FUNCTION CODE ----------------------------------------------------------------------------*/ +// deliberately plays near overflow points of int32 #if __has_attribute(no_sanitize) __attribute__((no_sanitize("integer"))) #endif -- GitLab From 81dd0f584e1c36b8bbf65737c83386d47cc6102a Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Mon, 5 Jul 2021 11:54:40 +0200 Subject: [PATCH 097/694] audio policy: add Spatializer effect control Add APIs to discover support for audio spatialization function and control a spatializer output mixer and effect creation to Audio Policy Service. When supported, a system service can retrieve a ISpatializer interface to query supported features and set a spatialization mode. When spatialization is enabled, the corresponding specialized output mixer is created and the effect applied. The audio policy manager will attach clients which audio attributes and format qualifying for spatialization to the specialized output mixer. Bug: 188502620 Test: make Change-Id: Ie2734fb9bb3ef9b945431c6c9bd110b1434a79cd --- media/libaudioclient/Android.bp | 5 + media/libaudioclient/AudioSystem.cpp | 41 ++ .../android/media/GetSpatializerResponse.aidl | 28 ++ .../aidl/android/media/HeadTrackingMode.aidl | 35 ++ .../android/media/IAudioPolicyService.aidl | 27 ++ .../media/INativeSpatializerCallback.aidl | 33 ++ .../aidl/android/media/ISpatializer.aidl | 68 ++++ .../android/media/SpatializationLevel.aidl | 34 ++ .../include/media/AudioSystem.h | 51 ++- services/audiopolicy/AudioPolicyInterface.h | 44 ++ services/audiopolicy/service/Android.bp | 4 + .../service/AudioPolicyInterfaceImpl.cpp | 38 ++ .../service/AudioPolicyService.cpp | 72 +++- .../audiopolicy/service/AudioPolicyService.h | 34 +- services/audiopolicy/service/Spatializer.cpp | 378 ++++++++++++++++++ services/audiopolicy/service/Spatializer.h | 205 ++++++++++ 16 files changed, 1086 insertions(+), 11 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/GetSpatializerResponse.aidl create mode 100644 media/libaudioclient/aidl/android/media/HeadTrackingMode.aidl create mode 100644 media/libaudioclient/aidl/android/media/INativeSpatializerCallback.aidl create mode 100644 media/libaudioclient/aidl/android/media/ISpatializer.aidl create mode 100644 media/libaudioclient/aidl/android/media/SpatializationLevel.aidl create mode 100644 services/audiopolicy/service/Spatializer.cpp create mode 100644 services/audiopolicy/service/Spatializer.h diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 63da4d143d..9b9ceea904 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -398,7 +398,9 @@ aidl_interface { "aidl/android/media/AudioProductStrategy.aidl", "aidl/android/media/AudioVolumeGroup.aidl", "aidl/android/media/DeviceRole.aidl", + "aidl/android/media/HeadTrackingMode.aidl", "aidl/android/media/SoundTriggerSession.aidl", + "aidl/android/media/SpatializationLevel.aidl", ], imports: [ "audioclient-types-aidl", @@ -473,10 +475,13 @@ aidl_interface { srcs: [ "aidl/android/media/GetInputForAttrResponse.aidl", "aidl/android/media/GetOutputForAttrResponse.aidl", + "aidl/android/media/GetSpatializerResponse.aidl", "aidl/android/media/Int.aidl", "aidl/android/media/RecordClientInfo.aidl", "aidl/android/media/IAudioPolicyService.aidl", "aidl/android/media/IAudioPolicyServiceClient.aidl", + "aidl/android/media/INativeSpatializerCallback.aidl", + "aidl/android/media/ISpatializer.aidl", ], imports: [ "audioclient-types-aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index cfa031fd74..65bf97ddad 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -2247,6 +2247,47 @@ status_t AudioSystem::getDevicesForRoleAndCapturePreset(audio_source_t audioSour return OK; } +status_t AudioSystem::getSpatializer(const sp& callback, + sp* spatializer) { + const sp& aps = AudioSystem::get_audio_policy_service(); + if (spatializer == nullptr) { + return BAD_VALUE; + } + if (aps == 0) { + return PERMISSION_DENIED; + } + media::GetSpatializerResponse response; + RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( + aps->getSpatializer(callback, &response))); + + *spatializer = response.spatializer; + return OK; +} + +status_t AudioSystem::canBeSpatialized(const audio_attributes_t *attr, + const audio_config_t *config, + const AudioDeviceTypeAddrVector &devices, + bool *canBeSpatialized) { + const sp& aps = AudioSystem::get_audio_policy_service(); + if (aps == 0) { + return PERMISSION_DENIED; + } + audio_attributes_t attributes = attr != nullptr ? *attr : AUDIO_ATTRIBUTES_INITIALIZER; + audio_config_t configuration = config != nullptr ? *config : AUDIO_CONFIG_INITIALIZER; + + std::optional attrAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); + std::optional configAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_config_t_AudioConfig(configuration, false /*isInput*/)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); + RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( + aps->canBeSpatialized(attrAidl, configAidl, devicesAidl, canBeSpatialized))); + return OK; +} + + class CaptureStateListenerImpl : public media::BnCaptureStateListener, public IBinder::DeathRecipient { public: diff --git a/media/libaudioclient/aidl/android/media/GetSpatializerResponse.aidl b/media/libaudioclient/aidl/android/media/GetSpatializerResponse.aidl new file mode 100644 index 0000000000..25115ace55 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/GetSpatializerResponse.aidl @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.ISpatializer; + +/** + * Used as a return value for IAudioPolicyService.getSpatializer() method + * {@hide} + */ + parcelable GetSpatializerResponse { + /* The ISpatializer interface if successful, null if not */ + @nullable ISpatializer spatializer; +} diff --git a/media/libaudioclient/aidl/android/media/HeadTrackingMode.aidl b/media/libaudioclient/aidl/android/media/HeadTrackingMode.aidl new file mode 100644 index 0000000000..d6cf41021d --- /dev/null +++ b/media/libaudioclient/aidl/android/media/HeadTrackingMode.aidl @@ -0,0 +1,35 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + + +/** + * The head tracking mode supported by the spatializer stage effect implementation. + * Used by methods of the ISpatializer interface. + * {@hide} + */ +@Backing(type="byte") +enum HeadTrackingMode { + /** Head tracking is active in a mode not listed below (forward compatibility) */ + OTHER = 0, + /** Head tracking is disabled */ + DISABLED = 1, + /** Head tracking is performed relative to the real work environment */ + RELATIVE_WORLD = 2, + /** Head tracking is performed relative to the device's screen */ + RELATIVE_SCREEN = 3, +} diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 86fb2ba221..7022b9d715 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -47,8 +47,10 @@ import android.media.DeviceRole; import android.media.EffectDescriptor; import android.media.GetInputForAttrResponse; import android.media.GetOutputForAttrResponse; +import android.media.GetSpatializerResponse; import android.media.IAudioPolicyServiceClient; import android.media.ICaptureStateListener; +import android.media.INativeSpatializerCallback; import android.media.Int; import android.media.SoundTriggerSession; @@ -348,4 +350,29 @@ interface IAudioPolicyService { DeviceRole role); boolean registerSoundTriggerCaptureStateListener(ICaptureStateListener listener); + + /** If a spatializer stage effect is present on the platform, this will return an + * ISpatializer interface (see GetSpatializerResponse,aidl) to control this + * feature. + * If no spatializer stage is present, a null interface is returned. + * The INativeSpatializerCallback passed must not be null. + * Only one ISpatializer interface can exist at a given time. The native audio policy + * service will reject the request if an interface was already acquired and previous owner + * did not die or call ISpatializer.release(). + */ + GetSpatializerResponse getSpatializer(INativeSpatializerCallback callback); + + /** Queries if some kind of spatialization will be performed if the audio playback context + * described by the provided arguments is present. + * The context is made of: + * - The audio attributes describing the playback use case. + * - The audio configuration describing the audio format, channels, sampling rate... + * - The devices describing the sink audio device selected for playback. + * All arguments are optional and only the specified arguments are used to match against + * supported criteria. For instance, supplying no argument will tell if spatialization is + * supported or not in general. + */ + boolean canBeSpatialized(in @nullable AudioAttributesInternal attr, + in @nullable AudioConfig config, + in AudioDevice[] devices); } diff --git a/media/libaudioclient/aidl/android/media/INativeSpatializerCallback.aidl b/media/libaudioclient/aidl/android/media/INativeSpatializerCallback.aidl new file mode 100644 index 0000000000..f34df056e9 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/INativeSpatializerCallback.aidl @@ -0,0 +1,33 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.SpatializationLevel; + +/** + * The INativeSpatializerCallback interface is a callback associated to the + * ISpatializer interface. The callback is used by the spatializer stage + * implementation in native audio server to communicate stage changes to the + * client controlling the spatializer with the ISpatializer interface. + * {@hide} + */ +interface INativeSpatializerCallback { + /** Called when the spatialization level applied by the vitualizer stage changes + * (e.g. when the spatializer is enabled or disabled) + */ + oneway void onLevelChanged(SpatializationLevel level); +} diff --git a/media/libaudioclient/aidl/android/media/ISpatializer.aidl b/media/libaudioclient/aidl/android/media/ISpatializer.aidl new file mode 100644 index 0000000000..212d8fef5a --- /dev/null +++ b/media/libaudioclient/aidl/android/media/ISpatializer.aidl @@ -0,0 +1,68 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.HeadTrackingMode; +import android.media.SpatializationLevel; + +/** + * The ISpatializer interface is used to control the native audio service implementation + * of the spatializer stage with headtracking when present on a platform. + * It is intended for exclusive use by the java AudioService running in system_server. + * It provides APIs to discover the feature availability and options as well as control and report + * the active state and modes of the spatializer and head tracking effect. + * {@hide} + */ +interface ISpatializer { + /** Releases a ISpatializer interface previously acquired. */ + void release(); + + /** Reports the list of supported spatialization levels (see SpatializationLevel.aidl). + * The list should never be empty if an ISpatializer interface was successfully + * retrieved with IAudioPolicyService.getSpatializer(). + */ + SpatializationLevel[] getSupportedLevels(); + + /** Selects the desired spatialization level (see SpatializationLevel.aidl). Selecting a level + * different from SpatializationLevel.NONE with create the specialized multichannel output + * mixer, create and enable the spatializer effect and let the audio policy attach eligible + * AudioTrack to this output stream. + */ + void setLevel(SpatializationLevel level); + + /** Gets the selected spatialization level (see SpatializationLevel.aidl) */ + SpatializationLevel getLevel(); + + /** Reports the list of supported head tracking modes (see HeadTrackingMode.aidl). The list can + * be empty if the spatializer implementation does not support head tracking or if no + * head tracking device is connected. + */ + HeadTrackingMode[] getSupportedHeadTrackingModes(); + + /** Selects the desired head tracking mode (see HeadTrackingMode.aidl) */ + void setDesiredHeadTrackingMode(HeadTrackingMode mode); + + /** Gets the actual head tracking mode. Can be different from the desired mode if conditions to + * enable the desired mode are not met (e.g if the head tracking device was removed) + */ + HeadTrackingMode getActualHeadTrackingMode(); + + /** Reset the head tracking algorithm to consider current head pose as neutral */ + void recenterHeadtracker(); + /** Set the screen to stage transform to use by the head tracking algorithm */ + void setGlobalTransform(in float[] screenToStage); +} diff --git a/media/libaudioclient/aidl/android/media/SpatializationLevel.aidl b/media/libaudioclient/aidl/android/media/SpatializationLevel.aidl new file mode 100644 index 0000000000..cef42bba5a --- /dev/null +++ b/media/libaudioclient/aidl/android/media/SpatializationLevel.aidl @@ -0,0 +1,34 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * The spatialization level or mode supported by the spatializer stage effect implementation. + * Used by methods of the ISpatializer interface. + * {@hide} + */ +@Backing(type="byte") +enum SpatializationLevel { + /** Spatialization is disabled. */ + NONE = 0, + /** The spatializer accepts audio with positional multichannel masks (e.g 5.1). */ + SPATIALIZER_MULTICHANNEL = 1, + /** The spatializer accepts audio made of a channel bed of positional multichannels (e.g 5.1) + * and audio objects positioned independently via meta data. + */ + SPATIALIZER_MCHAN_BED_PLUS_OBJECTS = 2, +} diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 2331adcb47..50ab42ab50 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -22,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -489,6 +491,49 @@ public: static status_t getDeviceForStrategy(product_strategy_t strategy, AudioDeviceTypeAddr &device); + + /** + * If a spatializer stage effect is present on the platform, this will return an + * ISpatializer interface to control this feature. + * If no spatializer stage is present, a null interface is returned. + * The INativeSpatializerCallback passed must not be null. + * Only one ISpatializer interface can exist at a given time. The native audio policy + * service will reject the request if an interface was already acquired and previous owner + * did not die or call ISpatializer.release(). + * @param callback in: the callback to receive state updates if the ISpatializer + * interface is acquired. + * @param spatializer out: the ISpatializer interface made available to control the + * platform spatializer + * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, PERMISSION_DENIED, BAD_VALUE + * in case of error. + */ + static status_t getSpatializer(const sp& callback, + sp* spatializer); + + /** + * Queries if some kind of spatialization will be performed if the audio playback context + * described by the provided arguments is present. + * The context is made of: + * - The audio attributes describing the playback use case. + * - The audio configuration describing the audio format, channels, sampling rate ... + * - The devices describing the sink audio device selected for playback. + * All arguments are optional and only the specified arguments are used to match against + * supported criteria. For instance, supplying no argument will tell if spatialization is + * supported or not in general. + * @param attr audio attributes describing the playback use case + * @param config audio configuration describing the audio format, channels, sampling rate... + * @param devices the sink audio device selected for playback + * @param canBeSpatialized out: true if spatialization is enabled for this context, + * false otherwise + * @return NO_ERROR in case of success, DEAD_OBJECT, NO_INIT, BAD_VALUE + * in case of error. + */ + static status_t canBeSpatialized(const audio_attributes_t *attr, + const audio_config_t *config, + const AudioDeviceTypeAddrVector &devices, + bool *canBeSpatialized); + + // A listener for capture state changes. class CaptureStateListener : public RefBase { public: @@ -501,11 +546,11 @@ public: virtual ~CaptureStateListener() = default; }; - // Regiseters a listener for sound trigger capture state changes. + // Registers a listener for sound trigger capture state changes. // There may only be one such listener registered at any point. - // The listener onStateChanged() method will be invoked sychronously from + // The listener onStateChanged() method will be invoked synchronously from // this call with the initial value. - // The listener onServiceDied() method will be invoked sychronously from + // The listener onServiceDied() method will be invoked synchronously from // this call if initial attempt to register failed. // If the audio policy service cannot be reached, this method will return // PERMISSION_DENIED and will not invoke the callback, otherwise, it will diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h index c9cf564eeb..8613b2ec91 100644 --- a/services/audiopolicy/AudioPolicyInterface.h +++ b/services/audiopolicy/AudioPolicyInterface.h @@ -334,6 +334,50 @@ public: virtual status_t getDevicesForRoleAndCapturePreset(audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) = 0; + + /** + * Queries if some kind of spatialization will be performed if the audio playback context + * described by the provided arguments is present. + * The context is made of: + * - The audio attributes describing the playback use case. + * - The audio configuration describing the audio format, channels, sampling rate ... + * - The devices describing the sink audio device selected for playback. + * All arguments are optional and only the specified arguments are used to match against + * supported criteria. For instance, supplying no argument will tell if spatialization is + * supported or not in general. + * @param attr audio attributes describing the playback use case + * @param config audio configuration describing the audio format, channels, sampling rate... + * @param devices the sink audio device selected for playback + * @return true if spatialization is enabled for this context, + * false otherwise + */ + virtual bool canBeSpatialized(const audio_attributes_t *attr, + const audio_config_t *config, + const AudioDeviceTypeAddrVector &devices) const = 0; + + /** + * Opens a specialized spatializer output if supported by the platform. + * If several spatializer output profiles exist, the one supporting the sink device + * corresponding to the provided audio attributes will be selected. + * Only one spatializer output stream can be opened at a time and an error is returned + * if one already exists. + * @param config audio format, channel mask and sampling rate to be used as the mixer + * configuration for the spatializer mixer created. + * @param attr audio attributes describing the playback use case that will drive the + * sink device selection + * @param output the IO handle of the output opened + * @return NO_ERROR if an output was opened, INVALID_OPERATION or BAD_VALUE otherwise + */ + virtual status_t getSpatializerOutput(const audio_config_base_t *config, + const audio_attributes_t *attr, + audio_io_handle_t *output) = 0; + + /** + * Closes a previously opened specialized spatializer output. + * @param output the IO handle of the output to close. + * @return NO_ERROR if an output was closed, INVALID_OPERATION or BAD_VALUE otherwise + */ + virtual status_t releaseSpatializerOutput(audio_io_handle_t output) = 0; }; diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 454c020489..5ffddc2858 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -16,6 +16,7 @@ cc_library_shared { "AudioPolicyInterfaceImpl.cpp", "AudioPolicyService.cpp", "CaptureStateNotifier.cpp", + "Spatializer.cpp", ], include_dirs: [ @@ -27,6 +28,7 @@ cc_library_shared { "libaudioclient", "libaudioclient_aidl_conversion", "libaudiofoundation", + "libaudiohal", "libaudiopolicy", "libaudiopolicymanagerdefault", "libaudioutils", @@ -40,6 +42,7 @@ cc_library_shared { "libmediautils", "libpermission", "libsensorprivacy", + "libshmemcompat", "libutils", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", @@ -55,6 +58,7 @@ cc_library_shared { ], header_libs: [ + "libaudiohal_headers", "libaudiopolicycommon", "libaudiopolicyengine_interface_headers", "libaudiopolicymanager_interface_headers", diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 114f776ad6..95c1bab771 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -2214,4 +2214,42 @@ Status AudioPolicyService::getDevicesForRoleAndCapturePreset( return Status::ok(); } +Status AudioPolicyService::getSpatializer( + const sp& callback, + media::GetSpatializerResponse* _aidl_return) { + _aidl_return->spatializer = nullptr; + LOG_ALWAYS_FATAL_IF(callback == nullptr); + RETURN_IF_BINDER_ERROR(binderStatusFromStatusT(mSpatializer->registerCallback(callback))); + _aidl_return->spatializer = mSpatializer; + return Status::ok(); +} + +Status AudioPolicyService::canBeSpatialized( + const std::optional& attrAidl, + const std::optional& configAidl, + const std::vector& devicesAidl, + bool* _aidl_return) { + if (mAudioPolicyManager == nullptr) { + return binderStatusFromStatusT(NO_INIT); + } + audio_attributes_t attr = AUDIO_ATTRIBUTES_INITIALIZER; + if (attrAidl.has_value()) { + attr = VALUE_OR_RETURN_BINDER_STATUS( + aidl2legacy_AudioAttributesInternal_audio_attributes_t(attrAidl.value())); + } + audio_config_t config = AUDIO_CONFIG_INITIALIZER; + if (configAidl.has_value()) { + config = VALUE_OR_RETURN_BINDER_STATUS( + aidl2legacy_AudioConfig_audio_config_t(configAidl.value(), + false /*isInput*/)); + } + AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( + convertContainer(devicesAidl, + aidl2legacy_AudioDeviceTypeAddress)); + + Mutex::Autolock _l(mLock); + *_aidl_return = mAudioPolicyManager->canBeSpatialized(&attr, &config, devices); + return Status::ok(); +} + } // namespace android diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index 73138932c9..86994edff3 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -141,6 +141,13 @@ void AudioPolicyService::onFirstRef() uidPolicy->registerSelf(); sensorPrivacyPolicy->registerSelf(); + // Create spatializer if supported + const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA); + AudioDeviceTypeAddrVector devices; + bool hasSpatializer = mAudioPolicyManager->canBeSpatialized(&attr, nullptr, devices); + if (hasSpatializer) { + mSpatializer = Spatializer::create(this); + } AudioSystem::audioPolicyReady(); } @@ -356,6 +363,49 @@ void AudioPolicyService::doOnRoutingUpdated() } } +void AudioPolicyService::onCheckSpatializer() +{ + Mutex::Autolock _l(mLock); + mOutputCommandThread->checkSpatializerCommand(); +} + +void AudioPolicyService::doOnCheckSpatializer() +{ + sp spatializer; + { + Mutex::Autolock _l(mLock); + spatializer = mSpatializer; + + if (spatializer != nullptr) { + audio_io_handle_t output = AUDIO_IO_HANDLE_NONE; + if (spatializer->getLevel() != media::SpatializationLevel::NONE + && spatializer->getOutput() == AUDIO_IO_HANDLE_NONE) { + const audio_attributes_t attr = attributes_initializer(AUDIO_USAGE_MEDIA); + audio_config_base_t config = spatializer->getAudioInConfig(); + status_t status = + mAudioPolicyManager->getSpatializerOutput(&config, &attr, &output); + if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) { + return; + } + mLock.unlock(); + status = spatializer->attachOutput(output); + mLock.lock(); + if (status != NO_ERROR) { + mAudioPolicyManager->releaseSpatializerOutput(output); + } + } else if (spatializer->getLevel() == media::SpatializationLevel::NONE + && spatializer->getOutput() != AUDIO_IO_HANDLE_NONE) { + mLock.unlock(); + output = spatializer->detachOutput(); + mLock.lock(); + if (output != AUDIO_IO_HANDLE_NONE) { + mAudioPolicyManager->releaseSpatializerOutput(output); + } + } + } + } +} + status_t AudioPolicyService::clientCreateAudioPatch(const struct audio_patch *patch, audio_patch_handle_t *handle, int delayMs) @@ -995,7 +1045,8 @@ status_t AudioPolicyService::onTransact( case TRANSACTION_addDevicesRoleForCapturePreset: case TRANSACTION_removeDevicesRoleForCapturePreset: case TRANSACTION_clearDevicesRoleForCapturePreset: - case TRANSACTION_getDevicesForRoleAndCapturePreset: { + case TRANSACTION_getDevicesForRoleAndCapturePreset: + case TRANSACTION_getSpatializer: { if (!isServiceUid(IPCThreadState::self()->getCallingUid())) { ALOGW("%s: transaction %d received from PID %d unauthorized UID %d", __func__, code, IPCThreadState::self()->getCallingPid(), @@ -1769,6 +1820,17 @@ bool AudioPolicyService::AudioCommandThread::threadLoop() mLock.lock(); } break; + case CHECK_SPATIALIZER: { + ALOGV("AudioCommandThread() processing updateUID states"); + svc = mService.promote(); + if (svc == 0) { + break; + } + mLock.unlock(); + svc->doOnCheckSpatializer(); + mLock.lock(); + } break; + default: ALOGW("AudioCommandThread() unknown command %d", command->mCommand); } @@ -2080,6 +2142,14 @@ void AudioPolicyService::AudioCommandThread::routingChangedCommand() sendCommand(command); } +void AudioPolicyService::AudioCommandThread::checkSpatializerCommand() +{ + spcommand = new AudioCommand(); + command->mCommand = CHECK_SPATIALIZER; + ALOGV("AudioCommandThread() adding check spatializer"); + sendCommand(command); +} + status_t AudioPolicyService::AudioCommandThread::sendCommand(sp& command, int delayMs) { { diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index f71d5b9a73..97d4c00375 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -19,6 +19,7 @@ #define ANDROID_AUDIOPOLICYSERVICE_H #include +#include #include #include #include @@ -38,6 +39,7 @@ #include #include "AudioPolicyEffects.h" #include "CaptureStateNotifier.h" +#include "Spatializer.h" #include #include #include @@ -53,7 +55,8 @@ using content::AttributionSourceState; class AudioPolicyService : public BinderService, public media::BnAudioPolicyService, - public IBinder::DeathRecipient + public IBinder::DeathRecipient, + public SpatializerPolicyCallback { friend class BinderService; @@ -249,11 +252,15 @@ public: binder::Status registerSoundTriggerCaptureStateListener( const sp& listener, bool* _aidl_return) override; - virtual status_t onTransact( - uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags); + binder::Status getSpatializer(const sp& callback, + media::GetSpatializerResponse* _aidl_return) override; + binder::Status canBeSpatialized( + const std::optional& attr, + const std::optional& config, + const std::vector& devices, + bool* _aidl_return) override; + + status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override; // IBinder::DeathRecipient virtual void binderDied(const wp& who); @@ -319,6 +326,15 @@ public: void onRoutingUpdated(); void doOnRoutingUpdated(); + /** + * Spatializer SpatializerPolicyCallback implementation. + * onCheckSpatializer() sends an event on mOutputCommandThread which executes + * doOnCheckSpatializer() to check if a Spatializer output must be opened or closed + * by audio policy manager and attach/detach the spatializer effect accordingly. + */ + void onCheckSpatializer() override; + void doOnCheckSpatializer(); + void setEffectSuspended(int effectId, audio_session_t sessionId, bool suspended); @@ -489,7 +505,8 @@ private: SET_EFFECT_SUSPENDED, AUDIO_MODULES_UPDATE, ROUTING_UPDATED, - UPDATE_UID_STATES + UPDATE_UID_STATES, + CHECK_SPATIALIZER }; AudioCommandThread (String8 name, const wp& service); @@ -538,6 +555,7 @@ private: void audioModulesUpdateCommand(); void routingChangedCommand(); void updateUidStatesCommand(); + void checkSpatializerCommand(); void insertCommand_l(AudioCommand *command, int delayMs = 0); private: class AudioCommandData; @@ -992,6 +1010,8 @@ private: CaptureStateNotifier mCaptureStateNotifier; + sp mSpatializer; + void *mLibraryHandle = nullptr; CreateAudioPolicyManagerInstance mCreateAudioPolicyManager; DestroyAudioPolicyManagerInstance mDestroyAudioPolicyManager; diff --git a/services/audiopolicy/service/Spatializer.cpp b/services/audiopolicy/service/Spatializer.cpp new file mode 100644 index 0000000000..33835151d5 --- /dev/null +++ b/services/audiopolicy/service/Spatializer.cpp @@ -0,0 +1,378 @@ +/* +** +** Copyright 2021, The Android Open Source Project +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +*/ + + +#define LOG_TAG "Spatializer" +//#define LOG_NDEBUG 0 +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "Spatializer.h" + +namespace android { + +using aidl_utils::statusTFromBinderStatus; +using aidl_utils::binderStatusFromStatusT; +using android::content::AttributionSourceState; +using binder::Status; +using media::HeadTrackingMode; +using media::SpatializationLevel; + +#define VALUE_OR_RETURN_BINDER_STATUS(x) \ + ({ auto _tmp = (x); \ + if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \ + std::move(_tmp.value()); }) + +#define RETURN_IF_BINDER_ERROR(x) \ + { \ + binder::Status _tmp = (x); \ + if (!_tmp.isOk()) return _tmp; \ + } + +// --------------------------------------------------------------------------- + +sp Spatializer::create(SpatializerPolicyCallback *callback) { + sp spatializer; + + sp effectsFactoryHal = EffectsFactoryHalInterface::create(); + if (effectsFactoryHal == nullptr) { + ALOGW("%s failed to create effect factory interface", __func__); + return spatializer; + } + + std::vector descriptors; + status_t status = + effectsFactoryHal->getDescriptors(FX_IID_VIRTUALIZER_STAGE, &descriptors); + if (status != NO_ERROR) { + ALOGW("%s failed to get spatializer descriptor, error %d", __func__, status); + return spatializer; + } + ALOG_ASSERT(!descriptors.empty(), + "%s getDescriptors() returned no error but empty list", __func__); + + //TODO: get supported spatialization modes from FX engine or descriptor + + sp effect; + status = effectsFactoryHal->createEffect(&descriptors[0].uuid, AUDIO_SESSION_OUTPUT_STAGE, + AUDIO_IO_HANDLE_NONE, AUDIO_PORT_HANDLE_NONE, &effect); + ALOGI("%s FX create status %d effect %p", __func__, status, effect.get()); + + if (status == NO_ERROR && effect != nullptr) { + spatializer = new Spatializer(descriptors[0], callback); + // TODO: Read supported config from engine + audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER; + config.channel_mask = AUDIO_CHANNEL_OUT_5POINT1; + spatializer->setAudioInConfig(config); + } + + return spatializer; +} + +Spatializer::Spatializer(effect_descriptor_t engineDescriptor, + SpatializerPolicyCallback *callback) + : mEngineDescriptor(engineDescriptor), mPolicyCallback(callback) { + ALOGV("%s", __func__); +} + +Spatializer::~Spatializer() { + ALOGV("%s", __func__); +} + +status_t Spatializer::registerCallback( + const sp& callback) { + Mutex::Autolock _l(mLock); + if (callback == nullptr) { + return BAD_VALUE; + } + + sp binder = IInterface::asBinder(callback); + status_t status = binder->linkToDeath(this); + if (status == NO_ERROR) { + mSpatializerCallback = callback; + } + ALOGV("%s status %d", __func__, status); + return status; +} + +// IBinder::DeathRecipient +void Spatializer::binderDied(__unused const wp &who) { + { + Mutex::Autolock _l(mLock); + mLevel = SpatializationLevel::NONE; + mSpatializerCallback.clear(); + } + ALOGV("%s", __func__); + mPolicyCallback->onCheckSpatializer(); +} + +// ISpatializer +Status Spatializer::getSupportedLevels(std::vector *levels) { + ALOGV("%s", __func__); + if (levels == nullptr) { + return binderStatusFromStatusT(BAD_VALUE); + } + //TODO: get this from engine + levels->push_back(SpatializationLevel::NONE); + levels->push_back(SpatializationLevel::SPATIALIZER_MULTICHANNEL); + return Status::ok(); +} + +Status Spatializer::setLevel(media::SpatializationLevel level) { + ALOGV("%s level %d", __func__, (int)level); + if (level != SpatializationLevel::NONE + && level != SpatializationLevel::SPATIALIZER_MULTICHANNEL) { + return binderStatusFromStatusT(BAD_VALUE); + } + sp callback; + bool levelChanged = false; + { + Mutex::Autolock _l(mLock); + levelChanged = mLevel != level; + mLevel = level; + callback = mSpatializerCallback; + } + + if (levelChanged) { + mPolicyCallback->onCheckSpatializer(); + if (callback != nullptr) { + callback->onLevelChanged(level); + } + } + return Status::ok(); +} + +Status Spatializer::getLevel(media::SpatializationLevel *level) { + if (level == nullptr) { + return binderStatusFromStatusT(BAD_VALUE); + } + Mutex::Autolock _l(mLock); + *level = mLevel; + ALOGV("%s level %d", __func__, (int)*level); + return Status::ok(); +} + +Status Spatializer::getSupportedHeadTrackingModes( + std::vector* modes) { + ALOGV("%s", __func__); + if (modes == nullptr) { + return binderStatusFromStatusT(BAD_VALUE); + } + //TODO: get this from: + // - The engine capabilities + // - If a head tracking sensor is registered and linked to a connected audio device + // - if we have indications on the screen orientation + modes->push_back(HeadTrackingMode::RELATIVE_WORLD); + return Status::ok(); +} + +Status Spatializer::setDesiredHeadTrackingMode(media::HeadTrackingMode mode) { + ALOGV("%s level %d", __func__, (int)mode); + if (mode != HeadTrackingMode::DISABLED + && mode != HeadTrackingMode::RELATIVE_WORLD) { + return binderStatusFromStatusT(BAD_VALUE); + } + { + Mutex::Autolock _l(mLock); + mHeadTrackingMode = mode; + } + return Status::ok(); +} + +Status Spatializer::getActualHeadTrackingMode(media::HeadTrackingMode *mode) { + if (mode == nullptr) { + return binderStatusFromStatusT(BAD_VALUE); + } + Mutex::Autolock _l(mLock); + *mode = mHeadTrackingMode; + ALOGV("%s mode %d", __func__, (int)*mode); + return Status::ok(); +} + +Status Spatializer::recenterHeadtracker() { + return Status::ok(); +} + +Status Spatializer::setGlobalTransform(const std::vector& screenToStage) { + Mutex::Autolock _l(mLock); + mScreenToStageTransform = screenToStage; + ALOGV("%s", __func__); + return Status::ok(); +} + +Status Spatializer::release() { + ALOGV("%s", __func__); + bool levelChanged = false; + { + Mutex::Autolock _l(mLock); + if (mSpatializerCallback == nullptr) { + return binderStatusFromStatusT(INVALID_OPERATION); + } + + sp binder = IInterface::asBinder(mSpatializerCallback); + binder->unlinkToDeath(this); + mSpatializerCallback.clear(); + + levelChanged = mLevel != SpatializationLevel::NONE; + mLevel = SpatializationLevel::NONE; + } + + if (levelChanged) { + mPolicyCallback->onCheckSpatializer(); + } + return Status::ok(); +} + +status_t Spatializer::attachOutput(audio_io_handle_t output) { + Mutex::Autolock _l(mLock); + ALOGV("%s output %d mOutput %d", __func__, (int)output, (int)mOutput); + if (mOutput != AUDIO_IO_HANDLE_NONE) { + LOG_ALWAYS_FATAL_IF(mEngine != nullptr, "%s output set without FX engine", __func__); + // remove FX instance + mEngine->setEnabled(false); + mEngine.clear(); + } + // create FX instance on output + AttributionSourceState attributionSource = AttributionSourceState(); + mEngine = new AudioEffect(attributionSource); + mEngine->set(nullptr, &mEngineDescriptor.uuid, 0, + Spatializer::engineCallback /* cbf */, this /* user */, + AUDIO_SESSION_OUTPUT_STAGE, output, + {} /* device */, false /* probe */, true /* notifyFramesProcessed */); + status_t status = mEngine->initCheck(); + ALOGV("%s mEngine create status %d", __func__, (int)status); + if (status != NO_ERROR) { + return status; + } + mEngine->setEnabled(true); + mOutput = output; + return NO_ERROR; +} + +audio_io_handle_t Spatializer::detachOutput() { + Mutex::Autolock _l(mLock); + ALOGV("%s mOutput %d", __func__, (int)mOutput); + if (mOutput == AUDIO_IO_HANDLE_NONE) { + return AUDIO_IO_HANDLE_NONE; + } + // remove FX instance + mEngine->setEnabled(false); + mEngine.clear(); + audio_io_handle_t output = mOutput; + mOutput = AUDIO_IO_HANDLE_NONE; + return output; +} + +void Spatializer::engineCallback(int32_t event, void *user, void *info) { + + if (user == nullptr) { + return; + } + const Spatializer * const me = reinterpret_cast(user); + switch (event) { + case AudioEffect::EVENT_FRAMES_PROCESSED: { + int frames = info == nullptr ? 0 : *(int *)info; + ALOGD("%s frames processed %d for me %p", __func__, frames, me); + } break; + default: + ALOGD("%s event %d", __func__, event); + break; + } +} + +// --------------------------------------------------------------------------- + +Spatializer::EffectClient::EffectClient(const sp& effectClient, + Spatializer& parent) + : BnEffect(), + mEffectClient(effectClient), mParent(parent) { +} + +Spatializer::EffectClient::~EffectClient() { +} + +// IEffect + +#define RETURN(code) \ + *_aidl_return = (code); \ + return Status::ok(); + +// Write a POD value into a vector of bytes (clears the previous buffer +// content). +template +void writeToBuffer(const T& value, std::vector* buffer) { + buffer->clear(); + appendToBuffer(value, buffer); +} + +Status Spatializer::EffectClient::enable(int32_t* _aidl_return) { + RETURN(OK); +} + +Status Spatializer::EffectClient::disable(int32_t* _aidl_return) { + RETURN(OK); +} + +Status Spatializer::EffectClient::command(int32_t cmdCode, + const std::vector& cmdData __unused, + int32_t maxResponseSize __unused, + std::vector* response __unused, + int32_t* _aidl_return) { + + // reject commands reserved for internal use by audio framework if coming from outside + // of audioserver + switch(cmdCode) { + case EFFECT_CMD_ENABLE: + case EFFECT_CMD_DISABLE: + case EFFECT_CMD_SET_PARAM_DEFERRED: + case EFFECT_CMD_SET_PARAM_COMMIT: + RETURN(BAD_VALUE); + case EFFECT_CMD_SET_PARAM: + case EFFECT_CMD_GET_PARAM: + break; + default: + if (cmdCode >= EFFECT_CMD_FIRST_PROPRIETARY) { + break; + } + android_errorWriteLog(0x534e4554, "62019992"); + RETURN(BAD_VALUE); + } + (void)mParent; + RETURN(OK); +} + +Status Spatializer::EffectClient::disconnect() { + mDisconnected = true; + return Status::ok(); +} + +Status Spatializer::EffectClient::getCblk(media::SharedFileRegion* _aidl_return) { + LOG_ALWAYS_FATAL_IF(!convertIMemoryToSharedFileRegion(mCblkMemory, _aidl_return)); + return Status::ok(); +} + +} // namespace android diff --git a/services/audiopolicy/service/Spatializer.h b/services/audiopolicy/service/Spatializer.h new file mode 100644 index 0000000000..b17795329f --- /dev/null +++ b/services/audiopolicy/service/Spatializer.h @@ -0,0 +1,205 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_SPATIALIZER_H +#define ANDROID_MEDIA_SPATIALIZER_H + +#include +#include +#include +#include + +#include +#include + + +namespace android { + + +// ---------------------------------------------------------------------------- + +/** + * A callback interface from the Spatializer object or its parent AudioPolicyService. + * This is implemented by the audio policy service hosting the Spatializer to perform + * actions needed when a state change inside the Spatializer requires some audio system + * changes that cannot be performed by the Spatializer. For instance opening or closing a + * spatializer output stream when the spatializer is enabled or disabled + */ +class SpatializerPolicyCallback { +public: + /** Called when a stage change occurs that requires the parent audio policy service to take + * some action. + */ + virtual void onCheckSpatializer() = 0; + + virtual ~SpatializerPolicyCallback() = default; +}; +/** + * The Spatializer class implements all functional controlling the multichannel spatializer + * with head tracking implementation in the native audio service: audio policy and audio flinger. + * It presents an AIDL interface available to the java audio service to discover the availability + * of the feature and options, control its state and register an active head tracking sensor. + * It maintains the current state of the platform spatializer and applies the stored parameters + * when the spatializer engine is created and enabled. + * Based on the requested spatializer level, it will request the creation of a specialized output + * mixer to the audio policy service which will in turn notify the Spatializer of the output + * stream on which a spatializer engine should be created, configured and enabled. + * The spatializer also hosts the head tracking management logic. This logic receives the + * desired head tracking mode and selected head tracking sensor, registers a sensor event listener + * and derives the compounded head pose information to the spatializer engine. + * + * Workflow: + * - Initialization: when the audio policy service starts, it checks if a spatializer effect + * engine exists and if the audio policy manager reports a dedicated spatializer output profile. + * If both conditions are met, a Spatializer object is created + * - Capabilities discovery: AudioService will call AudioSystem::canBeSpatialized() and if true, + * acquire an ISpatializer interface with AudioSystem::getSpatializer(). This interface + * will be used to query the implementation capabilities and configure the spatializer. + * - Enabling: when ISpatializer::setLevel() sets a level different from NONE the spatializer + * is considered enabled. The audio policy callback onCheckSpatializer() is called. This + * triggers a request to audio policy manager to open a spatialization output stream and a + * spatializer mixer is created in audio flinger. When an output is returned by audio policy + * manager, Spatializer::attachOutput() is called which creates and enables the spatializer + * stage engine on the specified output. + * - Disabling: when the spatialization level is set to NONE, the spatializer is considered + * disabled. The audio policy callback onCheckSpatializer() is called. This triggers a call + * to Spatializer::detachOutput() and the spatializer engine is released. Then a request is + * made to audio policy manager to release and close the spatializer output stream and the + * spatializer mixer thread is destroyed. + */ +class Spatializer : public media::BnSpatializer, public IBinder::DeathRecipient { +public: + + static sp create(SpatializerPolicyCallback *callback); + + ~Spatializer() override; + + /** ISpatializer, see ISpatializer.aidl */ + binder::Status release() override; + binder::Status getSupportedLevels(std::vector* levels) override; + binder::Status setLevel(media::SpatializationLevel level) override; + binder::Status getLevel(media::SpatializationLevel *level) override; + binder::Status getSupportedHeadTrackingModes( + std::vector* modes) override; + binder::Status setDesiredHeadTrackingMode(media::HeadTrackingMode mode) override; + binder::Status getActualHeadTrackingMode(media::HeadTrackingMode *mode) override; + binder::Status recenterHeadtracker() override; + binder::Status setGlobalTransform(const std::vector& screenToStage) override; + + /** IBinder::DeathRecipient. Listen to the death of the INativeSpatializerCallback. */ + virtual void binderDied(const wp& who); + + /** Registers a INativeSpatializerCallback when a client is attached to this Spatializer + * by audio policy service. + */ + status_t registerCallback(const sp& callback); + + /** Level getter for use by local classes. */ + media::SpatializationLevel getLevel() const { Mutex::Autolock _l(mLock); return mLevel; } + + /** Called by audio policy service when the special output mixer dedicated to spatialization + * is opened and the spatializer engine must be created. + */ + status_t attachOutput(audio_io_handle_t output); + /** Called by audio policy service when the special output mixer dedicated to spatialization + * is closed and the spatializer engine must be release. + */ + audio_io_handle_t detachOutput(); + /** Returns the output stream the spatializer is attached to. */ + audio_io_handle_t getOutput() const { Mutex::Autolock _l(mLock); return mOutput; } + + /** Sets the channel mask, sampling rate and format for the spatializer input. */ + void setAudioInConfig(const audio_config_base_t& config) { + Mutex::Autolock _l(mLock); + mAudioInConfig = config; + } + + /** Gets the channel mask, sampling rate and format set for the spatializer input. */ + audio_config_base_t getAudioInConfig() const { + Mutex::Autolock _l(mLock); + return mAudioInConfig; + } + + /** An implementation of an IEffect interface that can be used to pass advanced parameters to + * the spatializer engine. All APis are noop (i.e. the interface cannot be used to control + * the effect) except for passing parameters via the command() API. */ + class EffectClient: public android::media::BnEffect { + public: + + EffectClient(const sp& effectClient, + Spatializer& parent); + virtual ~EffectClient(); + + // IEffect + android::binder::Status enable(int32_t* _aidl_return) override; + android::binder::Status disable(int32_t* _aidl_return) override; + android::binder::Status command(int32_t cmdCode, + const std::vector& cmdData, + int32_t maxResponseSize, + std::vector* response, + int32_t* _aidl_return) override; + android::binder::Status disconnect() override; + android::binder::Status getCblk(media::SharedFileRegion* _aidl_return) override; + + private: + const sp mEffectClient; + sp mCblkMemory; + const Spatializer& mParent; + bool mDisconnected = false; + }; + +private: + + Spatializer(effect_descriptor_t engineDescriptor, + SpatializerPolicyCallback *callback); + + + static void engineCallback(int32_t event, void* user, void *info); + + /** Effect engine descriptor */ + const effect_descriptor_t mEngineDescriptor; + /** Callback interface to parent audio policy service */ + SpatializerPolicyCallback* mPolicyCallback; + + /** Mutex protecting internal state */ + mutable Mutex mLock; + + /** Client AudioEffect for the engine */ + sp mEngine GUARDED_BY(mLock); + /** Output stream the spatializer mixer thread is attached to */ + audio_io_handle_t mOutput GUARDED_BY(mLock) = AUDIO_IO_HANDLE_NONE; + /** Virtualizer engine input configuration */ + audio_config_base_t mAudioInConfig GUARDED_BY(mLock) = AUDIO_CONFIG_BASE_INITIALIZER; + + /** Callback interface to the client (AudioService) controlling this`Spatializer */ + sp mSpatializerCallback GUARDED_BY(mLock); + + /** Requested spatialization level */ + media::SpatializationLevel mLevel GUARDED_BY(mLock) = media::SpatializationLevel::NONE; + /** Requested head tracking mode */ + media::HeadTrackingMode mHeadTrackingMode GUARDED_BY(mLock) + = media::HeadTrackingMode::DISABLED; + /** Configured screen to stage transform */ + std::vector mScreenToStageTransform GUARDED_BY(mLock); + + /** Extended IEffect interface is one has been created */ + sp mEffectClient GUARDED_BY(mLock); +}; + + +}; // namespace android + +#endif // ANDROID_MEDIA_SPATIALIZER_H -- GitLab From 0d6ced917bc9a9cb66706f5751c104cd293b2b49 Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Wed, 18 Aug 2021 14:37:22 -0700 Subject: [PATCH 098/694] Increase cameraserver fuzz test timeout to 770 seconds. Some devices cannot complete executing a single instance of the test within the default alloted time-out. Bug: 187360866 Test: N / A yet; wait for time-outs to disappear from haiku Change-Id: I1c7db3ea6eb1b59e590a71bfd8316cc5d1db40ad Signed-off-by: Jayant Chowdhary --- .../libcameraservice/libcameraservice_fuzzer/Android.bp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp b/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp index 3d74f0baa0..4f080fe283 100644 --- a/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp +++ b/services/camera/libcameraservice/libcameraservice_fuzzer/Android.bp @@ -65,5 +65,10 @@ cc_fuzz { "android-media-fuzzing-reports@google.com", ], componentid: 155276, + libfuzzer_options: [ + //based on b/187360866 + "timeout=770", + ], + }, } -- GitLab From cf41ffc3d1dae661ec9e1a8e367f944c286b3a7c Mon Sep 17 00:00:00 2001 From: Giridhar Tippabathuni Date: Wed, 28 Jul 2021 12:50:05 +0530 Subject: [PATCH 099/694] Transcoder: Fix profile and level entry copier data type Fixed the source params KEY_PROFILE and KEY_LEVEL entry copier data types. Bug: 195124211 Test: atest -c CtsMediaTranscodingTestCases:MediaTranscodeManagerTest Change-Id: I50ecd4f183eb665c95a714e4905e0198f2cfe29d --- media/libmediatranscoding/transcoder/MediaTranscoder.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/media/libmediatranscoding/transcoder/MediaTranscoder.cpp b/media/libmediatranscoding/transcoder/MediaTranscoder.cpp index e20f7ab54b..411b6ef811 100644 --- a/media/libmediatranscoding/transcoder/MediaTranscoder.cpp +++ b/media/libmediatranscoding/transcoder/MediaTranscoder.cpp @@ -55,8 +55,8 @@ static std::shared_ptr createVideoTrackFormat(AMediaFormat* srcFor AMediaFormat_getString(srcFormat, AMEDIAFORMAT_KEY_MIME, &srcMime); if (!AMediaFormat_getString(options, AMEDIAFORMAT_KEY_MIME, &dstMime) || strcmp(srcMime, dstMime) == 0) { - srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_PROFILE, String)); - srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_LEVEL, String)); + srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_PROFILE, Int32)); + srcParamsToCopy.push_back(ENTRY_COPIER(AMEDIAFORMAT_KEY_LEVEL, Int32)); } // ------- Define parameters to copy from the caller's options ------- -- GitLab From 093c5f34fad4cf9daf2f7821a6c1574a9e7314e8 Mon Sep 17 00:00:00 2001 From: Hongguang Date: Mon, 9 Aug 2021 19:46:34 -0700 Subject: [PATCH 100/694] Add tuner legacy HIDL HAL support. The AIDL HAL based solution will be the default implementation. The tuner service will only create the legacy HIDL HAL based implementation when the HIDL HAL is available. Bug: 191825295 Test: atest android.media.tv.tuner.cts on both AIDL and HIDL HAL. Test: sampletunertvinput Change-Id: I8436ae80721ad943c60b5814b535f3b87a54ccda --- services/tuner/Android.bp | 5 + services/tuner/TunerFilter.h | 3 - services/tuner/TunerHelper.cpp | 101 ++ services/tuner/TunerHelper.h | 67 + services/tuner/TunerService.cpp | 84 +- services/tuner/TunerService.h | 57 +- services/tuner/hidl/TunerHidlDemux.cpp | 278 ++++ services/tuner/hidl/TunerHidlDemux.h | 75 ++ services/tuner/hidl/TunerHidlDescrambler.cpp | 149 +++ services/tuner/hidl/TunerHidlDescrambler.h | 66 + services/tuner/hidl/TunerHidlDvr.cpp | 257 ++++ services/tuner/hidl/TunerHidlDvr.h | 91 ++ services/tuner/hidl/TunerHidlFilter.cpp | 1002 +++++++++++++++ services/tuner/hidl/TunerHidlFilter.h | 215 ++++ services/tuner/hidl/TunerHidlFrontend.cpp | 1201 ++++++++++++++++++ services/tuner/hidl/TunerHidlFrontend.h | 123 ++ services/tuner/hidl/TunerHidlLnb.cpp | 160 +++ services/tuner/hidl/TunerHidlLnb.h | 84 ++ services/tuner/hidl/TunerHidlService.cpp | 584 +++++++++ services/tuner/hidl/TunerHidlService.h | 105 ++ services/tuner/hidl/TunerHidlTimeFilter.cpp | 133 ++ services/tuner/hidl/TunerHidlTimeFilter.h | 58 + services/tuner/main_tunerservice.cpp | 10 +- 23 files changed, 4793 insertions(+), 115 deletions(-) create mode 100644 services/tuner/TunerHelper.cpp create mode 100644 services/tuner/TunerHelper.h create mode 100644 services/tuner/hidl/TunerHidlDemux.cpp create mode 100644 services/tuner/hidl/TunerHidlDemux.h create mode 100644 services/tuner/hidl/TunerHidlDescrambler.cpp create mode 100644 services/tuner/hidl/TunerHidlDescrambler.h create mode 100644 services/tuner/hidl/TunerHidlDvr.cpp create mode 100644 services/tuner/hidl/TunerHidlDvr.h create mode 100644 services/tuner/hidl/TunerHidlFilter.cpp create mode 100644 services/tuner/hidl/TunerHidlFilter.h create mode 100644 services/tuner/hidl/TunerHidlFrontend.cpp create mode 100644 services/tuner/hidl/TunerHidlFrontend.h create mode 100644 services/tuner/hidl/TunerHidlLnb.cpp create mode 100644 services/tuner/hidl/TunerHidlLnb.h create mode 100644 services/tuner/hidl/TunerHidlService.cpp create mode 100644 services/tuner/hidl/TunerHidlService.h create mode 100644 services/tuner/hidl/TunerHidlTimeFilter.cpp create mode 100644 services/tuner/hidl/TunerHidlTimeFilter.h diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp index 8a1d45c460..b2b1c3bc79 100644 --- a/services/tuner/Android.bp +++ b/services/tuner/Android.bp @@ -36,9 +36,12 @@ cc_library { srcs: [ "Tuner*.cpp", + "hidl/Tuner*.cpp", ], shared_libs: [ + "android.hardware.tv.tuner@1.0", + "android.hardware.tv.tuner@1.1", "android.hardware.tv.tuner-V1-ndk", "libbase", "libbinder", @@ -79,6 +82,8 @@ cc_binary { ], shared_libs: [ + "android.hardware.tv.tuner@1.0", + "android.hardware.tv.tuner@1.1", "android.hardware.tv.tuner-V1-ndk", "libbase", "libbinder", diff --git a/services/tuner/TunerFilter.h b/services/tuner/TunerFilter.h index 86d178c62f..06c5b8008d 100644 --- a/services/tuner/TunerFilter.h +++ b/services/tuner/TunerFilter.h @@ -88,9 +88,6 @@ public: }; private: - bool isAudioFilter(); - bool isVideoFilter(); - shared_ptr mFilter; int32_t mId; int64_t mId64Bit; diff --git a/services/tuner/TunerHelper.cpp b/services/tuner/TunerHelper.cpp new file mode 100644 index 0000000000..dc671109c2 --- /dev/null +++ b/services/tuner/TunerHelper.cpp @@ -0,0 +1,101 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "TunerHelper.h" + +#include +#include +#include +#include +#include + +using ::aidl::android::media::tv::tunerresourcemanager::ITunerResourceManager; +using ::android::defaultServiceManager; +using ::android::IBinder; +using ::android::interface_cast; +using ::android::IServiceManager; +using ::android::sp; +using ::android::binder::Status; +using ::android::content::pm::IPackageManagerNative; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +// System Feature defined in PackageManager +static const ::android::String16 FEATURE_TUNER(::android::String16("android.hardware.tv.tuner")); + +int32_t TunerHelper::sResourceRequestCount = 0; + +bool TunerHelper::checkTunerFeature() { + sp serviceMgr = defaultServiceManager(); + sp packageMgr; + if (serviceMgr.get() == nullptr) { + ALOGE("%s: Cannot find service manager", __func__); + return false; + } + + sp binder = serviceMgr->waitForService(String16("package_native")); + packageMgr = interface_cast(binder); + if (packageMgr != nullptr) { + bool hasFeature = false; + Status status = packageMgr->hasSystemFeature(FEATURE_TUNER, 0, &hasFeature); + if (!status.isOk()) { + ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str()); + return false; + } + if (!hasFeature) { + ALOGD("Current device does not support tuner feaure."); + return false; + } + } else { + ALOGD("%s: Cannot find package manager.", __func__); + return false; + } + + return true; +} + +// TODO: update Demux, Descrambler. +void TunerHelper::updateTunerResources(const vector& feInfos, + const vector& lnbHandles) { + ::ndk::SpAIBinder binder(AServiceManager_waitForService("tv_tuner_resource_mgr")); + shared_ptr tunerRM = ITunerResourceManager::fromBinder(binder); + if (tunerRM == nullptr) { + return; + } + + tunerRM->setFrontendInfoList(feInfos); + tunerRM->setLnbInfoList(lnbHandles); +} + +// TODO: create a map between resource id and handles. +int TunerHelper::getResourceIdFromHandle(int resourceHandle, int /*type*/) { + return (resourceHandle & 0x00ff0000) >> 16; +} + +int TunerHelper::getResourceHandleFromId(int id, int resourceType) { + // TODO: build up randomly generated id to handle mapping + return (resourceType & 0x000000ff) << 24 | (id << 16) | (sResourceRequestCount++ & 0xffff); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/TunerHelper.h b/services/tuner/TunerHelper.h new file mode 100644 index 0000000000..0d8d6a5f6e --- /dev/null +++ b/services/tuner/TunerHelper.h @@ -0,0 +1,67 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERDVRHELPER_H +#define ANDROID_MEDIA_TUNERDVRHELPER_H + +#include +#include + +using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; +using ::android::String16; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +const static int TUNER_HAL_VERSION_UNKNOWN = 0; +const static int TUNER_HAL_VERSION_1_0 = 1 << 16; +const static int TUNER_HAL_VERSION_1_1 = (1 << 16) | 1; +const static int TUNER_HAL_VERSION_2_0 = 2 << 16; + +typedef enum { + FRONTEND, + LNB, + DEMUX, + DESCRAMBLER, +} TunerResourceType; + +class TunerHelper { +public: + static bool checkTunerFeature(); + + // TODO: update Demux, Descrambler. + static void updateTunerResources(const vector& feInfos, + const vector& lnbHandles); + // TODO: create a map between resource id and handles. + static int getResourceIdFromHandle(int resourceHandle, int type); + static int getResourceHandleFromId(int id, int resourceType); + +private: + static int32_t sResourceRequestCount; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERDVRHELPER_H diff --git a/services/tuner/TunerService.cpp b/services/tuner/TunerService.cpp index 0703700a2d..fe5d4ca2af 100644 --- a/services/tuner/TunerService.cpp +++ b/services/tuner/TunerService.cpp @@ -24,30 +24,20 @@ #include #include #include -#include #include -#include -#include #include #include "TunerDemux.h" #include "TunerDescrambler.h" #include "TunerFrontend.h" +#include "TunerHelper.h" #include "TunerLnb.h" using ::aidl::android::hardware::tv::tuner::IDemux; using ::aidl::android::hardware::tv::tuner::IDescrambler; using ::aidl::android::hardware::tv::tuner::IFrontend; using ::aidl::android::hardware::tv::tuner::Result; -using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; -using ::android::defaultServiceManager; -using ::android::IBinder; -using ::android::interface_cast; -using ::android::IServiceManager; using ::android::sp; -using ::android::String16; -using ::android::binder::Status; -using ::android::content::pm::IPackageManagerNative; namespace aidl { namespace android { @@ -56,34 +46,11 @@ namespace tv { namespace tuner { TunerService::TunerService() { - sp serviceMgr = defaultServiceManager(); - sp packageMgr; - if (serviceMgr.get() == nullptr) { - ALOGE("%s: Cannot find service manager", __func__); - return; - } else { - sp binder = serviceMgr->waitForService(String16("package_native")); - packageMgr = interface_cast(binder); - } - - if (packageMgr != nullptr) { - bool hasFeature = false; - Status status = packageMgr->hasSystemFeature(FEATURE_TUNER, 0, &hasFeature); - if (!status.isOk()) { - ALOGE("%s: hasSystemFeature failed: %s", __func__, status.exceptionMessage().c_str()); - return; - } - if (!hasFeature) { - ALOGD("Current device does not support tuner feaure."); - return; - } - } else { - ALOGD("%s: Cannot find package manager.", __func__); + if (!TunerHelper::checkTunerFeature()) { + ALOGD("Device doesn't have tuner hardware."); return; } - ::ndk::SpAIBinder binder(AServiceManager_waitForService("tv_tuner_resource_mgr")); - mTunerResourceManager = ITunerResourceManager::fromBinder(binder); updateTunerResources(); } @@ -174,7 +141,7 @@ bool TunerService::hasITuner() { static_cast(Result::UNAVAILABLE)); } - int id = getResourceIdFromHandle(frontendHandle, FRONTEND); + int id = TunerHelper::getResourceIdFromHandle(frontendHandle, FRONTEND); shared_ptr frontend; auto status = mTuner->openFrontendById(id, &frontend); if (status.isOk()) { @@ -192,7 +159,7 @@ bool TunerService::hasITuner() { } shared_ptr lnb; - int id = getResourceIdFromHandle(lnbHandle, LNB); + int id = TunerHelper::getResourceIdFromHandle(lnbHandle, LNB); auto status = mTuner->openLnbById(id, &lnb); if (status.isOk()) { *_aidl_return = ::ndk::SharedRefBase::make(lnb, id); @@ -228,7 +195,7 @@ bool TunerService::hasITuner() { } shared_ptr descrambler; - // int id = getResourceIdFromHandle(descramblerHandle, DESCRAMBLER); + // int id = TunerHelper::getResourceIdFromHandle(descramblerHandle, DESCRAMBLER); auto status = mTuner->openDescrambler(&descrambler); if (status.isOk()) { *_aidl_return = ::ndk::SharedRefBase::make(descrambler); @@ -237,31 +204,29 @@ bool TunerService::hasITuner() { return status; } +::ndk::ScopedAStatus TunerService::getTunerHalVersion(int* _aidl_return) { + hasITuner(); + *_aidl_return = mTunerVersion; + return ::ndk::ScopedAStatus::ok(); +} + void TunerService::updateTunerResources() { - if (!hasITuner() || mTunerResourceManager == nullptr) { + if (!hasITuner()) { ALOGE("Failed to updateTunerResources"); return; } - updateFrontendResources(); - updateLnbResources(); - // TODO: update Demux, Descrambler. -} - -::ndk::ScopedAStatus TunerService::getTunerHalVersion(int* _aidl_return) { - hasITuner(); - *_aidl_return = mTunerVersion; - return ::ndk::ScopedAStatus::ok(); + TunerHelper::updateTunerResources(getTRMFrontendInfos(), getTRMLnbHandles()); } -void TunerService::updateFrontendResources() { +vector TunerService::getTRMFrontendInfos() { + vector infos; vector ids; auto status = mTuner->getFrontendIds(&ids); if (!status.isOk()) { - return; + return infos; } - vector infos; for (int i = 0; i < ids.size(); i++) { FrontendInfo frontendInfo; auto res = mTuner->getFrontendInfo(ids[i], &frontendInfo); @@ -269,31 +234,24 @@ void TunerService::updateFrontendResources() { continue; } TunerFrontendInfo tunerFrontendInfo{ - .handle = getResourceHandleFromId((int)ids[i], FRONTEND), + .handle = TunerHelper::getResourceHandleFromId((int)ids[i], FRONTEND), .type = static_cast(frontendInfo.type), .exclusiveGroupId = frontendInfo.exclusiveGroupId, }; infos.push_back(tunerFrontendInfo); } - mTunerResourceManager->setFrontendInfoList(infos); -} -void TunerService::updateLnbResources() { - vector handles = getLnbHandles(); - if (handles.size() == 0) { - return; - } - mTunerResourceManager->setLnbInfoList(handles); + return infos; } -vector TunerService::getLnbHandles() { +vector TunerService::getTRMLnbHandles() { vector lnbHandles; if (mTuner != nullptr) { vector lnbIds; auto res = mTuner->getLnbIds(&lnbIds); if (res.isOk()) { for (int i = 0; i < lnbIds.size(); i++) { - lnbHandles.push_back(getResourceHandleFromId(lnbIds[i], LNB)); + lnbHandles.push_back(TunerHelper::getResourceHandleFromId(lnbIds[i], LNB)); } } } diff --git a/services/tuner/TunerService.h b/services/tuner/TunerService.h index 164bef8d93..159e53ef27 100644 --- a/services/tuner/TunerService.h +++ b/services/tuner/TunerService.h @@ -17,20 +17,24 @@ #ifndef ANDROID_MEDIA_TUNERSERVICE_H #define ANDROID_MEDIA_TUNERSERVICE_H -#include #include #include #include #include -#include +#include + +#include "TunerHelper.h" -using ::aidl::android::hardware::tv::tuner::BnFilterCallback; using ::aidl::android::hardware::tv::tuner::DemuxCapabilities; using ::aidl::android::hardware::tv::tuner::DemuxFilterEvent; using ::aidl::android::hardware::tv::tuner::DemuxFilterStatus; using ::aidl::android::hardware::tv::tuner::FrontendInfo; using ::aidl::android::hardware::tv::tuner::ITuner; -using ::aidl::android::media::tv::tunerresourcemanager::ITunerResourceManager; +using ::aidl::android::media::tv::tuner::BnTunerService; +using ::aidl::android::media::tv::tuner::ITunerDemux; +using ::aidl::android::media::tv::tuner::ITunerFrontend; +using ::aidl::android::media::tv::tuner::ITunerLnb; +using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; using namespace std; @@ -40,32 +44,6 @@ namespace media { namespace tv { namespace tuner { -const static int TUNER_HAL_VERSION_UNKNOWN = 0; -const static int TUNER_HAL_VERSION_1_0 = 1 << 16; -const static int TUNER_HAL_VERSION_1_1 = (1 << 16) | 1; -const static int TUNER_HAL_VERSION_2_0 = 2 << 16; -// System Feature defined in PackageManager -static const ::android::String16 FEATURE_TUNER(::android::String16("android.hardware.tv.tuner")); - -typedef enum { - FRONTEND, - LNB, - DEMUX, - DESCRAMBLER, -} TunerResourceType; - -struct FilterCallback : public BnFilterCallback { - ~FilterCallback() {} - virtual ::ndk::ScopedAStatus onFilterEvent( - const vector& /* events */) override { - return ::ndk::ScopedAStatus::ok(); - } - - virtual ::ndk::ScopedAStatus onFilterStatus(const DemuxFilterStatus /*status*/) override { - return ::ndk::ScopedAStatus::ok(); - } -}; - class TunerService : public BnTunerService { public: static char const *getServiceName() { return "media.tuner"; } @@ -89,28 +67,13 @@ public: shared_ptr* _aidl_return) override; ::ndk::ScopedAStatus getTunerHalVersion(int32_t* _aidl_return) override; - // TODO: create a map between resource id and handles. - static int getResourceIdFromHandle(int resourceHandle, int /*type*/) { - return (resourceHandle & 0x00ff0000) >> 16; - } - - int getResourceHandleFromId(int id, int resourceType) { - // TODO: build up randomly generated id to handle mapping - return (resourceType & 0x000000ff) << 24 - | (id << 16) - | (mResourceRequestCount++ & 0xffff); - } - private: bool hasITuner(); void updateTunerResources(); - void updateFrontendResources(); - void updateLnbResources(); - vector getLnbHandles(); + vector getTRMFrontendInfos(); + vector getTRMLnbHandles(); shared_ptr mTuner; - shared_ptr mTunerResourceManager; - int mResourceRequestCount = 0; int mTunerVersion = TUNER_HAL_VERSION_UNKNOWN; }; diff --git a/services/tuner/hidl/TunerHidlDemux.cpp b/services/tuner/hidl/TunerHidlDemux.cpp new file mode 100644 index 0000000000..5a921b9fe3 --- /dev/null +++ b/services/tuner/hidl/TunerHidlDemux.cpp @@ -0,0 +1,278 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlDemux" + +#include "TunerHidlDemux.h" + +#include "TunerHidlDvr.h" +#include "TunerHidlFilter.h" +#include "TunerHidlTimeFilter.h" + +using ::aidl::android::hardware::tv::tuner::DemuxFilterSubType; + +using HidlDemuxAlpFilterType = ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterType; +using HidlDemuxFilterMainType = ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; +using HidlDemuxFilterType = ::android::hardware::tv::tuner::V1_0::DemuxFilterType; +using HidlDemuxIpFilterType = ::android::hardware::tv::tuner::V1_0::DemuxIpFilterType; +using HidlDemuxMmtpFilterType = ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterType; +using HidlDemuxTlvFilterType = ::android::hardware::tv::tuner::V1_0::DemuxTlvFilterType; +using HidlDemuxTsFilterType = ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; +using HidlDvrType = ::android::hardware::tv::tuner::V1_0::DvrType; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlDemux::TunerHidlDemux(sp demux, int id) { + mDemux = demux; + mDemuxId = id; +} + +TunerHidlDemux::~TunerHidlDemux() { + mDemux = nullptr; +} + +::ndk::ScopedAStatus TunerHidlDemux::setFrontendDataSource( + const shared_ptr& in_frontend) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + int frontendId; + in_frontend->getFrontendId(&frontendId); + HidlResult res = mDemux->setFrontendDataSource(frontendId); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::setFrontendDataSourceById(int frontendId) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult res = mDemux->setFrontendDataSource(frontendId); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::openFilter(const DemuxFilterType& in_type, + int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlDemuxFilterMainType mainType = static_cast(in_type.mainType); + HidlDemuxFilterType filterType{ + .mainType = mainType, + }; + + switch (mainType) { + case HidlDemuxFilterMainType::TS: + filterType.subType.tsFilterType(static_cast( + in_type.subType.get())); + break; + case HidlDemuxFilterMainType::MMTP: + filterType.subType.mmtpFilterType(static_cast( + in_type.subType.get())); + break; + case HidlDemuxFilterMainType::IP: + filterType.subType.ipFilterType(static_cast( + in_type.subType.get())); + break; + case HidlDemuxFilterMainType::TLV: + filterType.subType.tlvFilterType(static_cast( + in_type.subType.get())); + break; + case HidlDemuxFilterMainType::ALP: + filterType.subType.alpFilterType(static_cast( + in_type.subType.get())); + break; + } + HidlResult status; + sp filterSp; + sp<::android::hardware::tv::tuner::V1_0::IFilterCallback> cbSp = + new TunerHidlFilter::FilterCallback(in_cb); + mDemux->openFilter(filterType, static_cast(in_bufferSize), cbSp, + [&](HidlResult r, const sp& filter) { + filterSp = filter; + status = r; + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(filterSp, in_type); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::openTimeFilter(shared_ptr* _aidl_return) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult status; + sp filterSp; + mDemux->openTimeFilter([&](HidlResult r, const sp& filter) { + filterSp = filter; + status = r; + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(filterSp); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::getAvSyncHwId(const shared_ptr& tunerFilter, + int32_t* _aidl_return) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + uint32_t avSyncHwId; + HidlResult res; + sp halFilter = static_cast(tunerFilter.get())->getHalFilter(); + mDemux->getAvSyncHwId(halFilter, [&](HidlResult r, uint32_t id) { + res = r; + avSyncHwId = id; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + *_aidl_return = (int)avSyncHwId; + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::getAvSyncTime(int32_t avSyncHwId, int64_t* _aidl_return) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + uint64_t time; + HidlResult res; + mDemux->getAvSyncTime(static_cast(avSyncHwId), [&](HidlResult r, uint64_t ts) { + res = r; + time = ts; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + *_aidl_return = (int64_t)time; + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::openDvr(DvrType in_dvbType, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult res; + sp callback = new TunerHidlDvr::DvrCallback(in_cb); + sp hidlDvr; + mDemux->openDvr(static_cast(in_dvbType), in_bufferSize, callback, + [&](HidlResult r, const sp& dvr) { + hidlDvr = dvr; + res = r; + }); + if (res != HidlResult::SUCCESS) { + *_aidl_return = nullptr; + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(hidlDvr, in_dvbType); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::connectCiCam(int32_t ciCamId) { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult res = mDemux->connectCiCam(static_cast(ciCamId)); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::disconnectCiCam() { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult res = mDemux->disconnectCiCam(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDemux::close() { + if (mDemux == nullptr) { + ALOGE("IDemux is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(HidlResult::UNAVAILABLE)); + } + + HidlResult res = mDemux->close(); + mDemux = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlDemux.h b/services/tuner/hidl/TunerHidlDemux.h new file mode 100644 index 0000000000..d535da6f33 --- /dev/null +++ b/services/tuner/hidl/TunerHidlDemux.h @@ -0,0 +1,75 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLDEMUX_H +#define ANDROID_MEDIA_TUNERHIDLDEMUX_H + +#include +#include + +using ::aidl::android::hardware::tv::tuner::DemuxFilterType; +using ::aidl::android::hardware::tv::tuner::DvrType; +using ::android::sp; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::android::hardware::tv::tuner::V1_0::IDemux; +using ::std::shared_ptr; +using ::std::vector; + +using HidlIDemux = ::android::hardware::tv::tuner::V1_0::IDemux; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlDemux : public BnTunerDemux { +public: + TunerHidlDemux(sp demux, int demuxId); + virtual ~TunerHidlDemux(); + + ::ndk::ScopedAStatus setFrontendDataSource( + const shared_ptr& in_frontend) override; + ::ndk::ScopedAStatus setFrontendDataSourceById(int frontendId) override; + ::ndk::ScopedAStatus openFilter(const DemuxFilterType& in_type, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openTimeFilter(shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getAvSyncHwId(const shared_ptr& in_tunerFilter, + int32_t* _aidl_return) override; + ::ndk::ScopedAStatus getAvSyncTime(int32_t in_avSyncHwId, int64_t* _aidl_return) override; + ::ndk::ScopedAStatus openDvr(DvrType in_dvbType, int32_t in_bufferSize, + const shared_ptr& in_cb, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus connectCiCam(int32_t in_ciCamId) override; + ::ndk::ScopedAStatus disconnectCiCam() override; + ::ndk::ScopedAStatus close() override; + + int getId() { return mDemuxId; } + +private: + sp mDemux; + int mDemuxId; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLDEMUX_H diff --git a/services/tuner/hidl/TunerHidlDescrambler.cpp b/services/tuner/hidl/TunerHidlDescrambler.cpp new file mode 100644 index 0000000000..dd8cd9c7f7 --- /dev/null +++ b/services/tuner/hidl/TunerHidlDescrambler.cpp @@ -0,0 +1,149 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlDescrambler" + +#include "TunerHidlDescrambler.h" + +#include + +#include "TunerHidlDemux.h" +#include "TunerHidlFilter.h" + +using ::aidl::android::hardware::tv::tuner::Result; + +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlDescrambler::TunerHidlDescrambler(sp descrambler) { + mDescrambler = descrambler; +} + +TunerHidlDescrambler::~TunerHidlDescrambler() { + mDescrambler = nullptr; +} + +::ndk::ScopedAStatus TunerHidlDescrambler::setDemuxSource( + const shared_ptr& in_tunerDemux) { + if (mDescrambler == nullptr) { + ALOGE("IDescrambler is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDescrambler->setDemuxSource( + static_cast(in_tunerDemux.get())->getId()); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDescrambler::setKeyToken(const vector& in_keyToken) { + if (mDescrambler == nullptr) { + ALOGE("IDescrambler is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDescrambler->setKeyToken(in_keyToken); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDescrambler::addPid( + const DemuxPid& in_pid, const shared_ptr& in_optionalSourceFilter) { + if (mDescrambler == nullptr) { + ALOGE("IDescrambler is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + sp halFilter = + (in_optionalSourceFilter == nullptr) + ? nullptr + : static_cast(in_optionalSourceFilter.get())->getHalFilter(); + HidlResult res = mDescrambler->addPid(getHidlDemuxPid(in_pid), halFilter); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDescrambler::removePid( + const DemuxPid& in_pid, const shared_ptr& in_optionalSourceFilter) { + if (mDescrambler == nullptr) { + ALOGE("IDescrambler is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + sp halFilter = + (in_optionalSourceFilter == nullptr) + ? nullptr + : static_cast(in_optionalSourceFilter.get())->getHalFilter(); + HidlResult res = mDescrambler->removePid(getHidlDemuxPid(in_pid), halFilter); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDescrambler::close() { + if (mDescrambler == nullptr) { + ALOGE("IDescrambler is not initialized."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDescrambler->close(); + mDescrambler = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +HidlDemuxPid TunerHidlDescrambler::getHidlDemuxPid(const DemuxPid& pid) { + HidlDemuxPid hidlPid; + switch (pid.getTag()) { + case DemuxPid::tPid: { + hidlPid.tPid((uint16_t)pid.get()); + break; + } + case DemuxPid::mmtpPid: { + hidlPid.mmtpPid((uint16_t)pid.get()); + break; + } + } + return hidlPid; +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlDescrambler.h b/services/tuner/hidl/TunerHidlDescrambler.h new file mode 100644 index 0000000000..9494968e9e --- /dev/null +++ b/services/tuner/hidl/TunerHidlDescrambler.h @@ -0,0 +1,66 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLDESCRAMBLER_H +#define ANDROID_MEDIA_TUNERHIDLDESCRAMBLER_H + +#include +#include +#include +#include + +using ::aidl::android::hardware::tv::tuner::DemuxPid; +using ::android::sp; +using ::android::hardware::Return; +using ::android::hardware::Void; + +using HidlDemuxPid = ::android::hardware::tv::tuner::V1_0::DemuxPid; +using HidlIDescrambler = ::android::hardware::tv::tuner::V1_0::IDescrambler; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlDescrambler : public BnTunerDescrambler { +public: + TunerHidlDescrambler(sp descrambler); + virtual ~TunerHidlDescrambler(); + + ::ndk::ScopedAStatus setDemuxSource(const std::shared_ptr& in_tunerDemux) override; + ::ndk::ScopedAStatus setKeyToken(const std::vector& in_keyToken) override; + ::ndk::ScopedAStatus addPid( + const DemuxPid& in_pid, + const std::shared_ptr& in_optionalSourceFilter) override; + ::ndk::ScopedAStatus removePid( + const DemuxPid& in_pid, + const std::shared_ptr& in_optionalSourceFilter) override; + ::ndk::ScopedAStatus close() override; + +private: + HidlDemuxPid getHidlDemuxPid(const DemuxPid& pid); + + sp mDescrambler; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLDESCRAMBLER_H diff --git a/services/tuner/hidl/TunerHidlDvr.cpp b/services/tuner/hidl/TunerHidlDvr.cpp new file mode 100644 index 0000000000..1a619d509f --- /dev/null +++ b/services/tuner/hidl/TunerHidlDvr.cpp @@ -0,0 +1,257 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlDvr" + +#include "TunerHidlDvr.h" + +#include +#include +#include +#include +#include + +using ::aidl::android::hardware::tv::tuner::DataFormat; +using ::aidl::android::hardware::tv::tuner::PlaybackStatus; +using ::aidl::android::hardware::tv::tuner::RecordStatus; +using ::aidl::android::hardware::tv::tuner::Result; +using ::android::unsafeHidlToAidlMQDescriptor; +using ::android::hardware::MessageQueue; +using ::android::hardware::MQDescriptorSync; + +using HidlDataFormat = ::android::hardware::tv::tuner::V1_0::DataFormat; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; +using MQDesc = MQDescriptorSync; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlDvr::TunerHidlDvr(sp dvr, DvrType type) { + mDvr = dvr; + mType = type; +} + +TunerHidlDvr::~TunerHidlDvr() { + mDvr = nullptr; +} + +::ndk::ScopedAStatus TunerHidlDvr::getQueueDesc(AidlMQDesc* _aidl_return) { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + MQDesc dvrMQDesc; + HidlResult res; + mDvr->getQueueDesc([&](HidlResult r, const MQDesc& desc) { + dvrMQDesc = desc; + res = r; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + AidlMQDesc aidlMQDesc; + unsafeHidlToAidlMQDescriptor(dvrMQDesc, &aidlMQDesc); + *_aidl_return = move(aidlMQDesc); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::configure(const DvrSettings& in_settings) { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDvr->configure(getHidlDvrSettings(in_settings)); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::attachFilter(const shared_ptr& in_filter) { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (in_filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + sp hidlFilter = static_cast(in_filter.get())->getHalFilter(); + if (hidlFilter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + HidlResult res = mDvr->attachFilter(hidlFilter); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::detachFilter(const shared_ptr& in_filter) { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (in_filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + sp halFilter = (static_cast(in_filter.get()))->getHalFilter(); + if (halFilter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + HidlResult res = mDvr->detachFilter(halFilter); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::start() { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDvr->start(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::stop() { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDvr->stop(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::flush() { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDvr->flush(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlDvr::close() { + if (mDvr == nullptr) { + ALOGE("IDvr is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mDvr->close(); + mDvr = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +HidlDvrSettings TunerHidlDvr::getHidlDvrSettings(const DvrSettings& settings) { + HidlDvrSettings s; + switch (mType) { + case DvrType::PLAYBACK: { + s.playback({ + .statusMask = + static_cast(settings.get().statusMask), + .lowThreshold = + static_cast(settings.get().lowThreshold), + .highThreshold = + static_cast(settings.get().highThreshold), + .dataFormat = static_cast( + settings.get().dataFormat), + .packetSize = + static_cast(settings.get().packetSize), + }); + return s; + } + case DvrType::RECORD: { + s.record({ + .statusMask = static_cast(settings.get().statusMask), + .lowThreshold = + static_cast(settings.get().lowThreshold), + .highThreshold = + static_cast(settings.get().highThreshold), + .dataFormat = + static_cast(settings.get().dataFormat), + .packetSize = static_cast(settings.get().packetSize), + }); + return s; + } + default: + break; + } + return s; +} + +/////////////// IDvrCallback /////////////////////// +Return TunerHidlDvr::DvrCallback::onRecordStatus(const HidlRecordStatus status) { + if (mTunerDvrCallback != nullptr) { + mTunerDvrCallback->onRecordStatus(static_cast(status)); + } + return Void(); +} + +Return TunerHidlDvr::DvrCallback::onPlaybackStatus(const HidlPlaybackStatus status) { + if (mTunerDvrCallback != nullptr) { + mTunerDvrCallback->onPlaybackStatus(static_cast(status)); + } + return Void(); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlDvr.h b/services/tuner/hidl/TunerHidlDvr.h new file mode 100644 index 0000000000..a280ff70b0 --- /dev/null +++ b/services/tuner/hidl/TunerHidlDvr.h @@ -0,0 +1,91 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLDVR_H +#define ANDROID_MEDIA_TUNERHIDLDVR_H + +#include +#include +#include +#include +#include +#include + +#include "TunerHidlFilter.h" + +using ::aidl::android::hardware::common::fmq::MQDescriptor; +using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite; +using ::aidl::android::hardware::tv::tuner::DvrSettings; +using ::aidl::android::hardware::tv::tuner::DvrType; +using ::android::sp; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::std::shared_ptr; +using ::std::vector; + +using HidlDvrSettings = ::android::hardware::tv::tuner::V1_0::DvrSettings; +using HidlIDvr = ::android::hardware::tv::tuner::V1_0::IDvr; +using HidlIDvrCallback = ::android::hardware::tv::tuner::V1_0::IDvrCallback; +using HidlPlaybackStatus = ::android::hardware::tv::tuner::V1_0::PlaybackStatus; +using HidlRecordStatus = ::android::hardware::tv::tuner::V1_0::RecordStatus; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +using AidlMQDesc = MQDescriptor; + +class TunerHidlDvr : public BnTunerDvr { +public: + TunerHidlDvr(sp dvr, DvrType type); + ~TunerHidlDvr(); + + ::ndk::ScopedAStatus getQueueDesc(AidlMQDesc* _aidl_return) override; + ::ndk::ScopedAStatus configure(const DvrSettings& in_settings) override; + ::ndk::ScopedAStatus attachFilter(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus detachFilter(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus start() override; + ::ndk::ScopedAStatus stop() override; + ::ndk::ScopedAStatus flush() override; + ::ndk::ScopedAStatus close() override; + + struct DvrCallback : public HidlIDvrCallback { + DvrCallback(const shared_ptr tunerDvrCallback) + : mTunerDvrCallback(tunerDvrCallback){}; + + virtual Return onRecordStatus(const HidlRecordStatus status); + virtual Return onPlaybackStatus(const HidlPlaybackStatus status); + + private: + shared_ptr mTunerDvrCallback; + }; + +private: + HidlDvrSettings getHidlDvrSettings(const DvrSettings& settings); + + sp mDvr; + DvrType mType; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLDVR_H diff --git a/services/tuner/hidl/TunerHidlFilter.cpp b/services/tuner/hidl/TunerHidlFilter.cpp new file mode 100644 index 0000000000..1573c8e821 --- /dev/null +++ b/services/tuner/hidl/TunerHidlFilter.cpp @@ -0,0 +1,1002 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlFilter" + +#include "TunerHidlFilter.h" + +#include +#include +#include +#include + +using ::aidl::android::hardware::tv::tuner::AudioExtraMetaData; +using ::aidl::android::hardware::tv::tuner::Constant; +using ::aidl::android::hardware::tv::tuner::DemuxAlpFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxAlpFilterSettingsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterDownloadEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterIpPayloadEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterMainType; +using ::aidl::android::hardware::tv::tuner::DemuxFilterMediaEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterMediaEventExtraMetaData; +using ::aidl::android::hardware::tv::tuner::DemuxFilterMmtpRecordEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterMonitorEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterPesEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterScIndexMask; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSectionBits; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSectionEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSectionSettingsCondition; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSectionSettingsConditionTableInfo; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSubType; +using ::aidl::android::hardware::tv::tuner::DemuxFilterTemiEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterTsRecordEvent; +using ::aidl::android::hardware::tv::tuner::DemuxIpAddress; +using ::aidl::android::hardware::tv::tuner::DemuxIpAddressIpAddress; +using ::aidl::android::hardware::tv::tuner::DemuxIpFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxIpFilterSettingsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxMmtpFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxMmtpFilterSettingsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxMmtpFilterType; +using ::aidl::android::hardware::tv::tuner::DemuxPid; +using ::aidl::android::hardware::tv::tuner::DemuxTlvFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxTlvFilterSettingsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxTsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxTsFilterSettingsFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxTsFilterType; +using ::aidl::android::hardware::tv::tuner::Result; +using ::aidl::android::hardware::tv::tuner::ScramblingStatus; +using ::android::dupToAidl; +using ::android::makeFromAidl; +using ::android::unsafeHidlToAidlMQDescriptor; +using ::android::hardware::hidl_handle; + +using HidlDemuxAlpLengthType = ::android::hardware::tv::tuner::V1_0::DemuxAlpLengthType; +using HidlDemuxFilterMainType = ::android::hardware::tv::tuner::V1_0::DemuxFilterMainType; +using HidlDemuxIpAddress = ::android::hardware::tv::tuner::V1_0::DemuxIpAddress; +using HidlDemuxMmtpFilterType = ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterType; +using HidlDemuxMmtpPid = ::android::hardware::tv::tuner::V1_0::DemuxMmtpPid; +using HidlDemuxRecordScIndexType = ::android::hardware::tv::tuner::V1_0::DemuxRecordScIndexType; +using HidlDemuxStreamId = ::android::hardware::tv::tuner::V1_0::DemuxStreamId; +using HidlDemuxTsFilterType = ::android::hardware::tv::tuner::V1_0::DemuxTsFilterType; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; +using HidlAudioStreamType = ::android::hardware::tv::tuner::V1_1::AudioStreamType; +using HidlConstant = ::android::hardware::tv::tuner::V1_1::Constant; +using HidlVideoStreamType = ::android::hardware::tv::tuner::V1_1::VideoStreamType; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlFilter::TunerHidlFilter(sp filter, DemuxFilterType type) + : mFilter(filter), mType(type) { + mFilter_1_1 = ::android::hardware::tv::tuner::V1_1::IFilter::castFrom(filter); +} + +TunerHidlFilter::~TunerHidlFilter() { + mFilter = nullptr; + mFilter_1_1 = nullptr; +} + +::ndk::ScopedAStatus TunerHidlFilter::getQueueDesc(AidlMQDesc* _aidl_return) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + MQDesc filterMQDesc; + HidlResult res; + mFilter->getQueueDesc([&](HidlResult r, const MQDesc& desc) { + filterMQDesc = desc; + res = r; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + AidlMQDesc aidlMQDesc; + unsafeHidlToAidlMQDescriptor(filterMQDesc, &aidlMQDesc); + *_aidl_return = move(aidlMQDesc); + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::getId(int32_t* _aidl_return) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + mFilter->getId([&](HidlResult r, uint32_t filterId) { + res = r; + mId = filterId; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + *_aidl_return = mId; + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::getId64Bit(int64_t* _aidl_return) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + mFilter_1_1->getId64Bit([&](HidlResult r, uint64_t filterId) { + res = r; + mId64Bit = filterId; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + *_aidl_return = mId64Bit; + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::configure(const DemuxFilterSettings& in_settings) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlDemuxFilterSettings settings; + switch (in_settings.getTag()) { + case DemuxFilterSettings::ts: { + getHidlTsSettings(in_settings, settings); + break; + } + case DemuxFilterSettings::mmtp: { + getHidlMmtpSettings(in_settings, settings); + break; + } + case DemuxFilterSettings::ip: { + getHidlIpSettings(in_settings, settings); + break; + } + case DemuxFilterSettings::tlv: { + getHidlTlvSettings(in_settings, settings); + break; + } + case DemuxFilterSettings::alp: { + getHidlAlpSettings(in_settings, settings); + break; + } + } + + HidlResult res = mFilter->configure(settings); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::configureMonitorEvent(int32_t monitorEventType) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter_1_1->configureMonitorEvent(monitorEventType); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::configureIpFilterContextId(int32_t cid) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter_1_1->configureIpCid(cid); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::configureAvStreamType(const AvStreamType& in_avStreamType) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlAvStreamType type; + if (!getHidlAvStreamType(in_avStreamType, type)) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_STATE)); + } + + HidlResult res = mFilter_1_1->configureAvStreamType(type); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::setDataSource(const shared_ptr& filter) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (filter == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + sp hidlFilter = static_cast(filter.get())->getHalFilter(); + HidlResult res = mFilter->setDataSource(hidlFilter); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::getAvSharedHandle(NativeHandle* out_avMemory, + int64_t* _aidl_return) { + if (mFilter_1_1 == nullptr) { + ALOGE("IFilter_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + mFilter_1_1->getAvSharedHandle([&](HidlResult r, hidl_handle avMemory, uint64_t avMemSize) { + res = r; + if (res == HidlResult::SUCCESS) { + *out_avMemory = dupToAidl(avMemory); + *_aidl_return = static_cast(avMemSize); + } else { + _aidl_return = nullptr; + } + }); + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::releaseAvHandle(const NativeHandle& in_handle, + int64_t in_avDataId) { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter->releaseAvHandle(hidl_handle(makeFromAidl(in_handle)), in_avDataId); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::start() { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter->start(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::stop() { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter->stop(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::flush() { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter->flush(); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFilter::close() { + if (mFilter == nullptr) { + ALOGE("IFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mFilter->close(); + mFilter = nullptr; + mFilter_1_1 = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +sp TunerHidlFilter::getHalFilter() { + return mFilter; +} + +bool TunerHidlFilter::getHidlAvStreamType(const AvStreamType avStreamType, HidlAvStreamType& type) { + if (isAudioFilter()) { + type.audio(static_cast(avStreamType.get())); + return true; + } + + if (isVideoFilter()) { + type.video(static_cast(avStreamType.get())); + return true; + } + + return false; +} + +bool TunerHidlFilter::isAudioFilter() { + return (mType.mainType == DemuxFilterMainType::TS && + mType.subType.get() == DemuxTsFilterType::AUDIO) || + (mType.mainType == DemuxFilterMainType::MMTP && + mType.subType.get() == DemuxMmtpFilterType::AUDIO); +} + +bool TunerHidlFilter::isVideoFilter() { + return (mType.mainType == DemuxFilterMainType::TS && + mType.subType.get() == DemuxTsFilterType::VIDEO) || + (mType.mainType == DemuxFilterMainType::MMTP && + mType.subType.get() == DemuxMmtpFilterType::VIDEO); +} + +void TunerHidlFilter::getHidlTsSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings) { + const DemuxTsFilterSettings& tsConf = settings.get(); + HidlDemuxTsFilterSettings ts{ + .tpid = static_cast(tsConf.tpid), + }; + + switch (tsConf.filterSettings.getTag()) { + case DemuxTsFilterSettingsFilterSettings::av: { + ts.filterSettings.av(getHidlAvSettings( + tsConf.filterSettings.get())); + break; + } + case DemuxTsFilterSettingsFilterSettings::section: { + ts.filterSettings.section(getHidlSectionSettings( + tsConf.filterSettings.get())); + break; + } + case DemuxTsFilterSettingsFilterSettings::pesData: { + ts.filterSettings.pesData(getHidlPesDataSettings( + tsConf.filterSettings.get())); + break; + } + case DemuxTsFilterSettingsFilterSettings::record: { + ts.filterSettings.record(getHidlRecordSettings( + tsConf.filterSettings.get())); + break; + } + default: { + ts.filterSettings.noinit(); + break; + } + } + hidlSettings.ts(ts); +} + +void TunerHidlFilter::getHidlMmtpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings) { + const DemuxMmtpFilterSettings& mmtpConf = settings.get(); + HidlDemuxMmtpFilterSettings mmtp{ + .mmtpPid = static_cast(mmtpConf.mmtpPid), + }; + + switch (mmtpConf.filterSettings.getTag()) { + case DemuxMmtpFilterSettingsFilterSettings::av: { + mmtp.filterSettings.av(getHidlAvSettings( + mmtpConf.filterSettings.get())); + break; + } + case DemuxMmtpFilterSettingsFilterSettings::section: { + mmtp.filterSettings.section(getHidlSectionSettings( + mmtpConf.filterSettings.get())); + break; + } + case DemuxMmtpFilterSettingsFilterSettings::pesData: { + mmtp.filterSettings.pesData(getHidlPesDataSettings( + mmtpConf.filterSettings.get())); + break; + } + case DemuxMmtpFilterSettingsFilterSettings::record: { + mmtp.filterSettings.record(getHidlRecordSettings( + mmtpConf.filterSettings.get())); + break; + } + case DemuxMmtpFilterSettingsFilterSettings::download: { + mmtp.filterSettings.download(getHidlDownloadSettings( + mmtpConf.filterSettings.get())); + break; + } + default: { + mmtp.filterSettings.noinit(); + break; + } + } + hidlSettings.mmtp(mmtp); +} + +void TunerHidlFilter::getHidlIpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings) { + const DemuxIpFilterSettings& ipConf = settings.get(); + HidlDemuxIpAddress ipAddr{ + .srcPort = static_cast(ipConf.ipAddr.srcPort), + .dstPort = static_cast(ipConf.ipAddr.dstPort), + }; + + ipConf.ipAddr.srcIpAddress.getTag() == DemuxIpAddressIpAddress::v6 + ? ipAddr.srcIpAddress.v6(getIpV6Address(ipConf.ipAddr.srcIpAddress)) + : ipAddr.srcIpAddress.v4(getIpV4Address(ipConf.ipAddr.srcIpAddress)); + ipConf.ipAddr.dstIpAddress.getTag() == DemuxIpAddressIpAddress::v6 + ? ipAddr.dstIpAddress.v6(getIpV6Address(ipConf.ipAddr.dstIpAddress)) + : ipAddr.dstIpAddress.v4(getIpV4Address(ipConf.ipAddr.dstIpAddress)); + + HidlDemuxIpFilterSettings ip; + ip.ipAddr = ipAddr; + + switch (ipConf.filterSettings.getTag()) { + case DemuxIpFilterSettingsFilterSettings::section: { + ip.filterSettings.section(getHidlSectionSettings( + ipConf.filterSettings.get())); + break; + } + case DemuxIpFilterSettingsFilterSettings::bPassthrough: { + ip.filterSettings.bPassthrough( + ipConf.filterSettings.get()); + break; + } + default: { + ip.filterSettings.noinit(); + break; + } + } + hidlSettings.ip(ip); +} + +hidl_array TunerHidlFilter::getIpV6Address( + const DemuxIpAddressIpAddress& addr) { + hidl_array ip; + if (addr.get().size() != IP_V6_LENGTH) { + return ip; + } + copy(addr.get().begin(), + addr.get().end(), ip.data()); + return ip; +} + +hidl_array TunerHidlFilter::getIpV4Address( + const DemuxIpAddressIpAddress& addr) { + hidl_array ip; + if (addr.get().size() != IP_V4_LENGTH) { + return ip; + } + copy(addr.get().begin(), + addr.get().end(), ip.data()); + return ip; +} + +void TunerHidlFilter::getHidlTlvSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings) { + const DemuxTlvFilterSettings& tlvConf = settings.get(); + HidlDemuxTlvFilterSettings tlv{ + .packetType = static_cast(tlvConf.packetType), + .isCompressedIpPacket = tlvConf.isCompressedIpPacket, + }; + + switch (tlvConf.filterSettings.getTag()) { + case DemuxTlvFilterSettingsFilterSettings::section: { + tlv.filterSettings.section(getHidlSectionSettings( + tlvConf.filterSettings.get())); + break; + } + case DemuxTlvFilterSettingsFilterSettings::bPassthrough: { + tlv.filterSettings.bPassthrough( + tlvConf.filterSettings.get()); + break; + } + default: { + tlv.filterSettings.noinit(); + break; + } + } + hidlSettings.tlv(tlv); +} + +void TunerHidlFilter::getHidlAlpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings) { + const DemuxAlpFilterSettings& alpConf = settings.get(); + HidlDemuxAlpFilterSettings alp{ + .packetType = static_cast(alpConf.packetType), + .lengthType = static_cast(alpConf.lengthType), + }; + + switch (alpConf.filterSettings.getTag()) { + case DemuxAlpFilterSettingsFilterSettings::section: { + alp.filterSettings.section(getHidlSectionSettings( + alpConf.filterSettings.get())); + break; + } + default: { + alp.filterSettings.noinit(); + break; + } + } + hidlSettings.alp(alp); +} + +HidlDemuxFilterAvSettings TunerHidlFilter::getHidlAvSettings( + const DemuxFilterAvSettings& settings) { + HidlDemuxFilterAvSettings av{ + .isPassthrough = settings.isPassthrough, + }; + return av; +} + +HidlDemuxFilterSectionSettings TunerHidlFilter::getHidlSectionSettings( + const DemuxFilterSectionSettings& settings) { + HidlDemuxFilterSectionSettings section{ + .isCheckCrc = settings.isCheckCrc, + .isRepeat = settings.isRepeat, + .isRaw = settings.isRaw, + }; + + switch (settings.condition.getTag()) { + case DemuxFilterSectionSettingsCondition::sectionBits: { + const DemuxFilterSectionBits& sectionBits = + settings.condition.get(); + vector filter(sectionBits.filter.begin(), sectionBits.filter.end()); + vector mask(sectionBits.mask.begin(), sectionBits.mask.end()); + vector mode(sectionBits.mode.begin(), sectionBits.mode.end()); + section.condition.sectionBits({ + .filter = filter, + .mask = mask, + .mode = mode, + }); + break; + } + case DemuxFilterSectionSettingsCondition::tableInfo: { + const DemuxFilterSectionSettingsConditionTableInfo& tableInfo = + settings.condition.get(); + section.condition.tableInfo({ + .tableId = static_cast(tableInfo.tableId), + .version = static_cast(tableInfo.version), + }); + break; + } + default: { + break; + } + } + return section; +} + +HidlDemuxFilterPesDataSettings TunerHidlFilter::getHidlPesDataSettings( + const DemuxFilterPesDataSettings& settings) { + HidlDemuxFilterPesDataSettings pes{ + .streamId = static_cast(settings.streamId), + .isRaw = settings.isRaw, + }; + return pes; +} + +HidlDemuxFilterRecordSettings TunerHidlFilter::getHidlRecordSettings( + const DemuxFilterRecordSettings& settings) { + HidlDemuxFilterRecordSettings record{ + .tsIndexMask = static_cast(settings.tsIndexMask), + .scIndexType = static_cast(settings.scIndexType), + }; + + switch (settings.scIndexMask.getTag()) { + case DemuxFilterScIndexMask::scIndex: { + record.scIndexMask.sc( + static_cast(settings.scIndexMask.get())); + break; + } + case DemuxFilterScIndexMask::scHevc: { + record.scIndexMask.scHevc( + static_cast(settings.scIndexMask.get())); + break; + } + } + return record; +} + +HidlDemuxFilterDownloadSettings TunerHidlFilter::getHidlDownloadSettings( + const DemuxFilterDownloadSettings& settings) { + HidlDemuxFilterDownloadSettings download{ + .downloadId = static_cast(settings.downloadId), + }; + return download; +} + +/////////////// FilterCallback /////////////////////// +Return TunerHidlFilter::FilterCallback::onFilterStatus(HidlDemuxFilterStatus status) { + if (mTunerFilterCallback != NULL) { + mTunerFilterCallback->onFilterStatus(static_cast(status)); + } + return Void(); +} + +Return TunerHidlFilter::FilterCallback::onFilterEvent( + const HidlDemuxFilterEvent& filterEvent) { + vector emptyEventsExt; + HidlDemuxFilterEventExt emptyFilterEventExt{ + .events = emptyEventsExt, + }; + onFilterEvent_1_1(filterEvent, emptyFilterEventExt); + return Void(); +} + +Return TunerHidlFilter::FilterCallback::onFilterEvent_1_1( + const HidlDemuxFilterEvent& filterEvent, const HidlDemuxFilterEventExt& filterEventExt) { + if (mTunerFilterCallback != NULL) { + vector events = filterEvent.events; + vector eventsExt = filterEventExt.events; + vector tunerEvents; + + getAidlFilterEvent(events, eventsExt, tunerEvents); + mTunerFilterCallback->onFilterEvent(tunerEvents); + } + return Void(); +} + +/////////////// FilterCallback Helper Methods /////////////////////// +void TunerHidlFilter::FilterCallback::getAidlFilterEvent( + const vector& events, + const vector& eventsExt, + vector& aidlEvents) { + if (events.empty() && !eventsExt.empty()) { + switch (eventsExt[0].getDiscriminator()) { + case HidlDemuxFilterEventExt::Event::hidl_discriminator::monitorEvent: { + getMonitorEvent(eventsExt, aidlEvents); + break; + } + case HidlDemuxFilterEventExt::Event::hidl_discriminator::startId: { + getRestartEvent(eventsExt, aidlEvents); + break; + } + default: { + break; + } + } + } + + if (!events.empty()) { + switch (events[0].getDiscriminator()) { + case HidlDemuxFilterEvent::Event::hidl_discriminator::media: { + getMediaEvent(events, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::section: { + getSectionEvent(events, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::pes: { + getPesEvent(events, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::tsRecord: { + getTsRecordEvent(events, eventsExt, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::mmtpRecord: { + getMmtpRecordEvent(events, eventsExt, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::download: { + getDownloadEvent(events, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::ipPayload: { + getIpPayloadEvent(events, aidlEvents); + break; + } + case HidlDemuxFilterEvent::Event::hidl_discriminator::temi: { + getTemiEvent(events, aidlEvents); + break; + } + default: { + break; + } + } + } +} + +void TunerHidlFilter::FilterCallback::getMediaEvent( + const vector& events, vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterMediaEvent& mediaEvent = events[i].media(); + DemuxFilterMediaEvent media; + + media.streamId = static_cast(mediaEvent.streamId); + media.isPtsPresent = mediaEvent.isPtsPresent; + media.pts = static_cast(mediaEvent.pts); + media.dataLength = static_cast(mediaEvent.dataLength); + media.offset = static_cast(mediaEvent.offset); + media.isSecureMemory = mediaEvent.isSecureMemory; + media.avDataId = static_cast(mediaEvent.avDataId); + media.mpuSequenceNumber = static_cast(mediaEvent.mpuSequenceNumber); + media.isPesPrivateData = mediaEvent.isPesPrivateData; + + if (mediaEvent.extraMetaData.getDiscriminator() == + HidlDemuxFilterMediaEvent::ExtraMetaData::hidl_discriminator::audio) { + AudioExtraMetaData audio; + audio.adFade = static_cast(mediaEvent.extraMetaData.audio().adFade); + audio.adPan = static_cast(mediaEvent.extraMetaData.audio().adPan); + audio.versionTextTag = + static_cast(mediaEvent.extraMetaData.audio().versionTextTag); + audio.adGainCenter = static_cast(mediaEvent.extraMetaData.audio().adGainCenter); + audio.adGainFront = static_cast(mediaEvent.extraMetaData.audio().adGainFront); + audio.adGainSurround = + static_cast(mediaEvent.extraMetaData.audio().adGainSurround); + media.extraMetaData.set(audio); + } else { + media.extraMetaData.set(true); + } + + if (mediaEvent.avMemory.getNativeHandle() != nullptr) { + media.avMemory = dupToAidl(mediaEvent.avMemory.getNativeHandle()); + } + + DemuxFilterEvent filterEvent; + filterEvent.set(move(media)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getSectionEvent( + const vector& events, vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterSectionEvent& sectionEvent = events[i].section(); + DemuxFilterSectionEvent section; + + section.tableId = static_cast(sectionEvent.tableId); + section.version = static_cast(sectionEvent.version); + section.sectionNum = static_cast(sectionEvent.sectionNum); + section.dataLength = static_cast(sectionEvent.dataLength); + + DemuxFilterEvent filterEvent; + filterEvent.set(move(section)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getPesEvent(const vector& events, + vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterPesEvent& pesEvent = events[i].pes(); + DemuxFilterPesEvent pes; + + pes.streamId = static_cast(pesEvent.streamId); + pes.dataLength = static_cast(pesEvent.dataLength); + pes.mpuSequenceNumber = static_cast(pesEvent.mpuSequenceNumber); + + DemuxFilterEvent filterEvent; + filterEvent.set(move(pes)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getTsRecordEvent( + const vector& events, + const vector& eventsExt, vector& res) { + for (int i = 0; i < events.size(); i++) { + DemuxFilterTsRecordEvent tsRecord; + const HidlDemuxFilterTsRecordEvent& tsRecordEvent = events[i].tsRecord(); + + DemuxFilterScIndexMask scIndexMask; + if (tsRecordEvent.scIndexMask.getDiscriminator() == + HidlDemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::sc) { + scIndexMask.set( + static_cast(tsRecordEvent.scIndexMask.sc())); + } else if (tsRecordEvent.scIndexMask.getDiscriminator() == + HidlDemuxFilterTsRecordEvent::ScIndexMask::hidl_discriminator::scHevc) { + scIndexMask.set( + static_cast(tsRecordEvent.scIndexMask.scHevc())); + } + + if (tsRecordEvent.pid.getDiscriminator() == HidlDemuxPid::hidl_discriminator::tPid) { + DemuxPid pid; + pid.set(static_cast(tsRecordEvent.pid.tPid())); + tsRecord.pid = pid; + } else { + DemuxPid pid; + pid.set(static_cast(Constant::INVALID_TS_PID)); + tsRecord.pid = pid; + } + + tsRecord.scIndexMask = scIndexMask; + tsRecord.tsIndexMask = static_cast(tsRecordEvent.tsIndexMask); + tsRecord.byteNumber = static_cast(tsRecordEvent.byteNumber); + + if (eventsExt.size() > i && + eventsExt[i].getDiscriminator() == + HidlDemuxFilterEventExt::Event::hidl_discriminator::tsRecord) { + tsRecord.pts = static_cast(eventsExt[i].tsRecord().pts); + tsRecord.firstMbInSlice = static_cast(eventsExt[i].tsRecord().firstMbInSlice); + } + + DemuxFilterEvent filterEvent; + filterEvent.set(move(tsRecord)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getMmtpRecordEvent( + const vector& events, + const vector& eventsExt, vector& res) { + for (int i = 0; i < events.size(); i++) { + DemuxFilterMmtpRecordEvent mmtpRecord; + const HidlDemuxFilterMmtpRecordEvent& mmtpRecordEvent = events[i].mmtpRecord(); + + mmtpRecord.scHevcIndexMask = static_cast(mmtpRecordEvent.scHevcIndexMask); + mmtpRecord.byteNumber = static_cast(mmtpRecordEvent.byteNumber); + + if (eventsExt.size() > i && + eventsExt[i].getDiscriminator() == + HidlDemuxFilterEventExt::Event::hidl_discriminator::mmtpRecord) { + mmtpRecord.pts = static_cast(eventsExt[i].mmtpRecord().pts); + mmtpRecord.mpuSequenceNumber = + static_cast(eventsExt[i].mmtpRecord().mpuSequenceNumber); + mmtpRecord.firstMbInSlice = + static_cast(eventsExt[i].mmtpRecord().firstMbInSlice); + mmtpRecord.tsIndexMask = static_cast(eventsExt[i].mmtpRecord().tsIndexMask); + } + + DemuxFilterEvent filterEvent; + filterEvent.set(move(mmtpRecord)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getDownloadEvent( + const vector& events, vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterDownloadEvent& downloadEvent = events[i].download(); + DemuxFilterDownloadEvent download; + + download.itemId = static_cast(downloadEvent.itemId); + download.itemFragmentIndex = static_cast(downloadEvent.itemFragmentIndex); + download.mpuSequenceNumber = static_cast(downloadEvent.mpuSequenceNumber); + download.lastItemFragmentIndex = static_cast(downloadEvent.lastItemFragmentIndex); + download.dataLength = static_cast(downloadEvent.dataLength); + + DemuxFilterEvent filterEvent; + filterEvent.set(move(download)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getIpPayloadEvent( + const vector& events, vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterIpPayloadEvent& ipPayloadEvent = events[i].ipPayload(); + DemuxFilterIpPayloadEvent ipPayload; + + ipPayload.dataLength = static_cast(ipPayloadEvent.dataLength); + + DemuxFilterEvent filterEvent; + filterEvent.set(move(ipPayload)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getTemiEvent( + const vector& events, vector& res) { + for (int i = 0; i < events.size(); i++) { + const HidlDemuxFilterTemiEvent& temiEvent = events[i].temi(); + DemuxFilterTemiEvent temi; + + temi.pts = static_cast(temiEvent.pts); + temi.descrTag = static_cast(temiEvent.descrTag); + vector descrData = temiEvent.descrData; + temi.descrData.resize(descrData.size()); + copy(descrData.begin(), descrData.end(), temi.descrData.begin()); + + DemuxFilterEvent filterEvent; + filterEvent.set(move(temi)); + res.push_back(move(filterEvent)); + } +} + +void TunerHidlFilter::FilterCallback::getMonitorEvent( + const vector& eventsExt, vector& res) { + HidlDemuxFilterMonitorEvent monitorEvent = eventsExt[0].monitorEvent(); + DemuxFilterMonitorEvent monitor; + + switch (monitorEvent.getDiscriminator()) { + case HidlDemuxFilterMonitorEvent::hidl_discriminator::scramblingStatus: { + monitor.set( + static_cast(monitorEvent.scramblingStatus())); + break; + } + case HidlDemuxFilterMonitorEvent::hidl_discriminator::cid: { + monitor.set(static_cast(monitorEvent.cid())); + break; + } + } + + DemuxFilterEvent filterEvent; + filterEvent.set(move(monitor)); + res.push_back(move(filterEvent)); +} + +void TunerHidlFilter::FilterCallback::getRestartEvent( + const vector& eventsExt, vector& res) { + DemuxFilterEvent filterEvent; + filterEvent.set(static_cast(eventsExt[0].startId())); + res.push_back(move(filterEvent)); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlFilter.h b/services/tuner/hidl/TunerHidlFilter.h new file mode 100644 index 0000000000..0111e0038d --- /dev/null +++ b/services/tuner/hidl/TunerHidlFilter.h @@ -0,0 +1,215 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLFILTER_H +#define ANDROID_MEDIA_TUNERHIDLFILTER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using ::aidl::android::hardware::common::NativeHandle; +using ::aidl::android::hardware::common::fmq::MQDescriptor; +using ::aidl::android::hardware::common::fmq::SynchronizedReadWrite; +using ::aidl::android::hardware::tv::tuner::AvStreamType; +using ::aidl::android::hardware::tv::tuner::DemuxFilterAvSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterDownloadSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterPesDataSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterRecordSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSectionSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterSettings; +using ::aidl::android::hardware::tv::tuner::DemuxFilterStatus; +using ::aidl::android::hardware::tv::tuner::DemuxFilterType; +using ::aidl::android::hardware::tv::tuner::DemuxIpAddressIpAddress; +using ::aidl::android::media::tv::tuner::BnTunerFilter; +using ::aidl::android::media::tv::tuner::ITunerFilterCallback; +using ::android::sp; +using ::android::hardware::hidl_array; +using ::android::hardware::MQDescriptorSync; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::std::shared_ptr; +using ::std::vector; + +using HidlAvStreamType = ::android::hardware::tv::tuner::V1_1::AvStreamType; +using HidlDemuxAlpFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxAlpFilterSettings; +using HidlDemuxFilterAvSettings = ::android::hardware::tv::tuner::V1_0::DemuxFilterAvSettings; +using HidlDemuxFilterDownloadEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadEvent; +using HidlDemuxFilterDownloadSettings = + ::android::hardware::tv::tuner::V1_0::DemuxFilterDownloadSettings; +using HidlDemuxFilterIpPayloadEvent = + ::android::hardware::tv::tuner::V1_0::DemuxFilterIpPayloadEvent; +using HidlDemuxFilterEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent; +using HidlDemuxFilterMediaEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterMediaEvent; +using HidlDemuxFilterMmtpRecordEvent = + ::android::hardware::tv::tuner::V1_0::DemuxFilterMmtpRecordEvent; +using HidlDemuxFilterPesDataSettings = + ::android::hardware::tv::tuner::V1_0::DemuxFilterPesDataSettings; +using HidlDemuxFilterPesEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterPesEvent; +using HidlDemuxFilterRecordSettings = + ::android::hardware::tv::tuner::V1_0::DemuxFilterRecordSettings; +using HidlDemuxFilterSectionEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionEvent; +using HidlDemuxFilterSectionSettings = + ::android::hardware::tv::tuner::V1_0::DemuxFilterSectionSettings; +using HidlDemuxFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxFilterSettings; +using HidlDemuxFilterStatus = ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; +using HidlDemuxFilterTemiEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterTemiEvent; +using HidlDemuxFilterTsRecordEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterTsRecordEvent; +using HidlDemuxIpFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxIpFilterSettings; +using HidlDemuxMmtpFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxMmtpFilterSettings; +using HidlDemuxTlvFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxTlvFilterSettings; +using HidlDemuxTsFilterSettings = ::android::hardware::tv::tuner::V1_0::DemuxTsFilterSettings; +using HidlDemuxPid = ::android::hardware::tv::tuner::V1_0::DemuxPid; +using HidlIFilter = ::android::hardware::tv::tuner::V1_0::IFilter; +using HidlDvStreamType = ::android::hardware::tv::tuner::V1_1::AvStreamType; +using HidlDemuxFilterEventExt = ::android::hardware::tv::tuner::V1_1::DemuxFilterEventExt; +using HidlDemuxFilterMonitorEvent = ::android::hardware::tv::tuner::V1_1::DemuxFilterMonitorEvent; +using HidlDemuxFilterTsRecordEventExt = + ::android::hardware::tv::tuner::V1_1::DemuxFilterTsRecordEventExt; +using HidlIFilterCallback = ::android::hardware::tv::tuner::V1_1::IFilterCallback; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +using MQDesc = MQDescriptorSync; +using AidlMQDesc = MQDescriptor; + +const static int IP_V4_LENGTH = 4; +const static int IP_V6_LENGTH = 16; + +class TunerHidlFilter : public BnTunerFilter { +public: + TunerHidlFilter(sp filter, DemuxFilterType type); + virtual ~TunerHidlFilter(); + + ::ndk::ScopedAStatus getId(int32_t* _aidl_return) override; + ::ndk::ScopedAStatus getId64Bit(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus getQueueDesc(AidlMQDesc* _aidl_return) override; + ::ndk::ScopedAStatus configure(const DemuxFilterSettings& in_settings) override; + ::ndk::ScopedAStatus configureMonitorEvent(int32_t in_monitorEventTypes) override; + ::ndk::ScopedAStatus configureIpFilterContextId(int32_t in_cid) override; + ::ndk::ScopedAStatus configureAvStreamType(const AvStreamType& in_avStreamType) override; + ::ndk::ScopedAStatus getAvSharedHandle(NativeHandle* out_avMemory, + int64_t* _aidl_return) override; + ::ndk::ScopedAStatus releaseAvHandle(const NativeHandle& in_handle, + int64_t in_avDataId) override; + ::ndk::ScopedAStatus setDataSource(const shared_ptr& in_filter) override; + ::ndk::ScopedAStatus start() override; + ::ndk::ScopedAStatus stop() override; + ::ndk::ScopedAStatus flush() override; + ::ndk::ScopedAStatus close() override; + + sp getHalFilter(); + + struct FilterCallback : public HidlIFilterCallback { + FilterCallback(const shared_ptr tunerFilterCallback) + : mTunerFilterCallback(tunerFilterCallback){}; + + virtual Return onFilterEvent(const HidlDemuxFilterEvent& filterEvent); + virtual Return onFilterEvent_1_1(const HidlDemuxFilterEvent& filterEvent, + const HidlDemuxFilterEventExt& filterEventExt); + virtual Return onFilterStatus(HidlDemuxFilterStatus status); + + void getAidlFilterEvent(const vector& events, + const vector& eventsExt, + vector& aidlEvents); + + void getMediaEvent(const vector& events, + vector& res); + void getSectionEvent(const vector& events, + vector& res); + void getPesEvent(const vector& events, + vector& res); + void getTsRecordEvent(const vector& events, + const vector& eventsExt, + vector& res); + void getMmtpRecordEvent(const vector& events, + const vector& eventsExt, + vector& res); + void getDownloadEvent(const vector& events, + vector& res); + void getIpPayloadEvent(const vector& events, + vector& res); + void getTemiEvent(const vector& events, + vector& res); + void getMonitorEvent(const vector& eventsExt, + vector& res); + void getRestartEvent(const vector& eventsExt, + vector& res); + + shared_ptr mTunerFilterCallback; + }; + +private: + bool isAudioFilter(); + bool isVideoFilter(); + + HidlDemuxFilterAvSettings getHidlAvSettings(const DemuxFilterAvSettings& settings); + HidlDemuxFilterSectionSettings getHidlSectionSettings( + const DemuxFilterSectionSettings& settings); + HidlDemuxFilterPesDataSettings getHidlPesDataSettings( + const DemuxFilterPesDataSettings& settings); + HidlDemuxFilterRecordSettings getHidlRecordSettings(const DemuxFilterRecordSettings& settings); + HidlDemuxFilterDownloadSettings getHidlDownloadSettings( + const DemuxFilterDownloadSettings& settings); + bool getHidlAvStreamType(const AvStreamType avStreamType, HidlAvStreamType& type); + void getHidlTsSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings); + void getHidlMmtpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings); + void getHidlIpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings); + void getHidlTlvSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings); + void getHidlAlpSettings(const DemuxFilterSettings& settings, + HidlDemuxFilterSettings& hidlSettings); + + hidl_array getIpV4Address(const DemuxIpAddressIpAddress& addr); + hidl_array getIpV6Address(const DemuxIpAddressIpAddress& addr); + + sp mFilter; + sp<::android::hardware::tv::tuner::V1_1::IFilter> mFilter_1_1; + int32_t mId; + int64_t mId64Bit; + DemuxFilterType mType; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLFILTER_H diff --git a/services/tuner/hidl/TunerHidlFrontend.cpp b/services/tuner/hidl/TunerHidlFrontend.cpp new file mode 100644 index 0000000000..bbfc90fb19 --- /dev/null +++ b/services/tuner/hidl/TunerHidlFrontend.cpp @@ -0,0 +1,1201 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//#define LOG_NDEBUG 0 +#define LOG_TAG "TunerHidlFrontend" + +#include "TunerHidlFrontend.h" + +#include + +#include "TunerHidlLnb.h" + +using ::aidl::android::hardware::tv::tuner::FrontendAnalogSettings; +using ::aidl::android::hardware::tv::tuner::FrontendAnalogSifStandard; +using ::aidl::android::hardware::tv::tuner::FrontendAnalogType; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Bandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3CodeRate; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Fec; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Modulation; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3PlpSettings; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Settings; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3TimeInterleaveMode; +using ::aidl::android::hardware::tv::tuner::FrontendAtscModulation; +using ::aidl::android::hardware::tv::tuner::FrontendAtscSettings; +using ::aidl::android::hardware::tv::tuner::FrontendBandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendCableTimeInterleaveMode; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbBandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbGuardInterval; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbModulation; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbSettings; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbTimeInterleaveMode; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbTransmissionMode; +using ::aidl::android::hardware::tv::tuner::FrontendDvbcAnnex; +using ::aidl::android::hardware::tv::tuner::FrontendDvbcBandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendDvbcModulation; +using ::aidl::android::hardware::tv::tuner::FrontendDvbcSettings; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsModulation; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsRolloff; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsSettings; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsStandard; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtBandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtConstellation; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtGuardInterval; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtHierarchy; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtSettings; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtStandard; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtTransmissionMode; +using ::aidl::android::hardware::tv::tuner::FrontendGuardInterval; +using ::aidl::android::hardware::tv::tuner::FrontendInnerFec; +using ::aidl::android::hardware::tv::tuner::FrontendInterleaveMode; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbs3Modulation; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbs3Rolloff; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbs3Settings; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbsModulation; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbsRolloff; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbsSettings; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtBandwidth; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtCoderate; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtGuardInterval; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtMode; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtModulation; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtSettings; +using ::aidl::android::hardware::tv::tuner::FrontendModulation; +using ::aidl::android::hardware::tv::tuner::FrontendModulationStatus; +using ::aidl::android::hardware::tv::tuner::FrontendRollOff; +using ::aidl::android::hardware::tv::tuner::FrontendScanAtsc3PlpInfo; +using ::aidl::android::hardware::tv::tuner::FrontendScanMessageStandard; +using ::aidl::android::hardware::tv::tuner::FrontendSpectralInversion; +using ::aidl::android::hardware::tv::tuner::FrontendStatusAtsc3PlpInfo; +using ::aidl::android::hardware::tv::tuner::FrontendTransmissionMode; +using ::aidl::android::hardware::tv::tuner::Result; + +using HidlFrontendStatusAtsc3PlpInfo = + ::aidl::android::hardware::tv::tuner::FrontendStatusAtsc3PlpInfo; +using HidlFrontendAnalogSifStandard = + ::android::hardware::tv::tuner::V1_0::FrontendAnalogSifStandard; +using HidlFrontendAnalogType = ::android::hardware::tv::tuner::V1_0::FrontendAnalogType; +using HidlFrontendAtscModulation = ::android::hardware::tv::tuner::V1_0::FrontendAtscModulation; +using HidlFrontendAtsc3Bandwidth = ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Bandwidth; +using HidlFrontendAtsc3CodeRate = ::android::hardware::tv::tuner::V1_0::FrontendAtsc3CodeRate; +using HidlFrontendAtsc3DemodOutputFormat = + ::android::hardware::tv::tuner::V1_0::FrontendAtsc3DemodOutputFormat; +using HidlFrontendAtsc3Fec = ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Fec; +using HidlFrontendAtsc3Modulation = ::android::hardware::tv::tuner::V1_0::FrontendAtsc3Modulation; +using HidlFrontendAtsc3TimeInterleaveMode = + ::android::hardware::tv::tuner::V1_0::FrontendAtsc3TimeInterleaveMode; +using HidlFrontendDvbcAnnex = ::android::hardware::tv::tuner::V1_0::FrontendDvbcAnnex; +using HidlFrontendDvbcModulation = ::android::hardware::tv::tuner::V1_0::FrontendDvbcModulation; +using HidlFrontendDvbcOuterFec = ::android::hardware::tv::tuner::V1_0::FrontendDvbcOuterFec; +using HidlFrontendDvbcSpectralInversion = + ::android::hardware::tv::tuner::V1_0::FrontendDvbcSpectralInversion; +using HidlFrontendDvbsModulation = ::android::hardware::tv::tuner::V1_0::FrontendDvbsModulation; +using HidlFrontendDvbsPilot = ::android::hardware::tv::tuner::V1_0::FrontendDvbsPilot; +using HidlFrontendDvbsRolloff = ::android::hardware::tv::tuner::V1_0::FrontendDvbsRolloff; +using HidlFrontendDvbsSettings = ::android::hardware::tv::tuner::V1_0::FrontendDvbsSettings; +using HidlFrontendDvbsStandard = ::android::hardware::tv::tuner::V1_0::FrontendDvbsStandard; +using HidlFrontendDvbsVcmMode = ::android::hardware::tv::tuner::V1_0::FrontendDvbsVcmMode; +using HidlFrontendDvbtBandwidth = ::android::hardware::tv::tuner::V1_0::FrontendDvbtBandwidth; +using HidlFrontendDvbtCoderate = ::android::hardware::tv::tuner::V1_0::FrontendDvbtCoderate; +using HidlFrontendDvbtConstellation = + ::android::hardware::tv::tuner::V1_0::FrontendDvbtConstellation; +using HidlFrontendDvbtGuardInterval = + ::android::hardware::tv::tuner::V1_0::FrontendDvbtGuardInterval; +using HidlFrontendDvbtHierarchy = ::android::hardware::tv::tuner::V1_0::FrontendDvbtHierarchy; +using HidlFrontendDvbtPlpMode = ::android::hardware::tv::tuner::V1_0::FrontendDvbtPlpMode; +using HidlFrontendDvbtSettings = ::android::hardware::tv::tuner::V1_0::FrontendDvbtSettings; +using HidlFrontendDvbtStandard = ::android::hardware::tv::tuner::V1_0::FrontendDvbtStandard; +using HidlFrontendDvbtTransmissionMode = + ::android::hardware::tv::tuner::V1_0::FrontendDvbtTransmissionMode; +using HidlFrontendInnerFec = ::android::hardware::tv::tuner::V1_0::FrontendInnerFec; +using HidlFrontendIsdbs3Coderate = ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Coderate; +using HidlFrontendIsdbs3Modulation = ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Modulation; +using HidlFrontendIsdbs3Rolloff = ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Rolloff; +using HidlFrontendIsdbs3Settings = ::android::hardware::tv::tuner::V1_0::FrontendIsdbs3Settings; +using HidlFrontendIsdbsCoderate = ::android::hardware::tv::tuner::V1_0::FrontendIsdbsCoderate; +using HidlFrontendIsdbsModulation = ::android::hardware::tv::tuner::V1_0::FrontendIsdbsModulation; +using HidlFrontendIsdbsRolloff = ::android::hardware::tv::tuner::V1_0::FrontendIsdbsRolloff; +using HidlFrontendIsdbsSettings = ::android::hardware::tv::tuner::V1_0::FrontendIsdbsSettings; +using HidlFrontendIsdbsStreamIdType = + ::android::hardware::tv::tuner::V1_0::FrontendIsdbsStreamIdType; +using HidlFrontendIsdbtBandwidth = ::android::hardware::tv::tuner::V1_0::FrontendIsdbtBandwidth; +using HidlFrontendIsdbtCoderate = ::android::hardware::tv::tuner::V1_0::FrontendIsdbtCoderate; +using HidlFrontendIsdbtGuardInterval = + ::android::hardware::tv::tuner::V1_0::FrontendIsdbtGuardInterval; +using HidlFrontendIsdbtMode = ::android::hardware::tv::tuner::V1_0::FrontendIsdbtMode; +using HidlFrontendIsdbtModulation = ::android::hardware::tv::tuner::V1_0::FrontendIsdbtModulation; +using HidlFrontendIsdbtSettings = ::android::hardware::tv::tuner::V1_0::FrontendIsdbtSettings; +using HidlFrontendModulationStatus = ::android::hardware::tv::tuner::V1_0::FrontendModulationStatus; +using HidlFrontendScanAtsc3PlpInfo = ::android::hardware::tv::tuner::V1_0::FrontendScanAtsc3PlpInfo; +using HidlFrontendScanType = ::android::hardware::tv::tuner::V1_0::FrontendScanType; +using HidlFrontendStatusType = ::android::hardware::tv::tuner::V1_0::FrontendStatusType; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; +using HidlFrontendAnalogAftFlag = ::android::hardware::tv::tuner::V1_1::FrontendAnalogAftFlag; +using HidlFrontendBandwidth = ::android::hardware::tv::tuner::V1_1::FrontendBandwidth; +using HidlFrontendCableTimeInterleaveMode = + ::android::hardware::tv::tuner::V1_1::FrontendCableTimeInterleaveMode; +using HidlFrontendDvbcBandwidth = ::android::hardware::tv::tuner::V1_1::FrontendDvbcBandwidth; +using HidlFrontendDtmbBandwidth = ::android::hardware::tv::tuner::V1_1::FrontendDtmbBandwidth; +using HidlFrontendDtmbCodeRate = ::android::hardware::tv::tuner::V1_1::FrontendDtmbCodeRate; +using HidlFrontendDtmbGuardInterval = + ::android::hardware::tv::tuner::V1_1::FrontendDtmbGuardInterval; +using HidlFrontendDtmbModulation = ::android::hardware::tv::tuner::V1_1::FrontendDtmbModulation; +using HidlFrontendDtmbTimeInterleaveMode = + ::android::hardware::tv::tuner::V1_1::FrontendDtmbTimeInterleaveMode; +using HidlFrontendDtmbTransmissionMode = + ::android::hardware::tv::tuner::V1_1::FrontendDtmbTransmissionMode; +using HidlFrontendDvbsScanType = ::android::hardware::tv::tuner::V1_1::FrontendDvbsScanType; +using HidlFrontendGuardInterval = ::android::hardware::tv::tuner::V1_1::FrontendGuardInterval; +using HidlFrontendInterleaveMode = ::android::hardware::tv::tuner::V1_1::FrontendInterleaveMode; +using HidlFrontendModulation = ::android::hardware::tv::tuner::V1_1::FrontendModulation; +using HidlFrontendRollOff = ::android::hardware::tv::tuner::V1_1::FrontendRollOff; +using HidlFrontendTransmissionMode = ::android::hardware::tv::tuner::V1_1::FrontendTransmissionMode; +using HidlFrontendSpectralInversion = + ::android::hardware::tv::tuner::V1_1::FrontendSpectralInversion; +using HidlFrontendStatusTypeExt1_1 = ::android::hardware::tv::tuner::V1_1::FrontendStatusTypeExt1_1; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlFrontend::TunerHidlFrontend(sp frontend, int id) { + mFrontend = frontend; + mFrontend_1_1 = ::android::hardware::tv::tuner::V1_1::IFrontend::castFrom(mFrontend); + mId = id; +} + +TunerHidlFrontend::~TunerHidlFrontend() { + mFrontend = nullptr; + mFrontend_1_1 = nullptr; + mId = -1; +} + +::ndk::ScopedAStatus TunerHidlFrontend::setCallback( + const shared_ptr& tunerFrontendCallback) { + if (mFrontend == nullptr) { + ALOGE("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (tunerFrontendCallback == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + sp frontendCallback = new FrontendCallback(tunerFrontendCallback); + HidlResult status = mFrontend->setCallback(frontendCallback); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::tune(const FrontendSettings& settings) { + if (mFrontend == nullptr) { + ALOGE("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + HidlFrontendSettings frontendSettings; + HidlFrontendSettingsExt1_1 frontendSettingsExt; + getHidlFrontendSettings(settings, frontendSettings, frontendSettingsExt); + if (mFrontend_1_1 != nullptr) { + status = mFrontend_1_1->tune_1_1(frontendSettings, frontendSettingsExt); + } else { + status = mFrontend->tune(frontendSettings); + } + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::stopTune() { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mFrontend->stopTune(); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::scan(const FrontendSettings& settings, + FrontendScanType frontendScanType) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + HidlFrontendSettings frontendSettings; + HidlFrontendSettingsExt1_1 frontendSettingsExt; + getHidlFrontendSettings(settings, frontendSettings, frontendSettingsExt); + if (mFrontend_1_1 != nullptr) { + status = mFrontend_1_1->scan_1_1(frontendSettings, + static_cast(frontendScanType), + frontendSettingsExt); + } else { + status = mFrontend->scan(frontendSettings, + static_cast(frontendScanType)); + } + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::stopScan() { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mFrontend->stopScan(); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::setLnb(const shared_ptr& lnb) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (lnb == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + HidlResult status = mFrontend->setLnb(static_cast(lnb.get())->getId()); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::setLna(bool bEnable) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mFrontend->setLna(bEnable); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::linkCiCamToFrontend(int32_t ciCamId, + int32_t* _aidl_return) { + if (mFrontend_1_1 == nullptr) { + ALOGD("IFrontend_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + int ltsId; + HidlResult status; + mFrontend_1_1->linkCiCam(static_cast(ciCamId), [&](HidlResult r, uint32_t id) { + status = r; + ltsId = id; + }); + + if (status == HidlResult::SUCCESS) { + *_aidl_return = ltsId; + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::unlinkCiCamToFrontend(int32_t ciCamId) { + if (mFrontend_1_1 == nullptr) { + ALOGD("IFrontend_1_1 is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mFrontend_1_1->unlinkCiCam(ciCamId); + if (status == HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::ok(); + } + + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); +} + +::ndk::ScopedAStatus TunerHidlFrontend::close() { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mFrontend->close(); + mFrontend = nullptr; + mFrontend_1_1 = nullptr; + + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFrontend::getStatus(const vector& in_statusTypes, + vector* _aidl_return) { + if (mFrontend == nullptr) { + ALOGD("IFrontend is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + vector status; + vector statusExt; + vector types; + vector typesExt; + for (auto s : in_statusTypes) { + if (static_cast(s) <= + static_cast(HidlFrontendStatusType::ATSC3_PLP_INFO)) { + types.push_back(static_cast(s)); + } else { + typesExt.push_back(static_cast(s)); + } + } + + mFrontend->getStatus(types, [&](HidlResult r, const hidl_vec& ss) { + res = r; + for (auto s : ss) { + status.push_back(s); + } + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + if (mFrontend_1_1 != nullptr) { + mFrontend_1_1->getStatusExt1_1( + typesExt, [&](HidlResult r, const hidl_vec& ss) { + res = r; + for (auto s : ss) { + statusExt.push_back(s); + } + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + } + + getAidlFrontendStatus(status, statusExt, *_aidl_return); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlFrontend::getFrontendId(int32_t* _aidl_return) { + *_aidl_return = mId; + return ::ndk::ScopedAStatus::ok(); +} + +/////////////// FrontendCallback /////////////////////// +Return TunerHidlFrontend::FrontendCallback::onEvent(HidlFrontendEventType frontendEventType) { + ALOGV("FrontendCallback::onEvent, type=%d", frontendEventType); + mTunerFrontendCallback->onEvent(static_cast(frontendEventType)); + return Void(); +} + +Return TunerHidlFrontend::FrontendCallback::onScanMessage( + HidlFrontendScanMessageType type, const HidlFrontendScanMessage& message) { + ALOGV("FrontendCallback::onScanMessage, type=%d", type); + FrontendScanMessage scanMessage; + switch (type) { + case HidlFrontendScanMessageType::LOCKED: { + scanMessage.set(message.isLocked()); + break; + } + case HidlFrontendScanMessageType::END: { + scanMessage.set(message.isEnd()); + break; + } + case HidlFrontendScanMessageType::PROGRESS_PERCENT: { + scanMessage.set(message.progressPercent()); + break; + } + case HidlFrontendScanMessageType::FREQUENCY: { + const vector& f = message.frequencies(); + vector lf(begin(f), end(f)); + scanMessage.set(lf); + break; + } + case HidlFrontendScanMessageType::SYMBOL_RATE: { + const vector& s = message.symbolRates(); + vector symbolRates(begin(s), end(s)); + scanMessage.set(symbolRates); + break; + } + case HidlFrontendScanMessageType::HIERARCHY: { + scanMessage.set( + static_cast(message.hierarchy())); + break; + } + case HidlFrontendScanMessageType::ANALOG_TYPE: { + scanMessage.set( + static_cast(message.analogType())); + break; + } + case HidlFrontendScanMessageType::PLP_IDS: { + const vector& p = message.plpIds(); + vector plpIds(begin(p), end(p)); + scanMessage.set(plpIds); + break; + } + case HidlFrontendScanMessageType::GROUP_IDS: { + const vector& g = message.groupIds(); + vector groupIds(begin(g), end(g)); + scanMessage.set(groupIds); + break; + } + case HidlFrontendScanMessageType::INPUT_STREAM_IDS: { + const vector& i = message.inputStreamIds(); + vector streamIds(begin(i), end(i)); + scanMessage.set(streamIds); + break; + } + case HidlFrontendScanMessageType::STANDARD: { + const HidlFrontendScanMessage::Standard& std = message.std(); + FrontendScanMessageStandard standard; + if (std.getDiscriminator() == HidlFrontendScanMessage::Standard::hidl_discriminator::sStd) { + standard.set( + static_cast(std.sStd())); + } else if (std.getDiscriminator() == + HidlFrontendScanMessage::Standard::hidl_discriminator::tStd) { + standard.set( + static_cast(std.tStd())); + } else if (std.getDiscriminator() == + HidlFrontendScanMessage::Standard::hidl_discriminator::sifStd) { + standard.set( + static_cast(std.sifStd())); + } + scanMessage.set(standard); + break; + } + case HidlFrontendScanMessageType::ATSC3_PLP_INFO: { + const vector& plpInfos = message.atsc3PlpInfos(); + vector tunerPlpInfos; + for (int i = 0; i < plpInfos.size(); i++) { + FrontendScanAtsc3PlpInfo plpInfo{ + .plpId = static_cast(plpInfos[i].plpId), + .bLlsFlag = plpInfos[i].bLlsFlag, + }; + tunerPlpInfos.push_back(plpInfo); + } + scanMessage.set(tunerPlpInfos); + break; + } + default: + break; + } + mTunerFrontendCallback->onScanMessage(static_cast(type), scanMessage); + return Void(); +} + +Return TunerHidlFrontend::FrontendCallback::onScanMessageExt1_1( + HidlFrontendScanMessageTypeExt1_1 type, const HidlFrontendScanMessageExt1_1& message) { + ALOGV("onScanMessageExt1_1::onScanMessage, type=%d", type); + FrontendScanMessage scanMessage; + switch (type) { + case HidlFrontendScanMessageTypeExt1_1::MODULATION: { + HidlFrontendModulation m = message.modulation(); + FrontendModulation modulation; + switch (m.getDiscriminator()) { + case HidlFrontendModulation::hidl_discriminator::dvbc: { + modulation.set(static_cast(m.dvbc())); + break; + } + case HidlFrontendModulation::hidl_discriminator::dvbt: { + modulation.set( + static_cast(m.dvbt())); + break; + } + case HidlFrontendModulation::hidl_discriminator::dvbs: { + modulation.set(static_cast(m.dvbs())); + break; + } + case HidlFrontendModulation::hidl_discriminator::isdbs: { + modulation.set( + static_cast(m.isdbs())); + break; + } + case HidlFrontendModulation::hidl_discriminator::isdbs3: { + modulation.set( + static_cast(m.isdbs3())); + break; + } + case HidlFrontendModulation::hidl_discriminator::isdbt: { + modulation.set( + static_cast(m.isdbt())); + break; + } + case HidlFrontendModulation::hidl_discriminator::atsc: { + modulation.set(static_cast(m.atsc())); + break; + } + case HidlFrontendModulation::hidl_discriminator::atsc3: { + modulation.set( + static_cast(m.atsc3())); + break; + } + case HidlFrontendModulation::hidl_discriminator::dtmb: { + modulation.set(static_cast(m.dtmb())); + break; + } + } + scanMessage.set(modulation); + break; + } + case HidlFrontendScanMessageTypeExt1_1::DVBC_ANNEX: { + scanMessage.set( + static_cast(message.annex())); + break; + } + case HidlFrontendScanMessageTypeExt1_1::HIGH_PRIORITY: { + scanMessage.set(message.isHighPriority()); + break; + } + default: { + break; + } + } + mTunerFrontendCallback->onScanMessage(static_cast(type), scanMessage); + return Void(); +} + +/////////////// TunerHidlFrontend Helper Methods /////////////////////// +void TunerHidlFrontend::getAidlFrontendStatus(const vector& hidlStatus, + const vector& hidlStatusExt, + vector& aidlStatus) { + for (HidlFrontendStatus s : hidlStatus) { + FrontendStatus status; + switch (s.getDiscriminator()) { + case HidlFrontendStatus::hidl_discriminator::isDemodLocked: { + status.set(s.isDemodLocked()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::snr: { + status.set((int)s.snr()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::ber: { + status.set((int)s.ber()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::per: { + status.set((int)s.per()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::preBer: { + status.set((int)s.preBer()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::signalQuality: { + status.set((int)s.signalQuality()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::signalStrength: { + status.set((int)s.signalStrength()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::symbolRate: { + status.set((int)s.symbolRate()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::innerFec: { + status.set(static_cast(s.innerFec())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::modulation: { + FrontendModulationStatus modulationStatus; + switch (s.modulation().getDiscriminator()) { + case HidlFrontendModulationStatus::hidl_discriminator::dvbc: + modulationStatus.set( + static_cast(s.modulation().dvbc())); + break; + case HidlFrontendModulationStatus::hidl_discriminator::dvbs: + modulationStatus.set( + static_cast(s.modulation().dvbs())); + break; + case HidlFrontendModulationStatus::hidl_discriminator::isdbs: + modulationStatus.set( + static_cast(s.modulation().isdbs())); + break; + case HidlFrontendModulationStatus::hidl_discriminator::isdbs3: + modulationStatus.set( + static_cast(s.modulation().isdbs3())); + break; + case HidlFrontendModulationStatus::hidl_discriminator::isdbt: + modulationStatus.set( + static_cast(s.modulation().isdbt())); + break; + } + status.set(modulationStatus); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::inversion: { + status.set( + static_cast(s.inversion())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::lnbVoltage: { + status.set(static_cast(s.lnbVoltage())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::plpId: { + status.set((int32_t)s.plpId()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::isEWBS: { + status.set(s.isEWBS()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::agc: { + status.set((int32_t)s.agc()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::isLnaOn: { + status.set(s.isLnaOn()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::isLayerError: { + vector e(s.isLayerError().begin(), s.isLayerError().end()); + status.set(e); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::mer: { + status.set(static_cast(s.mer())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::freqOffset: { + status.set(static_cast(s.freqOffset())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::hierarchy: { + status.set( + static_cast(s.hierarchy())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::isRfLocked: { + status.set(s.isRfLocked()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatus::hidl_discriminator::plpInfo: { + vector info; + for (auto i : s.plpInfo()) { + info.push_back({ + .plpId = static_cast(i.plpId), + .isLocked = i.isLocked, + .uec = static_cast(i.uec), + }); + } + status.set(info); + aidlStatus.push_back(status); + break; + } + } + } + + for (HidlFrontendStatusExt1_1 s : hidlStatusExt) { + FrontendStatus status; + switch (s.getDiscriminator()) { + case HidlFrontendStatusExt1_1::hidl_discriminator::modulations: { + vector aidlMod; + for (auto m : s.modulations()) { + switch (m.getDiscriminator()) { + case HidlFrontendModulation::hidl_discriminator::dvbc: + aidlMod.push_back(static_cast(m.dvbc())); + break; + case HidlFrontendModulation::hidl_discriminator::dvbs: + aidlMod.push_back(static_cast(m.dvbs())); + break; + case HidlFrontendModulation::hidl_discriminator::dvbt: + aidlMod.push_back(static_cast(m.dvbt())); + break; + case HidlFrontendModulation::hidl_discriminator::isdbs: + aidlMod.push_back(static_cast(m.isdbs())); + break; + case HidlFrontendModulation::hidl_discriminator::isdbs3: + aidlMod.push_back(static_cast(m.isdbs3())); + break; + case HidlFrontendModulation::hidl_discriminator::isdbt: + aidlMod.push_back(static_cast(m.isdbt())); + break; + case HidlFrontendModulation::hidl_discriminator::atsc: + aidlMod.push_back(static_cast(m.atsc())); + break; + case HidlFrontendModulation::hidl_discriminator::atsc3: + aidlMod.push_back(static_cast(m.atsc3())); + break; + case HidlFrontendModulation::hidl_discriminator::dtmb: + aidlMod.push_back(static_cast(m.dtmb())); + break; + } + } + status.set(aidlMod); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::bers: { + vector b(s.bers().begin(), s.bers().end()); + status.set(b); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::codeRates: { + vector codeRates; + for (auto c : s.codeRates()) { + codeRates.push_back(static_cast(c)); + } + status.set(codeRates); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::bandwidth: { + FrontendBandwidth bandwidth; + switch (s.bandwidth().getDiscriminator()) { + case HidlFrontendBandwidth::hidl_discriminator::atsc3: + bandwidth.set( + static_cast(s.bandwidth().atsc3())); + break; + case HidlFrontendBandwidth::hidl_discriminator::dvbc: + bandwidth.set( + static_cast(s.bandwidth().dvbc())); + break; + case HidlFrontendBandwidth::hidl_discriminator::dvbt: + bandwidth.set( + static_cast(s.bandwidth().dvbt())); + break; + case HidlFrontendBandwidth::hidl_discriminator::isdbt: + bandwidth.set( + static_cast(s.bandwidth().isdbt())); + break; + case HidlFrontendBandwidth::hidl_discriminator::dtmb: + bandwidth.set( + static_cast(s.bandwidth().dtmb())); + break; + } + status.set(bandwidth); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::interval: { + FrontendGuardInterval interval; + switch (s.interval().getDiscriminator()) { + case HidlFrontendGuardInterval::hidl_discriminator::dvbt: + interval.set( + static_cast(s.interval().dvbt())); + break; + case HidlFrontendGuardInterval::hidl_discriminator::isdbt: + interval.set( + static_cast(s.interval().isdbt())); + break; + case HidlFrontendGuardInterval::hidl_discriminator::dtmb: + interval.set( + static_cast(s.interval().dtmb())); + break; + } + status.set(interval); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::transmissionMode: { + FrontendTransmissionMode transmissionMode; + switch (s.transmissionMode().getDiscriminator()) { + case HidlFrontendTransmissionMode::hidl_discriminator::dvbt: + transmissionMode.set( + static_cast(s.transmissionMode().dvbt())); + break; + case HidlFrontendTransmissionMode::hidl_discriminator::isdbt: + transmissionMode.set( + static_cast(s.transmissionMode().isdbt())); + break; + case HidlFrontendTransmissionMode::hidl_discriminator::dtmb: + transmissionMode.set( + static_cast(s.transmissionMode().dtmb())); + break; + } + status.set(transmissionMode); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::uec: { + status.set(static_cast(s.uec())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::systemId: { + status.set(static_cast(s.systemId())); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::interleaving: { + vector aidlInter; + for (auto i : s.interleaving()) { + FrontendInterleaveMode leaveMode; + switch (i.getDiscriminator()) { + case HidlFrontendInterleaveMode::hidl_discriminator::atsc3: + leaveMode.set( + static_cast(i.atsc3())); + break; + case HidlFrontendInterleaveMode::hidl_discriminator::dvbc: + leaveMode.set( + static_cast(i.dvbc())); + break; + case HidlFrontendInterleaveMode::hidl_discriminator::dtmb: + leaveMode.set( + static_cast(i.dtmb())); + break; + } + aidlInter.push_back(leaveMode); + } + status.set(aidlInter); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::isdbtSegment: { + const vector& seg = s.isdbtSegment(); + vector i(seg.begin(), seg.end()); + status.set(i); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::tsDataRate: { + vector ts(s.tsDataRate().begin(), s.tsDataRate().end()); + status.set(ts); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::rollOff: { + FrontendRollOff rollOff; + switch (s.rollOff().getDiscriminator()) { + case HidlFrontendRollOff::hidl_discriminator::dvbs: + rollOff.set( + static_cast(s.rollOff().dvbs())); + break; + case HidlFrontendRollOff::hidl_discriminator::isdbs: + rollOff.set( + static_cast(s.rollOff().isdbs())); + break; + case HidlFrontendRollOff::hidl_discriminator::isdbs3: + rollOff.set( + static_cast(s.rollOff().isdbs3())); + break; + } + status.set(rollOff); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::isMiso: { + status.set(s.isMiso()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::isLinear: { + status.set(s.isLinear()); + aidlStatus.push_back(status); + break; + } + case HidlFrontendStatusExt1_1::hidl_discriminator::isShortFrames: { + status.set(s.isShortFrames()); + aidlStatus.push_back(status); + break; + } + } + } +} + +hidl_vec TunerHidlFrontend::getAtsc3PlpSettings( + const FrontendAtsc3Settings& settings) { + int len = settings.plpSettings.size(); + hidl_vec plps = hidl_vec(len); + // parse PLP settings + for (int i = 0; i < len; i++) { + uint8_t plpId = static_cast(settings.plpSettings[i].plpId); + HidlFrontendAtsc3Modulation modulation = + static_cast(settings.plpSettings[i].modulation); + HidlFrontendAtsc3TimeInterleaveMode interleaveMode = + static_cast( + settings.plpSettings[i].interleaveMode); + HidlFrontendAtsc3CodeRate codeRate = + static_cast(settings.plpSettings[i].codeRate); + HidlFrontendAtsc3Fec fec = static_cast(settings.plpSettings[i].fec); + HidlFrontendAtsc3PlpSettings frontendAtsc3PlpSettings{ + .plpId = plpId, + .modulation = modulation, + .interleaveMode = interleaveMode, + .codeRate = codeRate, + .fec = fec, + }; + plps[i] = frontendAtsc3PlpSettings; + } + return plps; +} + +HidlFrontendDvbsCodeRate TunerHidlFrontend::getDvbsCodeRate(const FrontendDvbsCodeRate& codeRate) { + HidlFrontendInnerFec innerFec = static_cast(codeRate.fec); + bool isLinear = codeRate.isLinear; + bool isShortFrames = codeRate.isShortFrames; + uint32_t bitsPer1000Symbol = static_cast(codeRate.bitsPer1000Symbol); + HidlFrontendDvbsCodeRate coderate{ + .fec = innerFec, + .isLinear = isLinear, + .isShortFrames = isShortFrames, + .bitsPer1000Symbol = bitsPer1000Symbol, + }; + return coderate; +} + +void TunerHidlFrontend::getHidlFrontendSettings(const FrontendSettings& aidlSettings, + HidlFrontendSettings& settings, + HidlFrontendSettingsExt1_1& settingsExt) { + switch (aidlSettings.getTag()) { + case FrontendSettings::analog: { + const FrontendAnalogSettings& analog = aidlSettings.get(); + settings.analog({ + .frequency = static_cast(analog.frequency), + .type = static_cast(analog.type), + .sifStandard = static_cast(analog.sifStandard), + }); + settingsExt.settingExt.analog({ + .aftFlag = static_cast(analog.aftFlag), + }); + settingsExt.endFrequency = static_cast(analog.endFrequency); + settingsExt.inversion = static_cast(analog.inversion); + break; + } + case FrontendSettings::atsc: { + const FrontendAtscSettings& atsc = aidlSettings.get(); + settings.atsc({ + .frequency = static_cast(atsc.frequency), + .modulation = static_cast(atsc.modulation), + }); + settingsExt.endFrequency = static_cast(atsc.endFrequency); + settingsExt.inversion = static_cast(atsc.inversion); + settingsExt.settingExt.noinit(); + break; + } + case FrontendSettings::atsc3: { + const FrontendAtsc3Settings& atsc3 = aidlSettings.get(); + settings.atsc3({ + .frequency = static_cast(atsc3.frequency), + .bandwidth = static_cast(atsc3.bandwidth), + .demodOutputFormat = + static_cast(atsc3.demodOutputFormat), + .plpSettings = getAtsc3PlpSettings(atsc3), + }); + settingsExt.endFrequency = static_cast(atsc3.endFrequency); + settingsExt.inversion = static_cast(atsc3.inversion); + settingsExt.settingExt.noinit(); + break; + } + case FrontendSettings::dvbc: { + const FrontendDvbcSettings& dvbc = aidlSettings.get(); + settings.dvbc({ + .frequency = static_cast(dvbc.frequency), + .modulation = static_cast(dvbc.modulation), + .fec = static_cast(dvbc.fec), + .symbolRate = static_cast(dvbc.symbolRate), + .outerFec = static_cast(dvbc.outerFec), + .annex = static_cast(dvbc.annex), + .spectralInversion = static_cast(dvbc.inversion), + }); + settingsExt.settingExt.dvbc({ + .interleaveMode = + static_cast(dvbc.interleaveMode), + .bandwidth = static_cast(dvbc.bandwidth), + }); + settingsExt.endFrequency = static_cast(dvbc.endFrequency); + settingsExt.inversion = static_cast(dvbc.inversion); + break; + } + case FrontendSettings::dvbs: { + const FrontendDvbsSettings& dvbs = aidlSettings.get(); + settings.dvbs({ + .frequency = static_cast(dvbs.frequency), + .modulation = static_cast(dvbs.modulation), + .coderate = getDvbsCodeRate(dvbs.coderate), + .symbolRate = static_cast(dvbs.symbolRate), + .rolloff = static_cast(dvbs.rolloff), + .pilot = static_cast(dvbs.pilot), + .inputStreamId = static_cast(dvbs.inputStreamId), + .standard = static_cast(dvbs.standard), + .vcmMode = static_cast(dvbs.vcmMode), + }); + settingsExt.settingExt.dvbs({ + .scanType = static_cast(dvbs.scanType), + .isDiseqcRxMessage = dvbs.isDiseqcRxMessage, + }); + settingsExt.endFrequency = static_cast(dvbs.endFrequency); + settingsExt.inversion = static_cast(dvbs.inversion); + break; + } + case FrontendSettings::dvbt: { + const FrontendDvbtSettings& dvbt = aidlSettings.get(); + settings.dvbt({ + .frequency = static_cast(dvbt.frequency), + .transmissionMode = + static_cast(dvbt.transmissionMode), + .bandwidth = static_cast(dvbt.bandwidth), + .constellation = static_cast(dvbt.constellation), + .hierarchy = static_cast(dvbt.hierarchy), + .hpCoderate = static_cast(dvbt.hpCoderate), + .lpCoderate = static_cast(dvbt.lpCoderate), + .guardInterval = static_cast(dvbt.guardInterval), + .isHighPriority = dvbt.isHighPriority, + .standard = static_cast(dvbt.standard), + .isMiso = dvbt.isMiso, + .plpMode = static_cast(dvbt.plpMode), + .plpId = static_cast(dvbt.plpId), + .plpGroupId = static_cast(dvbt.plpGroupId), + }); + settingsExt.settingExt.dvbt({ + .constellation = static_cast< + ::android::hardware::tv::tuner::V1_1::FrontendDvbtConstellation>( + dvbt.constellation), + .transmissionMode = static_cast< + ::android::hardware::tv::tuner::V1_1::FrontendDvbtTransmissionMode>( + dvbt.transmissionMode), + }); + settingsExt.endFrequency = static_cast(dvbt.endFrequency); + settingsExt.inversion = static_cast(dvbt.inversion); + break; + } + case FrontendSettings::isdbs: { + const FrontendIsdbsSettings& isdbs = aidlSettings.get(); + settings.isdbs({ + .frequency = static_cast(isdbs.frequency), + .streamId = static_cast(isdbs.streamId), + .streamIdType = static_cast(isdbs.streamIdType), + .modulation = static_cast(isdbs.modulation), + .coderate = static_cast(isdbs.coderate), + .symbolRate = static_cast(isdbs.symbolRate), + .rolloff = static_cast(isdbs.rolloff), + }); + settingsExt.endFrequency = static_cast(isdbs.endFrequency); + settingsExt.settingExt.noinit(); + break; + } + case FrontendSettings::isdbs3: { + const FrontendIsdbs3Settings& isdbs3 = aidlSettings.get(); + settings.isdbs3({ + .frequency = static_cast(isdbs3.frequency), + .streamId = static_cast(isdbs3.streamId), + .streamIdType = static_cast(isdbs3.streamIdType), + .modulation = static_cast(isdbs3.modulation), + .coderate = static_cast(isdbs3.coderate), + .symbolRate = static_cast(isdbs3.symbolRate), + .rolloff = static_cast(isdbs3.rolloff), + }); + settingsExt.endFrequency = static_cast(isdbs3.endFrequency); + settingsExt.settingExt.noinit(); + break; + } + case FrontendSettings::isdbt: { + const FrontendIsdbtSettings& isdbt = aidlSettings.get(); + settings.isdbt({ + .frequency = static_cast(isdbt.frequency), + .modulation = static_cast(isdbt.modulation), + .bandwidth = static_cast(isdbt.bandwidth), + .mode = static_cast(isdbt.mode), + .coderate = static_cast(isdbt.coderate), + .guardInterval = static_cast(isdbt.guardInterval), + .serviceAreaId = static_cast(isdbt.serviceAreaId), + }); + settingsExt.endFrequency = static_cast(isdbt.endFrequency); + settingsExt.inversion = static_cast(isdbt.inversion); + settingsExt.settingExt.noinit(); + break; + } + case FrontendSettings::dtmb: { + const FrontendDtmbSettings& dtmb = aidlSettings.get(); + settingsExt.settingExt.dtmb({ + .frequency = static_cast(dtmb.frequency), + .transmissionMode = + static_cast(dtmb.transmissionMode), + .bandwidth = static_cast(dtmb.bandwidth), + .modulation = static_cast(dtmb.modulation), + .codeRate = static_cast(dtmb.codeRate), + .guardInterval = static_cast(dtmb.guardInterval), + .interleaveMode = + static_cast(dtmb.interleaveMode), + }); + settingsExt.endFrequency = static_cast(dtmb.endFrequency); + settingsExt.inversion = static_cast(dtmb.inversion); + break; + } + default: + break; + } +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlFrontend.h b/services/tuner/hidl/TunerHidlFrontend.h new file mode 100644 index 0000000000..0abd80b2f3 --- /dev/null +++ b/services/tuner/hidl/TunerHidlFrontend.h @@ -0,0 +1,123 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLFRONTEND_H +#define ANDROID_MEDIA_TUNERHIDLFRONTEND_H + +#include +#include +#include +#include +#include +#include +#include + +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Settings; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsCodeRate; +using ::aidl::android::hardware::tv::tuner::FrontendEventType; +using ::aidl::android::hardware::tv::tuner::FrontendScanMessage; +using ::aidl::android::hardware::tv::tuner::FrontendScanMessageType; +using ::aidl::android::hardware::tv::tuner::FrontendScanType; +using ::aidl::android::hardware::tv::tuner::FrontendSettings; +using ::aidl::android::hardware::tv::tuner::FrontendStatus; +using ::aidl::android::hardware::tv::tuner::FrontendStatusType; +using ::android::sp; +using ::android::hardware::hidl_vec; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::std::shared_ptr; +using ::std::vector; + +using HidlFrontendAtsc3PlpSettings = ::android::hardware::tv::tuner::V1_0::FrontendAtsc3PlpSettings; +using HidlFrontendDvbsCodeRate = ::android::hardware::tv::tuner::V1_0::FrontendDvbsCodeRate; +using HidlFrontendEventType = ::android::hardware::tv::tuner::V1_0::FrontendEventType; +using HidlFrontendId = ::android::hardware::tv::tuner::V1_0::FrontendId; +using HidlFrontendScanMessage = ::android::hardware::tv::tuner::V1_0::FrontendScanMessage; +using HidlFrontendScanMessageType = ::android::hardware::tv::tuner::V1_0::FrontendScanMessageType; +using HidlFrontendSettings = ::android::hardware::tv::tuner::V1_0::FrontendSettings; +using HidlFrontendStatus = ::android::hardware::tv::tuner::V1_0::FrontendStatus; +using HidlIFrontend = ::android::hardware::tv::tuner::V1_0::IFrontend; +using HidlIFrontendCallback = ::android::hardware::tv::tuner::V1_1::IFrontendCallback; +using HidlFrontendScanMessageExt1_1 = + ::android::hardware::tv::tuner::V1_1::FrontendScanMessageExt1_1; +using HidlFrontendScanMessageTypeExt1_1 = + ::android::hardware::tv::tuner::V1_1::FrontendScanMessageTypeExt1_1; +using HidlFrontendSettingsExt1_1 = ::android::hardware::tv::tuner::V1_1::FrontendSettingsExt1_1; +using HidlFrontendStatusExt1_1 = ::android::hardware::tv::tuner::V1_1::FrontendStatusExt1_1; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlFrontend : public BnTunerFrontend { +public: + TunerHidlFrontend(sp frontend, int id); + virtual ~TunerHidlFrontend(); + + ::ndk::ScopedAStatus setCallback( + const shared_ptr& in_tunerFrontendCallback) override; + ::ndk::ScopedAStatus tune(const FrontendSettings& in_settings) override; + ::ndk::ScopedAStatus stopTune() override; + ::ndk::ScopedAStatus scan(const FrontendSettings& in_settings, + FrontendScanType in_frontendScanType) override; + ::ndk::ScopedAStatus stopScan() override; + ::ndk::ScopedAStatus setLnb(const shared_ptr& in_lnb) override; + ::ndk::ScopedAStatus setLna(bool in_bEnable) override; + ::ndk::ScopedAStatus linkCiCamToFrontend(int32_t in_ciCamId, int32_t* _aidl_return) override; + ::ndk::ScopedAStatus unlinkCiCamToFrontend(int32_t in_ciCamId) override; + ::ndk::ScopedAStatus close() override; + ::ndk::ScopedAStatus getStatus(const vector& in_statusTypes, + vector* _aidl_return) override; + ::ndk::ScopedAStatus getFrontendId(int32_t* _aidl_return) override; + + struct FrontendCallback : public HidlIFrontendCallback { + FrontendCallback(const shared_ptr tunerFrontendCallback) + : mTunerFrontendCallback(tunerFrontendCallback){}; + + virtual Return onEvent(HidlFrontendEventType frontendEventType); + virtual Return onScanMessage(HidlFrontendScanMessageType type, + const HidlFrontendScanMessage& message); + virtual Return onScanMessageExt1_1(HidlFrontendScanMessageTypeExt1_1 type, + const HidlFrontendScanMessageExt1_1& message); + + shared_ptr mTunerFrontendCallback; + }; + +private: + hidl_vec getAtsc3PlpSettings( + const FrontendAtsc3Settings& settings); + HidlFrontendDvbsCodeRate getDvbsCodeRate(const FrontendDvbsCodeRate& codeRate); + void getHidlFrontendSettings(const FrontendSettings& aidlSettings, + HidlFrontendSettings& settings, + HidlFrontendSettingsExt1_1& settingsExt); + void getAidlFrontendStatus(const vector& hidlStatus, + const vector& hidlStatusExt, + vector& aidlStatus); + + int mId; + sp mFrontend; + sp<::android::hardware::tv::tuner::V1_1::IFrontend> mFrontend_1_1; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLFRONTEND_H diff --git a/services/tuner/hidl/TunerHidlLnb.cpp b/services/tuner/hidl/TunerHidlLnb.cpp new file mode 100644 index 0000000000..a7e20bb8fc --- /dev/null +++ b/services/tuner/hidl/TunerHidlLnb.cpp @@ -0,0 +1,160 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlLnb" + +#include "TunerHidlLnb.h" + +#include + +using ::aidl::android::hardware::tv::tuner::Result; +using HidlLnbPosition = ::android::hardware::tv::tuner::V1_0::LnbPosition; +using HidlLnbTone = ::android::hardware::tv::tuner::V1_0::LnbTone; +using HidlLnbVoltage = ::android::hardware::tv::tuner::V1_0::LnbVoltage; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlLnb::TunerHidlLnb(sp lnb, int id) { + mLnb = lnb; + mId = id; +} + +TunerHidlLnb::~TunerHidlLnb() { + mLnb = nullptr; + mId = -1; +} + +::ndk::ScopedAStatus TunerHidlLnb::setCallback( + const shared_ptr& in_tunerLnbCallback) { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + if (in_tunerLnbCallback == nullptr) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::INVALID_ARGUMENT)); + } + + sp lnbCallback = new LnbCallback(in_tunerLnbCallback); + HidlResult status = mLnb->setCallback(lnbCallback); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlLnb::setVoltage(LnbVoltage in_voltage) { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mLnb->setVoltage(static_cast(in_voltage)); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlLnb::setTone(LnbTone in_tone) { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mLnb->setTone(static_cast(in_tone)); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlLnb::setSatellitePosition(LnbPosition in_position) { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mLnb->setSatellitePosition(static_cast(in_position)); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlLnb::sendDiseqcMessage(const vector& in_diseqcMessage) { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mLnb->sendDiseqcMessage(in_diseqcMessage); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlLnb::close() { + if (mLnb == nullptr) { + ALOGE("ILnb is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mLnb->close(); + mLnb = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +/////////////// ILnbCallback /////////////////////// +Return TunerHidlLnb::LnbCallback::onEvent(const HidlLnbEventType lnbEventType) { + if (mTunerLnbCallback != nullptr) { + mTunerLnbCallback->onEvent(static_cast(lnbEventType)); + } + return Void(); +} + +Return TunerHidlLnb::LnbCallback::onDiseqcMessage(const hidl_vec& diseqcMessage) { + if (mTunerLnbCallback != nullptr) { + vector msg(begin(diseqcMessage), end(diseqcMessage)); + mTunerLnbCallback->onDiseqcMessage(msg); + } + return Void(); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlLnb.h b/services/tuner/hidl/TunerHidlLnb.h new file mode 100644 index 0000000000..c496f48068 --- /dev/null +++ b/services/tuner/hidl/TunerHidlLnb.h @@ -0,0 +1,84 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLLNB_H +#define ANDROID_MEDIA_TUNERHIDLLNB_H + +#include +#include +#include +#include +#include +#include + +using ::aidl::android::hardware::tv::tuner::LnbEventType; +using ::aidl::android::hardware::tv::tuner::LnbPosition; +using ::aidl::android::hardware::tv::tuner::LnbTone; +using ::aidl::android::hardware::tv::tuner::LnbVoltage; +using ::android::sp; +using ::android::hardware::hidl_vec; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::std::shared_ptr; +using ::std::vector; + +using HidlILnb = ::android::hardware::tv::tuner::V1_0::ILnb; +using HidlILnbCallback = ::android::hardware::tv::tuner::V1_0::ILnbCallback; +using HidlLnbEventType = ::android::hardware::tv::tuner::V1_0::LnbEventType; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlLnb : public BnTunerLnb { +public: + TunerHidlLnb(sp lnb, int id); + virtual ~TunerHidlLnb(); + + ::ndk::ScopedAStatus setCallback( + const shared_ptr& in_tunerLnbCallback) override; + ::ndk::ScopedAStatus setVoltage(LnbVoltage in_voltage) override; + ::ndk::ScopedAStatus setTone(LnbTone in_tone) override; + ::ndk::ScopedAStatus setSatellitePosition(LnbPosition in_position) override; + ::ndk::ScopedAStatus sendDiseqcMessage(const vector& in_diseqcMessage) override; + ::ndk::ScopedAStatus close() override; + + int getId() { return mId; } + + struct LnbCallback : public HidlILnbCallback { + LnbCallback(const shared_ptr tunerLnbCallback) + : mTunerLnbCallback(tunerLnbCallback){}; + + virtual Return onEvent(const HidlLnbEventType lnbEventType); + virtual Return onDiseqcMessage(const hidl_vec& diseqcMessage); + + shared_ptr mTunerLnbCallback; + }; + +private: + int mId; + sp mLnb; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLLNB_H diff --git a/services/tuner/hidl/TunerHidlService.cpp b/services/tuner/hidl/TunerHidlService.cpp new file mode 100644 index 0000000000..9d9bc7eb3c --- /dev/null +++ b/services/tuner/hidl/TunerHidlService.cpp @@ -0,0 +1,584 @@ +/** + * Copyright (c) 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//#define LOG_NDEBUG 0 +#define LOG_TAG "TunerHidlService" + +#include "TunerHidlService.h" + +#include +#include +#include + +#include "TunerHelper.h" +#include "TunerHidlDemux.h" +#include "TunerHidlDescrambler.h" +#include "TunerHidlFrontend.h" +#include "TunerHidlLnb.h" + +using ::aidl::android::hardware::tv::tuner::FrontendAnalogCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendAtsc3Capabilities; +using ::aidl::android::hardware::tv::tuner::FrontendAtscCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendDtmbCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendDvbcCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendDvbsCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendDvbtCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbs3Capabilities; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbsCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendIsdbtCapabilities; +using ::aidl::android::hardware::tv::tuner::FrontendType; +using ::aidl::android::hardware::tv::tuner::Result; +using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; +using ::android::hardware::hidl_vec; + +using HidlFrontendId = ::android::hardware::tv::tuner::V1_0::FrontendId; +using HidlLnbId = ::android::hardware::tv::tuner::V1_0::LnbId; +using HidlFrontendType = ::android::hardware::tv::tuner::V1_1::FrontendType; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlService::TunerHidlService() { + if (!TunerHelper::checkTunerFeature()) { + ALOGD("Device doesn't have tuner hardware."); + return; + } + + updateTunerResources(); +} + +TunerHidlService::~TunerHidlService() {} + +binder_status_t TunerHidlService::instantiate() { + if (HidlITuner::getService() == nullptr) { + ALOGD("Failed to get ITuner HIDL HAL"); + return STATUS_NAME_NOT_FOUND; + } + + shared_ptr service = ::ndk::SharedRefBase::make(); + return AServiceManager_addService(service->asBinder().get(), getServiceName()); +} + +bool TunerHidlService::hasITuner() { + ALOGV("hasITuner"); + if (mTuner != nullptr) { + return true; + } + + mTuner = HidlITuner::getService(); + if (mTuner == nullptr) { + ALOGE("Failed to get ITuner service"); + return false; + } + mTunerVersion = TUNER_HAL_VERSION_1_0; + + mTuner_1_1 = ::android::hardware::tv::tuner::V1_1::ITuner::castFrom(mTuner); + if (mTuner_1_1 != nullptr) { + mTunerVersion = TUNER_HAL_VERSION_1_1; + } else { + ALOGD("Failed to get ITuner_1_1 service"); + } + + return true; +} + +bool TunerHidlService::hasITuner_1_1() { + ALOGV("hasITuner_1_1"); + hasITuner(); + return (mTunerVersion == TUNER_HAL_VERSION_1_1); +} + +::ndk::ScopedAStatus TunerHidlService::openDemux(int32_t /* in_demuxHandle */, + shared_ptr* _aidl_return) { + ALOGV("openDemux"); + if (!hasITuner()) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + uint32_t id; + sp demuxSp = nullptr; + mTuner->openDemux([&](HidlResult r, uint32_t demuxId, const sp& demux) { + demuxSp = demux; + id = demuxId; + res = r; + ALOGD("open demux, id = %d", demuxId); + }); + if (res == HidlResult::SUCCESS) { + *_aidl_return = ::ndk::SharedRefBase::make(demuxSp, id); + return ::ndk::ScopedAStatus::ok(); + } + + ALOGW("open demux failed, res = %d", res); + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); +} + +::ndk::ScopedAStatus TunerHidlService::getDemuxCaps(DemuxCapabilities* _aidl_return) { + ALOGV("getDemuxCaps"); + if (!hasITuner()) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res; + HidlDemuxCapabilities caps; + mTuner->getDemuxCaps([&](HidlResult r, const HidlDemuxCapabilities& demuxCaps) { + caps = demuxCaps; + res = r; + }); + if (res == HidlResult::SUCCESS) { + *_aidl_return = getAidlDemuxCaps(caps); + return ::ndk::ScopedAStatus::ok(); + } + + ALOGW("Get demux caps failed, res = %d", res); + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); +} + +::ndk::ScopedAStatus TunerHidlService::getFrontendIds(vector* ids) { + if (!hasITuner()) { + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + hidl_vec feIds; + HidlResult res = getHidlFrontendIds(feIds); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + ids->resize(feIds.size()); + copy(feIds.begin(), feIds.end(), ids->begin()); + + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::getFrontendInfo(int32_t id, FrontendInfo* _aidl_return) { + if (!hasITuner()) { + ALOGE("ITuner service is not init."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlFrontendInfo info; + HidlResult res = getHidlFrontendInfo(id, info); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + + HidlFrontendDtmbCapabilities dtmbCaps; + if (static_cast(info.type) == HidlFrontendType::DTMB) { + if (!hasITuner_1_1()) { + ALOGE("ITuner_1_1 service is not init."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + mTuner_1_1->getFrontendDtmbCapabilities( + id, [&](HidlResult r, const HidlFrontendDtmbCapabilities& caps) { + dtmbCaps = caps; + res = r; + }); + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + } + + *_aidl_return = getAidlFrontendInfo(info, dtmbCaps); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::openFrontend(int32_t frontendHandle, + shared_ptr* _aidl_return) { + if (!hasITuner()) { + ALOGE("ITuner service is not init."); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + sp frontend; + int id = TunerHelper::getResourceIdFromHandle(frontendHandle, FRONTEND); + mTuner->openFrontendById(id, [&](HidlResult result, const sp& fe) { + frontend = fe; + status = result; + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + *_aidl_return = ::ndk::SharedRefBase::make(frontend, id); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::openLnb(int lnbHandle, shared_ptr* _aidl_return) { + if (!hasITuner()) { + ALOGD("get ITuner failed"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + sp lnb; + int id = TunerHelper::getResourceIdFromHandle(lnbHandle, LNB); + mTuner->openLnbById(id, [&](HidlResult result, const sp& lnbSp) { + lnb = lnbSp; + status = result; + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(lnb, id); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::openLnbByName(const string& lnbName, + shared_ptr* _aidl_return) { + if (!hasITuner()) { + ALOGE("get ITuner failed"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + int lnbId; + HidlResult status; + sp lnb; + mTuner->openLnbByName(lnbName, [&](HidlResult r, HidlLnbId id, const sp& lnbSp) { + status = r; + lnb = lnbSp; + lnbId = static_cast(id); + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(lnb, lnbId); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::openDescrambler( + int32_t /*descramblerHandle*/, shared_ptr* _aidl_return) { + if (!hasITuner()) { + ALOGD("get ITuner failed"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + sp descrambler; + //int id = TunerHelper::getResourceIdFromHandle(descramblerHandle, DESCRAMBLER); + mTuner->openDescrambler([&](HidlResult r, const sp& descramblerSp) { + status = r; + descrambler = descramblerSp; + }); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + + *_aidl_return = ::ndk::SharedRefBase::make(descrambler); + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlService::getTunerHalVersion(int* _aidl_return) { + hasITuner(); + *_aidl_return = mTunerVersion; + return ::ndk::ScopedAStatus::ok(); +} + +void TunerHidlService::updateTunerResources() { + if (!hasITuner()) { + ALOGE("Failed to updateTunerResources"); + return; + } + + TunerHelper::updateTunerResources(getTRMFrontendInfos(), getTRMLnbHandles()); +} + +vector TunerHidlService::getTRMFrontendInfos() { + vector infos; + hidl_vec ids; + HidlResult res = getHidlFrontendIds(ids); + if (res != HidlResult::SUCCESS) { + return infos; + } + + for (int i = 0; i < ids.size(); i++) { + HidlFrontendInfo frontendInfo; + HidlResult res = getHidlFrontendInfo(static_cast(ids[i]), frontendInfo); + if (res != HidlResult::SUCCESS) { + continue; + } + TunerFrontendInfo tunerFrontendInfo{ + .handle = TunerHelper::getResourceHandleFromId(static_cast(ids[i]), + FRONTEND), + .type = static_cast(frontendInfo.type), + .exclusiveGroupId = static_cast(frontendInfo.exclusiveGroupId), + }; + infos.push_back(tunerFrontendInfo); + } + + return infos; +} + +vector TunerHidlService::getTRMLnbHandles() { + vector lnbHandles; + if (mTuner != nullptr) { + HidlResult res; + vector lnbIds; + mTuner->getLnbIds([&](HidlResult r, const hidl_vec& ids) { + lnbIds = ids; + res = r; + }); + if (res == HidlResult::SUCCESS && lnbIds.size() > 0) { + for (int i = 0; i < lnbIds.size(); i++) { + lnbHandles.push_back( + TunerHelper::getResourceHandleFromId(static_cast(lnbIds[i]), LNB)); + } + } + } + + return lnbHandles; +} + +HidlResult TunerHidlService::getHidlFrontendIds(hidl_vec& ids) { + if (mTuner == nullptr) { + return HidlResult::NOT_INITIALIZED; + } + HidlResult res; + mTuner->getFrontendIds([&](HidlResult r, const hidl_vec& frontendIds) { + ids = frontendIds; + res = r; + }); + return res; +} + +HidlResult TunerHidlService::getHidlFrontendInfo(const int id, HidlFrontendInfo& info) { + if (mTuner == nullptr) { + return HidlResult::NOT_INITIALIZED; + } + HidlResult res; + mTuner->getFrontendInfo(id, [&](HidlResult r, const HidlFrontendInfo& feInfo) { + info = feInfo; + res = r; + }); + return res; +} + +DemuxCapabilities TunerHidlService::getAidlDemuxCaps(const HidlDemuxCapabilities& caps) { + DemuxCapabilities aidlCaps{ + .numDemux = static_cast(caps.numDemux), + .numRecord = static_cast(caps.numRecord), + .numPlayback = static_cast(caps.numPlayback), + .numTsFilter = static_cast(caps.numTsFilter), + .numSectionFilter = static_cast(caps.numSectionFilter), + .numAudioFilter = static_cast(caps.numAudioFilter), + .numVideoFilter = static_cast(caps.numVideoFilter), + .numPesFilter = static_cast(caps.numPesFilter), + .numPcrFilter = static_cast(caps.numPcrFilter), + .numBytesInSectionFilter = static_cast(caps.numBytesInSectionFilter), + .filterCaps = static_cast(caps.filterCaps), + .bTimeFilter = caps.bTimeFilter, + }; + aidlCaps.linkCaps.resize(caps.linkCaps.size()); + copy(caps.linkCaps.begin(), caps.linkCaps.end(), aidlCaps.linkCaps.begin()); + return aidlCaps; +} + +FrontendInfo TunerHidlService::getAidlFrontendInfo( + const HidlFrontendInfo& halInfo, const HidlFrontendDtmbCapabilities& halDtmbCaps) { + FrontendInfo info{ + .type = static_cast(halInfo.type), + .minFrequency = static_cast(halInfo.minFrequency), + .maxFrequency = static_cast(halInfo.maxFrequency), + .minSymbolRate = static_cast(halInfo.minSymbolRate), + .maxSymbolRate = static_cast(halInfo.maxSymbolRate), + .acquireRange = static_cast(halInfo.acquireRange), + .exclusiveGroupId = static_cast(halInfo.exclusiveGroupId), + }; + for (int i = 0; i < halInfo.statusCaps.size(); i++) { + info.statusCaps.push_back(static_cast(halInfo.statusCaps[i])); + } + + FrontendCapabilities caps; + switch (halInfo.type) { + case ::android::hardware::tv::tuner::V1_0::FrontendType::ANALOG: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::analogCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendAnalogCapabilities analogCaps{ + .typeCap = static_cast(halInfo.frontendCaps.analogCaps().typeCap), + .sifStandardCap = + static_cast(halInfo.frontendCaps.analogCaps().sifStandardCap), + }; + caps.set(analogCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::ATSC: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::atscCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendAtscCapabilities atscCaps{ + .modulationCap = + static_cast(halInfo.frontendCaps.atscCaps().modulationCap), + }; + caps.set(atscCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::ATSC3: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::atsc3Caps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendAtsc3Capabilities atsc3Caps{ + .bandwidthCap = + static_cast(halInfo.frontendCaps.atsc3Caps().bandwidthCap), + .modulationCap = + static_cast(halInfo.frontendCaps.atsc3Caps().modulationCap), + .timeInterleaveModeCap = static_cast( + halInfo.frontendCaps.atsc3Caps().timeInterleaveModeCap), + .codeRateCap = + static_cast(halInfo.frontendCaps.atsc3Caps().codeRateCap), + .demodOutputFormatCap = static_cast( + halInfo.frontendCaps.atsc3Caps().demodOutputFormatCap), + .fecCap = static_cast(halInfo.frontendCaps.atsc3Caps().fecCap), + }; + caps.set(atsc3Caps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::DVBC: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::dvbcCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendDvbcCapabilities dvbcCaps{ + .modulationCap = + static_cast(halInfo.frontendCaps.dvbcCaps().modulationCap), + .fecCap = static_cast(halInfo.frontendCaps.dvbcCaps().fecCap), + .annexCap = static_cast(halInfo.frontendCaps.dvbcCaps().annexCap), + }; + caps.set(dvbcCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::DVBS: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::dvbsCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendDvbsCapabilities dvbsCaps{ + .modulationCap = + static_cast(halInfo.frontendCaps.dvbsCaps().modulationCap), + .innerfecCap = + static_cast(halInfo.frontendCaps.dvbsCaps().innerfecCap), + .standard = static_cast(halInfo.frontendCaps.dvbsCaps().standard), + }; + caps.set(dvbsCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::DVBT: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::dvbtCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendDvbtCapabilities dvbtCaps{ + .transmissionModeCap = static_cast( + halInfo.frontendCaps.dvbtCaps().transmissionModeCap), + .bandwidthCap = + static_cast(halInfo.frontendCaps.dvbtCaps().bandwidthCap), + .constellationCap = + static_cast(halInfo.frontendCaps.dvbtCaps().constellationCap), + .coderateCap = + static_cast(halInfo.frontendCaps.dvbtCaps().coderateCap), + .hierarchyCap = + static_cast(halInfo.frontendCaps.dvbtCaps().hierarchyCap), + .guardIntervalCap = + static_cast(halInfo.frontendCaps.dvbtCaps().guardIntervalCap), + .isT2Supported = halInfo.frontendCaps.dvbtCaps().isT2Supported, + .isMisoSupported = halInfo.frontendCaps.dvbtCaps().isMisoSupported, + }; + caps.set(dvbtCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::ISDBS: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::isdbsCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendIsdbsCapabilities isdbsCaps{ + .modulationCap = + static_cast(halInfo.frontendCaps.isdbsCaps().modulationCap), + .coderateCap = + static_cast(halInfo.frontendCaps.isdbsCaps().coderateCap), + }; + caps.set(isdbsCaps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::ISDBS3: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::isdbs3Caps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendIsdbs3Capabilities isdbs3Caps{ + .modulationCap = + static_cast(halInfo.frontendCaps.isdbs3Caps().modulationCap), + .coderateCap = + static_cast(halInfo.frontendCaps.isdbs3Caps().coderateCap), + }; + caps.set(isdbs3Caps); + } + break; + } + case ::android::hardware::tv::tuner::V1_0::FrontendType::ISDBT: { + if (HidlFrontendInfo::FrontendCapabilities::hidl_discriminator::isdbtCaps == + halInfo.frontendCaps.getDiscriminator()) { + FrontendIsdbtCapabilities isdbtCaps{ + .modeCap = static_cast(halInfo.frontendCaps.isdbtCaps().modeCap), + .bandwidthCap = + static_cast(halInfo.frontendCaps.isdbtCaps().bandwidthCap), + .modulationCap = + static_cast(halInfo.frontendCaps.isdbtCaps().modulationCap), + .coderateCap = + static_cast(halInfo.frontendCaps.isdbtCaps().coderateCap), + .guardIntervalCap = + static_cast(halInfo.frontendCaps.isdbtCaps().guardIntervalCap), + }; + caps.set(isdbtCaps); + } + break; + } + default: { + if (static_cast(info.type) == HidlFrontendType::DTMB) { + FrontendDtmbCapabilities dtmbCaps{ + .transmissionModeCap = static_cast(halDtmbCaps.transmissionModeCap), + .bandwidthCap = static_cast(halDtmbCaps.bandwidthCap), + .modulationCap = static_cast(halDtmbCaps.modulationCap), + .codeRateCap = static_cast(halDtmbCaps.codeRateCap), + .guardIntervalCap = static_cast(halDtmbCaps.guardIntervalCap), + .interleaveModeCap = static_cast(halDtmbCaps.interleaveModeCap), + }; + caps.set(dtmbCaps); + } + break; + } + } + + info.frontendCaps = caps; + return info; +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlService.h b/services/tuner/hidl/TunerHidlService.h new file mode 100644 index 0000000000..9f5f37103b --- /dev/null +++ b/services/tuner/hidl/TunerHidlService.h @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLSERVICE_H +#define ANDROID_MEDIA_TUNERHIDLSERVICE_H + +#include +#include +#include +#include +#include + +#include "TunerHelper.h" + +using ::aidl::android::hardware::tv::tuner::DemuxCapabilities; +using ::aidl::android::hardware::tv::tuner::DemuxFilterEvent; +using ::aidl::android::hardware::tv::tuner::DemuxFilterStatus; +using ::aidl::android::hardware::tv::tuner::FrontendInfo; +using ::aidl::android::media::tv::tuner::ITunerDemux; +using ::aidl::android::media::tv::tuner::ITunerDescrambler; +using ::aidl::android::media::tv::tuner::ITunerFrontend; +using ::aidl::android::media::tv::tuner::ITunerLnb; +using ::aidl::android::media::tv::tunerresourcemanager::TunerFrontendInfo; +using ::android::sp; +using ::android::hardware::hidl_vec; +using ::android::hardware::Return; +using ::android::hardware::Void; +using ::std::shared_ptr; +using ::std::vector; + +using HidlFrontendDtmbCapabilities = ::android::hardware::tv::tuner::V1_1::FrontendDtmbCapabilities; +using HidlDemuxFilterEvent = ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent; +using HidlDemuxFilterStatus = ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; +using HidlDemuxCapabilities = ::android::hardware::tv::tuner::V1_0::DemuxCapabilities; +using HidlFrontendInfo = ::android::hardware::tv::tuner::V1_0::FrontendInfo; +using HidlITuner = ::android::hardware::tv::tuner::V1_0::ITuner; +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; +using HidlFrontendId = ::android::hardware::tv::tuner::V1_0::FrontendId; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlService : public BnTunerService { +public: + static char const* getServiceName() { return "media.tuner"; } + static binder_status_t instantiate(); + TunerHidlService(); + virtual ~TunerHidlService(); + + ::ndk::ScopedAStatus getFrontendIds(vector* out_ids) override; + ::ndk::ScopedAStatus getFrontendInfo(int32_t in_frontendHandle, + FrontendInfo* _aidl_return) override; + ::ndk::ScopedAStatus openFrontend(int32_t in_frontendHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openLnb(int32_t in_lnbHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openLnbByName(const std::string& in_lnbName, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus openDemux(int32_t in_demuxHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getDemuxCaps(DemuxCapabilities* _aidl_return) override; + ::ndk::ScopedAStatus openDescrambler(int32_t in_descramblerHandle, + shared_ptr* _aidl_return) override; + ::ndk::ScopedAStatus getTunerHalVersion(int32_t* _aidl_return) override; + +private: + bool hasITuner(); + bool hasITuner_1_1(); + void updateTunerResources(); + vector getTRMFrontendInfos(); + vector getTRMLnbHandles(); + HidlResult getHidlFrontendIds(hidl_vec& ids); + HidlResult getHidlFrontendInfo(const int id, HidlFrontendInfo& info); + DemuxCapabilities getAidlDemuxCaps(const HidlDemuxCapabilities& caps); + FrontendInfo getAidlFrontendInfo(const HidlFrontendInfo& halInfo, + const HidlFrontendDtmbCapabilities& dtmbCaps); + + sp mTuner; + sp<::android::hardware::tv::tuner::V1_1::ITuner> mTuner_1_1; + int mTunerVersion = TUNER_HAL_VERSION_UNKNOWN; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLSERVICE_H diff --git a/services/tuner/hidl/TunerHidlTimeFilter.cpp b/services/tuner/hidl/TunerHidlTimeFilter.cpp new file mode 100644 index 0000000000..d0606d6580 --- /dev/null +++ b/services/tuner/hidl/TunerHidlTimeFilter.cpp @@ -0,0 +1,133 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "TunerHidlTimeFilter" + +#include "TunerHidlTimeFilter.h" + +#include +#include + +using ::aidl::android::hardware::tv::tuner::Constant64Bit; +using ::aidl::android::hardware::tv::tuner::Result; + +using HidlResult = ::android::hardware::tv::tuner::V1_0::Result; + +using namespace std; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +TunerHidlTimeFilter::TunerHidlTimeFilter(sp timeFilter) { + mTimeFilter = timeFilter; +} + +TunerHidlTimeFilter::~TunerHidlTimeFilter() { + mTimeFilter = nullptr; +} + +::ndk::ScopedAStatus TunerHidlTimeFilter::setTimeStamp(int64_t timeStamp) { + if (mTimeFilter == nullptr) { + ALOGE("ITimeFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mTimeFilter->setTimeStamp(static_cast(timeStamp)); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlTimeFilter::clearTimeStamp() { + if (mTimeFilter == nullptr) { + ALOGE("ITimeFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status = mTimeFilter->clearTimeStamp(); + if (status != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlTimeFilter::getSourceTime(int64_t* _aidl_return) { + if (mTimeFilter == nullptr) { + *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; + ALOGE("ITimeFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + mTimeFilter->getSourceTime([&](HidlResult r, uint64_t t) { + status = r; + *_aidl_return = static_cast(t); + }); + if (status != HidlResult::SUCCESS) { + *_aidl_return = static_cast(Constant64Bit::INVALID_PRESENTATION_TIME_STAMP); + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlTimeFilter::getTimeStamp(int64_t* _aidl_return) { + if (mTimeFilter == nullptr) { + *_aidl_return = (int64_t)Constant64Bit::INVALID_PRESENTATION_TIME_STAMP; + ALOGE("ITimeFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult status; + mTimeFilter->getTimeStamp([&](HidlResult r, uint64_t t) { + status = r; + *_aidl_return = static_cast(t); + }); + if (status != HidlResult::SUCCESS) { + *_aidl_return = static_cast(Constant64Bit::INVALID_PRESENTATION_TIME_STAMP); + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(status)); + } + return ::ndk::ScopedAStatus::ok(); +} + +::ndk::ScopedAStatus TunerHidlTimeFilter::close() { + if (mTimeFilter == nullptr) { + ALOGE("ITimeFilter is not initialized"); + return ::ndk::ScopedAStatus::fromServiceSpecificError( + static_cast(Result::UNAVAILABLE)); + } + + HidlResult res = mTimeFilter->close(); + mTimeFilter = nullptr; + + if (res != HidlResult::SUCCESS) { + return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); + } + return ::ndk::ScopedAStatus::ok(); +} + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl diff --git a/services/tuner/hidl/TunerHidlTimeFilter.h b/services/tuner/hidl/TunerHidlTimeFilter.h new file mode 100644 index 0000000000..97d59dce76 --- /dev/null +++ b/services/tuner/hidl/TunerHidlTimeFilter.h @@ -0,0 +1,58 @@ +/** + * Copyright 2021, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANDROID_MEDIA_TUNERHIDLTIMEFILTER_H +#define ANDROID_MEDIA_TUNERHIDLTIMEFILTER_H + +#include +#include +#include +#include + +using ::android::sp; +using ::android::hardware::Return; +using ::android::hardware::Void; + +using HidlITimeFilter = ::android::hardware::tv::tuner::V1_0::ITimeFilter; + +namespace aidl { +namespace android { +namespace media { +namespace tv { +namespace tuner { + +class TunerHidlTimeFilter : public BnTunerTimeFilter { +public: + TunerHidlTimeFilter(sp timeFilter); + virtual ~TunerHidlTimeFilter(); + + ::ndk::ScopedAStatus setTimeStamp(int64_t in_timeStamp) override; + ::ndk::ScopedAStatus clearTimeStamp() override; + ::ndk::ScopedAStatus getSourceTime(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus getTimeStamp(int64_t* _aidl_return) override; + ::ndk::ScopedAStatus close() override; + +private: + sp mTimeFilter; +}; + +} // namespace tuner +} // namespace tv +} // namespace media +} // namespace android +} // namespace aidl + +#endif // ANDROID_MEDIA_TUNERHIDLTIMEFILTER_H diff --git a/services/tuner/main_tunerservice.cpp b/services/tuner/main_tunerservice.cpp index bda2f71371..a014dead10 100644 --- a/services/tuner/main_tunerservice.cpp +++ b/services/tuner/main_tunerservice.cpp @@ -20,7 +20,9 @@ #include #include "TunerService.h" +#include "hidl/TunerHidlService.h" +using ::aidl::android::media::tv::tuner::TunerHidlService; using ::aidl::android::media::tv::tuner::TunerService; using namespace android; @@ -31,8 +33,12 @@ int main() { sp proc(ProcessState::self()); sp sm = defaultServiceManager(); - binder_status_t status = TunerService::instantiate(); - CHECK(status == STATUS_OK); + // Check legacy HIDL HAL first. If it's not existed, use AIDL HAL. + binder_status_t status = TunerHidlService::instantiate(); + if (status != STATUS_OK) { + status = TunerService::instantiate(); + CHECK(status == STATUS_OK); + } ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); -- GitLab From 9f285c93d6b5e3c74ccb29bbf873042a9e44a136 Mon Sep 17 00:00:00 2001 From: Hongguang Date: Thu, 19 Aug 2021 11:41:25 -0700 Subject: [PATCH 101/694] tuner: call to hal again to close transport FD by binder - Base on hardware binder design, the transport data from binder will be closed on the next transact(...). - Here TunerServer call to Tuner HAL again to trigger binder to close the fd and release shared memory occupied by it. Bug: 197008205 Test: Check whether there is tuner related fd leak. Change-Id: I5eb8e0f193e80a789ca48389c43eb859cb0b5c4a --- services/tuner/hidl/TunerHidlFilter.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/tuner/hidl/TunerHidlFilter.cpp b/services/tuner/hidl/TunerHidlFilter.cpp index 1573c8e821..2e9e4a682e 100644 --- a/services/tuner/hidl/TunerHidlFilter.cpp +++ b/services/tuner/hidl/TunerHidlFilter.cpp @@ -308,6 +308,11 @@ TunerHidlFilter::~TunerHidlFilter() { return ::ndk::ScopedAStatus::fromServiceSpecificError(static_cast(res)); } + // Call to HAL to make sure the transport FD was able to be closed by binder. + // This is a tricky workaround for a problem in Binder. + // TODO:[b/192048842] When that problem is fixed we may be able to remove or change this code. + mFilter->getId([&](HidlResult /* r */, uint32_t /* filterId*/){}); + return ::ndk::ScopedAStatus::ok(); } -- GitLab From a61b676c624d61d78e164efb8e0c15ea73e0304e Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Fri, 20 Aug 2021 16:01:00 +0200 Subject: [PATCH 102/694] spatializer: fix aidl interface dependency Create a separate library for spatializer aidl interfaces to solve double inclusion of some dependencies in framework.jar and services.jar Bug: 188502620 Test: atest StrictJavaPackagesTest#testBootClasspathAndSystemServerClasspath_nonDuplicateClasses Change-Id: I4c8a2149c650d22e335e73e73baaa361b58cda29 --- media/libaudioclient/Android.bp | 36 +++++++++++++++++++++++-- services/audiopolicy/service/Android.bp | 1 + 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 9b9ceea904..048aca206a 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -25,11 +25,13 @@ cc_library_headers { static_libs: [ "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", + "spatializer-aidl-cpp", "av-types-aidl-cpp", ], export_static_lib_headers: [ "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", + "spatializer-aidl-cpp", "av-types-aidl-cpp", ], target: { @@ -112,6 +114,7 @@ cc_library { "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", + "spatializer-aidl-cpp", "audiopolicy-types-aidl-cpp", "av-types-aidl-cpp", "capture_state_listener-aidl-cpp", @@ -137,6 +140,7 @@ cc_library { export_shared_lib_headers: [ "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", + "spatializer-aidl-cpp", "framework-permission-aidl-cpp", "libbinder", ], @@ -480,14 +484,42 @@ aidl_interface { "aidl/android/media/RecordClientInfo.aidl", "aidl/android/media/IAudioPolicyService.aidl", "aidl/android/media/IAudioPolicyServiceClient.aidl", - "aidl/android/media/INativeSpatializerCallback.aidl", - "aidl/android/media/ISpatializer.aidl", ], imports: [ "audioclient-types-aidl", "audiopolicy-types-aidl", "capture_state_listener-aidl", "framework-permission-aidl", + "spatializer-aidl", + ], + + double_loadable: true, + backend: { + cpp: { + min_sdk_version: "29", + apex_available: [ + "//apex_available:platform", + "com.android.media", + ], + }, + java: { + sdk_version: "module_current", + }, + }, +} + +aidl_interface { + name: "spatializer-aidl", + unstable: true, + local_include_dir: "aidl", + host_supported: true, + vendor_available: true, + srcs: [ + "aidl/android/media/INativeSpatializerCallback.aidl", + "aidl/android/media/ISpatializer.aidl", + ], + imports: [ + "audiopolicy-types-aidl", ], double_loadable: true, diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 5ffddc2858..8ae0901f31 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -50,6 +50,7 @@ cc_library_shared { "audiopolicy-types-aidl-cpp", "capture_state_listener-aidl-cpp", "framework-permission-aidl-cpp", + "spatializer-aidl-cpp", ], static_libs: [ -- GitLab From c98a29c3e1cd8e0551f6b60de6199a9cc451043f Mon Sep 17 00:00:00 2001 From: Harish Mahendrakar Date: Tue, 20 Jul 2021 17:26:12 -0700 Subject: [PATCH 103/694] C2SoftMpeg4Enc: Do not return 0 byte CSD for H263 Bug: 192791004 Test: recordvideo -2 Test: atest VtsHalMediaC2V1_0TargetVideoEncTest Test: atest CtsMediaV2TestCases Change-Id: If58a8b7c0e4d6097b9ecf4979ded50c4e628ae54 --- .../components/mpeg4_h263/C2SoftMpeg4Enc.cpp | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp index 3c87531e87..3bfec668b1 100644 --- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp +++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Enc.cpp @@ -436,16 +436,18 @@ void C2SoftMpeg4Enc::process( } ++mNumInputFrames; - std::unique_ptr csd = - C2StreamInitDataInfo::output::AllocUnique(outputSize, 0u); - if (!csd) { - ALOGE("CSD allocation failed"); - mSignalledError = true; - work->result = C2_NO_MEMORY; - return; + if (outputSize) { + std::unique_ptr csd = + C2StreamInitDataInfo::output::AllocUnique(outputSize, 0u); + if (!csd) { + ALOGE("CSD allocation failed"); + mSignalledError = true; + work->result = C2_NO_MEMORY; + return; + } + memcpy(csd->m.value, outPtr, outputSize); + work->worklets.front()->output.configUpdate.push_back(std::move(csd)); } - memcpy(csd->m.value, outPtr, outputSize); - work->worklets.front()->output.configUpdate.push_back(std::move(csd)); } // handle dynamic bitrate change -- GitLab From 47675b07cdd3bbe8bd90617a36c32490160d4a72 Mon Sep 17 00:00:00 2001 From: Hongguang Date: Mon, 23 Aug 2021 10:13:55 -0700 Subject: [PATCH 104/694] Remove useless _aidl_return = nullptr from tuner code. Bug: 191825295 Test: atest android.media.tv.tuner.cts Change-Id: I016dd8581ef1021c13edb4d5139f4cab02e344a9 --- services/tuner/hidl/TunerHidlFilter.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/tuner/hidl/TunerHidlFilter.cpp b/services/tuner/hidl/TunerHidlFilter.cpp index 2e9e4a682e..de82855c0a 100644 --- a/services/tuner/hidl/TunerHidlFilter.cpp +++ b/services/tuner/hidl/TunerHidlFilter.cpp @@ -283,8 +283,6 @@ TunerHidlFilter::~TunerHidlFilter() { if (res == HidlResult::SUCCESS) { *out_avMemory = dupToAidl(avMemory); *_aidl_return = static_cast(avMemSize); - } else { - _aidl_return = nullptr; } }); -- GitLab From 9ec08d02ac46e9246980fc0cddb6bc088a5e4e5c Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 6 Aug 2021 17:28:33 -0700 Subject: [PATCH 105/694] Update MIME types in AidlConversion and MediaDefs Add some IANA-listed types that were absent from MediaDefs. Also add unlisted types that have corresponding android.media.AudioFormat.ENCODING_* constants in the Java SDK. For the types related to MPEG4 audio use the convention described in RFC 6381 where various codecs are specified using the Audio Object Type Identifier from the ISO/IEC 14496-3 standard and its amendments. For the types related to MPEG-H audio use the identifiers from the ISO/IEC 23008-3 standard. Bug: 188932434 Test: m Change-Id: I87b77a90526a6b04ddebd7b3c4c16293edd1ae4e --- media/libaudioclient/AidlConversion.cpp | 137 +++++++----------- media/libstagefright/foundation/MediaDefs.cpp | 46 +++++- .../media/stagefright/foundation/MediaDefs.h | 39 ++++- 3 files changed, 138 insertions(+), 84 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index b0eb7bdda5..b3f6a152a1 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -724,7 +724,6 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_PCM_24_BIT_PACKED, make_AudioFormatDescription(media::PcmType::INT_24_BIT) }, { - // See the comment in MediaDefs.h. AUDIO_FORMAT_MP3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEG) }, { @@ -734,52 +733,41 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_AMR_WB, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AMR_WB) }, { - // Note: in MediaDefs.cpp MEDIA_MIMETYPE_AUDIO_AAC = "audio/mp4a-latm". - AUDIO_FORMAT_AAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_FORMAT) + AUDIO_FORMAT_AAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_MP4) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_MAIN, make_AudioFormatDescription("audio/aac.main") + AUDIO_FORMAT_AAC_MAIN, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_MAIN) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LC, make_AudioFormatDescription("audio/aac.lc") + AUDIO_FORMAT_AAC_LC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_SSR, make_AudioFormatDescription("audio/aac.ssr") + AUDIO_FORMAT_AAC_SSR, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_SSR) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LTP, make_AudioFormatDescription("audio/aac.ltp") + AUDIO_FORMAT_AAC_LTP, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LTP) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_HE_V1, make_AudioFormatDescription("audio/aac.he.v1") + AUDIO_FORMAT_AAC_HE_V1, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_HE_V1) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_SCALABLE, make_AudioFormatDescription("audio/aac.scalable") + AUDIO_FORMAT_AAC_SCALABLE, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_SCALABLE) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ERLC, make_AudioFormatDescription("audio/aac.erlc") + AUDIO_FORMAT_AAC_ERLC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ERLC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LD, make_AudioFormatDescription("audio/aac.ld") + AUDIO_FORMAT_AAC_LD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LD) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_HE_V2, make_AudioFormatDescription("audio/aac.he.v2") + AUDIO_FORMAT_AAC_HE_V2, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_HE_V2) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ELD, make_AudioFormatDescription("audio/aac.eld") + AUDIO_FORMAT_AAC_ELD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ELD) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_XHE, make_AudioFormatDescription("audio/aac.xhe") + AUDIO_FORMAT_AAC_XHE, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_XHE) }, // AUDIO_FORMAT_HE_AAC_V1 and HE_AAC_V2 are removed since they were deprecated long time // ago. @@ -796,7 +784,6 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_E_AC3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EAC3) }, { - // Note: not in the IANA registry. AUDIO_FORMAT_E_AC3_JOC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EAC3_JOC) }, { @@ -809,13 +796,12 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { // nested AudioFormatDescriptions. The legacy 'AUDIO_FORMAT_IEC61937' type doesn't // specify the format of the encapsulated bitstream. { - // Note: not in the IANA registry. AUDIO_FORMAT_IEC61937, - make_AudioFormatDescription(media::PcmType::INT_16_BIT, "audio/x-iec61937") + make_AudioFormatDescription(media::PcmType::INT_16_BIT, MEDIA_MIMETYPE_AUDIO_IEC61937) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_DOLBY_TRUEHD, make_AudioFormatDescription("audio/vnd.dolby.truehd") + AUDIO_FORMAT_DOLBY_TRUEHD, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DOLBY_TRUEHD) }, { AUDIO_FORMAT_EVRC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRC) @@ -830,11 +816,9 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_EVRCNW, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_EVRCNW) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADIF, make_AudioFormatDescription("audio/aac.adif") + AUDIO_FORMAT_AAC_ADIF, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADIF) }, { - // Note: not in the IANA registry. AUDIO_FORMAT_WMA, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_WMA) }, { @@ -845,7 +829,6 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_AMR_WB_PLUS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS) }, { - // Note: not in the IANA registry. AUDIO_FORMAT_MP2, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II) }, { @@ -859,7 +842,6 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_FLAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_FLAC) }, { - // Note: not in the IANA registry. AUDIO_FORMAT_ALAC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_ALAC) }, { @@ -867,52 +849,49 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_APE, make_AudioFormatDescription("audio/x-ape") }, { - // Note: not in the IANA registry. AUDIO_FORMAT_AAC_ADTS, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_MAIN, make_AudioFormatDescription("audio/aac-adts.main") + AUDIO_FORMAT_AAC_ADTS_MAIN, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_MAIN) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_LC, make_AudioFormatDescription("audio/aac-adts.lc") + AUDIO_FORMAT_AAC_ADTS_LC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_SSR, make_AudioFormatDescription("audio/aac-adts.ssr") + AUDIO_FORMAT_AAC_ADTS_SSR, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SSR) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_LTP, make_AudioFormatDescription("audio/aac-adts.ltp") + AUDIO_FORMAT_AAC_ADTS_LTP, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LTP) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_HE_V1, make_AudioFormatDescription("audio/aac-adts.he.v1") + AUDIO_FORMAT_AAC_ADTS_HE_V1, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_SCALABLE, make_AudioFormatDescription("audio/aac-adts.scalable") + AUDIO_FORMAT_AAC_ADTS_SCALABLE, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SCALABLE) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_ERLC, make_AudioFormatDescription("audio/aac-adts.erlc") + AUDIO_FORMAT_AAC_ADTS_ERLC, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ERLC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_LD, make_AudioFormatDescription("audio/aac-adts.ld") + AUDIO_FORMAT_AAC_ADTS_LD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LD) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_HE_V2, make_AudioFormatDescription("audio/aac-adts.he.v2") + AUDIO_FORMAT_AAC_ADTS_HE_V2, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_ELD, make_AudioFormatDescription("audio/aac-adts.eld") + AUDIO_FORMAT_AAC_ADTS_ELD, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ELD) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_ADTS_XHE, make_AudioFormatDescription("audio/aac-adts.xhe") + AUDIO_FORMAT_AAC_ADTS_XHE, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_ADTS_XHE) }, { // Note: not in the IANA registry. "vnd.octel.sbc" is not BT SBC. @@ -926,7 +905,6 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_APTX_HD, make_AudioFormatDescription("audio/vnd.qcom.aptx.hd") }, { - // Note: not in the IANA registry. Matches MediaDefs.cpp. AUDIO_FORMAT_AC4, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AC4) }, { @@ -934,35 +912,36 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_LDAC, make_AudioFormatDescription("audio/vnd.sony.ldac") }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MAT, make_AudioFormatDescription("audio/vnd.dolby.mat") + AUDIO_FORMAT_MAT, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DOLBY_MAT) }, { // Note: not in the IANA registry. - AUDIO_FORMAT_MAT_1_0, make_AudioFormatDescription("audio/vnd.dolby.mat.1.0") + AUDIO_FORMAT_MAT_1_0, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DOLBY_MAT + std::string(".1.0")) }, { // Note: not in the IANA registry. - AUDIO_FORMAT_MAT_2_0, make_AudioFormatDescription("audio/vnd.dolby.mat.2.0") + AUDIO_FORMAT_MAT_2_0, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DOLBY_MAT + std::string(".2.0")) }, { // Note: not in the IANA registry. - AUDIO_FORMAT_MAT_2_1, make_AudioFormatDescription("audio/vnd.dolby.mat.2.1") + AUDIO_FORMAT_MAT_2_1, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DOLBY_MAT + std::string(".2.1")) }, { AUDIO_FORMAT_AAC_LATM, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LATM_LC, make_AudioFormatDescription("audio/mp4a-latm.lc") + AUDIO_FORMAT_AAC_LATM_LC, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LATM_LC) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LATM_HE_V1, make_AudioFormatDescription("audio/mp4a-latm.he.v1") + AUDIO_FORMAT_AAC_LATM_HE_V1, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V1) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_AAC_LATM_HE_V2, make_AudioFormatDescription("audio/mp4a-latm.he.v2") + AUDIO_FORMAT_AAC_LATM_HE_V2, + make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V2) }, { // Note: not in the IANA registry. @@ -989,29 +968,23 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { AUDIO_FORMAT_LC3, make_AudioFormatDescription("audio/x-lc3") }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MPEGH, make_AudioFormatDescription("audio/x-mpegh") + AUDIO_FORMAT_MPEGH, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEGH_MHM1) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MPEGH_BL_L3, make_AudioFormatDescription("audio/x-mpegh.bl.l3") + AUDIO_FORMAT_MPEGH_BL_L3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L3) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MPEGH_BL_L4, make_AudioFormatDescription("audio/x-mpegh.bl.l4") + AUDIO_FORMAT_MPEGH_BL_L4, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L4) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MPEGH_LC_L3, make_AudioFormatDescription("audio/x-mpegh.lc.l3") + AUDIO_FORMAT_MPEGH_LC_L3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L3) }, { - // Note: not in the IANA registry. - AUDIO_FORMAT_MPEGH_LC_L4, make_AudioFormatDescription("audio/x-mpegh.lc.l4") + AUDIO_FORMAT_MPEGH_LC_L4, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L4) }, { - // Note: not in the IANA registry. AUDIO_FORMAT_IEC60958, - make_AudioFormatDescription(media::PcmType::INT_24_BIT, "audio/x-iec60958") + make_AudioFormatDescription(media::PcmType::INT_24_BIT, MEDIA_MIMETYPE_AUDIO_IEC60958) }, { AUDIO_FORMAT_DTS_UHD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DTS_UHD) diff --git a/media/libstagefright/foundation/MediaDefs.cpp b/media/libstagefright/foundation/MediaDefs.cpp index 0ec5ad5c3f..5c4ec17987 100644 --- a/media/libstagefright/foundation/MediaDefs.cpp +++ b/media/libstagefright/foundation/MediaDefs.cpp @@ -60,6 +60,10 @@ const char *MEDIA_MIMETYPE_AUDIO_EAC3_JOC = "audio/eac3-joc"; const char *MEDIA_MIMETYPE_AUDIO_AC4 = "audio/ac4"; const char *MEDIA_MIMETYPE_AUDIO_MPEGH_MHA1 = "audio/mha1"; const char *MEDIA_MIMETYPE_AUDIO_MPEGH_MHM1 = "audio/mhm1"; +const char *MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L3 = "audio/mhm1.03"; +const char *MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L4 = "audio/mhm1.04"; +const char *MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L3 = "audio/mhm1.0d"; +const char *MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L4 = "audio/mhm1.0e"; const char *MEDIA_MIMETYPE_AUDIO_SCRAMBLED = "audio/scrambled"; const char *MEDIA_MIMETYPE_AUDIO_ALAC = "audio/alac"; const char *MEDIA_MIMETYPE_AUDIO_WMA = "audio/x-ms-wma"; @@ -75,7 +79,47 @@ const char *MEDIA_MIMETYPE_AUDIO_EVRCNW = "audio/evrcnw"; const char *MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS = "audio/amr-wb+"; const char *MEDIA_MIMETYPE_AUDIO_APTX = "audio/aptx"; const char *MEDIA_MIMETYPE_AUDIO_DRA = "audio/vnd.dra"; -const char *MEDIA_MIMETYPE_AUDIO_AAC_FORMAT = "audio/aac"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT = "audio/vnd.dolby.mat"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_1_0 = "audio/vnd.dolby.mat.1.0"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_2_0 = "audio/vnd.dolby.mat.2.0"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_2_1 = "audio/vnd.dolby.mat.2.1"; +const char *MEDIA_MIMETYPE_AUDIO_DOLBY_TRUEHD = "audio/vnd.dolby.mlp"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_MP4 = "audio/mp4a.40"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_MAIN = "audio/mp4a.40.01"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LC = "audio/mp4a.40.02"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_SSR = "audio/mp4a.40.03"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LTP = "audio/mp4a.40.04"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_HE_V1 = "audio/mp4a.40.05"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_SCALABLE = "audio/mp4a.40.06"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ERLC = "audio/mp4a.40.17"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LD = "audio/mp4a.40.23"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_HE_V2 = "audio/mp4a.40.29"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ELD = "audio/mp4a.40.39"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_XHE = "audio/mp4a.40.42"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADIF = "audio/aac-adif"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_MAIN = "audio/aac-adts.01"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC = "audio/aac-adts.02"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SSR = "audio/aac-adts.03"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LTP = "audio/aac-adts.04"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1 = "audio/aac-adts.05"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SCALABLE = "audio/aac-adts.06"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ERLC = "audio/aac-adts.17"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LD = "audio/aac-adts.23"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2 = "audio/aac-adts.29"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ELD = "audio/aac-adts.39"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_XHE = "audio/aac-adts.42"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_LC = "audio/mp4a-latm.02"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V1 = "audio/mp4a-latm.05"; +const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V2 = "audio/mp4a-latm.29"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_IEC61937 = "audio/x-iec61937"; +// Note: not in the IANA registry. +const char *MEDIA_MIMETYPE_AUDIO_IEC60958 = "audio/x-iec60958"; const char *MEDIA_MIMETYPE_CONTAINER_MPEG4 = "video/mp4"; const char *MEDIA_MIMETYPE_CONTAINER_WAV = "audio/x-wav"; diff --git a/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h b/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h index afa0c6ddc3..fb8c2993b5 100644 --- a/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h +++ b/media/libstagefright/foundation/include/media/stagefright/foundation/MediaDefs.h @@ -62,6 +62,10 @@ extern const char *MEDIA_MIMETYPE_AUDIO_EAC3_JOC; extern const char *MEDIA_MIMETYPE_AUDIO_AC4; extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_MHA1; extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_MHM1; +extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L3; +extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_BL_L4; +extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L3; +extern const char *MEDIA_MIMETYPE_AUDIO_MPEGH_LC_L4; extern const char *MEDIA_MIMETYPE_AUDIO_SCRAMBLED; extern const char *MEDIA_MIMETYPE_AUDIO_ALAC; extern const char *MEDIA_MIMETYPE_AUDIO_WMA; @@ -77,7 +81,40 @@ extern const char *MEDIA_MIMETYPE_AUDIO_EVRCNW; extern const char *MEDIA_MIMETYPE_AUDIO_AMR_WB_PLUS; extern const char *MEDIA_MIMETYPE_AUDIO_APTX; extern const char *MEDIA_MIMETYPE_AUDIO_DRA; -extern const char *MEDIA_MIMETYPE_AUDIO_AAC_FORMAT; +extern const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT; +extern const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_1_0; +extern const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_2_0; +extern const char *MEDIA_MIMETYPE_AUDIO_DOLBY_MAT_2_1; +extern const char *MEDIA_MIMETYPE_AUDIO_DOLBY_TRUEHD; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_MP4; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_MAIN; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LC; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_SSR; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LTP; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_HE_V1; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_SCALABLE; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ERLC; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LD; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_HE_V2; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ELD; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_XHE; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADIF; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_MAIN; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LC; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SSR; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LTP; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V1; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_SCALABLE; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ERLC; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_LD; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_HE_V2; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_ELD; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS_XHE; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_LC; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V1; +extern const char *MEDIA_MIMETYPE_AUDIO_AAC_LATM_HE_V2; +extern const char *MEDIA_MIMETYPE_AUDIO_IEC61937; +extern const char *MEDIA_MIMETYPE_AUDIO_IEC60958; extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG4; extern const char *MEDIA_MIMETYPE_CONTAINER_WAV; -- GitLab From 57bd06fe7ee881813e28caf4e939114bc745b9ad Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 10 Aug 2021 16:41:54 -0700 Subject: [PATCH 106/694] Move common audio AIDL types to audio.media.audio.common The following types are being moved from 'android.media': - AudioChannelLayout - AudioFormatDescription - AudioFormatType - PcmType Updated usages and conversion functions. Bug: 188932434 Test: atest audio_aidl_conversion_tests Test: atest audiofoundation_parcelable_test Change-Id: Ib65a4f428da4a7f29ec22bc2a393617c6c4389d0 --- media/libaaudio/src/Android.bp | 2 + .../src/binding/AAudioStreamConfiguration.cpp | 5 +- .../binding/aidl/aaudio/StreamParameters.aidl | 2 +- media/libaudioclient/AidlConversion.cpp | 104 +++---- media/libaudioclient/Android.bp | 12 +- media/libaudioclient/AudioSystem.cpp | 11 +- media/libaudioclient/IAudioFlinger.cpp | 14 +- .../android/media/AudioChannelLayout.aidl | 274 ------------------ .../aidl/android/media/AudioConfig.aidl | 4 +- .../aidl/android/media/AudioConfigBase.aidl | 4 +- .../android/media/AudioFormatDescription.aidl | 84 ------ .../aidl/android/media/AudioFormatType.aidl | 48 --- .../aidl/android/media/AudioGain.aidl | 2 +- .../aidl/android/media/AudioGainConfig.aidl | 2 +- .../aidl/android/media/AudioIoDescriptor.aidl | 4 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 4 +- .../android/media/IAudioFlingerService.aidl | 4 +- .../android/media/IAudioPolicyService.aidl | 2 +- .../aidl/android/media/PcmType.aidl | 53 ---- media/libaudioclient/fuzzer/Android.bp | 1 + .../include/media/AidlConversion.h | 16 +- .../include/media/AudioCommonTypes.h | 20 +- .../include/media/IAudioFlinger.h | 8 +- media/libaudioclient/tests/Android.bp | 1 + .../audio_aidl_legacy_conversion_tests.cpp | 81 +++--- media/libaudiofoundation/Android.bp | 4 + media/libaudiofoundation/AudioProfile.cpp | 6 +- media/libaudiofoundation/tests/Android.bp | 1 + media/libmedia/Android.bp | 1 + services/audioflinger/Android.bp | 1 + services/audiopolicy/service/Android.bp | 1 + .../service/AudioPolicyInterfaceImpl.cpp | 15 +- .../audiopolicy/service/AudioPolicyService.h | 13 +- 34 files changed, 193 insertions(+), 615 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioFormatType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/PcmType.aidl diff --git a/media/libaaudio/src/Android.bp b/media/libaaudio/src/Android.bp index da59da6e7f..01aaa2ae8f 100644 --- a/media/libaaudio/src/Android.bp +++ b/media/libaaudio/src/Android.bp @@ -168,6 +168,7 @@ cc_library { "libbinder", "framework-permission-aidl-cpp", "aaudio-aidl-cpp", + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", ], @@ -246,6 +247,7 @@ aidl_interface { "binding/aidl/aaudio/IAAudioService.aidl", ], imports: [ + "android.media.audio.common.types", "audioclient-types-aidl", "shared-file-region-aidl", "framework-permission-aidl", diff --git a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp index cf7622560c..14d1671bfc 100644 --- a/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp +++ b/media/libaaudio/src/binding/AAudioStreamConfiguration.cpp @@ -29,7 +29,7 @@ using namespace aaudio; -using android::media::AudioFormatDescription; +using android::media::audio::common::AudioFormatDescription; AAudioStreamConfiguration::AAudioStreamConfiguration(const StreamParameters& parcelable) { setChannelMask(parcelable.channelMask); @@ -76,7 +76,8 @@ StreamParameters AAudioStreamConfiguration::parcelable() const { result.audioFormat = convAudioFormat.value(); } else { result.audioFormat = AudioFormatDescription{}; - result.audioFormat.type = android::media::AudioFormatType::SYS_RESERVED_INVALID; + result.audioFormat.type = + android::media::audio::common::AudioFormatType::SYS_RESERVED_INVALID; } static_assert(sizeof(aaudio_direction_t) == sizeof(result.direction)); result.direction = getDirection(); diff --git a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl index 3b274f2001..cc4f138cbf 100644 --- a/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl +++ b/media/libaaudio/src/binding/aidl/aaudio/StreamParameters.aidl @@ -16,7 +16,7 @@ package aaudio; -import android.media.AudioFormatDescription; +import android.media.audio.common.AudioFormatDescription; parcelable StreamParameters { int channelMask; // = AAUDIO_UNSPECIFIED; diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index b3f6a152a1..102e54a176 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -34,6 +34,10 @@ namespace android { using base::unexpected; +using media::audio::common::AudioChannelLayout; +using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioFormatType; +using media::audio::common::PcmType; namespace { @@ -388,21 +392,21 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy namespace { namespace detail { -using AudioChannelPair = std::pair; +using AudioChannelPair = std::pair; using AudioChannelPairs = std::vector; using AudioDevicePair = std::pair; using AudioDevicePairs = std::vector; -using AudioFormatPair = std::pair; +using AudioFormatPair = std::pair; using AudioFormatPairs = std::vector; } const detail::AudioChannelPairs& getInAudioChannelPairs() { static const detail::AudioChannelPairs pairs = { -#define DEFINE_INPUT_LAYOUT(n) \ - { \ - AUDIO_CHANNEL_IN_##n, \ - media::AudioChannelLayout::make( \ - media::AudioChannelLayout::LAYOUT_##n) \ +#define DEFINE_INPUT_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_IN_##n, \ + AudioChannelLayout::make( \ + AudioChannelLayout::LAYOUT_##n) \ } DEFINE_INPUT_LAYOUT(MONO), @@ -421,11 +425,11 @@ const detail::AudioChannelPairs& getInAudioChannelPairs() { const detail::AudioChannelPairs& getOutAudioChannelPairs() { static const detail::AudioChannelPairs pairs = { -#define DEFINE_OUTPUT_LAYOUT(n) \ - { \ - AUDIO_CHANNEL_OUT_##n, \ - media::AudioChannelLayout::make( \ - media::AudioChannelLayout::LAYOUT_##n) \ +#define DEFINE_OUTPUT_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_OUT_##n, \ + AudioChannelLayout::make( \ + AudioChannelLayout::LAYOUT_##n) \ } DEFINE_OUTPUT_LAYOUT(MONO), @@ -464,11 +468,11 @@ const detail::AudioChannelPairs& getOutAudioChannelPairs() { const detail::AudioChannelPairs& getVoiceAudioChannelPairs() { static const detail::AudioChannelPairs pairs = { -#define DEFINE_VOICE_LAYOUT(n) \ - { \ - AUDIO_CHANNEL_IN_VOICE_##n, \ - media::AudioChannelLayout::make( \ - media::AudioChannelLayout::VOICE_##n) \ +#define DEFINE_VOICE_LAYOUT(n) \ + { \ + AUDIO_CHANNEL_IN_VOICE_##n, \ + AudioChannelLayout::make( \ + AudioChannelLayout::VOICE_##n) \ } DEFINE_VOICE_LAYOUT(UPLINK_MONO), DEFINE_VOICE_LAYOUT(DNLINK_MONO), @@ -671,25 +675,25 @@ const detail::AudioDevicePairs& getAudioDevicePairs() { return pairs; } -media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { - media::AudioFormatDescription result; +AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) { + AudioFormatDescription result; result.type = type; return result; } -media::AudioFormatDescription make_AudioFormatDescription(media::PcmType pcm) { - auto result = make_AudioFormatDescription(media::AudioFormatType::PCM); +AudioFormatDescription make_AudioFormatDescription(PcmType pcm) { + auto result = make_AudioFormatDescription(AudioFormatType::PCM); result.pcm = pcm; return result; } -media::AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { - media::AudioFormatDescription result; +AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { + AudioFormatDescription result; result.encoding = encoding; return result; } -media::AudioFormatDescription make_AudioFormatDescription(media::PcmType transport, +AudioFormatDescription make_AudioFormatDescription(PcmType transport, const std::string& encoding) { auto result = make_AudioFormatDescription(encoding); result.pcm = transport; @@ -700,28 +704,28 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { static const detail::AudioFormatPairs pairs = {{ { AUDIO_FORMAT_INVALID, - make_AudioFormatDescription(media::AudioFormatType::SYS_RESERVED_INVALID) + make_AudioFormatDescription(AudioFormatType::SYS_RESERVED_INVALID) }, { - AUDIO_FORMAT_DEFAULT, media::AudioFormatDescription{} + AUDIO_FORMAT_DEFAULT, AudioFormatDescription{} }, { - AUDIO_FORMAT_PCM_16_BIT, make_AudioFormatDescription(media::PcmType::INT_16_BIT) + AUDIO_FORMAT_PCM_16_BIT, make_AudioFormatDescription(PcmType::INT_16_BIT) }, { - AUDIO_FORMAT_PCM_8_BIT, make_AudioFormatDescription(media::PcmType::UINT_8_BIT) + AUDIO_FORMAT_PCM_8_BIT, make_AudioFormatDescription(PcmType::UINT_8_BIT) }, { - AUDIO_FORMAT_PCM_32_BIT, make_AudioFormatDescription(media::PcmType::INT_32_BIT) + AUDIO_FORMAT_PCM_32_BIT, make_AudioFormatDescription(PcmType::INT_32_BIT) }, { - AUDIO_FORMAT_PCM_8_24_BIT, make_AudioFormatDescription(media::PcmType::FIXED_Q_8_24) + AUDIO_FORMAT_PCM_8_24_BIT, make_AudioFormatDescription(PcmType::FIXED_Q_8_24) }, { - AUDIO_FORMAT_PCM_FLOAT, make_AudioFormatDescription(media::PcmType::FLOAT_32_BIT) + AUDIO_FORMAT_PCM_FLOAT, make_AudioFormatDescription(PcmType::FLOAT_32_BIT) }, { - AUDIO_FORMAT_PCM_24_BIT_PACKED, make_AudioFormatDescription(media::PcmType::INT_24_BIT) + AUDIO_FORMAT_PCM_24_BIT_PACKED, make_AudioFormatDescription(PcmType::INT_24_BIT) }, { AUDIO_FORMAT_MP3, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_MPEG) @@ -797,7 +801,7 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { // specify the format of the encapsulated bitstream. { AUDIO_FORMAT_IEC61937, - make_AudioFormatDescription(media::PcmType::INT_16_BIT, MEDIA_MIMETYPE_AUDIO_IEC61937) + make_AudioFormatDescription(PcmType::INT_16_BIT, MEDIA_MIMETYPE_AUDIO_IEC61937) }, { AUDIO_FORMAT_DOLBY_TRUEHD, @@ -984,7 +988,7 @@ const detail::AudioFormatPairs& getAudioFormatPairs() { }, { AUDIO_FORMAT_IEC60958, - make_AudioFormatDescription(media::PcmType::INT_24_BIT, MEDIA_MIMETYPE_AUDIO_IEC60958) + make_AudioFormatDescription(PcmType::INT_24_BIT, MEDIA_MIMETYPE_AUDIO_IEC60958) }, { AUDIO_FORMAT_DTS_UHD, make_AudioFormatDescription(MEDIA_MIMETYPE_AUDIO_DTS_UHD) @@ -1028,14 +1032,14 @@ std::unordered_map make_ReverseMap(const std::vector>& v) } // namespace ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isInput) { - using ReverseMap = std::unordered_map; - using Tag = media::AudioChannelLayout::Tag; + const AudioChannelLayout& aidl, bool isInput) { + using ReverseMap = std::unordered_map; + using Tag = AudioChannelLayout::Tag; static const ReverseMap mIn = make_ReverseMap(getInAudioChannelPairs()); static const ReverseMap mOut = make_ReverseMap(getOutAudioChannelPairs()); static const ReverseMap mVoice = make_ReverseMap(getVoiceAudioChannelPairs()); - auto convert = [](const media::AudioChannelLayout& aidl, const ReverseMap& m, + auto convert = [](const AudioChannelLayout& aidl, const ReverseMap& m, const char* func, const char* type) -> ConversionResult { if (auto it = m.find(aidl); it != m.end()) { return it->second; @@ -1073,16 +1077,16 @@ ConversionResult aidl2legacy_AudioChannelLayout_audio_chan return unexpected(BAD_VALUE); } -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( audio_channel_mask_t legacy, bool isInput) { - using DirectMap = std::unordered_map; - using Tag = media::AudioChannelLayout::Tag; + using DirectMap = std::unordered_map; + using Tag = AudioChannelLayout::Tag; static const DirectMap mInAndVoice = make_DirectMap( getInAudioChannelPairs(), getVoiceAudioChannelPairs()); static const DirectMap mOut = make_DirectMap(getOutAudioChannelPairs()); auto convert = [](const audio_channel_mask_t legacy, const DirectMap& m, - const char* func, const char* type) -> ConversionResult { + const char* func, const char* type) -> ConversionResult { if (auto it = m.find(legacy); it != m.end()) { return it->second; } else { @@ -1093,9 +1097,9 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud }; if (legacy == AUDIO_CHANNEL_NONE) { - return media::AudioChannelLayout{}; + return AudioChannelLayout{}; } else if (legacy == AUDIO_CHANNEL_INVALID) { - return media::AudioChannelLayout::make(0); + return AudioChannelLayout::make(0); } const audio_channel_representation_t repr = audio_channel_mask_get_representation(legacy); @@ -1103,7 +1107,7 @@ ConversionResult legacy2aidl_audio_channel_mask_t_Aud if (audio_channel_mask_is_valid(legacy)) { const int indexMask = VALUE_OR_RETURN( convertIntegral(audio_channel_mask_get_bits(legacy))); - return media::AudioChannelLayout::make(indexMask); + return AudioChannelLayout::make(indexMask); } else { ALOGE("%s: legacy audio_channel_mask_t value 0x%x is invalid", __func__, legacy); return unexpected(BAD_VALUE); @@ -1144,8 +1148,8 @@ ConversionResult legacy2aidl_audio_devices_t_Audi } ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( - const media::AudioFormatDescription& aidl) { - static const std::unordered_map m = + const AudioFormatDescription& aidl) { + static const std::unordered_map m = make_ReverseMap(getAudioFormatPairs()); if (auto it = m.find(aidl); it != m.end()) { return it->second; @@ -1155,9 +1159,9 @@ ConversionResult aidl2legacy_AudioFormatDescription_audio_format } } -ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( +ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( audio_format_t legacy) { - static const std::unordered_map m = + static const std::unordered_map m = make_DirectMap(getAudioFormatPairs()); if (auto it = m.find(legacy); it != m.end()) { return it->second; @@ -2684,7 +2688,7 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isI } RETURN_IF_ERROR( convertRange(aidl.channelMasks.begin(), aidl.channelMasks.end(), legacy.channel_masks, - [isInput](const media::AudioChannelLayout& l) { + [isInput](const AudioChannelLayout& l) { return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); })); legacy.num_channel_masks = aidl.channelMasks.size(); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 048aca206a..471b15c159 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -51,6 +51,7 @@ cc_library_shared { "PolicyAidlConversion.cpp" ], shared_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", @@ -71,6 +72,7 @@ cc_library_shared { include_dirs: ["system/media/audio_utils/include"], export_include_dirs: ["include"], export_shared_lib_headers: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", @@ -111,6 +113,7 @@ cc_library { "TrackPlayerBase.cpp", ], shared_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", @@ -228,6 +231,7 @@ cc_library { "libaudioclient_aidl_conversion_util", ], shared_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libbase", "libbinder", @@ -239,6 +243,7 @@ cc_library { "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libbase", "shared-file-region-aidl-cpp", @@ -307,7 +312,6 @@ aidl_interface { local_include_dir: "aidl", srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", - "aidl/android/media/AudioChannelLayout.aidl", "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioConfig.aidl", "aidl/android/media/AudioConfigBase.aidl", @@ -319,8 +323,6 @@ aidl_interface { "aidl/android/media/AudioEncapsulationMode.aidl", "aidl/android/media/AudioEncapsulationMetadataType.aidl", "aidl/android/media/AudioEncapsulationType.aidl", - "aidl/android/media/AudioFormatDescription.aidl", - "aidl/android/media/AudioFormatType.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", "aidl/android/media/AudioGainConfig.aidl", @@ -360,7 +362,6 @@ aidl_interface { "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", "aidl/android/media/ExtraAudioDescriptor.aidl", - "aidl/android/media/PcmType.aidl", "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ @@ -407,6 +408,7 @@ aidl_interface { "aidl/android/media/SpatializationLevel.aidl", ], imports: [ + "android.media.audio.common.types", "audioclient-types-aidl", ], backend: { @@ -449,6 +451,7 @@ aidl_interface { "aidl/android/media/IAudioTrackCallback.aidl", ], imports: [ + "android.media.audio.common.types", "audioclient-types-aidl", "av-types-aidl", "effect-aidl", @@ -486,6 +489,7 @@ aidl_interface { "aidl/android/media/IAudioPolicyServiceClient.aidl", ], imports: [ + "android.media.audio.common.types", "audioclient-types-aidl", "audiopolicy-types-aidl", "capture_state_listener-aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 65bf97ddad..057befdc4d 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -51,8 +51,9 @@ namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; +using content::AttributionSourceState; using media::IAudioPolicyService; -using android::content::AttributionSourceState; +using media::audio::common::AudioFormatDescription; // client singleton for AudioFlinger binder interface Mutex AudioSystem::gLock; @@ -1877,7 +1878,7 @@ status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats, media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; std::vector surroundFormatsEnabledAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl, @@ -1904,7 +1905,7 @@ status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormat media::Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); - std::vector surroundFormatsAidl; + std::vector surroundFormatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getReportedSurroundFormats(&numSurroundFormatsAidl, &surroundFormatsAidl))); @@ -1920,7 +1921,7 @@ status_t AudioSystem::setSurroundFormatEnabled(audio_format_t audioFormat, bool const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::AudioFormatDescription audioFormatAidl = VALUE_OR_RETURN_STATUS( + AudioFormatDescription audioFormatAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormatDescription(audioFormat)); return statusTFromBinderStatus( aps->setSurroundFormatEnabled(audioFormatAidl, enabled)); @@ -1982,7 +1983,7 @@ status_t AudioSystem::getHwOffloadEncodingFormatsSupportedForA2DP( & aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - std::vector formatsAidl; + std::vector formatsAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getHwOffloadEncodingFormatsSupportedForA2DP(&formatsAidl))); *formats = VALUE_OR_RETURN_STATUS( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 6d2ec9352f..ee6489430b 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -30,6 +30,8 @@ namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; +using media::audio::common::AudioChannelLayout; +using media::audio::common::AudioFormatDescription; #define MAX_ITEMS_PER_LIST 1024 @@ -252,7 +254,7 @@ uint32_t AudioFlingerClientAdapter::sampleRate(audio_io_handle_t ioHandle) const audio_format_t AudioFlingerClientAdapter::format(audio_io_handle_t output) const { auto result = [&]() -> ConversionResult { int32_t outputAidl = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(output)); - media::AudioFormatDescription aidlRet; + AudioFormatDescription aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus(mDelegate->format(outputAidl, &aidlRet))); return aidl2legacy_AudioFormatDescription_audio_format_t(aidlRet); }(); @@ -420,9 +422,9 @@ size_t AudioFlingerClientAdapter::getInputBufferSize(uint32_t sampleRate, audio_ audio_channel_mask_t channelMask) const { auto result = [&]() -> ConversionResult { int32_t sampleRateAidl = VALUE_OR_RETURN(convertIntegral(sampleRate)); - media::AudioFormatDescription formatAidl = VALUE_OR_RETURN( + AudioFormatDescription formatAidl = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(format)); - media::AudioChannelLayout channelMaskAidl = VALUE_OR_RETURN( + AudioChannelLayout channelMaskAidl = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(channelMask, true /*isInput*/)); int64_t aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -820,7 +822,7 @@ Status AudioFlingerServerAdapter::sampleRate(int32_t ioHandle, int32_t* _aidl_re } Status AudioFlingerServerAdapter::format(int32_t output, - media::AudioFormatDescription* _aidl_return) { + AudioFormatDescription* _aidl_return) { audio_io_handle_t outputLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_int32_t_audio_io_handle_t(output)); *_aidl_return = VALUE_OR_RETURN_BINDER( @@ -948,8 +950,8 @@ Status AudioFlingerServerAdapter::registerClient(const sp(sampleRate)); audio_format_t formatLegacy = VALUE_OR_RETURN_BINDER( diff --git a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl b/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl deleted file mode 100644 index 32591055ae..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioChannelLayout.aidl +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * This structure describes a layout of a multi-channel stream. - * There are two possible ways for representing a layout: - * - * - indexed mask, which tells what channels of an audio frame are used, but - * doesn't label them in any way, thus a correspondence between channels in - * the same position of frames originating from different streams must be - * established externally; - * - * - layout mask, which gives a label to each channel, thus allowing to - * match channels between streams of different layouts. - * - * Both representations are agnostic of the direction of audio transfer. Also, - * by construction, the number of bits set to '1' in the mask indicates the - * number of channels in the audio frame. A channel mask per se only defines the - * presence or absence of a channel, not the order. Please see 'INTERLEAVE_*' - * constants for the platform convention of order. - * - * The structure also defines a "voice mask" which is a special case of - * layout mask, intended for processing voice audio from telecommunication - * use cases. - */ -union AudioChannelLayout { - /** - * This variant is used for representing the "null" ("none") value - * for the channel layout. The field value must always be '0'. - */ - int none = 0; - /** - * This variant is used for indicating an "invalid" layout for use by the - * framework only. HAL implementations must not accept or emit - * AudioChannelLayout values for this variant. The field value must always - * be '0'. - */ - int invalid = 0; - /** - * This variant is used for representing indexed masks. The mask indicates - * what channels are used. For example, the mask that specifies to use only - * channels 1 and 3 when interacting with a multi-channel device is defined - * as a combination of the 1st and the 3rd bits and thus is equal to 5. See - * also the 'INDEX_MASK_*' constants. The 'indexMask' field must have at - * least one bit set. - */ - int indexMask; - /** - * This variant is used for representing layout masks. - * It is recommended to use one of 'LAYOUT_*' values. The 'layoutMask' field - * must have at least one bit set. - */ - int layoutMask; - /** - * This variant is used for processing of voice audio input and output. - * It is recommended to use one of 'VOICE_*' values. The 'voiceMask' field - * must have at least one bit set. - */ - int voiceMask; - - /** - * 'INDEX_MASK_*' constants define how many channels are used. - * The mask constants below are 'canonical' masks. Each 'INDEX_MASK_N' - * constant declares that all N channels are used and arranges - * them starting from the LSB. - */ - const int INDEX_MASK_1 = (1 << 1) - 1; - const int INDEX_MASK_2 = (1 << 2) - 1; - const int INDEX_MASK_3 = (1 << 3) - 1; - const int INDEX_MASK_4 = (1 << 4) - 1; - const int INDEX_MASK_5 = (1 << 5) - 1; - const int INDEX_MASK_6 = (1 << 6) - 1; - const int INDEX_MASK_7 = (1 << 7) - 1; - const int INDEX_MASK_8 = (1 << 8) - 1; - const int INDEX_MASK_9 = (1 << 9) - 1; - const int INDEX_MASK_10 = (1 << 10) - 1; - const int INDEX_MASK_11 = (1 << 11) - 1; - const int INDEX_MASK_12 = (1 << 12) - 1; - const int INDEX_MASK_13 = (1 << 13) - 1; - const int INDEX_MASK_14 = (1 << 14) - 1; - const int INDEX_MASK_15 = (1 << 15) - 1; - const int INDEX_MASK_16 = (1 << 16) - 1; - const int INDEX_MASK_17 = (1 << 17) - 1; - const int INDEX_MASK_18 = (1 << 18) - 1; - const int INDEX_MASK_19 = (1 << 19) - 1; - const int INDEX_MASK_20 = (1 << 20) - 1; - const int INDEX_MASK_21 = (1 << 21) - 1; - const int INDEX_MASK_22 = (1 << 22) - 1; - const int INDEX_MASK_23 = (1 << 23) - 1; - const int INDEX_MASK_24 = (1 << 24) - 1; - - /** - * 'LAYOUT_*' constants define channel layouts recognized by - * the audio system. The order of the channels in the frame is assumed - * to be from the LSB to MSB for all the bits set to '1'. - */ - const int LAYOUT_MONO = CHANNEL_FRONT_LEFT; - const int LAYOUT_STEREO = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT; - const int LAYOUT_2POINT1 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_LOW_FREQUENCY; - const int LAYOUT_TRI = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_FRONT_CENTER; - const int LAYOUT_TRI_BACK = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_BACK_CENTER; - const int LAYOUT_3POINT1 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | CHANNEL_FRONT_CENTER | - CHANNEL_LOW_FREQUENCY; - const int LAYOUT_2POINT0POINT2 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; - const int LAYOUT_2POINT1POINT2 = - LAYOUT_2POINT0POINT2 | CHANNEL_LOW_FREQUENCY; - const int LAYOUT_3POINT0POINT2 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; - const int LAYOUT_3POINT1POINT2 = - LAYOUT_3POINT0POINT2 | CHANNEL_LOW_FREQUENCY; - const int LAYOUT_QUAD = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT; - const int LAYOUT_QUAD_SIDE = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; - const int LAYOUT_SURROUND = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER; - const int LAYOUT_PENTA = LAYOUT_QUAD | CHANNEL_FRONT_CENTER; - const int LAYOUT_5POINT1 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | - CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT; - const int LAYOUT_5POINT1_SIDE = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | - CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; - const int LAYOUT_5POINT1POINT2 = LAYOUT_5POINT1 | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; - const int LAYOUT_5POINT1POINT4 = LAYOUT_5POINT1 | - CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | - CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT; - const int LAYOUT_6POINT1 = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | - CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT | CHANNEL_BACK_CENTER; - const int LAYOUT_7POINT1 = LAYOUT_5POINT1 | - CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT; - const int LAYOUT_7POINT1POINT2 = LAYOUT_7POINT1 | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; - const int LAYOUT_7POINT1POINT4 = LAYOUT_7POINT1 | - CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | - CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT; - const int LAYOUT_9POINT1POINT4 = LAYOUT_7POINT1POINT4 | - CHANNEL_FRONT_WIDE_LEFT | CHANNEL_FRONT_WIDE_RIGHT; - const int LAYOUT_9POINT1POINT6 = LAYOUT_9POINT1POINT4 | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT; - const int LAYOUT_13POINT_360RA = - CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT | - CHANNEL_FRONT_CENTER | - CHANNEL_SIDE_LEFT | CHANNEL_SIDE_RIGHT | - CHANNEL_TOP_FRONT_LEFT | CHANNEL_TOP_FRONT_RIGHT | - CHANNEL_TOP_FRONT_CENTER | - CHANNEL_TOP_BACK_LEFT | CHANNEL_TOP_BACK_RIGHT | - CHANNEL_BOTTOM_FRONT_LEFT | CHANNEL_BOTTOM_FRONT_RIGHT | - CHANNEL_BOTTOM_FRONT_CENTER; - const int LAYOUT_22POINT2 = LAYOUT_7POINT1POINT4 | - CHANNEL_FRONT_LEFT_OF_CENTER | CHANNEL_FRONT_RIGHT_OF_CENTER | - CHANNEL_BACK_CENTER | CHANNEL_TOP_CENTER | - CHANNEL_TOP_FRONT_CENTER | CHANNEL_TOP_BACK_CENTER | - CHANNEL_TOP_SIDE_LEFT | CHANNEL_TOP_SIDE_RIGHT | - CHANNEL_BOTTOM_FRONT_LEFT | CHANNEL_BOTTOM_FRONT_RIGHT | - CHANNEL_BOTTOM_FRONT_CENTER | - CHANNEL_LOW_FREQUENCY_2; - const int LAYOUT_MONO_HAPTIC_A = - LAYOUT_MONO | CHANNEL_HAPTIC_A; - const int LAYOUT_STEREO_HAPTIC_A = - LAYOUT_STEREO | CHANNEL_HAPTIC_A; - const int LAYOUT_HAPTIC_AB = - CHANNEL_HAPTIC_A | CHANNEL_HAPTIC_B; - const int LAYOUT_MONO_HAPTIC_AB = - LAYOUT_MONO | LAYOUT_HAPTIC_AB; - const int LAYOUT_STEREO_HAPTIC_AB = - LAYOUT_STEREO | LAYOUT_HAPTIC_AB; - const int LAYOUT_FRONT_BACK = - CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER; - - /** - * Expresses the convention when stereo audio samples are stored interleaved - * in an array. This should improve readability by allowing code to use - * symbolic indices instead of hard-coded [0] and [1]. - * - * For multi-channel beyond stereo, the platform convention is that channels - * are interleaved in order from least significant channel mask bit to most - * significant channel mask bit, with unused bits skipped. Any exceptions - * to this convention will be noted at the appropriate API. - */ - const int INTERLEAVE_LEFT = 0; - const int INTERLEAVE_RIGHT = 1; - - /** - * 'CHANNEL_*' constants are used to build 'LAYOUT_*' masks. Each constant - * must have exactly one bit set. The values do not match - * 'android.media.AudioFormat.CHANNEL_OUT_*' constants from the SDK - * for better efficiency in masks processing. - */ - const int CHANNEL_FRONT_LEFT = 1 << 0; - const int CHANNEL_FRONT_RIGHT = 1 << 1; - const int CHANNEL_FRONT_CENTER = 1 << 2; - const int CHANNEL_LOW_FREQUENCY = 1 << 3; - const int CHANNEL_BACK_LEFT = 1 << 4; - const int CHANNEL_BACK_RIGHT = 1 << 5; - const int CHANNEL_FRONT_LEFT_OF_CENTER = 1 << 6; - const int CHANNEL_FRONT_RIGHT_OF_CENTER = 1 << 7; - const int CHANNEL_BACK_CENTER = 1 << 8; - const int CHANNEL_SIDE_LEFT = 1 << 9; - const int CHANNEL_SIDE_RIGHT = 1 << 10; - const int CHANNEL_TOP_CENTER = 1 << 11; - const int CHANNEL_TOP_FRONT_LEFT = 1 << 12; - const int CHANNEL_TOP_FRONT_CENTER = 1 << 13; - const int CHANNEL_TOP_FRONT_RIGHT = 1 << 14; - const int CHANNEL_TOP_BACK_LEFT = 1 << 15; - const int CHANNEL_TOP_BACK_CENTER = 1 << 16; - const int CHANNEL_TOP_BACK_RIGHT = 1 << 17; - const int CHANNEL_TOP_SIDE_LEFT = 1 << 18; - const int CHANNEL_TOP_SIDE_RIGHT = 1 << 19; - const int CHANNEL_BOTTOM_FRONT_LEFT = 1 << 20; - const int CHANNEL_BOTTOM_FRONT_CENTER = 1 << 21; - const int CHANNEL_BOTTOM_FRONT_RIGHT = 1 << 22; - const int CHANNEL_LOW_FREQUENCY_2 = 1 << 23; - const int CHANNEL_FRONT_WIDE_LEFT = 1 << 24; - const int CHANNEL_FRONT_WIDE_RIGHT = 1 << 25; - /** - * Haptic channels are not part of multichannel standards, however they - * enhance user experience when playing so they are packed together with the - * channels of the program. To avoid collision with positional channels the - * values for haptic channels start at the MSB of an integer (after the sign - * bit) and move down to LSB. - */ - const int CHANNEL_HAPTIC_B = 1 << 29; - const int CHANNEL_HAPTIC_A = 1 << 30; - - /** - * 'VOICE_*' constants define layouts for voice audio. The order of the - * channels in the frame is assumed to be from the LSB to MSB for all the - * bits set to '1'. - */ - const int VOICE_UPLINK_MONO = CHANNEL_VOICE_UPLINK; - const int VOICE_DNLINK_MONO = CHANNEL_VOICE_DNLINK; - const int VOICE_CALL_MONO = CHANNEL_VOICE_UPLINK | CHANNEL_VOICE_DNLINK; - - /** - * 'CHANNEL_VOICE_*' constants are used to build 'VOICE_*' masks. Each - * constant must have exactly one bit set. Use the same values as - * 'android.media.AudioFormat.CHANNEL_IN_VOICE_*' constants from the SDK. - */ - const int CHANNEL_VOICE_UPLINK = 0x4000; - const int CHANNEL_VOICE_DNLINK = 0x8000; -} diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl index 6996d4276f..aea7a3430e 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfig.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioChannelLayout; -import android.media.AudioFormatDescription; import android.media.AudioOffloadInfo; +import android.media.audio.common.AudioChannelLayout; +import android.media.audio.common.AudioFormatDescription; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl index e84161bce5..54b1780d20 100644 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioChannelLayout; -import android.media.AudioFormatDescription; +import android.media.audio.common.AudioChannelLayout; +import android.media.audio.common.AudioFormatDescription; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl b/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl deleted file mode 100644 index a6563485f6..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioFormatDescription.aidl +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioFormatType; -import android.media.PcmType; - -/** - * An extensible type for specifying audio formats. All formats are largely - * divided into two classes: PCM and non-PCM (bitstreams). Bitstreams can - * be encapsulated into PCM streams. - * - * The type defined in a way to make each format uniquely identifiable, so - * that if the framework and the HAL construct a value for the same type - * (e.g. PCM 16 bit), they will produce identical parcelables which will have - * identical hashes. This makes possible deduplicating type descriptions - * by the framework when they are received from different HAL modules without - * relying on having some centralized registry of enumeration values. - * - * {@hide} - */ -parcelable AudioFormatDescription { - /** - * The type of the audio format. See the 'AudioFormatType' for the - * list of supported values. - */ - AudioFormatType type = AudioFormatType.DEFAULT; - /** - * The type of the PCM stream or the transport stream for PCM - * encapsulations. See 'PcmType' for the list of supported values. - */ - PcmType pcm = PcmType.DEFAULT; - /** - * Optional encoding specification. Must be left empty when: - * - * - 'type == DEFAULT && pcm == DEFAULT' -- that means "default" type; - * - 'type == PCM' -- that means a regular PCM stream (not an encapsulation - * of an encoded bitstream). - * - * For PCM encapsulations of encoded bitstreams (e.g. an encapsulation - * according to IEC-61937 standard), the value of the 'pcm' field must - * be set accordingly, as an example, PCM_INT_16_BIT must be used for - * IEC-61937. Note that 'type == NON_PCM' in this case. - * - * Encoding names mostly follow IANA standards for media types (MIME), and - * frameworks/av/media/libstagefright/foundation/MediaDefs.cpp with the - * latter having priority. Since there are still many audio types not found - * in any of these lists, the following rules are applied: - * - * - If there is a direct MIME type for the encoding, the MIME type name - * is used as is, e.g. "audio/eac3" for the EAC-3 format. - * - If the encoding is a "subformat" of a MIME-registered format, - * the latter is augmented with a suffix, e.g. "audio/eac3-joc" for the - * JOC extension of EAC-3. - * - If it's a proprietary format, a "vnd." prefix is added, similar to - * IANA rules, e.g. "audio/vnd.dolby.truehd". - * - Otherwise, "x-" prefix is added, e.g. "audio/x-iec61937". - * - All MIME types not found in the IANA formats list have an associated - * comment. - * - * For PCM encapsulations with a known bitstream format, the latter - * is added to the encapsulation encoding as a suffix, after a "+" char. - * For example, an IEC61937 encapsulation of AC3 has the following - * representation: - * type = NON_PCM, - * pcm = PcmType.INT_16_BIT, - * encoding = "audio/x-iec61937+audio/ac3" - */ - @utf8InCpp String encoding; -} diff --git a/media/libaudioclient/aidl/android/media/AudioFormatType.aidl b/media/libaudioclient/aidl/android/media/AudioFormatType.aidl deleted file mode 100644 index 31ed2be376..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioFormatType.aidl +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * The type of the audio format. Only used as part of 'AudioFormatDescription' - * structure. - */ -@Backing(type="byte") -enum AudioFormatType { - /** - * "Default" type is used when the client does not care about the actual - * format. All fields of 'AudioFormatDescription' must have default / empty - * / null values. - */ - DEFAULT = 0, - /** - * When the 'encoding' field of 'AudioFormatDescription' is not empty, it - * specifies the codec used for bitstream (non-PCM) data. It is also used - * in the case when the bitstream data is encapsulated into a PCM stream, - * see the documentation for 'AudioFormatDescription'. - */ - NON_PCM = DEFAULT, - /** - * PCM type. The 'pcm' field of 'AudioFormatDescription' is used to specify - * the actual sample size and representation. - */ - PCM = 1, - /** - * Value reserved for system use only. HALs must never return this value to - * the system or accept it from the system. - */ - SYS_RESERVED_INVALID = -1, -} diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl index 4cfa96e44a..ff85b50399 100644 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGain.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.audio.common.AudioChannelLayout; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl index afa3aca3f3..f60c461318 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioChannelLayout; +import android.media.audio.common.AudioChannelLayout; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl index efdf99b699..b01f902760 100644 --- a/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioIoDescriptor.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioChannelLayout; -import android.media.AudioFormatDescription; import android.media.AudioPatch; +import android.media.audio.common.AudioChannelLayout; +import android.media.audio.common.AudioFormatDescription; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index be32a69e91..3908cb1a5d 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,14 +16,14 @@ package android.media; -import android.media.AudioChannelLayout; import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; import android.media.AudioPortConfigType; import android.media.AudioPortRole; import android.media.AudioPortType; -import android.media.AudioFormatDescription; +import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioChannelLayout; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 9fb8d494e5..3e234de990 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioChannelLayout; import android.media.AudioEncapsulationType; -import android.media.AudioFormatDescription; +import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioChannelLayout; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 16f70c133e..7b02a9db7a 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,7 +16,6 @@ package android.media; -import android.media.AudioChannelLayout; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -42,7 +41,8 @@ import android.media.IAudioTrack; import android.media.MicrophoneInfoData; import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; -import android.media.AudioFormatDescription; +import android.media.audio.common.AudioChannelLayout; +import android.media.audio.common.AudioFormatDescription; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 7022b9d715..74bfa05a08 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -16,7 +16,6 @@ package android.media; -import android.media.AudioFormatDescription; import android.content.AttributionSourceState; import android.media.AudioAttributesEx; @@ -53,6 +52,7 @@ import android.media.ICaptureStateListener; import android.media.INativeSpatializerCallback; import android.media.Int; import android.media.SoundTriggerSession; +import android.media.audio.common.AudioFormatDescription; /** * IAudioPolicyService interface (see AudioPolicyInterface for method descriptions). diff --git a/media/libaudioclient/aidl/android/media/PcmType.aidl b/media/libaudioclient/aidl/android/media/PcmType.aidl deleted file mode 100644 index c9e327cb71..0000000000 --- a/media/libaudioclient/aidl/android/media/PcmType.aidl +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * The type of the encoding used for representing PCM samples. Only used as - * part of 'AudioFormatDescription' structure. - */ -@Backing(type="byte") -enum PcmType { - /** - * "Default" value used when the type 'AudioFormatDescription' is "default". - */ - DEFAULT = 0, - /** - * Unsigned 8-bit integer. - */ - UINT_8_BIT = DEFAULT, - /** - * Signed 16-bit integer. - */ - INT_16_BIT = 1, - /** - * Signed 32-bit integer. - */ - INT_32_BIT = 2, - /** - * Q8.24 fixed point format. - */ - FIXED_Q_8_24 = 3, - /** - * IEEE 754 32-bit floating point format. - */ - FLOAT_32_BIT = 4, - /** - * Signed 24-bit integer. - */ - INT_24_BIT = 5, -} diff --git a/media/libaudioclient/fuzzer/Android.bp b/media/libaudioclient/fuzzer/Android.bp index b290aa82e8..969e3e677d 100644 --- a/media/libaudioclient/fuzzer/Android.bp +++ b/media/libaudioclient/fuzzer/Android.bp @@ -46,6 +46,7 @@ cc_fuzz { ], shared_libs: [ "android.hardware.audio.common-util", + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 2cf127c373..7e87a4e3e9 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -22,7 +22,6 @@ #include #include -#include #include #include #include @@ -32,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -54,6 +52,8 @@ #include #include #include +#include +#include #include #include @@ -132,9 +132,9 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const media::AudioChannelLayout& aidl, bool isInput); -ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - audio_channel_mask_t legacy, bool isInput); + const android::media::audio::common::AudioChannelLayout& aidl, bool isInput); +ConversionResult +legacy2aidl_audio_channel_mask_t_AudioChannelLayout(audio_channel_mask_t legacy, bool isInput); ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( const media::AudioDeviceDescription& aidl); @@ -142,9 +142,9 @@ ConversionResult legacy2aidl_audio_devices_t_Audi audio_devices_t legacy); ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( - const media::AudioFormatDescription& aidl); -ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription( - audio_format_t legacy); + const media::audio::common::AudioFormatDescription& aidl); +ConversionResult +legacy2aidl_audio_format_t_AudioFormatDescription(audio_format_t legacy); ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl); diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index bd341e3af0..b63f3897ae 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -19,9 +19,9 @@ #include -#include #include -#include +#include +#include #include #include #include @@ -42,10 +42,11 @@ namespace std { // possibility of processing types belonging to different versions of the type, // e.g. a HAL may be using a previous version of the AIDL interface. -template<> struct hash +template<> struct hash { - std::size_t operator()(const android::media::AudioChannelLayout& acl) const noexcept { - using Tag = android::media::AudioChannelLayout::Tag; + std::size_t operator()( + const android::media::audio::common::AudioChannelLayout& acl) const noexcept { + using Tag = android::media::audio::common::AudioChannelLayout::Tag; const size_t seed = std::hash{}(acl.getTag()); switch (acl.getTag()) { case Tag::none: @@ -72,13 +73,14 @@ template<> struct hash } }; -template<> struct hash +template<> struct hash { - std::size_t operator()(const android::media::AudioFormatDescription& afd) const noexcept { + std::size_t operator()( + const android::media::audio::common::AudioFormatDescription& afd) const noexcept { return hash_combine( - std::hash{}(afd.type), + std::hash{}(afd.type), hash_combine( - std::hash{}(afd.pcm), + std::hash{}(afd.pcm), std::hash{}(afd.encoding))); } }; diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index a2ce145e74..a74661acfb 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -570,7 +570,8 @@ public: Status createRecord(const media::CreateRecordRequest& request, media::CreateRecordResponse* _aidl_return) override; Status sampleRate(int32_t ioHandle, int32_t* _aidl_return) override; - Status format(int32_t output, media::AudioFormatDescription* _aidl_return) override; + Status format(int32_t output, + media::audio::common::AudioFormatDescription* _aidl_return) override; Status frameCount(int32_t ioHandle, int64_t* _aidl_return) override; Status latency(int32_t output, int32_t* _aidl_return) override; Status setMasterVolume(float value) override; @@ -592,8 +593,9 @@ public: Status getParameters(int32_t ioHandle, const std::string& keys, std::string* _aidl_return) override; Status registerClient(const sp& client) override; - Status getInputBufferSize(int32_t sampleRate, const media::AudioFormatDescription& format, - const media::AudioChannelLayout& channelMask, + Status getInputBufferSize(int32_t sampleRate, + const media::audio::common::AudioFormatDescription& format, + const media::audio::common::AudioChannelLayout& channelMask, int64_t* _aidl_return) override; Status openOutput(const media::OpenOutputRequest& request, media::OpenOutputResponse* _aidl_return) override; diff --git a/media/libaudioclient/tests/Android.bp b/media/libaudioclient/tests/Android.bp index 2279244f8b..891293e6cf 100644 --- a/media/libaudioclient/tests/Android.bp +++ b/media/libaudioclient/tests/Android.bp @@ -33,6 +33,7 @@ cc_test { "libutils", ], static_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", "libstagefright_foundation", diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index 424b387f42..253ccac26a 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -22,38 +22,43 @@ using namespace android; using namespace android::aidl_utils; +using media::audio::common::AudioChannelLayout; +using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioFormatType; +using media::audio::common::PcmType; + namespace { template size_t hash(const T& t) { return std::hash{}(t); } -media::AudioChannelLayout make_ACL_None() { - return media::AudioChannelLayout{}; +AudioChannelLayout make_ACL_None() { + return AudioChannelLayout{}; } -media::AudioChannelLayout make_ACL_Invalid() { - return media::AudioChannelLayout::make(0); +AudioChannelLayout make_ACL_Invalid() { + return AudioChannelLayout::make(0); } -media::AudioChannelLayout make_ACL_Stereo() { - return media::AudioChannelLayout::make( - media::AudioChannelLayout::LAYOUT_STEREO); +AudioChannelLayout make_ACL_Stereo() { + return AudioChannelLayout::make( + AudioChannelLayout::LAYOUT_STEREO); } -media::AudioChannelLayout make_ACL_ChannelIndex2() { - return media::AudioChannelLayout::make( - media::AudioChannelLayout::INDEX_MASK_2); +AudioChannelLayout make_ACL_ChannelIndex2() { + return AudioChannelLayout::make( + AudioChannelLayout::INDEX_MASK_2); } -media::AudioChannelLayout make_ACL_ChannelIndexArbitrary() { +AudioChannelLayout make_ACL_ChannelIndexArbitrary() { // Use channels 1 and 3. - return media::AudioChannelLayout::make(5); + return AudioChannelLayout::make(5); } -media::AudioChannelLayout make_ACL_VoiceCall() { - return media::AudioChannelLayout::make( - media::AudioChannelLayout::VOICE_CALL_MONO); +AudioChannelLayout make_ACL_VoiceCall() { + return AudioChannelLayout::make( + AudioChannelLayout::VOICE_CALL_MONO); } media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, @@ -86,52 +91,52 @@ media::AudioDeviceDescription make_ADD_BtScoHeadset() { media::AudioDeviceDescription::CONNECTION_BT_SCO()); } -media::AudioFormatDescription make_AudioFormatDescription(media::AudioFormatType type) { - media::AudioFormatDescription result; +AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) { + AudioFormatDescription result; result.type = type; return result; } -media::AudioFormatDescription make_AudioFormatDescription(media::PcmType pcm) { - auto result = make_AudioFormatDescription(media::AudioFormatType::PCM); +AudioFormatDescription make_AudioFormatDescription(PcmType pcm) { + auto result = make_AudioFormatDescription(AudioFormatType::PCM); result.pcm = pcm; return result; } -media::AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { - media::AudioFormatDescription result; +AudioFormatDescription make_AudioFormatDescription(const std::string& encoding) { + AudioFormatDescription result; result.encoding = encoding; return result; } -media::AudioFormatDescription make_AudioFormatDescription(media::PcmType transport, +AudioFormatDescription make_AudioFormatDescription(PcmType transport, const std::string& encoding) { auto result = make_AudioFormatDescription(encoding); result.pcm = transport; return result; } -media::AudioFormatDescription make_AFD_Default() { - return media::AudioFormatDescription{}; +AudioFormatDescription make_AFD_Default() { + return AudioFormatDescription{}; } -media::AudioFormatDescription make_AFD_Invalid() { - return make_AudioFormatDescription(media::AudioFormatType::SYS_RESERVED_INVALID); +AudioFormatDescription make_AFD_Invalid() { + return make_AudioFormatDescription(AudioFormatType::SYS_RESERVED_INVALID); } -media::AudioFormatDescription make_AFD_Pcm16Bit() { - return make_AudioFormatDescription(media::PcmType::INT_16_BIT); +AudioFormatDescription make_AFD_Pcm16Bit() { + return make_AudioFormatDescription(PcmType::INT_16_BIT); } -media::AudioFormatDescription make_AFD_Bitstream() { +AudioFormatDescription make_AFD_Bitstream() { return make_AudioFormatDescription("example"); } -media::AudioFormatDescription make_AFD_Encap() { - return make_AudioFormatDescription(media::PcmType::INT_16_BIT, "example.encap"); +AudioFormatDescription make_AFD_Encap() { + return make_AudioFormatDescription(PcmType::INT_16_BIT, "example.encap"); } -media::AudioFormatDescription make_AFD_Encap_with_Enc() { +AudioFormatDescription make_AFD_Encap_with_Enc() { auto afd = make_AFD_Encap(); afd.encoding += "+example"; return afd; @@ -160,7 +165,7 @@ class HashIdentityTest : public ::testing::Test { }; TEST_F(HashIdentityTest, AudioChannelLayoutHashIdentity) { - verifyHashIdentity({ + verifyHashIdentity({ make_ACL_None, make_ACL_Invalid, make_ACL_Stereo, make_ACL_ChannelIndex2, make_ACL_ChannelIndexArbitrary, make_ACL_VoiceCall}); } @@ -172,12 +177,12 @@ TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { } TEST_F(HashIdentityTest, AudioFormatDescriptionHashIdentity) { - verifyHashIdentity({ + verifyHashIdentity({ make_AFD_Default, make_AFD_Invalid, make_AFD_Pcm16Bit, make_AFD_Bitstream, make_AFD_Encap, make_AFD_Encap_with_Enc}); } -using ChannelLayoutParam = std::tuple; +using ChannelLayoutParam = std::tuple; class AudioChannelLayoutRoundTripTest : public testing::TestWithParam {}; TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { @@ -192,7 +197,7 @@ TEST_P(AudioChannelLayoutRoundTripTest, Aidl2Legacy2Aidl) { INSTANTIATE_TEST_SUITE_P(AudioChannelLayoutRoundTrip, AudioChannelLayoutRoundTripTest, testing::Combine( - testing::Values(media::AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), + testing::Values(AudioChannelLayout{}, make_ACL_Invalid(), make_ACL_Stereo(), make_ACL_ChannelIndex2(), make_ACL_ChannelIndexArbitrary()), testing::Values(false, true))); INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, @@ -216,7 +221,7 @@ INSTANTIATE_TEST_SUITE_P(AudioDeviceDescriptionRoundTrip, make_ADD_DefaultOut(), make_ADD_WiredHeadset(), make_ADD_BtScoHeadset())); class AudioFormatDescriptionRoundTripTest : - public testing::TestWithParam {}; + public testing::TestWithParam {}; TEST_P(AudioFormatDescriptionRoundTripTest, Aidl2Legacy2Aidl) { const auto initial = GetParam(); auto conv = aidl2legacy_AudioFormatDescription_audio_format_t(initial); @@ -227,4 +232,4 @@ TEST_P(AudioFormatDescriptionRoundTripTest, Aidl2Legacy2Aidl) { } INSTANTIATE_TEST_SUITE_P(AudioFormatDescriptionRoundTrip, AudioFormatDescriptionRoundTripTest, - testing::Values(make_AFD_Invalid(), media::AudioFormatDescription{}, make_AFD_Pcm16Bit())); + testing::Values(make_AFD_Invalid(), AudioFormatDescription{}, make_AFD_Pcm16Bit())); diff --git a/media/libaudiofoundation/Android.bp b/media/libaudiofoundation/Android.bp index 3bef55b3ab..727b86f4ae 100644 --- a/media/libaudiofoundation/Android.bp +++ b/media/libaudiofoundation/Android.bp @@ -24,9 +24,11 @@ cc_library_headers { "libmedia_helper_headers", ], static_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", ], export_static_lib_headers: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", ], host_supported: true, @@ -52,6 +54,7 @@ cc_library { ], shared_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", "libaudioutils", @@ -63,6 +66,7 @@ cc_library { ], export_shared_lib_headers: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", ], diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index 47b2d5488e..2d44f4a0c6 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -27,6 +27,8 @@ namespace android { +using media::audio::common::AudioChannelLayout; + bool operator == (const AudioProfile &left, const AudioProfile &right) { return (left.getFormat() == right.getFormat()) && @@ -160,7 +162,7 @@ AudioProfile::toParcelable(bool isInput) const { parcelable.name = mName; parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable.channelMasks = VALUE_OR_RETURN( - convertContainer>( + convertContainer>( mChannelMasks, [isInput](audio_channel_mask_t m) { return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); @@ -184,7 +186,7 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); legacy->mChannelMasks = VALUE_OR_RETURN( convertContainer(parcelable.channelMasks, - [isInput](const media::AudioChannelLayout& l) { + [isInput](const AudioChannelLayout& l) { return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); })); legacy->mSamplingRates = VALUE_OR_RETURN( diff --git a/media/libaudiofoundation/tests/Android.bp b/media/libaudiofoundation/tests/Android.bp index f3cd4468f8..3f1fbea86d 100644 --- a/media/libaudiofoundation/tests/Android.bp +++ b/media/libaudiofoundation/tests/Android.bp @@ -18,6 +18,7 @@ cc_test { ], static_libs: [ + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "libaudioclient_aidl_conversion", "libaudiofoundation", diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp index 9c1b563f6e..4a2523f4c2 100644 --- a/media/libmedia/Android.bp +++ b/media/libmedia/Android.bp @@ -347,6 +347,7 @@ cc_library { shared_libs: [ "android.hidl.token@1.0-utils", + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "av-types-aidl-cpp", "liblog", diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp index b91f302c8e..e4f1b47db8 100644 --- a/services/audioflinger/Android.bp +++ b/services/audioflinger/Android.bp @@ -54,6 +54,7 @@ cc_library_shared { ], shared_libs: [ + "android.media.audio.common.types-V1-cpp", "audioflinger-aidl-cpp", "audioclient-types-aidl-cpp", "av-types-aidl-cpp", diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 8ae0901f31..de1bc377a6 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -44,6 +44,7 @@ cc_library_shared { "libsensorprivacy", "libshmemcompat", "libutils", + "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", "audiopolicy-aidl-cpp", diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 95c1bab771..3ff927d4a6 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -44,6 +44,7 @@ namespace android { using binder::Status; using aidl_utils::binderStatusFromStatusT; using content::AttributionSourceState; +using media::audio::common::AudioFormatDescription; const std::vector& SYSTEM_USAGES = { AUDIO_USAGE_CALL_ASSISTANT, @@ -99,7 +100,7 @@ Status AudioPolicyService::setDeviceConnectionState( const media::AudioDevice& deviceAidl, media::AudioPolicyDeviceState stateAidl, const std::string& deviceNameAidl, - const media::AudioFormatDescription& encodedFormatAidl) { + const AudioFormatDescription& encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS( @@ -149,7 +150,7 @@ Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& de Status AudioPolicyService::handleDeviceConfigChange( const media::AudioDevice& deviceAidl, const std::string& deviceNameAidl, - const media::AudioFormatDescription& encodedFormatAidl) { + const AudioFormatDescription& encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( @@ -1827,7 +1828,7 @@ Status AudioPolicyService::getStreamVolumeDB( } Status AudioPolicyService::getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); @@ -1860,7 +1861,7 @@ Status AudioPolicyService::getSurroundFormats(media::Int* count, } Status AudioPolicyService::getReportedSurroundFormats( - media::Int* count, std::vector* formats) { + media::Int* count, std::vector* formats) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); if (numSurroundFormats > MAX_ITEMS_PER_LIST) { @@ -1887,7 +1888,7 @@ Status AudioPolicyService::getReportedSurroundFormats( } Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) { + std::vector* _aidl_return) { std::vector formats; if (mAudioPolicyManager == NULL) { @@ -1898,14 +1899,14 @@ Status AudioPolicyService::getHwOffloadEncodingFormatsSupportedForA2DP( RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getHwOffloadEncodingFormatsSupportedForA2DP(&formats))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>( + convertContainer>( formats, legacy2aidl_audio_format_t_AudioFormatDescription)); return Status::ok(); } Status AudioPolicyService::setSurroundFormatEnabled( - const media::AudioFormatDescription& audioFormatAidl, bool enabled) { + const AudioFormatDescription& audioFormatAidl, bool enabled) { audio_format_t audioFormat = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioFormatDescription_audio_format_t(audioFormatAidl)); if (mAudioPolicyManager == NULL) { diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 97d4c00375..129c7577ba 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -49,6 +49,7 @@ namespace android { using content::AttributionSourceState; +using media::audio::common::AudioFormatDescription; // ---------------------------------------------------------------------------- @@ -74,13 +75,13 @@ public: const media::AudioDevice& device, media::AudioPolicyDeviceState state, const std::string& deviceName, - const media::AudioFormatDescription& encodedFormat) override; + const AudioFormatDescription& encodedFormat) override; binder::Status getDeviceConnectionState(const media::AudioDevice& device, media::AudioPolicyDeviceState* _aidl_return) override; binder::Status handleDeviceConfigChange( const media::AudioDevice& device, const std::string& deviceName, - const media::AudioFormatDescription& encodedFormat) override; + const AudioFormatDescription& encodedFormat) override; binder::Status setPhoneState(media::AudioMode state, int32_t uid) override; binder::Status setForceUse(media::AudioPolicyForceUse usage, media::AudioPolicyForcedConfig config) override; @@ -199,13 +200,13 @@ public: const media::AudioDeviceDescription& device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, - std::vector* formats, + std::vector* formats, std::vector* formatsEnabled) override; binder::Status getReportedSurroundFormats( - media::Int* count, std::vector* formats) override; + media::Int* count, std::vector* formats) override; binder::Status getHwOffloadEncodingFormatsSupportedForA2DP( - std::vector* _aidl_return) override; - binder::Status setSurroundFormatEnabled(const media::AudioFormatDescription& audioFormat, + std::vector* _aidl_return) override; + binder::Status setSurroundFormatEnabled(const AudioFormatDescription& audioFormat, bool enabled) override; binder::Status setAssistantUid(int32_t uid) override; binder::Status setHotwordDetectionServiceUid(int32_t uid) override; -- GitLab From f6074fe387469e04bf50efaa0a5b3efe0f783393 Mon Sep 17 00:00:00 2001 From: Jasmine Cha Date: Tue, 17 Aug 2021 13:44:31 +0800 Subject: [PATCH 107/694] audio: Exported recommendedMuteDurationMs for output profiles - Added muteDuration to customize mute duration while switching device's path to avoid truncated sound at beginning. - Muted duration will be replaced only when there are defined duration in audio_policy_configuration.xml. Bug: 183344508 Test: manual audio test with different audio_policy_configuration.xml, which is with/without muteDuration definition. Signed-off-by: Jasmine Cha Change-Id: Idced0e256a6b8e91ba2704c5ad89fbf8aba62bf5 --- .../include/AudioOutputDescriptor.h | 4 ++++ .../common/managerdefinitions/include/IOProfile.h | 2 ++ .../managerdefinitions/src/AudioOutputDescriptor.cpp | 9 +++++++++ .../common/managerdefinitions/src/IOProfile.cpp | 1 + .../common/managerdefinitions/src/Serializer.cpp | 8 ++++++++ .../audiopolicy/managerdefault/AudioPolicyManager.cpp | 11 +++++++++-- 6 files changed, 33 insertions(+), 2 deletions(-) diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h index 7c7f02d31c..123011a022 100644 --- a/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h +++ b/services/audiopolicy/common/managerdefinitions/include/AudioOutputDescriptor.h @@ -307,6 +307,8 @@ public: DeviceVector mDevices; /**< current devices this output is routed to */ wp mPolicyMix; // non NULL when used by a dynamic policy + virtual uint32_t getRecommendedMuteDurationMs() const { return 0; } + protected: const sp mPolicyAudioPort; AudioPolicyClientInterface * const mClientInterface; @@ -415,6 +417,8 @@ public: */ DeviceVector filterSupportedDevices(const DeviceVector &devices) const; + uint32_t getRecommendedMuteDurationMs() const override; + const sp mProfile; // I/O profile this output derives from audio_io_handle_t mIoHandle; // output handle uint32_t mLatency; // diff --git a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h index a74cefa861..81828ed341 100644 --- a/services/audiopolicy/common/managerdefinitions/include/IOProfile.h +++ b/services/audiopolicy/common/managerdefinitions/include/IOProfile.h @@ -207,6 +207,8 @@ public: // Number of streams currently active for this profile. This is not the number of active clients // (AudioTrack or AudioRecord) but the number of active HAL streams. uint32_t curActiveCount; + // Mute duration while changing device on this output profile. + uint32_t recommendedMuteDurationMs = 0; private: DeviceVector mSupportedDevices; // supported devices: this input/output can be routed from/to diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp index f3d2326601..34b5c1ad59 100644 --- a/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp +++ b/services/audiopolicy/common/managerdefinitions/src/AudioOutputDescriptor.cpp @@ -670,6 +670,15 @@ status_t SwAudioOutputDescriptor::openDuplicating(const spgetRecommendedMuteDurationMs(), + mOutput2->getRecommendedMuteDurationMs()); + } + return mProfile->recommendedMuteDurationMs; +} + // HwAudioOutputDescriptor implementation HwAudioOutputDescriptor::HwAudioOutputDescriptor(const sp& source, AudioPolicyClientInterface *clientInterface) diff --git a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp index 09b614d329..624ad95b83 100644 --- a/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp +++ b/services/audiopolicy/common/managerdefinitions/src/IOProfile.cpp @@ -137,6 +137,7 @@ void IOProfile::dump(String8 *dst) const maxOpenCount, curOpenCount); dst->appendFormat(" - maxActiveCount: %u - curActiveCount: %u\n", maxActiveCount, curActiveCount); + dst->appendFormat(" - recommendedMuteDurationMs: %u ms\n", recommendedMuteDurationMs); } void IOProfile::log() diff --git a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp index 84ed6567b2..4dfef73e0e 100644 --- a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp +++ b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp @@ -123,6 +123,7 @@ struct MixPortTraits : public AndroidCollectionTraits PolicySerializer::deserializemaxActiveCount); } + + std::string recommendedmuteDurationMsLiteral = + getXmlAttribute(child, Attributes::recommendedMuteDurationMs); + if (!recommendedmuteDurationMsLiteral.empty()) { + convertTo(recommendedmuteDurationMsLiteral, mixPort->recommendedMuteDurationMs); + } + // Deserialize children AudioGainTraits::Collection gains; status = deserializeCollection(child, &gains, NULL); diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp index 6f87bf048e..87f46945d5 100644 --- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp +++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp @@ -6294,11 +6294,18 @@ uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const spisActive() && (devices != prevDevices)) { uint32_t tempMuteWaitMs = outputDesc->latency() * 2; - // temporary mute duration is conservatively set to 4 times the reported latency - uint32_t tempMuteDurationMs = outputDesc->latency() * 4; + if (muteWaitMs < tempMuteWaitMs) { muteWaitMs = tempMuteWaitMs; } + + // If recommended duration is defined, replace temporary mute duration to avoid + // truncated notifications at beginning, which depends on duration of changing path in HAL. + // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency. + uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs(); + uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ? + tempRecommendedMuteDuration : outputDesc->latency() * 4; + for (const auto &activeVs : outputDesc->getActiveVolumeSources()) { // make sure that we do not start the temporary mute period too early in case of // delayed device change -- GitLab From b2d43f6d5f4c4248c830779590a010eb7cfac9e8 Mon Sep 17 00:00:00 2001 From: Shuzhen Wang Date: Wed, 25 Aug 2021 14:01:11 -0700 Subject: [PATCH 108/694] Camera: minor log message fix Test: Build Bug: 197779469 Change-Id: I3ef6c04d078e0d9e6f1749808642ad01e00028e1 --- services/camera/libcameraservice/CameraService.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp index cc01ab2779..cd6b89dd2e 100644 --- a/services/camera/libcameraservice/CameraService.cpp +++ b/services/camera/libcameraservice/CameraService.cpp @@ -1336,7 +1336,7 @@ status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clien auto clientSp = current->getValue(); if (clientSp.get() != nullptr) { // should never be needed if (!clientSp->canCastToApiClient(effectiveApiLevel)) { - ALOGW("CameraService connect called from same client, but with a different" + ALOGW("CameraService connect called with a different" " API level, evicting prior client..."); } else if (clientSp->getRemote() == remoteCallback) { ALOGI("CameraService::connect X (PID %d) (second call from same" -- GitLab From 3032bfbdb5e16b6b2f934c63a784f56db97dfa73 Mon Sep 17 00:00:00 2001 From: Samiul Islam Date: Thu, 26 Aug 2021 11:41:21 +0100 Subject: [PATCH 109/694] libbinder: split out PackageManagerNative aidl Very few clients of libbinder use PackageManagerNative service, as such it's a waste to couple them together. Now, user of PackageManagerNative service need to add the corresponding aidl files as shared library. Bug: 183654927 Test: builds + presubmit Change-Id: I20e61b431eed267995fcd3c33cd1d62b2c9e29b5 --- media/libmediaplayerservice/Android.bp | 2 ++ media/libstagefright/Android.bp | 2 ++ media/utils/Android.bp | 2 ++ services/audioflinger/Android.bp | 2 ++ services/audiopolicy/service/Android.bp | 1 + services/mediametrics/Android.bp | 2 ++ services/tuner/Android.bp | 1 + 7 files changed, 12 insertions(+) diff --git a/media/libmediaplayerservice/Android.bp b/media/libmediaplayerservice/Android.bp index f55678da32..37f81035a6 100644 --- a/media/libmediaplayerservice/Android.bp +++ b/media/libmediaplayerservice/Android.bp @@ -65,6 +65,7 @@ cc_library { "libstagefright_foundation", "libstagefright_httplive", "libutils", + "packagemanager_aidl-cpp", ], header_libs: [ @@ -82,6 +83,7 @@ cc_library { export_shared_lib_headers: [ "libmedia", "framework-permission-aidl-cpp", + "packagemanager_aidl-cpp", ], include_dirs: [ diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp index a052a7050b..b412c9dff9 100644 --- a/media/libstagefright/Android.bp +++ b/media/libstagefright/Android.bp @@ -340,6 +340,7 @@ cc_library { "android.hardware.media.omx@1.0", "framework-permission-aidl-cpp", "libaudioclient_aidl_conversion", + "packagemanager_aidl-cpp", ], static_libs: [ @@ -371,6 +372,7 @@ cc_library { "libmedia", "android.hidl.allocator@1.0", "framework-permission-aidl-cpp", + "packagemanager_aidl-cpp", ], export_include_dirs: [ diff --git a/media/utils/Android.bp b/media/utils/Android.bp index 73c4e3bbf1..6e29ac8d83 100644 --- a/media/utils/Android.bp +++ b/media/utils/Android.bp @@ -51,6 +51,7 @@ cc_library { "libpermission", "android.hardware.graphics.bufferqueue@1.0", "android.hidl.token@1.0-utils", + "packagemanager_aidl-cpp", ], export_static_lib_headers: [ "libbatterystats_aidl", @@ -71,6 +72,7 @@ cc_library { export_shared_lib_headers: [ "libpermission", + "packagemanager_aidl-cpp", ], include_dirs: [ diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp index b91f302c8e..22e5d1a173 100644 --- a/services/audioflinger/Android.bp +++ b/services/audioflinger/Android.bp @@ -81,6 +81,7 @@ cc_library_shared { "libmedia_helper", "libshmemcompat", "libvibrator", + "packagemanager_aidl-cpp", ], static_libs: [ @@ -97,6 +98,7 @@ cc_library_shared { export_shared_lib_headers: [ "libpermission", + "packagemanager_aidl-cpp", ], cflags: [ diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 8ae0901f31..2c8aaadccc 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -50,6 +50,7 @@ cc_library_shared { "audiopolicy-types-aidl-cpp", "capture_state_listener-aidl-cpp", "framework-permission-aidl-cpp", + "packagemanager_aidl-cpp", "spatializer-aidl-cpp", ], diff --git a/services/mediametrics/Android.bp b/services/mediametrics/Android.bp index 0351d2df31..04fc430449 100644 --- a/services/mediametrics/Android.bp +++ b/services/mediametrics/Android.bp @@ -172,11 +172,13 @@ cc_library { "libstatspull", "libstatssocket", "libutils", + "packagemanager_aidl-cpp", ], export_shared_lib_headers: [ "libstatspull", "libstatssocket", + "packagemanager_aidl-cpp", ], static_libs: [ diff --git a/services/tuner/Android.bp b/services/tuner/Android.bp index b2b1c3bc79..ec62d4e276 100644 --- a/services/tuner/Android.bp +++ b/services/tuner/Android.bp @@ -52,6 +52,7 @@ cc_library { "liblog", "libmedia", "libutils", + "packagemanager_aidl-cpp", "tv_tuner_aidl_interface-ndk", "tv_tuner_resource_manager_aidl_interface-ndk", ], -- GitLab From 1a9a365a56e1769836a9ea4433e5ebff80d1df60 Mon Sep 17 00:00:00 2001 From: Phil Burk Date: Sat, 21 Aug 2021 00:32:03 +0000 Subject: [PATCH 110/694] aaudio: cleanup test build Use cc_binary for non-unit-tests. Bug: 197260415 Test: atest -c frameworks/av/media/libaaudio/tests Test: Then pick a numbered test. Change-Id: I0178397bf00ae64f63a70616782999938ce88fe8 --- media/libaaudio/tests/Android.bp | 110 +++++++------------------------ 1 file changed, 22 insertions(+), 88 deletions(-) diff --git a/media/libaaudio/tests/Android.bp b/media/libaaudio/tests/Android.bp index 98e9727434..ea00a5a1ff 100644 --- a/media/libaaudio/tests/Android.bp +++ b/media/libaaudio/tests/Android.bp @@ -48,7 +48,7 @@ cc_test { shared_libs: ["libaaudio_internal"], } -cc_test { +cc_binary { name: "test_timestamps", defaults: ["libaaudio_tests_defaults"], srcs: ["test_timestamps.cpp"], @@ -60,121 +60,71 @@ cc_test { name: "test_open_params", defaults: ["libaaudio_tests_defaults"], srcs: ["test_open_params.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -cc_test { +cc_binary { name: "test_no_close", defaults: ["libaaudio_tests_defaults"], srcs: ["test_no_close.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -cc_test { +cc_binary { name: "test_aaudio_recovery", defaults: ["libaaudio_tests_defaults"], srcs: ["test_recovery.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -cc_test { +cc_binary { name: "test_n_streams", defaults: ["libaaudio_tests_defaults"], srcs: ["test_n_streams.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -cc_test { +cc_binary { name: "test_bad_disconnect", defaults: ["libaaudio_tests_defaults"], srcs: ["test_bad_disconnect.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { name: "test_various", defaults: ["libaaudio_tests_defaults"], srcs: ["test_various.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { name: "test_session_id", defaults: ["libaaudio_tests_defaults"], srcs: ["test_session_id.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -cc_test { +cc_binary { name: "test_aaudio_monkey", defaults: ["libaaudio_tests_defaults"], srcs: ["test_aaudio_monkey.cpp"], header_libs: ["libaaudio_example_utils"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { name: "test_attributes", defaults: ["libaaudio_tests_defaults"], srcs: ["test_attributes.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { name: "test_interference", defaults: ["libaaudio_tests_defaults"], srcs: ["test_interference.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { @@ -196,28 +146,18 @@ cc_test { ], } -cc_test { +cc_binary { name: "test_return_stop", defaults: ["libaaudio_tests_defaults"], srcs: ["test_return_stop.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { name: "test_callback_race", defaults: ["libaaudio_tests_defaults"], srcs: ["test_callback_race.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } cc_test { @@ -238,7 +178,7 @@ cc_test { ], } -cc_test { +cc_binary { name: "test_steal_exclusive", defaults: ["libaaudio_tests_defaults"], srcs: ["test_steal_exclusive.cpp"], @@ -251,15 +191,9 @@ cc_test { ], } - -cc_test { +cc_binary { name: "test_disconnect_race", defaults: ["libaaudio_tests_defaults"], srcs: ["test_disconnect_race.cpp"], - shared_libs: [ - "libaaudio", - "libbinder", - "libcutils", - "libutils", - ], + shared_libs: ["libaaudio"], } -- GitLab From d0ba1bb0ea94382ce3fa5dc8492626cbf8c47b14 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Fri, 27 Aug 2021 16:22:16 +0000 Subject: [PATCH 111/694] Simplify some code in NuPlayerRenderer Change-Id: I1c349eaf4fed59668e5972c846729c24adfe2ba1 Test: Untested. Non-functional change. --- .../nuplayer/NuPlayerRenderer.cpp | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp index 4a65f717d0..2828d44af3 100644 --- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp +++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp @@ -1673,24 +1673,18 @@ void NuPlayer::Renderer::onFlush(const sp &msg) { mDrainAudioQueuePending = false; - if (offloadingAudio()) { - mAudioSink->pause(); - mAudioSink->flush(); - if (!mPaused) { - mAudioSink->start(); - } - } else { - mAudioSink->pause(); - mAudioSink->flush(); + mAudioSink->pause(); + mAudioSink->flush(); + if (!offloadingAudio()) { // Call stop() to signal to the AudioSink to completely fill the // internal buffer before resuming playback. // FIXME: this is ignored after flush(). mAudioSink->stop(); - if (!mPaused) { - mAudioSink->start(); - } mNumFramesWritten = 0; } + if (!mPaused) { + mAudioSink->start(); + } mNextAudioClockUpdateTimeUs = -1; } else { flushQueue(&mVideoQueue); -- GitLab From d0b9615730186883592845261980ebaa0c0a837f Mon Sep 17 00:00:00 2001 From: Pirama Arumuga Nainar Date: Thu, 26 Aug 2021 22:00:04 -0700 Subject: [PATCH 112/694] [ExtractorUnitTest] Fix linker failures with upstream lld Bug: http://b/197965342 This change is needed to build this test with upstream lld. Avoid linking static libraries that are already needed by shared_lib dependencies of ExtractorUnitTest (e.g. libmedia.so). - Use shared libstagefright and libstagefright_foundation instead. - libstagefright_mpeg2extractor does not have a shared variant but it seems unnecessary to link this test. Test: build with aosp/1809741 which has lld with the above behavior. Change-Id: Id83e6446a3bf903c891367de8ea2b23bc57efa34 --- media/extractors/tests/Android.bp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/media/extractors/tests/Android.bp b/media/extractors/tests/Android.bp index 5d97d9a576..23c74f74d4 100644 --- a/media/extractors/tests/Android.bp +++ b/media/extractors/tests/Android.bp @@ -45,14 +45,11 @@ cc_test { "libdatasource", "libwatchdog", - "libstagefright", "libstagefright_id3", "libstagefright_flacdec", "libstagefright_esds", "libstagefright_mpeg2support", - "libstagefright_mpeg2extractor", "libstagefright_foundation_colorutils_ndk", - "libstagefright_foundation", "libstagefright_metadatautils", "libmedia_midiiowrapper", @@ -74,6 +71,8 @@ cc_test { "libcutils", "libmediandk", "libmedia", + "libstagefright", + "libstagefright_foundation", "libcrypto", "libhidlmemory", "libhidlbase", -- GitLab From 70982a68b0425e623278e693b1811dfa61264178 Mon Sep 17 00:00:00 2001 From: Wonsik Kim Date: Thu, 26 Aug 2021 16:32:35 -0700 Subject: [PATCH 113/694] aacdec: fix memory leak at onStop() onStop() may invoke initDecoder() which could reallocate output ring buffer without releasing the existing one. Bug: 196484690 Test: cts/media/device-small Change-Id: I245aaf2a3c2d471e02befbd67fbe30e54ac8967a --- media/codec2/components/aac/C2SoftAacDec.cpp | 8 +++----- media/codec2/components/aac/C2SoftAacDec.h | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/media/codec2/components/aac/C2SoftAacDec.cpp b/media/codec2/components/aac/C2SoftAacDec.cpp index 342d7718ea..57cdcd0a9d 100644 --- a/media/codec2/components/aac/C2SoftAacDec.cpp +++ b/media/codec2/components/aac/C2SoftAacDec.cpp @@ -287,6 +287,7 @@ c2_status_t C2SoftAacDec::onStop() { mOutputDelayRingBufferWritePos = 0; mOutputDelayRingBufferReadPos = 0; mOutputDelayRingBufferFilled = 0; + mOutputDelayRingBuffer.reset(); mBuffersInfo.clear(); status_t status = UNKNOWN_ERROR; @@ -308,10 +309,7 @@ void C2SoftAacDec::onRelease() { aacDecoder_Close(mAACDecoder); mAACDecoder = nullptr; } - if (mOutputDelayRingBuffer) { - delete[] mOutputDelayRingBuffer; - mOutputDelayRingBuffer = nullptr; - } + mOutputDelayRingBuffer.reset(); } status_t C2SoftAacDec::initDecoder() { @@ -327,7 +325,7 @@ status_t C2SoftAacDec::initDecoder() { mOutputDelayCompensated = 0; mOutputDelayRingBufferSize = 2048 * MAX_CHANNEL_COUNT * kNumDelayBlocksMax; - mOutputDelayRingBuffer = new short[mOutputDelayRingBufferSize]; + mOutputDelayRingBuffer.reset(new short[mOutputDelayRingBufferSize]); mOutputDelayRingBufferWritePos = 0; mOutputDelayRingBufferReadPos = 0; mOutputDelayRingBufferFilled = 0; diff --git a/media/codec2/components/aac/C2SoftAacDec.h b/media/codec2/components/aac/C2SoftAacDec.h index 986187c905..a03fc705e7 100644 --- a/media/codec2/components/aac/C2SoftAacDec.h +++ b/media/codec2/components/aac/C2SoftAacDec.h @@ -93,7 +93,7 @@ private: bool mEndOfOutput; int32_t mOutputDelayCompensated; int32_t mOutputDelayRingBufferSize; - short *mOutputDelayRingBuffer; + std::unique_ptr mOutputDelayRingBuffer; int32_t mOutputDelayRingBufferWritePos; int32_t mOutputDelayRingBufferReadPos; int32_t mOutputDelayRingBufferFilled; -- GitLab From 0e1d1a092a2505b2e31dc77926a7f96f260f4575 Mon Sep 17 00:00:00 2001 From: Wonsik Kim Date: Thu, 26 Aug 2021 13:57:02 -0700 Subject: [PATCH 114/694] codec2 vndk: clean up block pool cache when it's released The cache was growing indefinitely eating up memory as codecs get created. Bug: 196484690 Test: cts/media/device-small Change-Id: I47dcc6a803293f845274d6a5f1a29fcd4819d9de --- .../vndk/C2PlatformStorePluginLoader.cpp | 11 ++-- media/codec2/vndk/C2Store.cpp | 58 ++++++++++--------- .../include/C2PlatformStorePluginLoader.h | 14 +++-- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/media/codec2/vndk/C2PlatformStorePluginLoader.cpp b/media/codec2/vndk/C2PlatformStorePluginLoader.cpp index bee028af68..2a888a8f19 100644 --- a/media/codec2/vndk/C2PlatformStorePluginLoader.cpp +++ b/media/codec2/vndk/C2PlatformStorePluginLoader.cpp @@ -59,13 +59,14 @@ C2PlatformStorePluginLoader::~C2PlatformStorePluginLoader() { c2_status_t C2PlatformStorePluginLoader::createBlockPool( ::C2Allocator::id_t allocatorId, ::C2BlockPool::local_id_t blockPoolId, - std::shared_ptr* pool) { + std::shared_ptr* pool, + std::function deleter) { if (mCreateBlockPool == nullptr) { ALOGD("Handle or CreateBlockPool symbol is null"); return C2_NOT_FOUND; } - std::shared_ptr<::C2BlockPool> ptr(mCreateBlockPool(allocatorId, blockPoolId)); + std::shared_ptr<::C2BlockPool> ptr(mCreateBlockPool(allocatorId, blockPoolId), deleter); if (ptr) { *pool = ptr; return C2_OK; @@ -75,14 +76,16 @@ c2_status_t C2PlatformStorePluginLoader::createBlockPool( } c2_status_t C2PlatformStorePluginLoader::createAllocator( - ::C2Allocator::id_t allocatorId, std::shared_ptr* const allocator) { + ::C2Allocator::id_t allocatorId, + std::shared_ptr* const allocator, + std::function deleter) { if (mCreateAllocator == nullptr) { ALOGD("Handle or CreateAllocator symbol is null"); return C2_NOT_FOUND; } c2_status_t res = C2_CORRUPTED; - allocator->reset(mCreateAllocator(allocatorId, &res)); + allocator->reset(mCreateAllocator(allocatorId, &res), deleter); if (res != C2_OK) { ALOGD("Failed to CreateAllocator by id: %u, res: %d", allocatorId, res); allocator->reset(); diff --git a/media/codec2/vndk/C2Store.cpp b/media/codec2/vndk/C2Store.cpp index c07c09e182..1660c381b9 100644 --- a/media/codec2/vndk/C2Store.cpp +++ b/media/codec2/vndk/C2Store.cpp @@ -443,6 +443,7 @@ class _C2BlockPoolCache { public: _C2BlockPoolCache() : mBlockPoolSeqId(C2BlockPool::PLATFORM_START + 1) {} +private: c2_status_t _createBlockPool( C2PlatformAllocatorStore::id_t allocatorId, std::vector> components, @@ -456,14 +457,19 @@ public: if (allocatorId == C2AllocatorStore::DEFAULT_LINEAR) { allocatorId = GetPreferredLinearAllocatorId(GetCodec2PoolMask()); } + auto deleter = [this, poolId](C2BlockPool *pool) { + std::unique_lock lock(mMutex); + mBlockPools.erase(poolId); + mComponents.erase(poolId); + delete pool; + }; switch(allocatorId) { case C2PlatformAllocatorStore::ION: /* also ::DMABUFHEAP */ res = allocatorStore->fetchAllocator( C2PlatformAllocatorStore::ION, &allocator); if (res == C2_OK) { - std::shared_ptr ptr = - std::make_shared( - allocator, poolId); + std::shared_ptr ptr( + new C2PooledBlockPool(allocator, poolId), deleter); *pool = ptr; mBlockPools[poolId] = ptr; mComponents[poolId].insert( @@ -475,9 +481,8 @@ public: res = allocatorStore->fetchAllocator( C2PlatformAllocatorStore::BLOB, &allocator); if (res == C2_OK) { - std::shared_ptr ptr = - std::make_shared( - allocator, poolId); + std::shared_ptr ptr( + new C2PooledBlockPool(allocator, poolId), deleter); *pool = ptr; mBlockPools[poolId] = ptr; mComponents[poolId].insert( @@ -490,8 +495,8 @@ public: res = allocatorStore->fetchAllocator( C2AllocatorStore::DEFAULT_GRAPHIC, &allocator); if (res == C2_OK) { - std::shared_ptr ptr = - std::make_shared(allocator, poolId); + std::shared_ptr ptr( + new C2PooledBlockPool(allocator, poolId), deleter); *pool = ptr; mBlockPools[poolId] = ptr; mComponents[poolId].insert( @@ -503,9 +508,8 @@ public: res = allocatorStore->fetchAllocator( C2PlatformAllocatorStore::BUFFERQUEUE, &allocator); if (res == C2_OK) { - std::shared_ptr ptr = - std::make_shared( - allocator, poolId); + std::shared_ptr ptr( + new C2BufferQueueBlockPool(allocator, poolId), deleter); *pool = ptr; mBlockPools[poolId] = ptr; mComponents[poolId].insert( @@ -517,7 +521,7 @@ public: // Try to create block pool from platform store plugins. std::shared_ptr ptr; res = C2PlatformStorePluginLoader::GetInstance()->createBlockPool( - allocatorId, poolId, &ptr); + allocatorId, poolId, &ptr, deleter); if (res == C2_OK) { *pool = ptr; mBlockPools[poolId] = ptr; @@ -530,17 +534,20 @@ public: return res; } +public: c2_status_t createBlockPool( C2PlatformAllocatorStore::id_t allocatorId, std::vector> components, std::shared_ptr *pool) { + std::unique_lock lock(mMutex); return _createBlockPool(allocatorId, components, mBlockPoolSeqId++, pool); } - bool getBlockPool( + c2_status_t getBlockPool( C2BlockPool::local_id_t blockPoolId, std::shared_ptr component, std::shared_ptr *pool) { + std::unique_lock lock(mMutex); // TODO: use one iterator for multiple blockpool type scalability. std::shared_ptr ptr; auto it = mBlockPools.find(blockPoolId); @@ -558,14 +565,22 @@ public: }); if (found != mComponents[blockPoolId].end()) { *pool = ptr; - return true; + return C2_OK; } } } - return false; + // TODO: remove this. this is temporary + if (blockPoolId == C2BlockPool::PLATFORM_START) { + return _createBlockPool( + C2PlatformAllocatorStore::BUFFERQUEUE, {component}, blockPoolId, pool); + } + return C2_NOT_FOUND; } private: + // Deleter needs to hold this mutex, and there is a small chance that deleter + // is invoked while the mutex is held. + std::recursive_mutex mMutex; C2BlockPool::local_id_t mBlockPoolSeqId; std::map> mBlockPools; @@ -574,7 +589,6 @@ private: static std::unique_ptr<_C2BlockPoolCache> sBlockPoolCache = std::make_unique<_C2BlockPoolCache>(); -static std::mutex sBlockPoolCacheMutex; } // anynymous namespace @@ -582,15 +596,12 @@ c2_status_t GetCodec2BlockPool( C2BlockPool::local_id_t id, std::shared_ptr component, std::shared_ptr *pool) { pool->reset(); - std::lock_guard lock(sBlockPoolCacheMutex); std::shared_ptr allocatorStore = GetCodec2PlatformAllocatorStore(); std::shared_ptr allocator; c2_status_t res = C2_NOT_FOUND; if (id >= C2BlockPool::PLATFORM_START) { - if (sBlockPoolCache->getBlockPool(id, component, pool)) { - return C2_OK; - } + return sBlockPoolCache->getBlockPool(id, component, pool); } switch (id) { @@ -606,11 +617,6 @@ c2_status_t GetCodec2BlockPool( *pool = std::make_shared(allocator); } break; - // TODO: remove this. this is temporary - case C2BlockPool::PLATFORM_START: - res = sBlockPoolCache->_createBlockPool( - C2PlatformAllocatorStore::BUFFERQUEUE, {component}, id, pool); - break; default: break; } @@ -623,7 +629,6 @@ c2_status_t CreateCodec2BlockPool( std::shared_ptr *pool) { pool->reset(); - std::lock_guard lock(sBlockPoolCacheMutex); return sBlockPoolCache->createBlockPool(allocatorId, components, pool); } @@ -633,7 +638,6 @@ c2_status_t CreateCodec2BlockPool( std::shared_ptr *pool) { pool->reset(); - std::lock_guard lock(sBlockPoolCacheMutex); return sBlockPoolCache->createBlockPool(allocatorId, {component}, pool); } diff --git a/media/codec2/vndk/include/C2PlatformStorePluginLoader.h b/media/codec2/vndk/include/C2PlatformStorePluginLoader.h index 4c106435d6..73d1b5e839 100644 --- a/media/codec2/vndk/include/C2PlatformStorePluginLoader.h +++ b/media/codec2/vndk/include/C2PlatformStorePluginLoader.h @@ -61,9 +61,11 @@ public: * \retval C2_NOT_FOUND the extension symbol was not found. * \retval C2_BAD_INDEX the input allocatorId is not defined in platform store extension. */ - c2_status_t createBlockPool(::C2Allocator::id_t allocatorId, - ::C2BlockPool::local_id_t blockPoolId, - std::shared_ptr* pool); + c2_status_t createBlockPool( + ::C2Allocator::id_t allocatorId, + ::C2BlockPool::local_id_t blockPoolId, + std::shared_ptr* pool, + std::function deleter = std::default_delete()); /** * Creates allocator from platform store extension. @@ -81,8 +83,10 @@ public: * \retval C2_BAD_INDEX the input allocatorId is not defined in platform store extension. * \retval C2_NO_MEMORY not enough memory to create the allocator */ - c2_status_t createAllocator(::C2Allocator::id_t allocatorId, - std::shared_ptr* const allocator); + c2_status_t createAllocator( + ::C2Allocator::id_t allocatorId, + std::shared_ptr* const allocator, + std::function deleter = std::default_delete()); private: explicit C2PlatformStorePluginLoader(const char *libPath); -- GitLab From ab8e5af87da9974ff5ce1204e3db41d9799234e3 Mon Sep 17 00:00:00 2001 From: Harish Mahendrakar Date: Thu, 26 Aug 2021 16:35:48 -0700 Subject: [PATCH 115/694] C2SoftVp8: List profile0 as supported profile VP8 encoder/decoder plugins didn't correctly advertise the profile they supported as profile enum wasn't defined earlier for vp8. Though Codec2InfoBuilder sets a default profile for vp8 codecs in Android S, this change is still needed when this is installed on older devices as part of mainline update. Bug: 194154048 On Android R Test: Install S swcodec mainline module on R and test run mts-user -m CtsMediaV2TestCases \ -t android.mediav2.cts.EncodeDecodeAccuracyTest On Android S Test: revert the change in Codec2InfoBuilder that sets default vp8 profile and test the above MTS test Test: atest CtsMediaV2TestCases Test: atest VtsHalMediaC2V1_0TargetVideoDecTest Test: atest VtsHalMediaC2V1_0TargetVideoEncTest Change-Id: I7534e25bcb7ccd8834b9e72b431471c735f75c33 --- media/codec2/components/vpx/C2SoftVpxDec.cpp | 12 +++++- media/codec2/components/vpx/C2SoftVpxEnc.h | 42 +++++++++++++------- 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/media/codec2/components/vpx/C2SoftVpxDec.cpp b/media/codec2/components/vpx/C2SoftVpxDec.cpp index 2953d900df..45e2ca8c11 100644 --- a/media/codec2/components/vpx/C2SoftVpxDec.cpp +++ b/media/codec2/components/vpx/C2SoftVpxDec.cpp @@ -149,8 +149,16 @@ public: #else addParameter( DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL) - .withConstValue(new C2StreamProfileLevelInfo::input(0u, - C2Config::PROFILE_UNUSED, C2Config::LEVEL_UNUSED)) + .withDefault(new C2StreamProfileLevelInfo::input(0u, + C2Config::PROFILE_VP8_0, C2Config::LEVEL_UNUSED)) + .withFields({ + C2F(mProfileLevel, profile).equalTo( + PROFILE_VP8_0 + ), + C2F(mProfileLevel, level).equalTo( + LEVEL_UNUSED), + }) + .withSetter(ProfileLevelSetter, mSize) .build()); #endif diff --git a/media/codec2/components/vpx/C2SoftVpxEnc.h b/media/codec2/components/vpx/C2SoftVpxEnc.h index c98b802bff..926b2e9d5a 100644 --- a/media/codec2/components/vpx/C2SoftVpxEnc.h +++ b/media/codec2/components/vpx/C2SoftVpxEnc.h @@ -324,21 +324,35 @@ class C2SoftVpxEnc::IntfImpl : public SimpleInterface::BaseParams { .withConstValue(new C2StreamIntraRefreshTuning::output( 0u, C2Config::INTRA_REFRESH_DISABLED, 0.)) .build()); - +#ifdef VP9 addParameter( - DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL) - .withDefault(new C2StreamProfileLevelInfo::output( - 0u, PROFILE_VP9_0, LEVEL_VP9_4_1)) - .withFields({ - C2F(mProfileLevel, profile).equalTo( - PROFILE_VP9_0 - ), - C2F(mProfileLevel, level).equalTo( - LEVEL_VP9_4_1), - }) - .withSetter(ProfileLevelSetter) - .build()); - + DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL) + .withDefault(new C2StreamProfileLevelInfo::output( + 0u, PROFILE_VP9_0, LEVEL_VP9_4_1)) + .withFields({ + C2F(mProfileLevel, profile).equalTo( + PROFILE_VP9_0 + ), + C2F(mProfileLevel, level).equalTo( + LEVEL_VP9_4_1), + }) + .withSetter(ProfileLevelSetter) + .build()); +#else + addParameter( + DefineParam(mProfileLevel, C2_PARAMKEY_PROFILE_LEVEL) + .withDefault(new C2StreamProfileLevelInfo::output( + 0u, PROFILE_VP8_0, LEVEL_UNUSED)) + .withFields({ + C2F(mProfileLevel, profile).equalTo( + PROFILE_VP8_0 + ), + C2F(mProfileLevel, level).equalTo( + LEVEL_UNUSED), + }) + .withSetter(ProfileLevelSetter) + .build()); +#endif addParameter( DefineParam(mRequestSync, C2_PARAMKEY_REQUEST_SYNC_FRAME) .withDefault(new C2StreamRequestSyncFrameTuning::output(0u, C2_FALSE)) -- GitLab From fc18e6327044acefd2ddfce642d4e558dfc8f60f Mon Sep 17 00:00:00 2001 From: Atneya Date: Tue, 31 Aug 2021 18:59:21 -0400 Subject: [PATCH 116/694] AudioFlinger: Add client shared heap size to dump. Test: Manual dumpsys of AudioFlinger. Change-Id: I4156e6a4da770a58d2f2e7ab71140ce591dd98ee --- services/audioflinger/AudioFlinger.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 8a32b72553..33b71c55f0 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -566,10 +566,12 @@ void AudioFlinger::dumpClients(int fd, const Vector& args __unused) String8 result; result.append("Clients:\n"); + result.append(" pid heap_size\n"); for (size_t i = 0; i < mClients.size(); ++i) { sp client = mClients.valueAt(i).promote(); if (client != 0) { - result.appendFormat(" pid: %d\n", client->pid()); + result.appendFormat("%6d %12zu\n", client->pid(), + client->heap()->getMemoryHeap()->getSize()); } } -- GitLab From dbf036454ee1685f13e043691678a5d4ec23dfba Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 25 Aug 2021 18:15:32 -0700 Subject: [PATCH 117/694] Move common data types to android.media.audio.common AIDL The following types got moved: - AudioConfig - AudioConfigBase - AudioEncapsulationMode - AudioOffloadInfo - AudioStreamType - AudioUsage Updated references to the types. Bug: 188932434 Test: m Change-Id: I429632ea639d4d9e0aa176109ffe0cc1cb6ad049 --- media/libaudioclient/AidlConversion.cpp | 260 +++++++++--------- media/libaudioclient/Android.bp | 6 - media/libaudioclient/AudioEffect.cpp | 2 +- media/libaudioclient/AudioSystem.cpp | 41 +-- media/libaudioclient/AudioTrack.cpp | 2 +- media/libaudioclient/AudioVolumeGroup.cpp | 4 +- media/libaudioclient/IAudioFlinger.cpp | 21 +- .../aidl/android/media/AudioAttributesEx.aidl | 2 +- .../media/AudioAttributesInternal.aidl | 2 +- .../aidl/android/media/AudioConfig.aidl | 32 --- .../aidl/android/media/AudioConfigBase.aidl | 29 -- .../android/media/AudioEncapsulationMode.aidl | 26 -- .../aidl/android/media/AudioMix.aidl | 2 +- .../media/AudioMixMatchCriterionValue.aidl | 2 +- .../aidl/android/media/AudioOffloadInfo.aidl | 51 ---- .../media/AudioPortConfigMixExtUseCase.aidl | 2 +- .../aidl/android/media/AudioStreamType.aidl | 42 --- .../aidl/android/media/AudioUsage.aidl | 45 --- .../aidl/android/media/AudioVolumeGroup.aidl | 2 +- .../android/media/CreateRecordRequest.aidl | 2 +- .../android/media/CreateRecordResponse.aidl | 2 +- .../android/media/CreateTrackRequest.aidl | 2 +- .../android/media/CreateTrackResponse.aidl | 2 +- .../media/GetOutputForAttrResponse.aidl | 2 +- .../android/media/IAudioFlingerService.aidl | 2 +- .../android/media/IAudioPolicyService.aidl | 10 +- .../media/IAudioPolicyServiceClient.aidl | 2 +- .../aidl/android/media/OpenInputRequest.aidl | 2 +- .../aidl/android/media/OpenInputResponse.aidl | 2 +- .../aidl/android/media/OpenOutputRequest.aidl | 4 +- .../android/media/OpenOutputResponse.aidl | 2 +- .../include/media/AidlConversion.h | 37 +-- .../include/media/AudioSystem.h | 4 +- .../include/media/IAudioFlinger.h | 13 +- .../service/AudioPolicyInterfaceImpl.cpp | 37 +-- .../service/AudioPolicyService.cpp | 4 +- .../audiopolicy/service/AudioPolicyService.h | 36 +-- 37 files changed, 269 insertions(+), 469 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioConfig.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioConfigBase.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioEncapsulationMode.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioStreamType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioUsage.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 80b9820a70..3d65a54d12 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -35,8 +35,14 @@ namespace android { using base::unexpected; using media::audio::common::AudioChannelLayout; +using media::audio::common::AudioConfig; +using media::audio::common::AudioConfigBase; +using media::audio::common::AudioEncapsulationMode; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioFormatType; +using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioStreamType; +using media::audio::common::AudioUsage; using media::audio::common::PcmType; namespace { @@ -1494,79 +1500,81 @@ legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( } ConversionResult aidl2legacy_AudioStreamType_audio_stream_type_t( - media::AudioStreamType aidl) { + AudioStreamType aidl) { switch (aidl) { - case media::AudioStreamType::DEFAULT: + case AudioStreamType::INVALID: + break; // return error + case AudioStreamType::DEFAULT: return AUDIO_STREAM_DEFAULT; - case media::AudioStreamType::VOICE_CALL: + case AudioStreamType::VOICE_CALL: return AUDIO_STREAM_VOICE_CALL; - case media::AudioStreamType::SYSTEM: + case AudioStreamType::SYSTEM: return AUDIO_STREAM_SYSTEM; - case media::AudioStreamType::RING: + case AudioStreamType::RING: return AUDIO_STREAM_RING; - case media::AudioStreamType::MUSIC: + case AudioStreamType::MUSIC: return AUDIO_STREAM_MUSIC; - case media::AudioStreamType::ALARM: + case AudioStreamType::ALARM: return AUDIO_STREAM_ALARM; - case media::AudioStreamType::NOTIFICATION: + case AudioStreamType::NOTIFICATION: return AUDIO_STREAM_NOTIFICATION; - case media::AudioStreamType::BLUETOOTH_SCO: + case AudioStreamType::BLUETOOTH_SCO: return AUDIO_STREAM_BLUETOOTH_SCO; - case media::AudioStreamType::ENFORCED_AUDIBLE: + case AudioStreamType::ENFORCED_AUDIBLE: return AUDIO_STREAM_ENFORCED_AUDIBLE; - case media::AudioStreamType::DTMF: + case AudioStreamType::DTMF: return AUDIO_STREAM_DTMF; - case media::AudioStreamType::TTS: + case AudioStreamType::TTS: return AUDIO_STREAM_TTS; - case media::AudioStreamType::ACCESSIBILITY: + case AudioStreamType::ACCESSIBILITY: return AUDIO_STREAM_ACCESSIBILITY; - case media::AudioStreamType::ASSISTANT: + case AudioStreamType::ASSISTANT: return AUDIO_STREAM_ASSISTANT; - case media::AudioStreamType::REROUTING: + case AudioStreamType::SYS_RESERVED_REROUTING: return AUDIO_STREAM_REROUTING; - case media::AudioStreamType::PATCH: + case AudioStreamType::SYS_RESERVED_PATCH: return AUDIO_STREAM_PATCH; - case media::AudioStreamType::CALL_ASSISTANT: + case AudioStreamType::CALL_ASSISTANT: return AUDIO_STREAM_CALL_ASSISTANT; } return unexpected(BAD_VALUE); } -ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamType( +ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamType( audio_stream_type_t legacy) { switch (legacy) { case AUDIO_STREAM_DEFAULT: - return media::AudioStreamType::DEFAULT; + return AudioStreamType::DEFAULT; case AUDIO_STREAM_VOICE_CALL: - return media::AudioStreamType::VOICE_CALL; + return AudioStreamType::VOICE_CALL; case AUDIO_STREAM_SYSTEM: - return media::AudioStreamType::SYSTEM; + return AudioStreamType::SYSTEM; case AUDIO_STREAM_RING: - return media::AudioStreamType::RING; + return AudioStreamType::RING; case AUDIO_STREAM_MUSIC: - return media::AudioStreamType::MUSIC; + return AudioStreamType::MUSIC; case AUDIO_STREAM_ALARM: - return media::AudioStreamType::ALARM; + return AudioStreamType::ALARM; case AUDIO_STREAM_NOTIFICATION: - return media::AudioStreamType::NOTIFICATION; + return AudioStreamType::NOTIFICATION; case AUDIO_STREAM_BLUETOOTH_SCO: - return media::AudioStreamType::BLUETOOTH_SCO; + return AudioStreamType::BLUETOOTH_SCO; case AUDIO_STREAM_ENFORCED_AUDIBLE: - return media::AudioStreamType::ENFORCED_AUDIBLE; + return AudioStreamType::ENFORCED_AUDIBLE; case AUDIO_STREAM_DTMF: - return media::AudioStreamType::DTMF; + return AudioStreamType::DTMF; case AUDIO_STREAM_TTS: - return media::AudioStreamType::TTS; + return AudioStreamType::TTS; case AUDIO_STREAM_ACCESSIBILITY: - return media::AudioStreamType::ACCESSIBILITY; + return AudioStreamType::ACCESSIBILITY; case AUDIO_STREAM_ASSISTANT: - return media::AudioStreamType::ASSISTANT; + return AudioStreamType::ASSISTANT; case AUDIO_STREAM_REROUTING: - return media::AudioStreamType::REROUTING; + return AudioStreamType::SYS_RESERVED_REROUTING; case AUDIO_STREAM_PATCH: - return media::AudioStreamType::PATCH; + return AudioStreamType::SYS_RESERVED_PATCH; case AUDIO_STREAM_CALL_ASSISTANT: - return media::AudioStreamType::CALL_ASSISTANT; + return AudioStreamType::CALL_ASSISTANT; } return unexpected(BAD_VALUE); } @@ -1998,103 +2006,105 @@ legacy2aidl_audio_content_type_t_AudioContentType(audio_content_type_t legacy) { } ConversionResult -aidl2legacy_AudioUsage_audio_usage_t(media::AudioUsage aidl) { +aidl2legacy_AudioUsage_audio_usage_t(AudioUsage aidl) { switch (aidl) { - case media::AudioUsage::UNKNOWN: + case AudioUsage::INVALID: + break; // return error + case AudioUsage::UNKNOWN: return AUDIO_USAGE_UNKNOWN; - case media::AudioUsage::MEDIA: + case AudioUsage::MEDIA: return AUDIO_USAGE_MEDIA; - case media::AudioUsage::VOICE_COMMUNICATION: + case AudioUsage::VOICE_COMMUNICATION: return AUDIO_USAGE_VOICE_COMMUNICATION; - case media::AudioUsage::VOICE_COMMUNICATION_SIGNALLING: + case AudioUsage::VOICE_COMMUNICATION_SIGNALLING: return AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING; - case media::AudioUsage::ALARM: + case AudioUsage::ALARM: return AUDIO_USAGE_ALARM; - case media::AudioUsage::NOTIFICATION: + case AudioUsage::NOTIFICATION: return AUDIO_USAGE_NOTIFICATION; - case media::AudioUsage::NOTIFICATION_TELEPHONY_RINGTONE: + case AudioUsage::NOTIFICATION_TELEPHONY_RINGTONE: return AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE; - case media::AudioUsage::NOTIFICATION_COMMUNICATION_REQUEST: + case AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_REQUEST: return AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST; - case media::AudioUsage::NOTIFICATION_COMMUNICATION_INSTANT: + case AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_INSTANT: return AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT; - case media::AudioUsage::NOTIFICATION_COMMUNICATION_DELAYED: + case AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_DELAYED: return AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED; - case media::AudioUsage::NOTIFICATION_EVENT: + case AudioUsage::NOTIFICATION_EVENT: return AUDIO_USAGE_NOTIFICATION_EVENT; - case media::AudioUsage::ASSISTANCE_ACCESSIBILITY: + case AudioUsage::ASSISTANCE_ACCESSIBILITY: return AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY; - case media::AudioUsage::ASSISTANCE_NAVIGATION_GUIDANCE: + case AudioUsage::ASSISTANCE_NAVIGATION_GUIDANCE: return AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE; - case media::AudioUsage::ASSISTANCE_SONIFICATION: + case AudioUsage::ASSISTANCE_SONIFICATION: return AUDIO_USAGE_ASSISTANCE_SONIFICATION; - case media::AudioUsage::GAME: + case AudioUsage::GAME: return AUDIO_USAGE_GAME; - case media::AudioUsage::VIRTUAL_SOURCE: + case AudioUsage::VIRTUAL_SOURCE: return AUDIO_USAGE_VIRTUAL_SOURCE; - case media::AudioUsage::ASSISTANT: + case AudioUsage::ASSISTANT: return AUDIO_USAGE_ASSISTANT; - case media::AudioUsage::CALL_ASSISTANT: + case AudioUsage::CALL_ASSISTANT: return AUDIO_USAGE_CALL_ASSISTANT; - case media::AudioUsage::EMERGENCY: + case AudioUsage::EMERGENCY: return AUDIO_USAGE_EMERGENCY; - case media::AudioUsage::SAFETY: + case AudioUsage::SAFETY: return AUDIO_USAGE_SAFETY; - case media::AudioUsage::VEHICLE_STATUS: + case AudioUsage::VEHICLE_STATUS: return AUDIO_USAGE_VEHICLE_STATUS; - case media::AudioUsage::ANNOUNCEMENT: + case AudioUsage::ANNOUNCEMENT: return AUDIO_USAGE_ANNOUNCEMENT; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_usage_t_AudioUsage(audio_usage_t legacy) { switch (legacy) { case AUDIO_USAGE_UNKNOWN: - return media::AudioUsage::UNKNOWN; + return AudioUsage::UNKNOWN; case AUDIO_USAGE_MEDIA: - return media::AudioUsage::MEDIA; + return AudioUsage::MEDIA; case AUDIO_USAGE_VOICE_COMMUNICATION: - return media::AudioUsage::VOICE_COMMUNICATION; + return AudioUsage::VOICE_COMMUNICATION; case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING: - return media::AudioUsage::VOICE_COMMUNICATION_SIGNALLING; + return AudioUsage::VOICE_COMMUNICATION_SIGNALLING; case AUDIO_USAGE_ALARM: - return media::AudioUsage::ALARM; + return AudioUsage::ALARM; case AUDIO_USAGE_NOTIFICATION: - return media::AudioUsage::NOTIFICATION; + return AudioUsage::NOTIFICATION; case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE: - return media::AudioUsage::NOTIFICATION_TELEPHONY_RINGTONE; + return AudioUsage::NOTIFICATION_TELEPHONY_RINGTONE; case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST: - return media::AudioUsage::NOTIFICATION_COMMUNICATION_REQUEST; + return AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_REQUEST; case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT: - return media::AudioUsage::NOTIFICATION_COMMUNICATION_INSTANT; + return AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_INSTANT; case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED: - return media::AudioUsage::NOTIFICATION_COMMUNICATION_DELAYED; + return AudioUsage::SYS_RESERVED_NOTIFICATION_COMMUNICATION_DELAYED; case AUDIO_USAGE_NOTIFICATION_EVENT: - return media::AudioUsage::NOTIFICATION_EVENT; + return AudioUsage::NOTIFICATION_EVENT; case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY: - return media::AudioUsage::ASSISTANCE_ACCESSIBILITY; + return AudioUsage::ASSISTANCE_ACCESSIBILITY; case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE: - return media::AudioUsage::ASSISTANCE_NAVIGATION_GUIDANCE; + return AudioUsage::ASSISTANCE_NAVIGATION_GUIDANCE; case AUDIO_USAGE_ASSISTANCE_SONIFICATION: - return media::AudioUsage::ASSISTANCE_SONIFICATION; + return AudioUsage::ASSISTANCE_SONIFICATION; case AUDIO_USAGE_GAME: - return media::AudioUsage::GAME; + return AudioUsage::GAME; case AUDIO_USAGE_VIRTUAL_SOURCE: - return media::AudioUsage::VIRTUAL_SOURCE; + return AudioUsage::VIRTUAL_SOURCE; case AUDIO_USAGE_ASSISTANT: - return media::AudioUsage::ASSISTANT; + return AudioUsage::ASSISTANT; case AUDIO_USAGE_CALL_ASSISTANT: - return media::AudioUsage::CALL_ASSISTANT; + return AudioUsage::CALL_ASSISTANT; case AUDIO_USAGE_EMERGENCY: - return media::AudioUsage::EMERGENCY; + return AudioUsage::EMERGENCY; case AUDIO_USAGE_SAFETY: - return media::AudioUsage::SAFETY; + return AudioUsage::SAFETY; case AUDIO_USAGE_VEHICLE_STATUS: - return media::AudioUsage::VEHICLE_STATUS; + return AudioUsage::VEHICLE_STATUS; case AUDIO_USAGE_ANNOUNCEMENT: - return media::AudioUsage::ANNOUNCEMENT; + return AudioUsage::ANNOUNCEMENT; } return unexpected(BAD_VALUE); } @@ -2219,44 +2229,44 @@ legacy2aidl_audio_attributes_t_AudioAttributesInternal(const audio_attributes_t& } ConversionResult -aidl2legacy_AudioEncapsulationMode_audio_encapsulation_mode_t(media::AudioEncapsulationMode aidl) { +aidl2legacy_AudioEncapsulationMode_audio_encapsulation_mode_t(AudioEncapsulationMode aidl) { switch (aidl) { - case media::AudioEncapsulationMode::NONE: + case AudioEncapsulationMode::INVALID: + break; // return error + case AudioEncapsulationMode::NONE: return AUDIO_ENCAPSULATION_MODE_NONE; - case media::AudioEncapsulationMode::ELEMENTARY_STREAM: + case AudioEncapsulationMode::ELEMENTARY_STREAM: return AUDIO_ENCAPSULATION_MODE_ELEMENTARY_STREAM; - case media::AudioEncapsulationMode::HANDLE: + case AudioEncapsulationMode::HANDLE: return AUDIO_ENCAPSULATION_MODE_HANDLE; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_encapsulation_mode_t_AudioEncapsulationMode(audio_encapsulation_mode_t legacy) { switch (legacy) { case AUDIO_ENCAPSULATION_MODE_NONE: - return media::AudioEncapsulationMode::NONE; + return AudioEncapsulationMode::NONE; case AUDIO_ENCAPSULATION_MODE_ELEMENTARY_STREAM: - return media::AudioEncapsulationMode::ELEMENTARY_STREAM; + return AudioEncapsulationMode::ELEMENTARY_STREAM; case AUDIO_ENCAPSULATION_MODE_HANDLE: - return media::AudioEncapsulationMode::HANDLE; + return AudioEncapsulationMode::HANDLE; } return unexpected(BAD_VALUE); } ConversionResult -aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& aidl) { - audio_offload_info_t legacy; - legacy.version = VALUE_OR_RETURN(convertIntegral(aidl.version)); - legacy.size = sizeof(audio_offload_info_t); - audio_config_base_t config = VALUE_OR_RETURN( - aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.config, false /*isInput*/)); - legacy.sample_rate = config.sample_rate; - legacy.channel_mask = config.channel_mask; - legacy.format = config.format; +aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const AudioOffloadInfo& aidl) { + audio_offload_info_t legacy = AUDIO_INFO_INITIALIZER; + audio_config_base_t base = VALUE_OR_RETURN( + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.base, false /*isInput*/)); + legacy.sample_rate = base.sample_rate; + legacy.channel_mask = base.channel_mask; + legacy.format = base.format; legacy.stream_type = VALUE_OR_RETURN( aidl2legacy_AudioStreamType_audio_stream_type_t(aidl.streamType)); - legacy.bit_rate = VALUE_OR_RETURN(convertIntegral(aidl.bitRate)); + legacy.bit_rate = VALUE_OR_RETURN(convertIntegral(aidl.bitRatePerSecond)); legacy.duration_us = VALUE_OR_RETURN(convertIntegral(aidl.durationUs)); legacy.has_video = aidl.hasVideo; legacy.is_streaming = aidl.isStreaming; @@ -2270,22 +2280,20 @@ aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& legacy) { - media::AudioOffloadInfo aidl; + AudioOffloadInfo aidl; // Version 0.1 fields. if (legacy.size < offsetof(audio_offload_info_t, usage) + sizeof(audio_offload_info_t::usage)) { return unexpected(BAD_VALUE); } - aidl.version = VALUE_OR_RETURN(convertIntegral(legacy.version)); - aidl.config.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.config.channelMask = VALUE_OR_RETURN(legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - legacy.channel_mask, false /*isInput*/)); - aidl.config.format = VALUE_OR_RETURN( - legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); + const audio_config_base_t base = { .sample_rate = legacy.sample_rate, + .channel_mask = legacy.channel_mask, .format = legacy.format }; + aidl.base = VALUE_OR_RETURN(legacy2aidl_audio_config_base_t_AudioConfigBase( + base, false /*isInput*/)); aidl.streamType = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(legacy.stream_type)); - aidl.bitRate = VALUE_OR_RETURN(convertIntegral(legacy.bit_rate)); + aidl.bitRatePerSecond = VALUE_OR_RETURN(convertIntegral(legacy.bit_rate)); aidl.durationUs = VALUE_OR_RETURN(convertIntegral(legacy.duration_us)); aidl.hasVideo = legacy.has_video; aidl.isStreaming = legacy.is_streaming; @@ -2309,25 +2317,25 @@ legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& le } ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput) { - audio_config_t legacy; - legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); - legacy.channel_mask = VALUE_OR_RETURN( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); - legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); +aidl2legacy_AudioConfig_audio_config_t(const AudioConfig& aidl, bool isInput) { + const audio_config_base_t legacyBase = VALUE_OR_RETURN( + aidl2legacy_AudioConfigBase_audio_config_base_t(aidl.base, isInput)); + audio_config_t legacy = AUDIO_CONFIG_INITIALIZER; + legacy.sample_rate = legacyBase.sample_rate; + legacy.channel_mask = legacyBase.channel_mask; + legacy.format = legacyBase.format; legacy.offload_info = VALUE_OR_RETURN( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(aidl.offloadInfo)); legacy.frame_count = VALUE_OR_RETURN(convertIntegral(aidl.frameCount)); return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput) { - media::AudioConfig aidl; - aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.channelMask = VALUE_OR_RETURN( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); - aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); + const audio_config_base_t base = { .sample_rate = legacy.sample_rate, + .channel_mask = legacy.channel_mask, .format = legacy.format }; + AudioConfig aidl; + aidl.base = VALUE_OR_RETURN(legacy2aidl_audio_config_base_t_AudioConfigBase(base, isInput)); aidl.offloadInfo = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(legacy.offload_info)); aidl.frameCount = VALUE_OR_RETURN(convertIntegral(legacy.frame_count)); @@ -2335,7 +2343,7 @@ legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInpu } ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput) { +aidl2legacy_AudioConfigBase_audio_config_base_t(const AudioConfigBase& aidl, bool isInput) { audio_config_base_t legacy; legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); legacy.channel_mask = VALUE_OR_RETURN( @@ -2344,9 +2352,9 @@ aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& ai return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput) { - media::AudioConfigBase aidl; + AudioConfigBase aidl; aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); @@ -2496,9 +2504,9 @@ aidl2legacy_AudioEncapsulationMode_mask(int32_t aidl) { return convertBitmask( + AudioEncapsulationMode>( aidl, aidl2legacy_AudioEncapsulationMode_audio_encapsulation_mode_t, - indexToEnum_index, + indexToEnum_index, enumToMask_index); } @@ -2506,11 +2514,11 @@ ConversionResult legacy2aidl_AudioEncapsulationMode_mask(uint32_t legacy) { return convertBitmask( legacy, legacy2aidl_audio_encapsulation_mode_t_AudioEncapsulationMode, indexToEnum_index, - enumToMask_index); + enumToMask_index); } ConversionResult diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 0a260514a7..5b60a40561 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -313,14 +313,11 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioClient.aidl", - "aidl/android/media/AudioConfig.aidl", - "aidl/android/media/AudioConfigBase.aidl", "aidl/android/media/AudioContentType.aidl", "aidl/android/media/AudioDevice.aidl", "aidl/android/media/AudioDeviceDescription.aidl", "aidl/android/media/AudioDeviceType.aidl", "aidl/android/media/AudioDualMonoMode.aidl", - "aidl/android/media/AudioEncapsulationMode.aidl", "aidl/android/media/AudioEncapsulationMetadataType.aidl", "aidl/android/media/AudioEncapsulationType.aidl", "aidl/android/media/AudioFlag.aidl", @@ -333,7 +330,6 @@ aidl_interface { "aidl/android/media/AudioIoFlags.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioMode.aidl", - "aidl/android/media/AudioOffloadInfo.aidl", "aidl/android/media/AudioOutputFlags.aidl", "aidl/android/media/AudioPatch.aidl", "aidl/android/media/AudioPlaybackRate.aidl", @@ -354,10 +350,8 @@ aidl_interface { "aidl/android/media/AudioProfile.aidl", "aidl/android/media/AudioSourceType.aidl", "aidl/android/media/AudioStandard.aidl", - "aidl/android/media/AudioStreamType.aidl", "aidl/android/media/AudioTimestampInternal.aidl", "aidl/android/media/AudioUniqueIdUse.aidl", - "aidl/android/media/AudioUsage.aidl", "aidl/android/media/AudioUuid.aidl", "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", diff --git a/media/libaudioclient/AudioEffect.cpp b/media/libaudioclient/AudioEffect.cpp index 909159952c..50a9735c3f 100644 --- a/media/libaudioclient/AudioEffect.cpp +++ b/media/libaudioclient/AudioEffect.cpp @@ -666,7 +666,7 @@ status_t AudioEffect::addStreamDefaultEffect(const char *typeStr, media::AudioUuid uuidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(uuid)); std::string opPackageNameAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_String16_string(opPackageName)); - media::AudioUsage usageAidl = VALUE_OR_RETURN_STATUS( + media::audio::common::AudioUsage usageAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_usage_t_AudioUsage(usage)); int32_t retAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 057befdc4d..e15643a052 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -53,7 +53,12 @@ using aidl_utils::statusTFromBinderStatus; using binder::Status; using content::AttributionSourceState; using media::IAudioPolicyService; +using media::audio::common::AudioConfig; +using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioStreamType; +using media::audio::common::AudioUsage; // client singleton for AudioFlinger binder interface Mutex AudioSystem::gLock; @@ -955,7 +960,7 @@ audio_io_handle_t AudioSystem::getOutput(audio_stream_type_t stream) { if (aps == 0) return AUDIO_IO_HANDLE_NONE; auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN( + AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t outputAidl; RETURN_IF_ERROR( @@ -1003,7 +1008,7 @@ status_t AudioSystem::getOutputForAttr(audio_attributes_t* attr, media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(*attr)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); - media::AudioConfig configAidl = VALUE_OR_RETURN_STATUS( + AudioConfig configAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_t_AudioConfig(*config, false /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_output_flags_t_int32_t_mask(flags)); @@ -1097,7 +1102,7 @@ status_t AudioSystem::getInputForAttr(const audio_attributes_t* attr, int32_t inputAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(*input)); int32_t riidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_unique_id_t_int32_t(riid)); int32_t sessionAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_session_t_int32_t(session)); - media::AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS( + AudioConfigBase configAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_base_t_AudioConfigBase(*config, true /*isInput*/)); int32_t flagsAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); int32_t selectedDeviceIdAidl = VALUE_OR_RETURN_STATUS( @@ -1154,7 +1159,7 @@ status_t AudioSystem::initStreamVolume(audio_stream_type_t stream, const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexMinAidl = VALUE_OR_RETURN_STATUS(convertIntegral(indexMin)); int32_t indexMaxAidl = VALUE_OR_RETURN_STATUS(convertIntegral(indexMax)); @@ -1168,7 +1173,7 @@ status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream, const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral(index)); media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( @@ -1183,7 +1188,7 @@ status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream, const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); @@ -1259,7 +1264,7 @@ product_strategy_t AudioSystem::getStrategyForStream(audio_stream_type_t stream) if (aps == 0) return PRODUCT_STRATEGY_NONE; auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN( + AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t resultAidl; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -1274,7 +1279,7 @@ DeviceTypeSet AudioSystem::getDevicesForStream(audio_stream_type_t stream) { if (aps == 0) return DeviceTypeSet{}; auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN( + AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); std::vector resultAidl; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -1373,7 +1378,7 @@ status_t AudioSystem::isStreamActive(audio_stream_type_t stream, bool* state, ui if (aps == 0) return PERMISSION_DENIED; if (state == NULL) return BAD_VALUE; - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t inPastMsAidl = VALUE_OR_RETURN_STATUS(convertIntegral(inPastMs)); RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( @@ -1387,7 +1392,7 @@ status_t AudioSystem::isStreamActiveRemotely(audio_stream_type_t stream, bool* s if (aps == 0) return PERMISSION_DENIED; if (state == NULL) return BAD_VALUE; - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t inPastMsAidl = VALUE_OR_RETURN_STATUS(convertIntegral(inPastMs)); RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( @@ -1445,9 +1450,9 @@ status_t AudioSystem::setSupportedSystemUsages(const std::vector& const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == nullptr) return PERMISSION_DENIED; - std::vector systemUsagesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(systemUsages, - legacy2aidl_audio_usage_t_AudioUsage)); + std::vector systemUsagesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(systemUsages, + legacy2aidl_audio_usage_t_AudioUsage)); return statusTFromBinderStatus(aps->setSupportedSystemUsages(systemUsagesAidl)); } @@ -1467,7 +1472,7 @@ audio_offload_mode_t AudioSystem::getOffloadSupport(const audio_offload_info_t& if (aps == 0) return AUDIO_OFFLOAD_NOT_SUPPORTED; auto result = [&]() -> ConversionResult { - media::AudioOffloadInfo infoAidl = VALUE_OR_RETURN( + AudioOffloadInfo infoAidl = VALUE_OR_RETURN( legacy2aidl_audio_offload_info_t_AudioOffloadInfo(info)); media::AudioOffloadMode retAidl; RETURN_IF_ERROR( @@ -1839,7 +1844,7 @@ AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devi if (aps == 0) return NAN; auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN( + AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN(convertIntegral(index)); media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN( @@ -2278,7 +2283,7 @@ status_t AudioSystem::canBeSpatialized(const audio_attributes_t *attr, std::optional attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); - std::optional configAidl = VALUE_OR_RETURN_STATUS( + std::optional configAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_t_AudioConfig(configuration, false /*isInput*/)); std::vector devicesAidl = VALUE_OR_RETURN_STATUS( convertContainer>(devices, @@ -2464,9 +2469,9 @@ Status AudioSystem::AudioPolicyServiceClient::onDynamicPolicyMixStateUpdate( Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( int32_t event, const media::RecordClientInfo& clientInfo, - const media::AudioConfigBase& clientConfig, + const AudioConfigBase& clientConfig, const std::vector& clientEffects, - const media::AudioConfigBase& deviceConfig, + const AudioConfigBase& deviceConfig, const std::vector& effects, int32_t patchHandle, media::AudioSourceType source) { diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp index 1149790412..0f8c17ca16 100644 --- a/media/libaudioclient/AudioTrack.cpp +++ b/media/libaudioclient/AudioTrack.cpp @@ -170,7 +170,7 @@ bool AudioTrack::isDirectOutputSupported(const audio_config_base_t& config, if (aps == 0) return false; auto result = [&]() -> ConversionResult { - media::AudioConfigBase configAidl = VALUE_OR_RETURN( + media::audio::common::AudioConfigBase configAidl = VALUE_OR_RETURN( legacy2aidl_audio_config_base_t_AudioConfigBase(config, false /*isInput*/)); media::AudioAttributesInternal attributesAidl = VALUE_OR_RETURN( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); diff --git a/media/libaudioclient/AudioVolumeGroup.cpp b/media/libaudioclient/AudioVolumeGroup.cpp index 361f7b834d..36696cdedc 100644 --- a/media/libaudioclient/AudioVolumeGroup.cpp +++ b/media/libaudioclient/AudioVolumeGroup.cpp @@ -31,6 +31,8 @@ namespace android { +using media::audio::common::AudioStreamType; + status_t AudioVolumeGroup::readFromParcel(const Parcel *parcel) { media::AudioVolumeGroup aidl; @@ -55,7 +57,7 @@ legacy2aidl_AudioVolumeGroup(const AudioVolumeGroup& legacy) { legacy.getAudioAttributes(), legacy2aidl_audio_attributes_t_AudioAttributesInternal)); aidl.streams = VALUE_OR_RETURN( - convertContainer>(legacy.getStreamTypes(), + convertContainer>(legacy.getStreamTypes(), legacy2aidl_audio_stream_type_t_AudioStreamType)); return aidl; } diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index ee6489430b..c5a7c96449 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -32,6 +32,7 @@ using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::audio::common::AudioChannelLayout; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioStreamType; #define MAX_ITEMS_PER_LIST 1024 @@ -321,14 +322,14 @@ status_t AudioFlingerClientAdapter::getMasterBalance(float* balance) const{ status_t AudioFlingerClientAdapter::setStreamVolume(audio_stream_type_t stream, float value, audio_io_handle_t output) { - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t outputAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output)); return statusTFromBinderStatus(mDelegate->setStreamVolume(streamAidl, value, outputAidl)); } status_t AudioFlingerClientAdapter::setStreamMute(audio_stream_type_t stream, bool muted) { - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); return statusTFromBinderStatus(mDelegate->setStreamMute(streamAidl, muted)); } @@ -336,7 +337,7 @@ status_t AudioFlingerClientAdapter::setStreamMute(audio_stream_type_t stream, bo float AudioFlingerClientAdapter::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const { auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t outputAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(output)); float aidlRet; @@ -350,7 +351,7 @@ float AudioFlingerClientAdapter::streamVolume(audio_stream_type_t stream, bool AudioFlingerClientAdapter::streamMute(audio_stream_type_t stream) const { auto result = [&]() -> ConversionResult { - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); bool aidlRet; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -481,7 +482,7 @@ status_t AudioFlingerClientAdapter::closeInput(audio_io_handle_t input) { } status_t AudioFlingerClientAdapter::invalidateStream(audio_stream_type_t stream) { - media::AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( + AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); return statusTFromBinderStatus(mDelegate->invalidateStream(streamAidl)); } @@ -872,7 +873,7 @@ Status AudioFlingerServerAdapter::getMasterBalance(float* _aidl_return) { return Status::fromStatusT(mDelegate->getMasterBalance(_aidl_return)); } -Status AudioFlingerServerAdapter::setStreamVolume(media::AudioStreamType stream, float value, +Status AudioFlingerServerAdapter::setStreamVolume(AudioStreamType stream, float value, int32_t output) { audio_stream_type_t streamLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioStreamType_audio_stream_type_t(stream)); @@ -881,13 +882,13 @@ Status AudioFlingerServerAdapter::setStreamVolume(media::AudioStreamType stream, return Status::fromStatusT(mDelegate->setStreamVolume(streamLegacy, value, outputLegacy)); } -Status AudioFlingerServerAdapter::setStreamMute(media::AudioStreamType stream, bool muted) { +Status AudioFlingerServerAdapter::setStreamMute(AudioStreamType stream, bool muted) { audio_stream_type_t streamLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioStreamType_audio_stream_type_t(stream)); return Status::fromStatusT(mDelegate->setStreamMute(streamLegacy, muted)); } -Status AudioFlingerServerAdapter::streamVolume(media::AudioStreamType stream, int32_t output, +Status AudioFlingerServerAdapter::streamVolume(AudioStreamType stream, int32_t output, float* _aidl_return) { audio_stream_type_t streamLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioStreamType_audio_stream_type_t(stream)); @@ -897,7 +898,7 @@ Status AudioFlingerServerAdapter::streamVolume(media::AudioStreamType stream, in return Status::ok(); } -Status AudioFlingerServerAdapter::streamMute(media::AudioStreamType stream, bool* _aidl_return) { +Status AudioFlingerServerAdapter::streamMute(AudioStreamType stream, bool* _aidl_return) { audio_stream_type_t streamLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioStreamType_audio_stream_type_t(stream)); *_aidl_return = mDelegate->streamMute(streamLegacy); @@ -1008,7 +1009,7 @@ Status AudioFlingerServerAdapter::closeInput(int32_t input) { return Status::fromStatusT(mDelegate->closeInput(inputLegacy)); } -Status AudioFlingerServerAdapter::invalidateStream(media::AudioStreamType stream) { +Status AudioFlingerServerAdapter::invalidateStream(AudioStreamType stream) { audio_stream_type_t streamLegacy = VALUE_OR_RETURN_BINDER( aidl2legacy_AudioStreamType_audio_stream_type_t(stream)); return Status::fromStatusT(mDelegate->invalidateStream(streamLegacy)); diff --git a/media/libaudioclient/aidl/android/media/AudioAttributesEx.aidl b/media/libaudioclient/aidl/android/media/AudioAttributesEx.aidl index 04a02c721b..335866f566 100644 --- a/media/libaudioclient/aidl/android/media/AudioAttributesEx.aidl +++ b/media/libaudioclient/aidl/android/media/AudioAttributesEx.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioAttributesInternal; -import android.media.AudioStreamType; +import android.media.audio.common.AudioStreamType; /** * This is the equivalent of the android::AudioAttributes C++ type. diff --git a/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl b/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl index 699df0adad..1e8d65d0dc 100644 --- a/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl +++ b/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl @@ -18,7 +18,7 @@ package android.media; import android.media.AudioContentType; import android.media.AudioSourceType; -import android.media.AudioUsage; +import android.media.audio.common.AudioUsage; /** * The "Internal" suffix of this type name is to disambiguate it from the diff --git a/media/libaudioclient/aidl/android/media/AudioConfig.aidl b/media/libaudioclient/aidl/android/media/AudioConfig.aidl deleted file mode 100644 index aea7a3430e..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioConfig.aidl +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioOffloadInfo; -import android.media.audio.common.AudioChannelLayout; -import android.media.audio.common.AudioFormatDescription; - -/** - * {@hide} - */ -parcelable AudioConfig { - int sampleRate; - AudioChannelLayout channelMask; - AudioFormatDescription format; - AudioOffloadInfo offloadInfo; - long frameCount; -} diff --git a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl b/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl deleted file mode 100644 index 54b1780d20..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioConfigBase.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.audio.common.AudioChannelLayout; -import android.media.audio.common.AudioFormatDescription; - -/** - * {@hide} - */ -parcelable AudioConfigBase { - int sampleRate; - AudioChannelLayout channelMask; - AudioFormatDescription format; -} diff --git a/media/libaudioclient/aidl/android/media/AudioEncapsulationMode.aidl b/media/libaudioclient/aidl/android/media/AudioEncapsulationMode.aidl deleted file mode 100644 index 9e04e82eac..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioEncapsulationMode.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioEncapsulationMode { - NONE = 0, - ELEMENTARY_STREAM = 1, - HANDLE = 2, -} diff --git a/media/libaudioclient/aidl/android/media/AudioMix.aidl b/media/libaudioclient/aidl/android/media/AudioMix.aidl index 7473372a13..6a8980f43f 100644 --- a/media/libaudioclient/aidl/android/media/AudioMix.aidl +++ b/media/libaudioclient/aidl/android/media/AudioMix.aidl @@ -16,12 +16,12 @@ package android.media; -import android.media.AudioConfig; import android.media.AudioDevice; import android.media.AudioMixCallbackFlag; import android.media.AudioMixMatchCriterion; import android.media.AudioMixRouteFlag; import android.media.AudioMixType; +import android.media.audio.common.AudioConfig; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl b/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl index e26a9e19be..498349f26a 100644 --- a/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl +++ b/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioSourceType; -import android.media.AudioUsage; +import android.media.audio.common.AudioUsage; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl b/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl deleted file mode 100644 index f326305996..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioOffloadInfo.aidl +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioConfigBase; -import android.media.AudioEncapsulationMode; -import android.media.AudioStreamType; -import android.media.AudioUsage; - -/** - * {@hide} - */ -parcelable AudioOffloadInfo { - /** Version of the info structure. Interpreted as a uint16_t version constant. */ - int version; - /** Audio configuration. */ - AudioConfigBase config; - /** Stream type. */ - AudioStreamType streamType; - /** Bit rate in bits per second. */ - int bitRate; - /** Duration in microseconds, -1 if unknown. */ - long durationUs; - /** true if stream is tied to a video stream. */ - boolean hasVideo; - /** true if streaming, false if local playback. */ - boolean isStreaming; - int bitWidth; - /** Offload fragment size. */ - int offloadBufferSize; - AudioUsage usage; - AudioEncapsulationMode encapsulationMode; - /** Content id from tuner HAL (0 if none). */ - int contentId; - /** Sync id from tuner HAL (0 if none). */ - int syncId; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl index c61f044ecf..8d97740a3f 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioSourceType; -import android.media.AudioStreamType; +import android.media.audio.common.AudioStreamType; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioStreamType.aidl b/media/libaudioclient/aidl/android/media/AudioStreamType.aidl deleted file mode 100644 index d7778828e5..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioStreamType.aidl +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioStreamType { - DEFAULT = -1, - VOICE_CALL = 0, - SYSTEM = 1, - RING = 2, - MUSIC = 3, - ALARM = 4, - NOTIFICATION = 5, - BLUETOOTH_SCO = 6, - ENFORCED_AUDIBLE = 7, - DTMF = 8, - TTS = 9, - ACCESSIBILITY = 10, - ASSISTANT = 11, - /** For dynamic policy output mixes. Only used by the audio policy */ - REROUTING = 12, - /** For audio flinger tracks volume. Only used by the audioflinger */ - PATCH = 13, - /** stream for corresponding to AUDIO_USAGE_CALL_ASSISTANT */ - CALL_ASSISTANT = 14, -} diff --git a/media/libaudioclient/aidl/android/media/AudioUsage.aidl b/media/libaudioclient/aidl/android/media/AudioUsage.aidl deleted file mode 100644 index 66c5c30e14..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioUsage.aidl +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioUsage { - UNKNOWN = 0, - MEDIA = 1, - VOICE_COMMUNICATION = 2, - VOICE_COMMUNICATION_SIGNALLING = 3, - ALARM = 4, - NOTIFICATION = 5, - NOTIFICATION_TELEPHONY_RINGTONE = 6, - NOTIFICATION_COMMUNICATION_REQUEST = 7, - NOTIFICATION_COMMUNICATION_INSTANT = 8, - NOTIFICATION_COMMUNICATION_DELAYED = 9, - NOTIFICATION_EVENT = 10, - ASSISTANCE_ACCESSIBILITY = 11, - ASSISTANCE_NAVIGATION_GUIDANCE = 12, - ASSISTANCE_SONIFICATION = 13, - GAME = 14, - VIRTUAL_SOURCE = 15, - ASSISTANT = 16, - CALL_ASSISTANT = 17, - EMERGENCY = 1000, - SAFETY = 1001, - VEHICLE_STATUS = 1002, - ANNOUNCEMENT = 1003, -} diff --git a/media/libaudioclient/aidl/android/media/AudioVolumeGroup.aidl b/media/libaudioclient/aidl/android/media/AudioVolumeGroup.aidl index 3a29a084dd..b95a1d3d33 100644 --- a/media/libaudioclient/aidl/android/media/AudioVolumeGroup.aidl +++ b/media/libaudioclient/aidl/android/media/AudioVolumeGroup.aidl @@ -17,7 +17,7 @@ package android.media; import android.media.AudioAttributesInternal; -import android.media.AudioStreamType; +import android.media.audio.common.AudioStreamType; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl b/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl index 7e3c24018f..b938a3eda7 100644 --- a/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl +++ b/media/libaudioclient/aidl/android/media/CreateRecordRequest.aidl @@ -18,7 +18,7 @@ package android.media; import android.media.AudioAttributesInternal; import android.media.AudioClient; -import android.media.AudioConfigBase; +import android.media.audio.common.AudioConfigBase; /** * CreateRecordRequest contains all input arguments sent by AudioRecord to AudioFlinger diff --git a/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl b/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl index 61195d096a..7d159d0506 100644 --- a/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl +++ b/media/libaudioclient/aidl/android/media/CreateRecordResponse.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioConfigBase; import android.media.IAudioRecord; import android.media.SharedFileRegion; +import android.media.audio.common.AudioConfigBase; /** * CreateRecordResponse contains all output arguments returned by AudioFlinger to AudioRecord diff --git a/media/libaudioclient/aidl/android/media/CreateTrackRequest.aidl b/media/libaudioclient/aidl/android/media/CreateTrackRequest.aidl index 014b3cace5..212221e51c 100644 --- a/media/libaudioclient/aidl/android/media/CreateTrackRequest.aidl +++ b/media/libaudioclient/aidl/android/media/CreateTrackRequest.aidl @@ -18,9 +18,9 @@ package android.media; import android.media.AudioAttributesInternal; import android.media.AudioClient; -import android.media.AudioConfig; import android.media.IAudioTrackCallback; import android.media.SharedFileRegion; +import android.media.audio.common.AudioConfig; /** * CreateTrackInput contains all input arguments sent by AudioTrack to AudioFlinger diff --git a/media/libaudioclient/aidl/android/media/CreateTrackResponse.aidl b/media/libaudioclient/aidl/android/media/CreateTrackResponse.aidl index 40473fa0e6..da6f4548d6 100644 --- a/media/libaudioclient/aidl/android/media/CreateTrackResponse.aidl +++ b/media/libaudioclient/aidl/android/media/CreateTrackResponse.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioStreamType; +import android.media.audio.common.AudioStreamType; import android.media.IAudioTrack; /** diff --git a/media/libaudioclient/aidl/android/media/GetOutputForAttrResponse.aidl b/media/libaudioclient/aidl/android/media/GetOutputForAttrResponse.aidl index 164fb9df30..963877a1cd 100644 --- a/media/libaudioclient/aidl/android/media/GetOutputForAttrResponse.aidl +++ b/media/libaudioclient/aidl/android/media/GetOutputForAttrResponse.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioStreamType; +import android.media.audio.common.AudioStreamType; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 7b02a9db7a..758ae071a8 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -20,7 +20,6 @@ import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; import android.media.AudioPortConfig; -import android.media.AudioStreamType; import android.media.AudioUniqueIdUse; import android.media.AudioUuid; import android.media.AudioVibratorInfo; @@ -43,6 +42,7 @@ import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; import android.media.audio.common.AudioChannelLayout; import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioStreamType; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 74bfa05a08..37834c93b2 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -20,13 +20,10 @@ import android.content.AttributionSourceState; import android.media.AudioAttributesEx; import android.media.AudioAttributesInternal; -import android.media.AudioConfig; -import android.media.AudioConfigBase; import android.media.AudioDevice; import android.media.AudioDeviceDescription; import android.media.AudioMix; import android.media.AudioMode; -import android.media.AudioOffloadInfo; import android.media.AudioOffloadMode; import android.media.AudioPatch; import android.media.AudioPolicyDeviceState; @@ -38,8 +35,6 @@ import android.media.AudioPortRole; import android.media.AudioPortType; import android.media.AudioProductStrategy; import android.media.AudioSourceType; -import android.media.AudioStreamType; -import android.media.AudioUsage; import android.media.AudioUuid; import android.media.AudioVolumeGroup; import android.media.DeviceRole; @@ -52,7 +47,12 @@ import android.media.ICaptureStateListener; import android.media.INativeSpatializerCallback; import android.media.Int; import android.media.SoundTriggerSession; +import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioConfigBase; import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioOffloadInfo; +import android.media.audio.common.AudioStreamType; +import android.media.audio.common.AudioUsage; /** * IAudioPolicyService interface (see AudioPolicyInterface for method descriptions). diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl index a7782b86fd..cf66644584 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl @@ -16,10 +16,10 @@ package android.media; -import android.media.AudioConfigBase; import android.media.AudioSourceType; import android.media.EffectDescriptor; import android.media.RecordClientInfo; +import android.media.audio.common.AudioConfigBase; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl index 2e55526b03..cd8a32598a 100644 --- a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl +++ b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioConfig; import android.media.AudioDevice; import android.media.AudioSourceType; +import android.media.audio.common.AudioConfig; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl b/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl index b613ba53eb..b4de4048de 100644 --- a/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl +++ b/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioConfig; import android.media.AudioDevice; +import android.media.audio.common.AudioConfig; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/OpenOutputRequest.aidl b/media/libaudioclient/aidl/android/media/OpenOutputRequest.aidl index 1541948fec..90e7ea6d23 100644 --- a/media/libaudioclient/aidl/android/media/OpenOutputRequest.aidl +++ b/media/libaudioclient/aidl/android/media/OpenOutputRequest.aidl @@ -16,9 +16,9 @@ package android.media; -import android.media.AudioConfig; -import android.media.AudioConfigBase; import android.media.AudioPort; +import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioConfigBase; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/OpenOutputResponse.aidl b/media/libaudioclient/aidl/android/media/OpenOutputResponse.aidl index a051969ca6..451a0bf70e 100644 --- a/media/libaudioclient/aidl/android/media/OpenOutputResponse.aidl +++ b/media/libaudioclient/aidl/android/media/OpenOutputResponse.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioConfig; +import android.media.audio.common.AudioConfig; /** * {@hide} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 7e87a4e3e9..0a434594b1 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -23,11 +23,8 @@ #include #include -#include -#include #include #include -#include #include #include #include @@ -53,7 +50,12 @@ #include #include #include +#include +#include +#include +#include #include +#include #include #include @@ -192,9 +194,9 @@ legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( const audio_port_config_device_ext& legacy); ConversionResult aidl2legacy_AudioStreamType_audio_stream_type_t( - media::AudioStreamType aidl); -ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamType( - audio_stream_type_t legacy); + media::audio::common::AudioStreamType aidl); +ConversionResult +legacy2aidl_audio_stream_type_t_AudioStreamType(audio_stream_type_t legacy); ConversionResult aidl2legacy_AudioSourceType_audio_source_t( media::AudioSourceType aidl); @@ -242,8 +244,8 @@ ConversionResult legacy2aidl_audio_content_type_t_AudioContentType(audio_content_type_t legacy); ConversionResult -aidl2legacy_AudioUsage_audio_usage_t(media::AudioUsage aidl); -ConversionResult +aidl2legacy_AudioUsage_audio_usage_t(media::audio::common::AudioUsage aidl); +ConversionResult legacy2aidl_audio_usage_t_AudioUsage(audio_usage_t legacy); ConversionResult @@ -262,23 +264,26 @@ ConversionResult legacy2aidl_audio_attributes_t_AudioAttributesInternal(const audio_attributes_t& legacy); ConversionResult -aidl2legacy_AudioEncapsulationMode_audio_encapsulation_mode_t(media::AudioEncapsulationMode aidl); -ConversionResult +aidl2legacy_AudioEncapsulationMode_audio_encapsulation_mode_t( + media::audio::common::AudioEncapsulationMode aidl); +ConversionResult legacy2aidl_audio_encapsulation_mode_t_AudioEncapsulationMode(audio_encapsulation_mode_t legacy); ConversionResult -aidl2legacy_AudioOffloadInfo_audio_offload_info_t(const media::AudioOffloadInfo& aidl); -ConversionResult +aidl2legacy_AudioOffloadInfo_audio_offload_info_t( + const media::audio::common::AudioOffloadInfo& aidl); +ConversionResult legacy2aidl_audio_offload_info_t_AudioOffloadInfo(const audio_offload_info_t& legacy); ConversionResult -aidl2legacy_AudioConfig_audio_config_t(const media::AudioConfig& aidl, bool isInput); -ConversionResult +aidl2legacy_AudioConfig_audio_config_t(const media::audio::common::AudioConfig& aidl, bool isInput); +ConversionResult legacy2aidl_audio_config_t_AudioConfig(const audio_config_t& legacy, bool isInput); ConversionResult -aidl2legacy_AudioConfigBase_audio_config_base_t(const media::AudioConfigBase& aidl, bool isInput); -ConversionResult +aidl2legacy_AudioConfigBase_audio_config_base_t( + const media::audio::common::AudioConfigBase& aidl, bool isInput); +ConversionResult legacy2aidl_audio_config_base_t_AudioConfigBase(const audio_config_base_t& legacy, bool isInput); ConversionResult> diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 50ab42ab50..dbd1f6bc8c 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -689,9 +689,9 @@ private: binder::Status onRecordingConfigurationUpdate( int32_t event, const media::RecordClientInfo& clientInfo, - const media::AudioConfigBase& clientConfig, + const media::audio::common::AudioConfigBase& clientConfig, const std::vector& clientEffects, - const media::AudioConfigBase& deviceConfig, + const media::audio::common::AudioConfigBase& deviceConfig, const std::vector& effects, int32_t patchHandle, media::AudioSourceType source) override; diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index a74661acfb..6d62b6b2ca 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -580,11 +580,12 @@ public: Status masterMute(bool* _aidl_return) override; Status setMasterBalance(float balance) override; Status getMasterBalance(float* _aidl_return) override; - Status setStreamVolume(media::AudioStreamType stream, float value, int32_t output) override; - Status setStreamMute(media::AudioStreamType stream, bool muted) override; - Status - streamVolume(media::AudioStreamType stream, int32_t output, float* _aidl_return) override; - Status streamMute(media::AudioStreamType stream, bool* _aidl_return) override; + Status setStreamVolume(media::audio::common::AudioStreamType stream, + float value, int32_t output) override; + Status setStreamMute(media::audio::common::AudioStreamType stream, bool muted) override; + Status streamVolume(media::audio::common::AudioStreamType stream, + int32_t output, float* _aidl_return) override; + Status streamMute(media::audio::common::AudioStreamType stream, bool* _aidl_return) override; Status setMode(media::AudioMode mode) override; Status setMicMute(bool state) override; Status getMicMute(bool* _aidl_return) override; @@ -606,7 +607,7 @@ public: Status openInput(const media::OpenInputRequest& request, media::OpenInputResponse* _aidl_return) override; Status closeInput(int32_t input) override; - Status invalidateStream(media::AudioStreamType stream) override; + Status invalidateStream(media::audio::common::AudioStreamType stream) override; Status setVoiceVolume(float volume) override; Status getRenderPosition(int32_t output, media::RenderPosition* _aidl_return) override; Status getInputFramesLost(int32_t ioHandle, int32_t* _aidl_return) override; diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 3ff927d4a6..9346de3696 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -44,7 +44,12 @@ namespace android { using binder::Status; using aidl_utils::binderStatusFromStatusT; using content::AttributionSourceState; +using media::audio::common::AudioConfig; +using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioStreamType; +using media::audio::common::AudioUsage; const std::vector& SYSTEM_USAGES = { AUDIO_USAGE_CALL_ASSISTANT, @@ -258,7 +263,7 @@ Status AudioPolicyService::getForceUse(media::AudioPolicyForceUse usageAidl, return Status::ok(); } -Status AudioPolicyService::getOutput(media::AudioStreamType streamAidl, int32_t* _aidl_return) +Status AudioPolicyService::getOutput(AudioStreamType streamAidl, int32_t* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -282,7 +287,7 @@ Status AudioPolicyService::getOutput(media::AudioStreamType streamAidl, int32_t* Status AudioPolicyService::getOutputForAttr(const media::AudioAttributesInternal& attrAidl, int32_t sessionAidl, const AttributionSourceState& attributionSource, - const media::AudioConfig& configAidl, + const AudioConfig& configAidl, int32_t flagsAidl, int32_t selectedDeviceIdAidl, media::GetOutputForAttrResponse* _aidl_return) @@ -511,7 +516,7 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& int32_t riidAidl, int32_t sessionAidl, const AttributionSourceState& attributionSource, - const media::AudioConfigBase& configAidl, + const AudioConfigBase& configAidl, int32_t flagsAidl, int32_t selectedDeviceIdAidl, media::GetInputForAttrResponse* _aidl_return) { @@ -902,7 +907,7 @@ Status AudioPolicyService::releaseInput(int32_t portIdAidl) return Status::ok(); } -Status AudioPolicyService::initStreamVolume(media::AudioStreamType streamAidl, +Status AudioPolicyService::initStreamVolume(AudioStreamType streamAidl, int32_t indexMinAidl, int32_t indexMaxAidl) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( @@ -925,7 +930,7 @@ Status AudioPolicyService::initStreamVolume(media::AudioStreamType streamAidl, return binderStatusFromStatusT(NO_ERROR); } -Status AudioPolicyService::setStreamVolumeIndex(media::AudioStreamType streamAidl, +Status AudioPolicyService::setStreamVolumeIndex(AudioStreamType streamAidl, const media::AudioDeviceDescription& deviceAidl, int32_t indexAidl) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( @@ -950,7 +955,7 @@ Status AudioPolicyService::setStreamVolumeIndex(media::AudioStreamType streamAid device)); } -Status AudioPolicyService::getStreamVolumeIndex(media::AudioStreamType streamAidl, +Status AudioPolicyService::getStreamVolumeIndex(AudioStreamType streamAidl, const media::AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( @@ -1056,7 +1061,7 @@ Status AudioPolicyService::getMaxVolumeIndexForAttributes( return Status::ok(); } -Status AudioPolicyService::getStrategyForStream(media::AudioStreamType streamAidl, +Status AudioPolicyService::getStrategyForStream(AudioStreamType streamAidl, int32_t* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -1081,7 +1086,7 @@ Status AudioPolicyService::getStrategyForStream(media::AudioStreamType streamAid //audio policy: use audio_device_t appropriately Status AudioPolicyService::getDevicesForStream( - media::AudioStreamType streamAidl, + AudioStreamType streamAidl, std::vector* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -1204,7 +1209,7 @@ Status AudioPolicyService::moveEffectsToIo(const std::vector& idsAidl, return binderStatusFromStatusT(mAudioPolicyManager->moveEffectsToIo(ids, io)); } -Status AudioPolicyService::isStreamActive(media::AudioStreamType streamAidl, int32_t inPastMsAidl, +Status AudioPolicyService::isStreamActive(AudioStreamType streamAidl, int32_t inPastMsAidl, bool* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -1223,7 +1228,7 @@ Status AudioPolicyService::isStreamActive(media::AudioStreamType streamAidl, int return Status::ok(); } -Status AudioPolicyService::isStreamActiveRemotely(media::AudioStreamType streamAidl, +Status AudioPolicyService::isStreamActiveRemotely(AudioStreamType streamAidl, int32_t inPastMsAidl, bool* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( @@ -1327,7 +1332,7 @@ Status AudioPolicyService::addSourceDefaultEffect(const media::AudioUuid& typeAi Status AudioPolicyService::addStreamDefaultEffect(const media::AudioUuid& typeAidl, const std::string& opPackageNameAidl, const media::AudioUuid& uuidAidl, - int32_t priority, media::AudioUsage usageAidl, + int32_t priority, AudioUsage usageAidl, int32_t* _aidl_return) { effect_uuid_t type = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioUuid_audio_uuid_t(typeAidl)); @@ -1375,7 +1380,7 @@ Status AudioPolicyService::removeStreamDefaultEffect(int32_t idAidl) } Status AudioPolicyService::setSupportedSystemUsages( - const std::vector& systemUsagesAidl) { + const std::vector& systemUsagesAidl) { size_t size = systemUsagesAidl.size(); if (size > MAX_ITEMS_PER_LIST) { size = MAX_ITEMS_PER_LIST; @@ -1414,7 +1419,7 @@ Status AudioPolicyService::setAllowedCapturePolicy(int32_t uidAidl, int32_t capt mAudioPolicyManager->setAllowedCapturePolicy(uid, capturePolicy)); } -Status AudioPolicyService::getOffloadSupport(const media::AudioOffloadInfo& infoAidl, +Status AudioPolicyService::getOffloadSupport(const AudioOffloadInfo& infoAidl, media::AudioOffloadMode* _aidl_return) { audio_offload_info_t info = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioOffloadInfo_audio_offload_info_t(infoAidl)); @@ -1430,7 +1435,7 @@ Status AudioPolicyService::getOffloadSupport(const media::AudioOffloadInfo& info } Status AudioPolicyService::isDirectOutputSupported( - const media::AudioConfigBase& configAidl, + const AudioConfigBase& configAidl, const media::AudioAttributesInternal& attributesAidl, bool* _aidl_return) { audio_config_base_t config = VALUE_OR_RETURN_BINDER_STATUS( @@ -1810,7 +1815,7 @@ Status AudioPolicyService::getMasterMono(bool* _aidl_return) Status AudioPolicyService::getStreamVolumeDB( - media::AudioStreamType streamAidl, int32_t indexAidl, + AudioStreamType streamAidl, int32_t indexAidl, const media::AudioDeviceDescription& deviceAidl, float* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -2227,7 +2232,7 @@ Status AudioPolicyService::getSpatializer( Status AudioPolicyService::canBeSpatialized( const std::optional& attrAidl, - const std::optional& configAidl, + const std::optional& configAidl, const std::vector& devicesAidl, bool* _aidl_return) { if (mAudioPolicyManager == nullptr) { diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index 86994edff3..db646335be 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -495,14 +495,14 @@ void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate( int32_t eventAidl = VALUE_OR_RETURN_STATUS(convertIntegral(event)); media::RecordClientInfo clientInfoAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_record_client_info_t_RecordClientInfo(*clientInfo)); - media::AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS( + AudioConfigBase clientConfigAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_base_t_AudioConfigBase( *clientConfig, true /*isInput*/)); std::vector clientEffectsAidl = VALUE_OR_RETURN_STATUS( convertContainer>( clientEffects, legacy2aidl_effect_descriptor_t_EffectDescriptor)); - media::AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS( + AudioConfigBase deviceConfigAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_base_t_AudioConfigBase( *deviceConfig, true /*isInput*/)); std::vector effectsAidl = VALUE_OR_RETURN_STATUS( diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 129c7577ba..a6237bc7f1 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -49,7 +49,11 @@ namespace android { using content::AttributionSourceState; +using media::audio::common::AudioConfig; +using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioStreamType; +using media::audio::common::AudioUsage; // ---------------------------------------------------------------------------- @@ -87,10 +91,10 @@ public: media::AudioPolicyForcedConfig config) override; binder::Status getForceUse(media::AudioPolicyForceUse usage, media::AudioPolicyForcedConfig* _aidl_return) override; - binder::Status getOutput(media::AudioStreamType stream, int32_t* _aidl_return) override; + binder::Status getOutput(AudioStreamType stream, int32_t* _aidl_return) override; binder::Status getOutputForAttr(const media::AudioAttributesInternal& attr, int32_t session, const AttributionSourceState &attributionSource, - const media::AudioConfig& config, + const AudioConfig& config, int32_t flags, int32_t selectedDeviceId, media::GetOutputForAttrResponse* _aidl_return) override; binder::Status startOutput(int32_t portId) override; @@ -99,18 +103,18 @@ public: binder::Status getInputForAttr(const media::AudioAttributesInternal& attr, int32_t input, int32_t riid, int32_t session, const AttributionSourceState &attributionSource, - const media::AudioConfigBase& config, int32_t flags, + const AudioConfigBase& config, int32_t flags, int32_t selectedDeviceId, media::GetInputForAttrResponse* _aidl_return) override; binder::Status startInput(int32_t portId) override; binder::Status stopInput(int32_t portId) override; binder::Status releaseInput(int32_t portId) override; - binder::Status initStreamVolume(media::AudioStreamType stream, int32_t indexMin, + binder::Status initStreamVolume(AudioStreamType stream, int32_t indexMin, int32_t indexMax) override; - binder::Status setStreamVolumeIndex(media::AudioStreamType stream, + binder::Status setStreamVolumeIndex(AudioStreamType stream, const media::AudioDeviceDescription& device, int32_t index) override; - binder::Status getStreamVolumeIndex(media::AudioStreamType stream, + binder::Status getStreamVolumeIndex(AudioStreamType stream, const media::AudioDeviceDescription& device, int32_t* _aidl_return) override; binder::Status setVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, @@ -123,10 +127,10 @@ public: int32_t* _aidl_return) override; binder::Status getMinVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, int32_t* _aidl_return) override; - binder::Status getStrategyForStream(media::AudioStreamType stream, + binder::Status getStrategyForStream(AudioStreamType stream, int32_t* _aidl_return) override; binder::Status getDevicesForStream( - media::AudioStreamType stream, + AudioStreamType stream, std::vector* _aidl_return) override; binder::Status getDevicesForAttributes(const media::AudioAttributesEx& attr, std::vector* _aidl_return) override; @@ -137,9 +141,9 @@ public: binder::Status unregisterEffect(int32_t id) override; binder::Status setEffectEnabled(int32_t id, bool enabled) override; binder::Status moveEffectsToIo(const std::vector& ids, int32_t io) override; - binder::Status isStreamActive(media::AudioStreamType stream, int32_t inPastMs, + binder::Status isStreamActive(AudioStreamType stream, int32_t inPastMs, bool* _aidl_return) override; - binder::Status isStreamActiveRemotely(media::AudioStreamType stream, int32_t inPastMs, + binder::Status isStreamActiveRemotely(AudioStreamType stream, int32_t inPastMs, bool* _aidl_return) override; binder::Status isSourceActive(media::AudioSourceType source, bool* _aidl_return) override; binder::Status queryDefaultPreProcessing( @@ -153,15 +157,15 @@ public: binder::Status addStreamDefaultEffect(const media::AudioUuid& type, const std::string& opPackageName, const media::AudioUuid& uuid, int32_t priority, - media::AudioUsage usage, int32_t* _aidl_return) override; + AudioUsage usage, int32_t* _aidl_return) override; binder::Status removeSourceDefaultEffect(int32_t id) override; binder::Status removeStreamDefaultEffect(int32_t id) override; binder::Status setSupportedSystemUsages( - const std::vector& systemUsages) override; + const std::vector& systemUsages) override; binder::Status setAllowedCapturePolicy(int32_t uid, int32_t capturePolicy) override; - binder::Status getOffloadSupport(const media::AudioOffloadInfo& info, + binder::Status getOffloadSupport(const media::audio::common::AudioOffloadInfo& info, media::AudioOffloadMode* _aidl_return) override; - binder::Status isDirectOutputSupported(const media::AudioConfigBase& config, + binder::Status isDirectOutputSupported(const AudioConfigBase& config, const media::AudioAttributesInternal& attributes, bool* _aidl_return) override; binder::Status listAudioPorts(media::AudioPortRole role, media::AudioPortType type, @@ -196,7 +200,7 @@ public: binder::Status stopAudioSource(int32_t portId) override; binder::Status setMasterMono(bool mono) override; binder::Status getMasterMono(bool* _aidl_return) override; - binder::Status getStreamVolumeDB(media::AudioStreamType stream, int32_t index, + binder::Status getStreamVolumeDB(AudioStreamType stream, int32_t index, const media::AudioDeviceDescription& device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, @@ -257,7 +261,7 @@ public: media::GetSpatializerResponse* _aidl_return) override; binder::Status canBeSpatialized( const std::optional& attr, - const std::optional& config, + const std::optional& config, const std::vector& devices, bool* _aidl_return) override; -- GitLab From dd2314b301dd14f12b265a2222f2ed650edb5f5a Mon Sep 17 00:00:00 2001 From: Ryan Savitski Date: Fri, 27 Aug 2021 16:25:15 +0100 Subject: [PATCH 118/694] framework media seccomp: allow syscalls made by dynamic profilers within the process context There are potential memory leaks in at least media.swcodec, which heap profiling can help with (see linked bug). However the profiling requires making some socket-related syscalls from within the process, which are currently blocked by the media seccomp policy. This patch adds the necessary extra syscalls to allow for profiling of select media processes on arm64 devices. Note that several socket operations have always been allowed, even when not explicitly listed in these policy files. This is because external/minijail/util.c allowlists logging-related syscalls by default, which on Android requires the use of sockets (connect, fcntl, sendto, socket, writev). Even if this wasn't the case, some of these syscalls would still be needed for crash_dump to work. I've edited the framework files directly for the short term, and will look at a more maintainable solution for the future (likely moving to @include-able files as with crash_dump and code_coverage). Tested and verified on sc-dev userdebug device (with MODULE_BUILD_FROM_SOURCE=true): * arm64 media.extractor profileable and doesn't crash * arm64 media.swcodec profileable and doesn't crash Limitations: * not addressing arm32 or x86 policies as I don't have the appropriate devices to test with, and I'm assuming that arm64 is of main interest for the profiling investigation in the short term anyway. * not addressing media.codec (/vendor/bin/hw/android.hardware.media.omx@1.0-service) as I don't understand why its arm64 policy is a copypaste of arm32, as well as being unable to test the process in practice (unsure how to trigger allocations in it for the heap profiler). * this doesn't cover other media processes, including some vendor things. I'm happy to reduce the scope of the patch to just swcodec, or otherwise cover more architectures if they're considered critical. Looking for reviewer input on that, as I'm not familiar with these processes. Bug: 197184220 Bug: 198421643 Change-Id: I7815e9e00514e20ff41d4eabeb779113b0519a87 --- .../seccomp_policy/mediaswcodec-arm64.policy | 10 ++++++++++ .../seccomp_policy/mediaextractor-arm64.policy | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy b/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy index 4c51a9c47b..7ff858b662 100644 --- a/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy +++ b/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy @@ -79,4 +79,14 @@ getgid: 1 getegid: 1 getgroups: 1 +# Android profiler (heapprofd, traced_perf) additions, where not already +# covered by the rest of the file, or by builtin minijail allow-listing of +# logging-related syscalls. +# TODO(b/197184220): this is a targeted addition for a specific investigation, +# and addresses just the arm64 framework av service policies. In the future, we +# should make this more general (e.g. a central file that can be @included in +# other policy files). +setsockopt: 1 +sendmsg: 1 + @include /apex/com.android.media.swcodec/etc/seccomp_policy/code_coverage.arm64.policy diff --git a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy index 9bbd53b5e2..e54c9187e7 100644 --- a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy +++ b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy @@ -46,5 +46,16 @@ mremap: 1 # Required by Sanitizers sched_yield: 1 +# Android profiler (heapprofd, traced_perf) additions, where not already +# covered by the rest of the file, or by builtin minijail allow-listing of +# logging-related syscalls. +# TODO(b/197184220): this is a targeted addition for a specific investigation, +# and addresses just the arm64 framework av service policies. In the future, we +# should make this more general (e.g. a central file that can be @included in +# other policy files). +setsockopt: 1 +sendmsg: 1 +set_tid_address: 1 + @include /apex/com.android.media/etc/seccomp_policy/crash_dump.arm64.policy @include /apex/com.android.media/etc/seccomp_policy/code_coverage.arm64.policy -- GitLab From 621f0e12017a2d057aeaa1937e979ce61b2ac3cf Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Thu, 2 Sep 2021 10:29:09 +0100 Subject: [PATCH 119/694] Fix heap-buffer-overflow in MPEG4Extractor Caused by the extractor assuming that sample size will never exceed the declared max input size (as in AMEDIAFORMAT_KEY_MAX_INPUT_SIZE). Bug: 188893559 Test: Ran the fuzzer using the bug's testcase. Change-Id: I31f2b9a4f1b561c4466c76ea2af8dd532622102a --- media/extractors/mp4/MPEG4Extractor.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index fbcd554046..252a497dec 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -157,6 +157,7 @@ private: MediaBufferHelper *mBuffer; + size_t mSrcBufferSize; uint8_t *mSrcBuffer; bool mIsHeif; @@ -5083,6 +5084,7 @@ MPEG4Source::MPEG4Source( mNALLengthSize(0), mStarted(false), mBuffer(NULL), + mSrcBufferSize(0), mSrcBuffer(NULL), mItemTable(itemTable), mElstShiftStartTicks(elstShiftStartTicks), @@ -5264,6 +5266,7 @@ media_status_t MPEG4Source::start() { // file probably specified a bad max size return AMEDIA_ERROR_MALFORMED; } + mSrcBufferSize = max_size; mStarted = true; @@ -5280,6 +5283,7 @@ media_status_t MPEG4Source::stop() { mBuffer = NULL; } + mSrcBufferSize = 0; delete[] mSrcBuffer; mSrcBuffer = NULL; @@ -6467,6 +6471,10 @@ media_status_t MPEG4Source::read( // Whole NAL units are returned but each fragment is prefixed by // the start code (0x00 00 00 01). ssize_t num_bytes_read = 0; + if (mSrcBufferSize < size) { + // We are trying to read a sample larger than the expected max sample size. + return AMEDIA_ERROR_MALFORMED; + } num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); if (num_bytes_read < (ssize_t)size) { -- GitLab From 7091c403c7e83e0634627df40086fc9e49b26a28 Mon Sep 17 00:00:00 2001 From: Andy Hung Date: Thu, 2 Sep 2021 12:01:43 -0700 Subject: [PATCH 120/694] MediaMetricsService: Remove IMediaMetricsService.cpp We're using IMediaMetricsService.aidl now. Test: compiles Bug: 198663006 Change-Id: I44f52ff6c558d99c661b3d2a732f5e37b3abb07f --- .../libmediametrics/IMediaMetricsService.cpp | 141 ------------------ 1 file changed, 141 deletions(-) delete mode 100644 media/libmediametrics/IMediaMetricsService.cpp diff --git a/media/libmediametrics/IMediaMetricsService.cpp b/media/libmediametrics/IMediaMetricsService.cpp deleted file mode 100644 index b5675e6e96..0000000000 --- a/media/libmediametrics/IMediaMetricsService.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "MediaMetrics" - -#include -#include -#include - -#include -#include -#include - -#include // for status_t -#include -#include -#include - -#include -#include - -namespace android { - -// TODO: Currently ONE_WAY transactions, make both ONE_WAY and synchronous options. - -enum { - SUBMIT_ITEM = IBinder::FIRST_CALL_TRANSACTION, - SUBMIT_BUFFER, -}; - -class BpMediaMetricsService: public BpInterface -{ -public: - explicit BpMediaMetricsService(const sp& impl) - : BpInterface(impl) - { - } - - status_t submit(mediametrics::Item *item) override - { - if (item == nullptr) { - return BAD_VALUE; - } - ALOGV("%s: (ONEWAY) item=%s", __func__, item->toString().c_str()); - - Parcel data; - data.writeInterfaceToken(IMediaMetricsService::getInterfaceDescriptor()); - - status_t status = item->writeToParcel(&data); - if (status != NO_ERROR) { // assume failure logged in item - return status; - } - - status = remote()->transact( - SUBMIT_ITEM, data, nullptr /* reply */, IBinder::FLAG_ONEWAY); - ALOGW_IF(status != NO_ERROR, "%s: bad response from service for submit, status=%d", - __func__, status); - return status; - } - - status_t submitBuffer(const char *buffer, size_t length) override - { - if (buffer == nullptr || length > INT32_MAX) { - return BAD_VALUE; - } - ALOGV("%s: (ONEWAY) length:%zu", __func__, length); - - Parcel data; - data.writeInterfaceToken(IMediaMetricsService::getInterfaceDescriptor()); - - status_t status = data.writeInt32(length) - ?: data.write((uint8_t*)buffer, length); - if (status != NO_ERROR) { - return status; - } - - status = remote()->transact( - SUBMIT_BUFFER, data, nullptr /* reply */, IBinder::FLAG_ONEWAY); - ALOGW_IF(status != NO_ERROR, "%s: bad response from service for submit, status=%d", - __func__, status); - return status; - } -}; - -IMPLEMENT_META_INTERFACE(MediaMetricsService, "android.media.IMediaMetricsService"); - -// ---------------------------------------------------------------------- - -status_t BnMediaMetricsService::onTransact( - uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) -{ - switch (code) { - case SUBMIT_ITEM: { - CHECK_INTERFACE(IMediaMetricsService, data, reply); - - mediametrics::Item * const item = mediametrics::Item::create(); - status_t status = item->readFromParcel(data); - if (status != NO_ERROR) { // assume failure logged in item - return status; - } - status = submitInternal(item, true /* release */); - // assume failure logged by submitInternal - return NO_ERROR; - } - case SUBMIT_BUFFER: { - CHECK_INTERFACE(IMediaMetricsService, data, reply); - int32_t length; - status_t status = data.readInt32(&length); - if (status != NO_ERROR || length <= 0) { - return BAD_VALUE; - } - const void *ptr = data.readInplace(length); - if (ptr == nullptr) { - return BAD_VALUE; - } - status = submitBuffer(static_cast(ptr), length); - // assume failure logged by submitBuffer - return NO_ERROR; - } - - default: - return BBinder::onTransact(code, data, reply, flags); - } -} - -// ---------------------------------------------------------------------------- - -} // namespace android -- GitLab From 7df01786de74375f2b6a271d7d1a2b470249c3be Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Fri, 3 Sep 2021 13:06:22 +0100 Subject: [PATCH 121/694] Fix buffer leak in MPEG4Extractor Bug: 188893559 Test: Ran the fuzzer using the bug's testcase. Change-Id: Ia7d851f1f5f4f3025f4e2e239c7e1ef9bc6f7b0e --- media/extractors/mp4/MPEG4Extractor.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 252a497dec..9e4fbd578f 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6471,17 +6471,18 @@ media_status_t MPEG4Source::read( // Whole NAL units are returned but each fragment is prefixed by // the start code (0x00 00 00 01). ssize_t num_bytes_read = 0; - if (mSrcBufferSize < size) { + bool mSrcBufferFitsDataToRead = size <= mSrcBufferSize; + if (mSrcBufferFitsDataToRead) { + num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); + } else { // We are trying to read a sample larger than the expected max sample size. - return AMEDIA_ERROR_MALFORMED; + // Fall through and let the failure be handled by the following if. } - num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; - - return AMEDIA_ERROR_IO; + return mSrcBufferFitsDataToRead ? AMEDIA_ERROR_IO : AMEDIA_ERROR_MALFORMED; } uint8_t *dstData = (uint8_t *)mBuffer->data(); -- GitLab From 57c44c002666bf75d73f09c844295aac80e45dfc Mon Sep 17 00:00:00 2001 From: jiabin Date: Tue, 31 Aug 2021 23:18:35 +0000 Subject: [PATCH 122/694] Add interface to query the mmap support. Currently, the mmap support is defined in system property. But the vendor may set the values wrongly which may cause some CTS tests fail. These values are best known by the HAL. In that case, add interface to query MMAP support. Test: atest AAudioTests Test: Run OboeTester TEST OUTPUT Test: Verify that MMAP is showed as enabled if supported Test: Try toggling MMAP on and off when opening streams Bug: 193275465 Change-Id: Ida9060b93fa3315031fc451bdea2004ba95207e7 --- media/audioserver/Android.bp | 2 +- media/audioserver/main_audioserver.cpp | 28 ++++++- .../libaaudio/src/core/AudioStreamBuilder.cpp | 55 +++++++++++-- media/libaudioclient/Android.bp | 3 + media/libaudioclient/AudioSystem.cpp | 10 +++ media/libaudioclient/IAudioFlinger.cpp | 15 ++++ .../aidl/android/media/AudioMMapPolicy.aidl | 40 +++++++++ .../android/media/AudioMMapPolicyInfo.aidl | 29 +++++++ .../android/media/AudioMMapPolicyType.aidl | 34 ++++++++ .../android/media/IAudioFlingerService.aidl | 4 + .../include/media/AudioSystem.h | 6 ++ .../include/media/IAudioFlinger.h | 14 ++++ media/libaudiohal/Android.bp | 1 + media/libaudiohal/impl/Android.bp | 3 + media/libaudiohal/impl/DeviceHalHidl.cpp | 10 +++ media/libaudiohal/impl/DeviceHalHidl.h | 4 + media/libaudiohal/impl/DeviceHalLocal.cpp | 7 ++ media/libaudiohal/impl/DeviceHalLocal.h | 4 + media/libaudiohal/impl/PropertyUtils.cpp | 82 +++++++++++++++++++ media/libaudiohal/impl/PropertyUtils.h | 32 ++++++++ .../media/audiohal/DeviceHalInterface.h | 6 ++ services/audioflinger/AudioFlinger.cpp | 23 ++++++ services/audioflinger/AudioFlinger.h | 6 ++ services/audioflinger/AudioHwDevice.cpp | 6 ++ services/audioflinger/AudioHwDevice.h | 4 + 25 files changed, 417 insertions(+), 11 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl create mode 100644 media/libaudiohal/impl/PropertyUtils.cpp create mode 100644 media/libaudiohal/impl/PropertyUtils.h diff --git a/media/audioserver/Android.bp b/media/audioserver/Android.bp index be25ffbe38..e4fc4ded59 100644 --- a/media/audioserver/Android.bp +++ b/media/audioserver/Android.bp @@ -26,6 +26,7 @@ cc_binary { shared_libs: [ "libaaudioservice", + "libaudioclient", "libaudioflinger", "libaudiopolicyservice", "libaudioprocessing", @@ -41,7 +42,6 @@ cc_binary { "libpowermanager", "libutils", "libvibrator", - ], // TODO check if we still need all of these include directories diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp index 8ee1efb2f3..e0740de6a9 100644 --- a/media/audioserver/main_audioserver.cpp +++ b/media/audioserver/main_audioserver.cpp @@ -17,20 +17,26 @@ #define LOG_TAG "audioserver" //#define LOG_NDEBUG 0 +#include + #include #include #include #include +#include +#include +#include +#include #include #include #include +#include #include #include #include // from include_dirs -#include "aaudio/AAudioTesting.h" // aaudio_policy_t, AAUDIO_PROP_MMAP_POLICY, AAUDIO_POLICY_* #include "AudioFlinger.h" #include "AudioPolicyService.h" #include "AAudioService.h" @@ -146,10 +152,24 @@ int main(int argc __unused, char **argv) // AAudioService should only be used in OC-MR1 and later. // And only enable the AAudioService if the system MMAP policy explicitly allows it. // This prevents a client from misusing AAudioService when it is not supported. - aaudio_policy_t mmapPolicy = property_get_int32(AAUDIO_PROP_MMAP_POLICY, - AAUDIO_POLICY_NEVER); - if (mmapPolicy == AAUDIO_POLICY_AUTO || mmapPolicy == AAUDIO_POLICY_ALWAYS) { + // If we cannot get audio flinger here, there must be some serious problems. In that case, + // attempting to call audio flinger on a null pointer could make the process crash + // and attract attentions. + sp af = AudioSystem::get_audio_flinger(); + std::vector policyInfos; + status_t status = af->getMmapPolicyInfos( + media::AudioMMapPolicyType::DEFAULT, &policyInfos); + // Initialize aaudio service when querying mmap policy succeeds and + // any of the policy supports MMAP. + if (status == NO_ERROR || + std::any_of(policyInfos.begin(), policyInfos.end(), [](const auto& info) { + return info.mmapPolicy == media::AudioMMapPolicy::AUTO || + info.mmapPolicy == media::AudioMMapPolicy::ALWAYS; + })) { AAudioService::instantiate(); + } else { + ALOGD("Do not init aaudio service, status %d, policy info size %zu", + status, policyInfos.size()); } ProcessState::self()->startThreadPool(); diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp index a8fd0d91c4..2a6b23524a 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.cpp +++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp @@ -20,9 +20,14 @@ #include #include +#include #include #include +#include +#include +#include +#include #include "binding/AAudioBinderClient.h" #include "client/AudioStreamInternalCapture.h" @@ -86,6 +91,37 @@ static aaudio_result_t builder_createStream(aaudio_direction_t direction, return result; } +namespace { + +aaudio_policy_t aidl2legacy_aaudio_policy(android::media::AudioMMapPolicy aidl) { + switch (aidl) { + case android::media::AudioMMapPolicy::NEVER: + return AAUDIO_POLICY_NEVER; + case android::media::AudioMMapPolicy::AUTO: + return AAUDIO_POLICY_AUTO; + case android::media::AudioMMapPolicy::ALWAYS: + return AAUDIO_POLICY_ALWAYS; + case android::media::AudioMMapPolicy::UNSPECIFIED: + default: + return AAUDIO_UNSPECIFIED; + } +} + +// The aaudio policy will be ALWAYS, NEVER, UNSPECIFIED only when all policy info are +// ALWAYS, NEVER or UNSPECIFIED. Otherwise, the aaudio policy will be AUTO. +aaudio_policy_t getAAudioPolicy( + const std::vector& policyInfos) { + if (policyInfos.empty()) return AAUDIO_POLICY_AUTO; + for (size_t i = 1; i < policyInfos.size(); ++i) { + if (policyInfos.at(i).mmapPolicy != policyInfos.at(0).mmapPolicy) { + return AAUDIO_POLICY_AUTO; + } + } + return aidl2legacy_aaudio_policy(policyInfos.at(0).mmapPolicy); +} + +} // namespace + // Try to open using MMAP path if that is allowed. // Fall back to Legacy path if MMAP not available. // Exact behavior is controlled by MMapPolicy. @@ -104,25 +140,32 @@ aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) { return result; } + std::vector policyInfos; // The API setting is the highest priority. aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy(); // If not specified then get from a system property. - if (mmapPolicy == AAUDIO_UNSPECIFIED) { - mmapPolicy = AAudioProperty_getMMapPolicy(); + if (mmapPolicy == AAUDIO_UNSPECIFIED && android::AudioSystem::getMmapPolicyInfo( + android::media::AudioMMapPolicyType::DEFAULT, &policyInfos) == NO_ERROR) { + mmapPolicy = getAAudioPolicy(policyInfos); } // If still not specified then use the default. if (mmapPolicy == AAUDIO_UNSPECIFIED) { mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT; } - int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy(); - if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) { - mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; + policyInfos.clear(); + aaudio_policy_t mmapExclusivePolicy = AAUDIO_UNSPECIFIED; + if (android::AudioSystem::getMmapPolicyInfo( + android::media::AudioMMapPolicyType::EXCLUSIVE, &policyInfos) == NO_ERROR) { + mmapExclusivePolicy = getAAudioPolicy(policyInfos); + } + if (mmapExclusivePolicy == AAUDIO_UNSPECIFIED) { + mmapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; } aaudio_sharing_mode_t sharingMode = getSharingMode(); if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE) - && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) { + && (mmapExclusivePolicy == AAUDIO_POLICY_NEVER)) { ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__); sharingMode = AAUDIO_SHARING_MODE_SHARED; setSharingMode(sharingMode); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 0a260514a7..921e2d2ba4 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -331,6 +331,9 @@ aidl_interface { "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", + "aidl/android/media/AudioMMapPolicy.aidl", + "aidl/android/media/AudioMMapPolicyInfo.aidl", + "aidl/android/media/AudioMMapPolicyType.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioMode.aidl", "aidl/android/media/AudioOffloadInfo.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 057befdc4d..be0dff8c25 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -2353,6 +2353,16 @@ status_t AudioSystem::setVibratorInfos( return af->setVibratorInfos(vibratorInfos); } +status_t AudioSystem::getMmapPolicyInfo( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + const sp& af = AudioSystem::get_audio_flinger(); + if (af == nullptr) { + return PERMISSION_DENIED; + } + return af->getMmapPolicyInfos(policyType, policyInfos); +} + // --------------------------------------------------------------------------- int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index ee6489430b..566f77c26c 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -17,6 +17,9 @@ #define LOG_TAG "IAudioFlinger" //#define LOG_NDEBUG 0 + +#include + #include #include @@ -777,6 +780,12 @@ status_t AudioFlingerClientAdapter::updateSecondaryOutputs( return statusTFromBinderStatus(mDelegate->updateSecondaryOutputs(trackSecondaryOutputInfos)); } +status_t AudioFlingerClientAdapter::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + return statusTFromBinderStatus(mDelegate->getMmapPolicyInfos(policyType, policyInfos)); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // AudioFlingerServerAdapter @@ -1249,4 +1258,10 @@ Status AudioFlingerServerAdapter::updateSecondaryOutputs( return Status::fromStatusT(mDelegate->updateSecondaryOutputs(trackSecondaryOutputs)); } +Status AudioFlingerServerAdapter::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *_aidl_return) { + return Status::fromStatusT(mDelegate->getMmapPolicyInfos(policyType, _aidl_return)); +} + } // namespace android diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl new file mode 100644 index 0000000000..e3fa951390 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +/** + * Audio MMAP policy describe how the aaudio MMAP feature is used. + * {@hide} + */ +@Backing(type="int") +enum AudioMMapPolicy { + /** + * The policy is unspecified. + */ + UNSPECIFIED = 0, + /** + * The MMAP feature is disabled and never used. + */ + NEVER = 1, + /** + * If MMAP feature works then uses it. Otherwise, fall back to something else. + */ + AUTO = 2, + /** + * The MMAP feature must be used. If not available then fail. + */ + ALWAYS = 3, +} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl new file mode 100644 index 0000000000..ad7bd45312 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +import android.media.AudioDevice; +import android.media.AudioMMapPolicy; + +/** + * Audio MMAP policy info describes how an aaudio MMAP feature can be + * used on a particular device. + * {@hide} + */ +parcelable AudioMMapPolicyInfo { + AudioDevice device; + AudioMMapPolicy mmapPolicy = AudioMMapPolicy.UNSPECIFIED; +} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl new file mode 100644 index 0000000000..d6acd2cca3 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +/** + * The aaudio MMAP policy type. + * {@hide} + */ +@Backing(type="int") +enum AudioMMapPolicyType { + /** + * Default aaudio mmap policy. It is used to query whether the + * aaudio MMAP could be used or not. + */ + DEFAULT = 1, + /** + * Exclusive aaudio mmap policy. It is used to query whether the + * aaudio MMAP could be used in exclusive mode or not. + */ + EXCLUSIVE = 2, +} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 7b02a9db7a..de859b8ad7 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioMMapPolicyInfo; +import android.media.AudioMMapPolicyType; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -217,4 +219,6 @@ interface IAudioFlingerService { // This usually happens when there is a dynamic policy registered. void updateSecondaryOutputs( in TrackSecondaryOutputInfo[] trackSecondaryOutputInfos); + + AudioMMapPolicyInfo[] getMmapPolicyInfos(AudioMMapPolicyType policyType); } diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 50ab42ab50..0da8186586 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -19,6 +19,8 @@ #include +#include +#include #include #include #include @@ -613,6 +615,10 @@ public: static status_t setVibratorInfos(const std::vector& vibratorInfos); + static status_t getMmapPolicyInfo( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + private: class AudioFlingerClient: public IBinder::DeathRecipient, public media::BnAudioFlingerClient diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index a74661acfb..03ad9b0569 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -37,6 +37,8 @@ #include #include +#include +#include #include #include #include @@ -348,6 +350,10 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; + + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; }; /** @@ -445,6 +451,10 @@ public: status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) override; + private: const sp mDelegate; }; @@ -529,6 +539,7 @@ public: SET_AUDIO_HAL_PIDS = media::BnAudioFlingerService::TRANSACTION_setAudioHalPids, SET_VIBRATOR_INFOS = media::BnAudioFlingerService::TRANSACTION_setVibratorInfos, UPDATE_SECONDARY_OUTPUTS = media::BnAudioFlingerService::TRANSACTION_updateSecondaryOutputs, + GET_MMAP_POLICY_INFOS = media::BnAudioFlingerService::TRANSACTION_getMmapPolicyInfos, }; /** @@ -641,6 +652,9 @@ public: Status setVibratorInfos(const std::vector& vibratorInfos) override; Status updateSecondaryOutputs( const std::vector& trackSecondaryOutputInfos) override; + Status getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *_aidl_return) override; private: const sp mDelegate; diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp index bd24c84dbc..5fe74f9d71 100644 --- a/media/libaudiohal/Android.bp +++ b/media/libaudiohal/Android.bp @@ -30,6 +30,7 @@ cc_library_shared { ], shared_libs: [ + "audioclient-types-aidl-cpp", "libdl", "libhidlbase", "liblog", diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp index a2c6e8aeba..ed39231efd 100644 --- a/media/libaudiohal/impl/Android.bp +++ b/media/libaudiohal/impl/Android.bp @@ -23,6 +23,8 @@ cc_defaults { "EffectHalHidl.cpp", "EffectsFactoryHalHidl.cpp", "StreamHalHidl.cpp", + + "PropertyUtils.cpp", ], cflags: [ @@ -50,6 +52,7 @@ cc_defaults { "libmedia_helper", "libmediautils", "libutils", + "audioclient-types-aidl-cpp", ], header_libs: [ "android.hardware.audio.common.util@all-versions", diff --git a/media/libaudiohal/impl/DeviceHalHidl.cpp b/media/libaudiohal/impl/DeviceHalHidl.cpp index aa94eeaf16..e4ab46f4c9 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.cpp +++ b/media/libaudiohal/impl/DeviceHalHidl.cpp @@ -20,6 +20,7 @@ //#define LOG_NDEBUG 0 #include +#include #include #include #include @@ -32,6 +33,7 @@ #include "DeviceHalHidl.h" #include "EffectHalHidl.h" #include "ParameterUtils.h" +#include "PropertyUtils.h" #include "StreamHalHidl.h" using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils; @@ -457,6 +459,14 @@ status_t DeviceHalHidl::removeDeviceEffect( } #endif +status_t DeviceHalHidl::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + // TODO: this is just for test, faking a data by querying the system property. + // When AIDL HAL is ready, this should query AIDL HAL when possible. + return utils::getMmapPolicyInfosFromSystemProperty(policyType, policyInfos); +} + status_t DeviceHalHidl::dump(int fd, const Vector& args) { if (mDevice == 0) return NO_INIT; native_handle_t* hidlHandle = native_handle_create(1, 0); diff --git a/media/libaudiohal/impl/DeviceHalHidl.h b/media/libaudiohal/impl/DeviceHalHidl.h index 2694ab3a12..b93390b2ae 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.h +++ b/media/libaudiohal/impl/DeviceHalHidl.h @@ -119,6 +119,10 @@ class DeviceHalHidl : public DeviceHalInterface, public ConversionHelperHidl status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) override; + status_t dump(int fd, const Vector& args) override; private: diff --git a/media/libaudiohal/impl/DeviceHalLocal.cpp b/media/libaudiohal/impl/DeviceHalLocal.cpp index e0304afd54..bc37886e8c 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.cpp +++ b/media/libaudiohal/impl/DeviceHalLocal.cpp @@ -20,6 +20,7 @@ #include #include "DeviceHalLocal.h" +#include "PropertyUtils.h" #include "StreamHalLocal.h" namespace android { @@ -233,6 +234,12 @@ status_t DeviceHalLocal::removeDeviceEffect( return INVALID_OPERATION; } +status_t DeviceHalLocal::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + return utils::getMmapPolicyInfosFromSystemProperty(policyType, policyInfos); +} + status_t DeviceHalLocal::dump(int fd, const Vector& /* args */) { return mDev->dump(mDev, fd); } diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h index 2fde936b36..869b1b7606 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.h +++ b/media/libaudiohal/impl/DeviceHalLocal.h @@ -112,6 +112,10 @@ class DeviceHalLocal : public DeviceHalInterface status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) override; + status_t dump(int fd, const Vector& args) override; void closeOutputStream(struct audio_stream_out *stream_out); diff --git a/media/libaudiohal/impl/PropertyUtils.cpp b/media/libaudiohal/impl/PropertyUtils.cpp new file mode 100644 index 0000000000..55eec2ba7b --- /dev/null +++ b/media/libaudiohal/impl/PropertyUtils.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "PropertyUtils.h" + +namespace android { +namespace CPP_VERSION { +namespace utils { + +std::string getMmapPolicyProperty(media::AudioMMapPolicyType policyType) { + switch (policyType) { + case media::AudioMMapPolicyType::DEFAULT: + return "aaudio.mmap_policy"; + case media::AudioMMapPolicyType::EXCLUSIVE: + return "aaudio.mmap_exclusive_policy"; + default: + return ""; + } +} + +#define MMAP_POLICY_UNSPECIFIED 0 +#define MMAP_POLICY_NEVER 1 +#define MMAP_POLICY_AUTO 2 +#define MMAP_POLICY_ALWAYS 3 + +int getDefaultPolicyFromType(media::AudioMMapPolicyType policyType) { + switch (policyType) { + case media::AudioMMapPolicyType::EXCLUSIVE: + return MMAP_POLICY_UNSPECIFIED; + case media::AudioMMapPolicyType::DEFAULT: + default: + return MMAP_POLICY_NEVER; + } +} + +media::AudioMMapPolicy legacy2aidlAudioMMapPolicy(int legacy) { + switch (legacy) { + case MMAP_POLICY_NEVER: + return media::AudioMMapPolicy::NEVER; + case MMAP_POLICY_AUTO: + return media::AudioMMapPolicy::AUTO; + case MMAP_POLICY_ALWAYS: + return media::AudioMMapPolicy::ALWAYS; + case MMAP_POLICY_UNSPECIFIED: + default: + return media::AudioMMapPolicy::UNSPECIFIED; + } +} + +status_t getMmapPolicyInfosFromSystemProperty( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + media::AudioMMapPolicyInfo policyInfo; + const std::string propertyStr = getMmapPolicyProperty(policyType); + if (propertyStr.empty()) { + return BAD_VALUE; + } + policyInfo.mmapPolicy = utils::legacy2aidlAudioMMapPolicy( + property_get_int32(propertyStr.c_str(), utils::getDefaultPolicyFromType(policyType))); + policyInfos->push_back(policyInfo); + return NO_ERROR; +} + +} // namespace utils +} // namespace CPP_VERSION +} // namespace android \ No newline at end of file diff --git a/media/libaudiohal/impl/PropertyUtils.h b/media/libaudiohal/impl/PropertyUtils.h new file mode 100644 index 0000000000..b9d0057af4 --- /dev/null +++ b/media/libaudiohal/impl/PropertyUtils.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +namespace android { +namespace CPP_VERSION { +namespace utils { + +status_t getMmapPolicyInfosFromSystemProperty( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + +} // namespace utils +} // namespace CPP_VERSION +} // namespace android diff --git a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h index 69cbcecf14..b93c8d26af 100644 --- a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h @@ -17,6 +17,8 @@ #ifndef ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H #define ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H +#include +#include #include #include #include @@ -120,6 +122,10 @@ class DeviceHalInterface : public RefBase virtual status_t removeDeviceEffect( audio_port_handle_t device, sp effect) = 0; + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; + virtual status_t dump(int fd, const Vector& args) = 0; protected: diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 33b71c55f0..e34b58e5db 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -335,6 +335,29 @@ status_t AudioFlinger::updateSecondaryOutputs( return NO_ERROR; } +status_t AudioFlinger::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + AutoMutex lock(mHardwareLock); + if (mPolicyInfos.find(policyType) != mPolicyInfos.end()) { + *policyInfos = mPolicyInfos[policyType]; + return NO_ERROR; + } + for (size_t i = 0; i < mAudioHwDevs.size(); ++i) { + AudioHwDevice *dev = mAudioHwDevs.valueAt(i); + std::vector infos; + status_t status = dev->getMmapPolicyInfos(policyType, &infos); + if (status != NO_ERROR) { + ALOGE("Failed to query mmap policy info of %d, error %d", + mAudioHwDevs.keyAt(i), status); + continue; + } + policyInfos->insert(policyInfos->end(), infos.begin(), infos.end()); + } + mPolicyInfos[policyType] = *policyInfos; + return NO_ERROR; +} + // getDefaultVibratorInfo_l must be called with AudioFlinger lock held. std::optional AudioFlinger::getDefaultVibratorInfo_l() { if (mAudioVibratorInfos.empty()) { diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index d6bf0ae29a..b5d587bd8e 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -282,6 +282,10 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs); + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -1004,6 +1008,8 @@ private: // Keep in sync with java definition in media/java/android/media/AudioRecord.java static constexpr int32_t kMaxSharedAudioHistoryMs = 5000; + + std::map> mPolicyInfos; }; #undef INCLUDING_FROM_AUDIOFLINGER_H diff --git a/services/audioflinger/AudioHwDevice.cpp b/services/audioflinger/AudioHwDevice.cpp index 16b25f6828..f70840f626 100644 --- a/services/audioflinger/AudioHwDevice.cpp +++ b/services/audioflinger/AudioHwDevice.cpp @@ -102,5 +102,11 @@ status_t AudioHwDevice::getAudioPort(struct audio_port_v7 *port) const { return mHwDevice->getAudioPort(port); } +status_t AudioHwDevice::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) const { + return mHwDevice->getMmapPolicyInfos(policyType, policyInfos); +} + }; // namespace android diff --git a/services/audioflinger/AudioHwDevice.h b/services/audioflinger/AudioHwDevice.h index fc2c693ed5..b72072f656 100644 --- a/services/audioflinger/AudioHwDevice.h +++ b/services/audioflinger/AudioHwDevice.h @@ -85,6 +85,10 @@ public: status_t getAudioPort(struct audio_port_v7 *port) const; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) const; + private: const audio_module_handle_t mHandle; const char * const mModuleName; -- GitLab From 07fc504dda81608f605495bddafb4140d7e99065 Mon Sep 17 00:00:00 2001 From: Emilian Peev Date: Thu, 2 Sep 2021 18:18:06 -0700 Subject: [PATCH 123/694] Camera: Avoid duplicate zoom ratio entries In case we have small enough max digital range, the calculated zoom ratios might get truncated and reference the same zoom value. Check for any previous duplicates and skip the ratios if needed. Bug: 198414316 Test: atest -c cts/tests/camera/src/android/hardware/cts/CameraTest.java Change-Id: If63169e9de6bc6d33e93ce1c1597e0d0a9813371 --- .../api1/client2/Parameters.cpp | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/services/camera/libcameraservice/api1/client2/Parameters.cpp b/services/camera/libcameraservice/api1/client2/Parameters.cpp index 80508e4152..a406e62863 100644 --- a/services/camera/libcameraservice/api1/client2/Parameters.cpp +++ b/services/camera/libcameraservice/api1/client2/Parameters.cpp @@ -864,7 +864,6 @@ status_t Parameters::initialize(CameraDeviceBase *device, int deviceVersion) { if (fabs(maxDigitalZoom.data.f[0] - 1.f) > 0.00001f) { params.set(CameraParameters::KEY_ZOOM, zoom); - params.set(CameraParameters::KEY_MAX_ZOOM, NUM_ZOOM_STEPS - 1); { String8 zoomRatios; @@ -872,18 +871,34 @@ status_t Parameters::initialize(CameraDeviceBase *device, int deviceVersion) { float zoomIncrement = (maxDigitalZoom.data.f[0] - zoom) / (NUM_ZOOM_STEPS-1); bool addComma = false; - for (size_t i=0; i < NUM_ZOOM_STEPS; i++) { + int previousZoom = -1; + size_t zoomSteps = 0; + for (size_t i = 0; i < NUM_ZOOM_STEPS; i++) { + int currentZoom = static_cast(zoom * 100); + if (previousZoom == currentZoom) { + zoom += zoomIncrement; + continue; + } if (addComma) zoomRatios += ","; addComma = true; - zoomRatios += String8::format("%d", static_cast(zoom * 100)); + zoomRatios += String8::format("%d", currentZoom); zoom += zoomIncrement; + previousZoom = currentZoom; + zoomSteps++; + } + + if (zoomSteps > 0) { + params.set(CameraParameters::KEY_ZOOM_RATIOS, zoomRatios); + params.set(CameraParameters::KEY_ZOOM_SUPPORTED, + CameraParameters::TRUE); + params.set(CameraParameters::KEY_MAX_ZOOM, zoomSteps - 1); + zoomAvailable = true; + } else { + params.set(CameraParameters::KEY_ZOOM_SUPPORTED, + CameraParameters::FALSE); } - params.set(CameraParameters::KEY_ZOOM_RATIOS, zoomRatios); } - params.set(CameraParameters::KEY_ZOOM_SUPPORTED, - CameraParameters::TRUE); - zoomAvailable = true; } else { params.set(CameraParameters::KEY_ZOOM_SUPPORTED, CameraParameters::FALSE); -- GitLab From ddceeccb8ae7c68c40cebbad304285637ccdb312 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 3 Sep 2021 13:58:56 -0700 Subject: [PATCH 124/694] Move more types from android.media -> a.m.audio.common SAIDL Move types that are known to be used by audio HALs (those listed in h/i/audio/common/7.0/types.hal): - AudioContentType - AudioEncapsulationMetadataType - AudioEncapsulationType - AudioMode - AudioSource (renamed from AudioSourceType to match the name of MediaRecorder.AudioSource) - AudioUuid Bug: 198812639 Test: m Test: m audioflinger_fuzzer Change-Id: I25b4503d3bbfcba9d21cc5c628b76a6d025b709c --- media/libaudioclient/AidlConversion.cpp | 183 +++++++++--------- media/libaudioclient/Android.bp | 6 - media/libaudioclient/AudioEffect.cpp | 14 +- media/libaudioclient/AudioSystem.cpp | 35 ++-- media/libaudioclient/IAudioFlinger.cpp | 14 +- media/libaudioclient/PolicyAidlConversion.cpp | 4 +- .../media/AudioAttributesInternal.aidl | 6 +- .../aidl/android/media/AudioContentType.aidl | 25 --- .../media/AudioEncapsulationMetadataType.aidl | 26 --- .../android/media/AudioEncapsulationType.aidl | 29 --- .../media/AudioMixMatchCriterionValue.aidl | 4 +- .../aidl/android/media/AudioMode.aidl | 30 --- .../media/AudioPortConfigMixExtUseCase.aidl | 4 +- .../aidl/android/media/AudioProfile.aidl | 2 +- .../aidl/android/media/AudioSourceType.aidl | 43 ---- .../aidl/android/media/AudioUuid.aidl | 27 --- .../aidl/android/media/EffectDescriptor.aidl | 2 +- .../android/media/ExtraAudioDescriptor.aidl | 2 +- .../android/media/IAudioFlingerService.aidl | 4 +- .../android/media/IAudioPolicyService.aidl | 20 +- .../media/IAudioPolicyServiceClient.aidl | 4 +- .../aidl/android/media/OpenInputRequest.aidl | 4 +- .../aidl/android/media/RecordClientInfo.aidl | 4 +- .../fuzzer/audioflinger_fuzzer.cpp | 2 +- .../include/media/AidlConversion.h | 39 ++-- .../include/media/AudioSystem.h | 7 +- .../include/media/IAudioFlinger.h | 5 +- .../include/media/PolicyAidlConversion.h | 1 - services/audioflinger/AudioFlinger.cpp | 2 +- .../service/AudioPolicyClientImpl.cpp | 2 +- .../service/AudioPolicyInterfaceImpl.cpp | 43 ++-- .../service/AudioPolicyService.cpp | 4 +- .../audiopolicy/service/AudioPolicyService.h | 29 +-- 33 files changed, 231 insertions(+), 395 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioContentType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioEncapsulationMetadataType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioEncapsulationType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioMode.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioSourceType.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioUuid.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 3d65a54d12..b499cfadd9 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -37,12 +37,18 @@ using base::unexpected; using media::audio::common::AudioChannelLayout; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; +using media::audio::common::AudioContentType; +using media::audio::common::AudioEncapsulationMetadataType; using media::audio::common::AudioEncapsulationMode; +using media::audio::common::AudioEncapsulationType; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioFormatType; +using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; +using media::audio::common::AudioUuid; using media::audio::common::PcmType; namespace { @@ -1504,7 +1510,7 @@ ConversionResult aidl2legacy_AudioStreamType_audio_stream_t switch (aidl) { case AudioStreamType::INVALID: break; // return error - case AudioStreamType::DEFAULT: + case AudioStreamType::SYS_RESERVED_DEFAULT: return AUDIO_STREAM_DEFAULT; case AudioStreamType::VOICE_CALL: return AUDIO_STREAM_VOICE_CALL; @@ -1544,7 +1550,7 @@ ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamTyp audio_stream_type_t legacy) { switch (legacy) { case AUDIO_STREAM_DEFAULT: - return AudioStreamType::DEFAULT; + return AudioStreamType::SYS_RESERVED_DEFAULT; case AUDIO_STREAM_VOICE_CALL: return AudioStreamType::VOICE_CALL; case AUDIO_STREAM_SYSTEM: @@ -1579,77 +1585,76 @@ ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamTyp return unexpected(BAD_VALUE); } -ConversionResult aidl2legacy_AudioSourceType_audio_source_t( - media::AudioSourceType aidl) { +ConversionResult aidl2legacy_AudioSource_audio_source_t( + AudioSource aidl) { switch (aidl) { - case media::AudioSourceType::INVALID: - // This value does not have an enum + case AudioSource::SYS_RESERVED_INVALID: return AUDIO_SOURCE_INVALID; - case media::AudioSourceType::DEFAULT: + case AudioSource::DEFAULT: return AUDIO_SOURCE_DEFAULT; - case media::AudioSourceType::MIC: + case AudioSource::MIC: return AUDIO_SOURCE_MIC; - case media::AudioSourceType::VOICE_UPLINK: + case AudioSource::VOICE_UPLINK: return AUDIO_SOURCE_VOICE_UPLINK; - case media::AudioSourceType::VOICE_DOWNLINK: + case AudioSource::VOICE_DOWNLINK: return AUDIO_SOURCE_VOICE_DOWNLINK; - case media::AudioSourceType::VOICE_CALL: + case AudioSource::VOICE_CALL: return AUDIO_SOURCE_VOICE_CALL; - case media::AudioSourceType::CAMCORDER: + case AudioSource::CAMCORDER: return AUDIO_SOURCE_CAMCORDER; - case media::AudioSourceType::VOICE_RECOGNITION: + case AudioSource::VOICE_RECOGNITION: return AUDIO_SOURCE_VOICE_RECOGNITION; - case media::AudioSourceType::VOICE_COMMUNICATION: + case AudioSource::VOICE_COMMUNICATION: return AUDIO_SOURCE_VOICE_COMMUNICATION; - case media::AudioSourceType::REMOTE_SUBMIX: + case AudioSource::REMOTE_SUBMIX: return AUDIO_SOURCE_REMOTE_SUBMIX; - case media::AudioSourceType::UNPROCESSED: + case AudioSource::UNPROCESSED: return AUDIO_SOURCE_UNPROCESSED; - case media::AudioSourceType::VOICE_PERFORMANCE: + case AudioSource::VOICE_PERFORMANCE: return AUDIO_SOURCE_VOICE_PERFORMANCE; - case media::AudioSourceType::ECHO_REFERENCE: + case AudioSource::ECHO_REFERENCE: return AUDIO_SOURCE_ECHO_REFERENCE; - case media::AudioSourceType::FM_TUNER: + case AudioSource::FM_TUNER: return AUDIO_SOURCE_FM_TUNER; - case media::AudioSourceType::HOTWORD: + case AudioSource::HOTWORD: return AUDIO_SOURCE_HOTWORD; } return unexpected(BAD_VALUE); } -ConversionResult legacy2aidl_audio_source_t_AudioSourceType( +ConversionResult legacy2aidl_audio_source_t_AudioSource( audio_source_t legacy) { switch (legacy) { case AUDIO_SOURCE_INVALID: - return media::AudioSourceType::INVALID; + return AudioSource::SYS_RESERVED_INVALID; case AUDIO_SOURCE_DEFAULT: - return media::AudioSourceType::DEFAULT; + return AudioSource::DEFAULT; case AUDIO_SOURCE_MIC: - return media::AudioSourceType::MIC; + return AudioSource::MIC; case AUDIO_SOURCE_VOICE_UPLINK: - return media::AudioSourceType::VOICE_UPLINK; + return AudioSource::VOICE_UPLINK; case AUDIO_SOURCE_VOICE_DOWNLINK: - return media::AudioSourceType::VOICE_DOWNLINK; + return AudioSource::VOICE_DOWNLINK; case AUDIO_SOURCE_VOICE_CALL: - return media::AudioSourceType::VOICE_CALL; + return AudioSource::VOICE_CALL; case AUDIO_SOURCE_CAMCORDER: - return media::AudioSourceType::CAMCORDER; + return AudioSource::CAMCORDER; case AUDIO_SOURCE_VOICE_RECOGNITION: - return media::AudioSourceType::VOICE_RECOGNITION; + return AudioSource::VOICE_RECOGNITION; case AUDIO_SOURCE_VOICE_COMMUNICATION: - return media::AudioSourceType::VOICE_COMMUNICATION; + return AudioSource::VOICE_COMMUNICATION; case AUDIO_SOURCE_REMOTE_SUBMIX: - return media::AudioSourceType::REMOTE_SUBMIX; + return AudioSource::REMOTE_SUBMIX; case AUDIO_SOURCE_UNPROCESSED: - return media::AudioSourceType::UNPROCESSED; + return AudioSource::UNPROCESSED; case AUDIO_SOURCE_VOICE_PERFORMANCE: - return media::AudioSourceType::VOICE_PERFORMANCE; + return AudioSource::VOICE_PERFORMANCE; case AUDIO_SOURCE_ECHO_REFERENCE: - return media::AudioSourceType::ECHO_REFERENCE; + return AudioSource::ECHO_REFERENCE; case AUDIO_SOURCE_FM_TUNER: - return media::AudioSourceType::FM_TUNER; + return AudioSource::FM_TUNER; case AUDIO_SOURCE_HOTWORD: - return media::AudioSourceType::HOTWORD; + return AudioSource::HOTWORD; } return unexpected(BAD_VALUE); } @@ -1683,7 +1688,7 @@ ConversionResult aidl2legacy_AudioPortConfigM case media::AudioPortRole::SINK: // This is not a bug. A SINK role corresponds to the source field. - legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSourceType_audio_source_t( + legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSource_audio_source_t( VALUE_OR_RETURN(UNION_GET(aidl, source)))); return legacy; } @@ -1706,7 +1711,7 @@ ConversionResult legacy2aidl_AudioPortConfi case AUDIO_PORT_ROLE_SINK: // This is not a bug. A SINK role corresponds to the source field. UNION_SET(aidl, source, - VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSourceType(legacy.source))); + VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSource(legacy.source))); return aidl; } LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail @@ -1972,35 +1977,35 @@ ConversionResult legacy2aidl_AudioClient_AudioClient( } ConversionResult -aidl2legacy_AudioContentType_audio_content_type_t(media::AudioContentType aidl) { +aidl2legacy_AudioContentType_audio_content_type_t(AudioContentType aidl) { switch (aidl) { - case media::AudioContentType::UNKNOWN: + case AudioContentType::UNKNOWN: return AUDIO_CONTENT_TYPE_UNKNOWN; - case media::AudioContentType::SPEECH: + case AudioContentType::SPEECH: return AUDIO_CONTENT_TYPE_SPEECH; - case media::AudioContentType::MUSIC: + case AudioContentType::MUSIC: return AUDIO_CONTENT_TYPE_MUSIC; - case media::AudioContentType::MOVIE: + case AudioContentType::MOVIE: return AUDIO_CONTENT_TYPE_MOVIE; - case media::AudioContentType::SONIFICATION: + case AudioContentType::SONIFICATION: return AUDIO_CONTENT_TYPE_SONIFICATION; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_content_type_t_AudioContentType(audio_content_type_t legacy) { switch (legacy) { case AUDIO_CONTENT_TYPE_UNKNOWN: - return media::AudioContentType::UNKNOWN; + return AudioContentType::UNKNOWN; case AUDIO_CONTENT_TYPE_SPEECH: - return media::AudioContentType::SPEECH; + return AudioContentType::SPEECH; case AUDIO_CONTENT_TYPE_MUSIC: - return media::AudioContentType::MUSIC; + return AudioContentType::MUSIC; case AUDIO_CONTENT_TYPE_MOVIE: - return media::AudioContentType::MOVIE; + return AudioContentType::MOVIE; case AUDIO_CONTENT_TYPE_SONIFICATION: - return media::AudioContentType::SONIFICATION; + return AudioContentType::SONIFICATION; } return unexpected(BAD_VALUE); } @@ -2210,7 +2215,7 @@ aidl2legacy_AudioAttributesInternal_audio_attributes_t(const media::AudioAttribu legacy.content_type = VALUE_OR_RETURN( aidl2legacy_AudioContentType_audio_content_type_t(aidl.contentType)); legacy.usage = VALUE_OR_RETURN(aidl2legacy_AudioUsage_audio_usage_t(aidl.usage)); - legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSourceType_audio_source_t(aidl.source)); + legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSource_audio_source_t(aidl.source)); legacy.flags = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_flags_mask_t_mask(aidl.flags)); RETURN_IF_ERROR(aidl2legacy_string(aidl.tags, legacy.tags, sizeof(legacy.tags))); return legacy; @@ -2222,7 +2227,7 @@ legacy2aidl_audio_attributes_t_AudioAttributesInternal(const audio_attributes_t& aidl.contentType = VALUE_OR_RETURN( legacy2aidl_audio_content_type_t_AudioContentType(legacy.content_type)); aidl.usage = VALUE_OR_RETURN(legacy2aidl_audio_usage_t_AudioUsage(legacy.usage)); - aidl.source = VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSourceType(legacy.source)); + aidl.source = VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSource(legacy.source)); aidl.flags = VALUE_OR_RETURN(legacy2aidl_audio_flags_mask_t_int32_t_mask(legacy.flags)); aidl.tags = VALUE_OR_RETURN(legacy2aidl_string(legacy.tags, sizeof(legacy.tags))); return aidl; @@ -2417,7 +2422,7 @@ legacy2aidl_AudioTimestamp_AudioTimestampInternal(const AudioTimestamp& legacy) } ConversionResult -aidl2legacy_AudioUuid_audio_uuid_t(const media::AudioUuid& aidl) { +aidl2legacy_AudioUuid_audio_uuid_t(const AudioUuid& aidl) { audio_uuid_t legacy; legacy.timeLow = VALUE_OR_RETURN(convertReinterpret(aidl.timeLow)); legacy.timeMid = VALUE_OR_RETURN(convertIntegral(aidl.timeMid)); @@ -2430,9 +2435,9 @@ aidl2legacy_AudioUuid_audio_uuid_t(const media::AudioUuid& aidl) { return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_uuid_t_AudioUuid(const audio_uuid_t& legacy) { - media::AudioUuid aidl; + AudioUuid aidl; aidl.timeLow = VALUE_OR_RETURN(convertReinterpret(legacy.timeLow)); aidl.timeMid = VALUE_OR_RETURN(convertIntegral(legacy.timeMid)); aidl.timeHiAndVersion = VALUE_OR_RETURN(convertIntegral(legacy.timeHiAndVersion)); @@ -2473,28 +2478,28 @@ legacy2aidl_effect_descriptor_t_EffectDescriptor(const effect_descriptor_t& lega ConversionResult aidl2legacy_AudioEncapsulationMetadataType_audio_encapsulation_metadata_type_t( - media::AudioEncapsulationMetadataType aidl) { + AudioEncapsulationMetadataType aidl) { switch (aidl) { - case media::AudioEncapsulationMetadataType::NONE: + case AudioEncapsulationMetadataType::NONE: return AUDIO_ENCAPSULATION_METADATA_TYPE_NONE; - case media::AudioEncapsulationMetadataType::FRAMEWORK_TUNER: + case AudioEncapsulationMetadataType::FRAMEWORK_TUNER: return AUDIO_ENCAPSULATION_METADATA_TYPE_FRAMEWORK_TUNER; - case media::AudioEncapsulationMetadataType::DVB_AD_DESCRIPTOR: + case AudioEncapsulationMetadataType::DVB_AD_DESCRIPTOR: return AUDIO_ENCAPSULATION_METADATA_TYPE_DVB_AD_DESCRIPTOR; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_encapsulation_metadata_type_t_AudioEncapsulationMetadataType( audio_encapsulation_metadata_type_t legacy) { switch (legacy) { case AUDIO_ENCAPSULATION_METADATA_TYPE_NONE: - return media::AudioEncapsulationMetadataType::NONE; + return AudioEncapsulationMetadataType::NONE; case AUDIO_ENCAPSULATION_METADATA_TYPE_FRAMEWORK_TUNER: - return media::AudioEncapsulationMetadataType::FRAMEWORK_TUNER; + return AudioEncapsulationMetadataType::FRAMEWORK_TUNER; case AUDIO_ENCAPSULATION_METADATA_TYPE_DVB_AD_DESCRIPTOR: - return media::AudioEncapsulationMetadataType::DVB_AD_DESCRIPTOR; + return AudioEncapsulationMetadataType::DVB_AD_DESCRIPTOR; } return unexpected(BAD_VALUE); } @@ -2526,9 +2531,9 @@ aidl2legacy_AudioEncapsulationMetadataType_mask(int32_t aidl) { return convertBitmask( + AudioEncapsulationMetadataType>( aidl, aidl2legacy_AudioEncapsulationMetadataType_audio_encapsulation_metadata_type_t, - indexToEnum_index, + indexToEnum_index, enumToMask_index); } @@ -2536,11 +2541,11 @@ ConversionResult legacy2aidl_AudioEncapsulationMetadataType_mask(uint32_t legacy) { return convertBitmask( legacy, legacy2aidl_audio_encapsulation_metadata_type_t_AudioEncapsulationMetadataType, indexToEnum_index, - enumToMask_index); + enumToMask_index); } ConversionResult @@ -2859,43 +2864,43 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { } ConversionResult -aidl2legacy_AudioMode_audio_mode_t(media::AudioMode aidl) { +aidl2legacy_AudioMode_audio_mode_t(AudioMode aidl) { switch (aidl) { - case media::AudioMode::INVALID: + case AudioMode::SYS_RESERVED_INVALID: return AUDIO_MODE_INVALID; - case media::AudioMode::CURRENT: + case AudioMode::SYS_RESERVED_CURRENT: return AUDIO_MODE_CURRENT; - case media::AudioMode::NORMAL: + case AudioMode::NORMAL: return AUDIO_MODE_NORMAL; - case media::AudioMode::RINGTONE: + case AudioMode::RINGTONE: return AUDIO_MODE_RINGTONE; - case media::AudioMode::IN_CALL: + case AudioMode::IN_CALL: return AUDIO_MODE_IN_CALL; - case media::AudioMode::IN_COMMUNICATION: + case AudioMode::IN_COMMUNICATION: return AUDIO_MODE_IN_COMMUNICATION; - case media::AudioMode::CALL_SCREEN: + case AudioMode::CALL_SCREEN: return AUDIO_MODE_CALL_SCREEN; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_mode_t_AudioMode(audio_mode_t legacy) { switch (legacy) { case AUDIO_MODE_INVALID: - return media::AudioMode::INVALID; + return AudioMode::SYS_RESERVED_INVALID; case AUDIO_MODE_CURRENT: - return media::AudioMode::CURRENT; + return AudioMode::SYS_RESERVED_CURRENT; case AUDIO_MODE_NORMAL: - return media::AudioMode::NORMAL; + return AudioMode::NORMAL; case AUDIO_MODE_RINGTONE: - return media::AudioMode::RINGTONE; + return AudioMode::RINGTONE; case AUDIO_MODE_IN_CALL: - return media::AudioMode::IN_CALL; + return AudioMode::IN_CALL; case AUDIO_MODE_IN_COMMUNICATION: - return media::AudioMode::IN_COMMUNICATION; + return AudioMode::IN_COMMUNICATION; case AUDIO_MODE_CALL_SCREEN: - return media::AudioMode::CALL_SCREEN; + return AudioMode::CALL_SCREEN; case AUDIO_MODE_CNT: break; } @@ -3102,24 +3107,24 @@ legacy2aidl_audio_extra_audio_descriptor_ExtraAudioDescriptor( ConversionResult aidl2legacy_AudioEncapsulationType_audio_encapsulation_type_t( - const media::AudioEncapsulationType& aidl) { + const AudioEncapsulationType& aidl) { switch (aidl) { - case media::AudioEncapsulationType::NONE: + case AudioEncapsulationType::NONE: return AUDIO_ENCAPSULATION_TYPE_NONE; - case media::AudioEncapsulationType::IEC61937: + case AudioEncapsulationType::IEC61937: return AUDIO_ENCAPSULATION_TYPE_IEC61937; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( const audio_encapsulation_type_t & legacy) { switch (legacy) { case AUDIO_ENCAPSULATION_TYPE_NONE: - return media::AudioEncapsulationType::NONE; + return AudioEncapsulationType::NONE; case AUDIO_ENCAPSULATION_TYPE_IEC61937: - return media::AudioEncapsulationType::IEC61937; + return AudioEncapsulationType::IEC61937; } return unexpected(BAD_VALUE); } diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 5b60a40561..322f360b5b 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -313,13 +313,10 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioClient.aidl", - "aidl/android/media/AudioContentType.aidl", "aidl/android/media/AudioDevice.aidl", "aidl/android/media/AudioDeviceDescription.aidl", "aidl/android/media/AudioDeviceType.aidl", "aidl/android/media/AudioDualMonoMode.aidl", - "aidl/android/media/AudioEncapsulationMetadataType.aidl", - "aidl/android/media/AudioEncapsulationType.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", "aidl/android/media/AudioGainConfig.aidl", @@ -329,7 +326,6 @@ aidl_interface { "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", - "aidl/android/media/AudioMode.aidl", "aidl/android/media/AudioOutputFlags.aidl", "aidl/android/media/AudioPatch.aidl", "aidl/android/media/AudioPlaybackRate.aidl", @@ -348,11 +344,9 @@ aidl_interface { "aidl/android/media/AudioPortSessionExt.aidl", "aidl/android/media/AudioPortType.aidl", "aidl/android/media/AudioProfile.aidl", - "aidl/android/media/AudioSourceType.aidl", "aidl/android/media/AudioStandard.aidl", "aidl/android/media/AudioTimestampInternal.aidl", "aidl/android/media/AudioUniqueIdUse.aidl", - "aidl/android/media/AudioUuid.aidl", "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", "aidl/android/media/ExtraAudioDescriptor.aidl", diff --git a/media/libaudioclient/AudioEffect.cpp b/media/libaudioclient/AudioEffect.cpp index 50a9735c3f..65daa3c644 100644 --- a/media/libaudioclient/AudioEffect.cpp +++ b/media/libaudioclient/AudioEffect.cpp @@ -42,6 +42,8 @@ namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::IAudioPolicyService; +using media::audio::common::AudioSource; +using media::audio::common::AudioUuid; namespace { @@ -619,12 +621,12 @@ status_t AudioEffect::addSourceDefaultEffect(const char *typeStr, uuid = *EFFECT_UUID_NULL; } - media::AudioUuid typeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(type)); - media::AudioUuid uuidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(uuid)); + AudioUuid typeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(type)); + AudioUuid uuidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(uuid)); std::string opPackageNameAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_String16_string(opPackageName)); - media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(source)); + AudioSource sourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(source)); int32_t retAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->addSourceDefaultEffect(typeAidl, opPackageNameAidl, uuidAidl, priority, sourceAidl, @@ -662,8 +664,8 @@ status_t AudioEffect::addStreamDefaultEffect(const char *typeStr, uuid = *EFFECT_UUID_NULL; } - media::AudioUuid typeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(type)); - media::AudioUuid uuidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(uuid)); + AudioUuid typeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(type)); + AudioUuid uuidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_uuid_t_AudioUuid(uuid)); std::string opPackageNameAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_String16_string(opPackageName)); media::audio::common::AudioUsage usageAidl = VALUE_OR_RETURN_STATUS( diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index e15643a052..46ad296e74 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -57,6 +57,7 @@ using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; @@ -1405,8 +1406,8 @@ status_t AudioSystem::isSourceActive(audio_source_t stream, bool* state) { if (aps == 0) return PERMISSION_DENIED; if (state == NULL) return BAD_VALUE; - media::AudioSourceType streamAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(stream)); + AudioSource streamAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(stream)); RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->isSourceActive(streamAidl, state))); return OK; @@ -1724,7 +1725,7 @@ audio_mode_t AudioSystem::getPhoneState() { if (aps == 0) return AUDIO_MODE_INVALID; auto result = [&]() -> ConversionResult { - media::AudioMode retAidl; + media::audio::common::AudioMode retAidl; RETURN_IF_ERROR(statusTFromBinderStatus(aps->getPhoneState(&retAidl))); return aidl2legacy_AudioMode_audio_mode_t(retAidl); }(); @@ -2178,8 +2179,8 @@ status_t AudioSystem::setDevicesRoleForCapturePreset(audio_source_t audioSource, return PERMISSION_DENIED; } - media::AudioSourceType audioSourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(audioSource)); + AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); std::vector devicesAidl = VALUE_OR_RETURN_STATUS( convertContainer>(devices, @@ -2195,8 +2196,8 @@ status_t AudioSystem::addDevicesRoleForCapturePreset(audio_source_t audioSource, if (aps == 0) { return PERMISSION_DENIED; } - media::AudioSourceType audioSourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(audioSource)); + AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); std::vector devicesAidl = VALUE_OR_RETURN_STATUS( convertContainer>(devices, @@ -2211,8 +2212,8 @@ status_t AudioSystem::removeDevicesRoleForCapturePreset( if (aps == 0) { return PERMISSION_DENIED; } - media::AudioSourceType audioSourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(audioSource)); + AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); std::vector devicesAidl = VALUE_OR_RETURN_STATUS( convertContainer>(devices, @@ -2227,8 +2228,8 @@ status_t AudioSystem::clearDevicesRoleForCapturePreset(audio_source_t audioSourc if (aps == 0) { return PERMISSION_DENIED; } - media::AudioSourceType audioSourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(audioSource)); + AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); return statusTFromBinderStatus( aps->clearDevicesRoleForCapturePreset(audioSourceAidl, roleAidl)); @@ -2241,8 +2242,8 @@ status_t AudioSystem::getDevicesForRoleAndCapturePreset(audio_source_t audioSour if (aps == 0) { return PERMISSION_DENIED; } - media::AudioSourceType audioSourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(audioSource)); + AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); std::vector devicesAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( @@ -2474,7 +2475,7 @@ Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( const AudioConfigBase& deviceConfig, const std::vector& effects, int32_t patchHandle, - media::AudioSourceType source) { + AudioSource source) { record_config_callback cb = NULL; { Mutex::Autolock _l(AudioSystem::gLock); @@ -2500,7 +2501,7 @@ Status AudioSystem::AudioPolicyServiceClient::onRecordingConfigurationUpdate( audio_patch_handle_t patchHandleLegacy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_patch_handle_t(patchHandle)); audio_source_t sourceLegacy = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(source)); + aidl2legacy_AudioSource_audio_source_t(source)); cb(eventLegacy, &clientInfoLegacy, &clientConfigLegacy, clientEffectsLegacy, &deviceConfigLegacy, effectsLegacy, patchHandleLegacy, sourceLegacy); } @@ -2544,7 +2545,7 @@ aidl2legacy_RecordClientInfo_record_client_info_t(const media::RecordClientInfo& legacy.riid = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_unique_id_t(aidl.riid)); legacy.uid = VALUE_OR_RETURN(aidl2legacy_int32_t_uid_t(aidl.uid)); legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl.session)); - legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSourceType_audio_source_t(aidl.source)); + legacy.source = VALUE_OR_RETURN(aidl2legacy_AudioSource_audio_source_t(aidl.source)); legacy.port_id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.portId)); legacy.silenced = aidl.silenced; return legacy; @@ -2556,7 +2557,7 @@ legacy2aidl_record_client_info_t_RecordClientInfo(const record_client_info_t& le aidl.riid = VALUE_OR_RETURN(legacy2aidl_audio_unique_id_t_int32_t(legacy.riid)); aidl.uid = VALUE_OR_RETURN(legacy2aidl_uid_t_int32_t(legacy.uid)); aidl.session = VALUE_OR_RETURN(legacy2aidl_audio_session_t_int32_t(legacy.session)); - aidl.source = VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSourceType(legacy.source)); + aidl.source = VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSource(legacy.source)); aidl.portId = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.port_id)); aidl.silenced = legacy.silenced; return aidl; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index c5a7c96449..b67f1f76bb 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -32,7 +32,9 @@ using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::audio::common::AudioChannelLayout; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioMode; using media::audio::common::AudioStreamType; +using media::audio::common::AudioUuid; #define MAX_ITEMS_PER_LIST 1024 @@ -363,7 +365,7 @@ bool AudioFlingerClientAdapter::streamMute(audio_stream_type_t stream) const { } status_t AudioFlingerClientAdapter::setMode(audio_mode_t mode) { - media::AudioMode modeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_mode_t_AudioMode(mode)); + AudioMode modeAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_mode_t_AudioMode(mode)); return statusTFromBinderStatus(mDelegate->setMode(modeAidl)); } @@ -581,9 +583,9 @@ status_t AudioFlingerClientAdapter::getEffectDescriptor(const effect_uuid_t* pEf const effect_uuid_t* pTypeUUID, uint32_t preferredTypeFlag, effect_descriptor_t* pDescriptor) const { - media::AudioUuid effectUuidAidl = VALUE_OR_RETURN_STATUS( + AudioUuid effectUuidAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_uuid_t_AudioUuid(*pEffectUUID)); - media::AudioUuid typeUuidAidl = VALUE_OR_RETURN_STATUS( + AudioUuid typeUuidAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_uuid_t_AudioUuid(*pTypeUUID)); int32_t preferredTypeFlagAidl = VALUE_OR_RETURN_STATUS( convertReinterpret(preferredTypeFlag)); @@ -905,7 +907,7 @@ Status AudioFlingerServerAdapter::streamMute(AudioStreamType stream, bool* _aidl return Status::ok(); } -Status AudioFlingerServerAdapter::setMode(media::AudioMode mode) { +Status AudioFlingerServerAdapter::setMode(AudioMode mode) { audio_mode_t modeLegacy = VALUE_OR_RETURN_BINDER(aidl2legacy_AudioMode_audio_mode_t(mode)); return Status::fromStatusT(mDelegate->setMode(modeLegacy)); } @@ -1084,8 +1086,8 @@ AudioFlingerServerAdapter::queryEffect(int32_t index, media::EffectDescriptor* _ return Status::ok(); } -Status AudioFlingerServerAdapter::getEffectDescriptor(const media::AudioUuid& effectUUID, - const media::AudioUuid& typeUUID, +Status AudioFlingerServerAdapter::getEffectDescriptor(const AudioUuid& effectUUID, + const AudioUuid& typeUUID, int32_t preferredTypeFlag, media::EffectDescriptor* _aidl_return) { effect_uuid_t effectUuidLegacy = VALUE_OR_RETURN_BINDER( diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index 676bb37406..c3b7ce7cdb 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -152,7 +152,7 @@ aidl2legacy_AudioMixMatchCriterionValue( case media::AudioMixMatchCriterionValue::source: legacy.mSource = VALUE_OR_RETURN( - aidl2legacy_AudioSourceType_audio_source_t(UNION_GET(aidl, source).value())); + aidl2legacy_AudioSource_audio_source_t(UNION_GET(aidl, source).value())); *rule |= RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET; return legacy; @@ -184,7 +184,7 @@ legacy2aidl_AudioMixMatchCriterionValue( case RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET: UNION_SET(aidl, source, - VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSourceType(legacy.mSource))); + VALUE_OR_RETURN(legacy2aidl_audio_source_t_AudioSource(legacy.mSource))); break; case RULE_MATCH_UID: diff --git a/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl b/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl index 1e8d65d0dc..2e7420633d 100644 --- a/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl +++ b/media/libaudioclient/aidl/android/media/AudioAttributesInternal.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioContentType; -import android.media.AudioSourceType; +import android.media.audio.common.AudioContentType; +import android.media.audio.common.AudioSource; import android.media.audio.common.AudioUsage; /** @@ -28,7 +28,7 @@ import android.media.audio.common.AudioUsage; parcelable AudioAttributesInternal { AudioContentType contentType; AudioUsage usage; - AudioSourceType source; + AudioSource source; // Bitmask, indexed by AudioFlag. int flags; @utf8InCpp String tags; /* UTF8 */ diff --git a/media/libaudioclient/aidl/android/media/AudioContentType.aidl b/media/libaudioclient/aidl/android/media/AudioContentType.aidl deleted file mode 100644 index f734fba18a..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioContentType.aidl +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -@Backing(type="int") -enum AudioContentType { - UNKNOWN = 0, - SPEECH = 1, - MUSIC = 2, - MOVIE = 3, - SONIFICATION = 4, -} diff --git a/media/libaudioclient/aidl/android/media/AudioEncapsulationMetadataType.aidl b/media/libaudioclient/aidl/android/media/AudioEncapsulationMetadataType.aidl deleted file mode 100644 index b03adfe382..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioEncapsulationMetadataType.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioEncapsulationMetadataType { - NONE = 0, - FRAMEWORK_TUNER = 1, - DVB_AD_DESCRIPTOR = 2, -} diff --git a/media/libaudioclient/aidl/android/media/AudioEncapsulationType.aidl b/media/libaudioclient/aidl/android/media/AudioEncapsulationType.aidl deleted file mode 100644 index b08a604c3c..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioEncapsulationType.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * Audio encapsulation type is used to describe if the audio data should be sent with a particular - * encapsulation type or not. - * - * {@hide} - */ -@Backing(type="int") -enum AudioEncapsulationType { - NONE = 0, - IEC61937 = 1, -} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl b/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl index 498349f26a..921a93aa38 100644 --- a/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl +++ b/media/libaudioclient/aidl/android/media/AudioMixMatchCriterionValue.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioSourceType; +import android.media.audio.common.AudioSource; import android.media.audio.common.AudioUsage; /** @@ -24,7 +24,7 @@ import android.media.audio.common.AudioUsage; */ union AudioMixMatchCriterionValue { AudioUsage usage = AudioUsage.UNKNOWN; - AudioSourceType source; + AudioSource source; /** Interpreted as uid_t. */ int uid; int userId; diff --git a/media/libaudioclient/aidl/android/media/AudioMode.aidl b/media/libaudioclient/aidl/android/media/AudioMode.aidl deleted file mode 100644 index 7067dd3b09..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMode.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioMode { - INVALID = -2, - CURRENT = -1, - NORMAL = 0, - RINGTONE = 1, - IN_CALL = 2, - IN_COMMUNICATION = 3, - CALL_SCREEN = 4, -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl index 8d97740a3f..58bc1a56d3 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioSourceType; +import android.media.audio.common.AudioSource; import android.media.audio.common.AudioStreamType; /** @@ -33,5 +33,5 @@ union AudioPortConfigMixExtUseCase { /** This to be set if the containing config has the AudioPortRole::SOURCE role. */ AudioStreamType stream; /** This to be set if the containing config has the AudioPortRole::SINK role. */ - AudioSourceType source; + AudioSource source; } diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfile.aidl index 3e234de990..9378ab39b6 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfile.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioEncapsulationType; +import android.media.audio.common.AudioEncapsulationType; import android.media.audio.common.AudioFormatDescription; import android.media.audio.common.AudioChannelLayout; diff --git a/media/libaudioclient/aidl/android/media/AudioSourceType.aidl b/media/libaudioclient/aidl/android/media/AudioSourceType.aidl deleted file mode 100644 index 8673b9270f..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioSourceType.aidl +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioSourceType { - INVALID = -1, - DEFAULT = 0, - MIC = 1, - VOICE_UPLINK = 2, - VOICE_DOWNLINK = 3, - VOICE_CALL = 4, - CAMCORDER = 5, - VOICE_RECOGNITION = 6, - VOICE_COMMUNICATION = 7, - REMOTE_SUBMIX = 8, - UNPROCESSED = 9, - VOICE_PERFORMANCE = 10, - ECHO_REFERENCE = 1997, - FM_TUNER = 1998, - /** - * A low-priority, preemptible audio source for for background software - * hotword detection. Same tuning as VOICE_RECOGNITION. - * Used only internally by the framework. - */ - HOTWORD = 1999, -} diff --git a/media/libaudioclient/aidl/android/media/AudioUuid.aidl b/media/libaudioclient/aidl/android/media/AudioUuid.aidl deleted file mode 100644 index bba9039ac4..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioUuid.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -parcelable AudioUuid { - int timeLow; - int timeMid; - int timeHiAndVersion; - int clockSeq; - byte[] node; // Length = 6 -} diff --git a/media/libaudioclient/aidl/android/media/EffectDescriptor.aidl b/media/libaudioclient/aidl/android/media/EffectDescriptor.aidl index 35a3d7467f..e5b515806f 100644 --- a/media/libaudioclient/aidl/android/media/EffectDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/EffectDescriptor.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioUuid; +import android.media.audio.common.AudioUuid; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl b/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl index ec5b67a0ce..0ea0e4fd92 100644 --- a/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioEncapsulationType; import android.media.AudioStandard; +import android.media.audio.common.AudioEncapsulationType; /** * The audio descriptor that descibes playback/capture capabilities according to diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 758ae071a8..0f84af639f 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,12 +16,10 @@ package android.media; -import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; import android.media.AudioPortConfig; import android.media.AudioUniqueIdUse; -import android.media.AudioUuid; import android.media.AudioVibratorInfo; import android.media.CreateEffectRequest; import android.media.CreateEffectResponse; @@ -42,7 +40,9 @@ import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; import android.media.audio.common.AudioChannelLayout; import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioMode; import android.media.audio.common.AudioStreamType; +import android.media.audio.common.AudioUuid; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 37834c93b2..528a432ba7 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -23,7 +23,6 @@ import android.media.AudioAttributesInternal; import android.media.AudioDevice; import android.media.AudioDeviceDescription; import android.media.AudioMix; -import android.media.AudioMode; import android.media.AudioOffloadMode; import android.media.AudioPatch; import android.media.AudioPolicyDeviceState; @@ -34,8 +33,6 @@ import android.media.AudioPortConfig; import android.media.AudioPortRole; import android.media.AudioPortType; import android.media.AudioProductStrategy; -import android.media.AudioSourceType; -import android.media.AudioUuid; import android.media.AudioVolumeGroup; import android.media.DeviceRole; import android.media.EffectDescriptor; @@ -50,9 +47,12 @@ import android.media.SoundTriggerSession; import android.media.audio.common.AudioConfig; import android.media.audio.common.AudioConfigBase; import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioMode; import android.media.audio.common.AudioOffloadInfo; +import android.media.audio.common.AudioSource; import android.media.audio.common.AudioStreamType; import android.media.audio.common.AudioUsage; +import android.media.audio.common.AudioUuid; /** * IAudioPolicyService interface (see AudioPolicyInterface for method descriptions). @@ -157,7 +157,7 @@ interface IAudioPolicyService { boolean isStreamActiveRemotely(AudioStreamType stream, int inPastMs); - boolean isSourceActive(AudioSourceType source); + boolean isSourceActive(AudioSource source); /** * On input, count represents the maximum length of the returned array. @@ -172,7 +172,7 @@ interface IAudioPolicyService { @utf8InCpp String opPackageName, in AudioUuid uuid, int priority, - AudioSourceType source); + AudioSource source); int /* audio_unique_id_t */ addStreamDefaultEffect(in AudioUuid type, @utf8InCpp String opPackageName, @@ -331,22 +331,22 @@ interface IAudioPolicyService { AudioDevice[] getDevicesForRoleAndStrategy(int /* product_strategy_t */ strategy, DeviceRole role); - void setDevicesRoleForCapturePreset(AudioSourceType audioSource, + void setDevicesRoleForCapturePreset(AudioSource audioSource, DeviceRole role, in AudioDevice[] devices); - void addDevicesRoleForCapturePreset(AudioSourceType audioSource, + void addDevicesRoleForCapturePreset(AudioSource audioSource, DeviceRole role, in AudioDevice[] devices); - void removeDevicesRoleForCapturePreset(AudioSourceType audioSource, + void removeDevicesRoleForCapturePreset(AudioSource audioSource, DeviceRole role, in AudioDevice[] devices); - void clearDevicesRoleForCapturePreset(AudioSourceType audioSource, + void clearDevicesRoleForCapturePreset(AudioSource audioSource, DeviceRole role); - AudioDevice[] getDevicesForRoleAndCapturePreset(AudioSourceType audioSource, + AudioDevice[] getDevicesForRoleAndCapturePreset(AudioSource audioSource, DeviceRole role); boolean registerSoundTriggerCaptureStateListener(ICaptureStateListener listener); diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl index cf66644584..d93a59dfbb 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyServiceClient.aidl @@ -16,10 +16,10 @@ package android.media; -import android.media.AudioSourceType; import android.media.EffectDescriptor; import android.media.RecordClientInfo; import android.media.audio.common.AudioConfigBase; +import android.media.audio.common.AudioSource; /** * {@hide} @@ -43,7 +43,7 @@ oneway interface IAudioPolicyServiceClient { in AudioConfigBase deviceConfig, in EffectDescriptor[] effects, int /* audio_patch_handle_t */ patchHandle, - AudioSourceType source); + AudioSource source); /** Notifies a change of audio routing */ void onRoutingUpdated(); } diff --git a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl index cd8a32598a..fe3c2f9f8f 100644 --- a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl +++ b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl @@ -17,8 +17,8 @@ package android.media; import android.media.AudioDevice; -import android.media.AudioSourceType; import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioSource; /** * {@hide} @@ -30,7 +30,7 @@ parcelable OpenInputRequest { int input; AudioConfig config; AudioDevice device; - AudioSourceType source; + AudioSource source; /** Bitmask, indexed by AudioInputFlag. */ int flags; } diff --git a/media/libaudioclient/aidl/android/media/RecordClientInfo.aidl b/media/libaudioclient/aidl/android/media/RecordClientInfo.aidl index 328046072f..7dad58d613 100644 --- a/media/libaudioclient/aidl/android/media/RecordClientInfo.aidl +++ b/media/libaudioclient/aidl/android/media/RecordClientInfo.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioSourceType; +import android.media.audio.common.AudioSource; /** * {@hide} @@ -28,7 +28,7 @@ parcelable RecordClientInfo { int uid; /** Interpreted as audio_session_t. */ int session; - AudioSourceType source; + AudioSource source; /** Interpreted as audio_port_handle_t. */ int portId; boolean silenced; diff --git a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp index 52868d9012..80fe1ba7a6 100644 --- a/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp +++ b/media/libaudioclient/fuzzer/audioflinger_fuzzer.cpp @@ -604,7 +604,7 @@ status_t AudioFlingerFuzzer::invokeAudioInputDevice() { request.config = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_t_AudioConfig(config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); - request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); + request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSource(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); media::OpenInputResponse response{}; diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 0a434594b1..0671dd709d 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -25,8 +25,6 @@ #include #include #include -#include -#include #include #include #include @@ -34,7 +32,6 @@ #include #include #include -#include #include #include #include @@ -52,10 +49,16 @@ #include #include #include -#include +#include +#include #include +#include #include +#include +#include +#include #include +#include #include #include @@ -198,9 +201,10 @@ ConversionResult aidl2legacy_AudioStreamType_audio_stream_t ConversionResult legacy2aidl_audio_stream_type_t_AudioStreamType(audio_stream_type_t legacy); -ConversionResult aidl2legacy_AudioSourceType_audio_source_t( - media::AudioSourceType aidl); -ConversionResult legacy2aidl_audio_source_t_AudioSourceType( +ConversionResult aidl2legacy_AudioSource_audio_source_t( + media::audio::common::AudioSource aidl); +ConversionResult + legacy2aidl_audio_source_t_AudioSource( audio_source_t legacy); ConversionResult aidl2legacy_int32_t_audio_session_t(int32_t aidl); @@ -239,8 +243,9 @@ ConversionResult legacy2aidl_AudioClient_AudioClient( const AudioClient& legacy); ConversionResult -aidl2legacy_AudioContentType_audio_content_type_t(media::AudioContentType aidl); -ConversionResult +aidl2legacy_AudioContentType_audio_content_type_t( + media::audio::common::AudioContentType aidl); +ConversionResult legacy2aidl_audio_content_type_t_AudioContentType(audio_content_type_t legacy); ConversionResult @@ -302,8 +307,8 @@ ConversionResult legacy2aidl_AudioTimestamp_AudioTimestampInternal(const AudioTimestamp& legacy); ConversionResult -aidl2legacy_AudioUuid_audio_uuid_t(const media::AudioUuid& aidl); -ConversionResult +aidl2legacy_AudioUuid_audio_uuid_t(const media::audio::common::AudioUuid& aidl); +ConversionResult legacy2aidl_audio_uuid_t_AudioUuid(const audio_uuid_t& legacy); ConversionResult @@ -313,8 +318,8 @@ legacy2aidl_effect_descriptor_t_EffectDescriptor(const effect_descriptor_t& lega ConversionResult aidl2legacy_AudioEncapsulationMetadataType_audio_encapsulation_metadata_type_t( - media::AudioEncapsulationMetadataType aidl); -ConversionResult + media::audio::common::AudioEncapsulationMetadataType aidl); +ConversionResult legacy2aidl_audio_encapsulation_metadata_type_t_AudioEncapsulationMetadataType( audio_encapsulation_metadata_type_t legacy); @@ -367,8 +372,8 @@ ConversionResult legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy); ConversionResult -aidl2legacy_AudioMode_audio_mode_t(media::AudioMode aidl); -ConversionResult +aidl2legacy_AudioMode_audio_mode_t(media::audio::common::AudioMode aidl); +ConversionResult legacy2aidl_audio_mode_t_AudioMode(audio_mode_t legacy); ConversionResult @@ -415,8 +420,8 @@ legacy2aidl_audio_extra_audio_descriptor_ExtraAudioDescriptor( ConversionResult aidl2legacy_AudioEncapsulationType_audio_encapsulation_type_t( - const media::AudioEncapsulationType& aidl); -ConversionResult + const media::audio::common::AudioEncapsulationType& aidl); +ConversionResult legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType( const audio_encapsulation_type_t & legacy); diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index dbd1f6bc8c..3c610afa66 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -19,6 +19,9 @@ #include +#include +#include + #include #include #include @@ -33,13 +36,11 @@ #include #include #include -#include #include #include #include #include #include -#include using android::content::AttributionSourceState; @@ -694,7 +695,7 @@ private: const media::audio::common::AudioConfigBase& deviceConfig, const std::vector& effects, int32_t patchHandle, - media::AudioSourceType source) override; + media::audio::common::AudioSource source) override; binder::Status onRoutingUpdated(); private: diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 6d62b6b2ca..25ded3851e 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -586,7 +586,7 @@ public: Status streamVolume(media::audio::common::AudioStreamType stream, int32_t output, float* _aidl_return) override; Status streamMute(media::audio::common::AudioStreamType stream, bool* _aidl_return) override; - Status setMode(media::AudioMode mode) override; + Status setMode(media::audio::common::AudioMode mode) override; Status setMicMute(bool state) override; Status getMicMute(bool* _aidl_return) override; Status setRecordSilenced(int32_t portId, bool silenced) override; @@ -616,7 +616,8 @@ public: Status releaseAudioSessionId(int32_t audioSession, int32_t pid) override; Status queryNumberEffects(int32_t* _aidl_return) override; Status queryEffect(int32_t index, media::EffectDescriptor* _aidl_return) override; - Status getEffectDescriptor(const media::AudioUuid& effectUUID, const media::AudioUuid& typeUUID, + Status getEffectDescriptor(const media::audio::common::AudioUuid& effectUUID, + const media::audio::common::AudioUuid& typeUUID, int32_t preferredTypeFlag, media::EffectDescriptor* _aidl_return) override; Status createEffect(const media::CreateEffectRequest& request, diff --git a/media/libaudioclient/include/media/PolicyAidlConversion.h b/media/libaudioclient/include/media/PolicyAidlConversion.h index 873f27acbf..edecfeff31 100644 --- a/media/libaudioclient/include/media/PolicyAidlConversion.h +++ b/media/libaudioclient/include/media/PolicyAidlConversion.h @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 33b71c55f0..1bfacd570c 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -2859,7 +2859,7 @@ status_t AudioFlinger::openInput(const media::OpenInputRequest& request, &config, device.mType, device.address().c_str(), - VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSourceType_audio_source_t(request.source)), + VALUE_OR_RETURN_STATUS(aidl2legacy_AudioSource_audio_source_t(request.source)), VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_input_flags_t_mask(request.flags)), AUDIO_DEVICE_NONE, String8{}); diff --git a/services/audiopolicy/service/AudioPolicyClientImpl.cpp b/services/audiopolicy/service/AudioPolicyClientImpl.cpp index c8db45bfd9..aaf6fbaa05 100644 --- a/services/audiopolicy/service/AudioPolicyClientImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyClientImpl.cpp @@ -139,7 +139,7 @@ status_t AudioPolicyService::AudioPolicyClient::openInput(audio_module_handle_t request.config = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_t_AudioConfig(*config, true /*isInput*/)); request.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(deviceTypeAddr)); - request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSourceType(source)); + request.source = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_source_t_AudioSource(source)); request.flags = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_input_flags_t_int32_t_mask(flags)); media::OpenInputResponse response; diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 9346de3696..dd68ae4031 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -47,9 +47,12 @@ using content::AttributionSourceState; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; +using media::audio::common::AudioUuid; const std::vector& SYSTEM_USAGES = { AUDIO_USAGE_CALL_ASSISTANT, @@ -176,7 +179,7 @@ Status AudioPolicyService::handleDeviceConfigChange( deviceNameAidl.c_str(), encodedFormat)); } -Status AudioPolicyService::setPhoneState(media::AudioMode stateAidl, int32_t uidAidl) +Status AudioPolicyService::setPhoneState(AudioMode stateAidl, int32_t uidAidl) { audio_mode_t state = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioMode_audio_mode_t(stateAidl)); @@ -208,7 +211,7 @@ Status AudioPolicyService::setPhoneState(media::AudioMode stateAidl, int32_t uid return Status::ok(); } -Status AudioPolicyService::getPhoneState(media::AudioMode* _aidl_return) { +Status AudioPolicyService::getPhoneState(AudioMode* _aidl_return) { Mutex::Autolock _l(mLock); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS(legacy2aidl_audio_mode_t_AudioMode(mPhoneState)); return Status::ok(); @@ -1248,9 +1251,9 @@ Status AudioPolicyService::isStreamActiveRemotely(AudioStreamType streamAidl, return Status::ok(); } -Status AudioPolicyService::isSourceActive(media::AudioSourceType sourceAidl, bool* _aidl_return) { +Status AudioPolicyService::isSourceActive(AudioSource sourceAidl, bool* _aidl_return) { audio_source_t source = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(sourceAidl)); + aidl2legacy_AudioSource_audio_source_t(sourceAidl)); if (mAudioPolicyManager == NULL) { return binderStatusFromStatusT(NO_INIT); } @@ -1302,11 +1305,11 @@ Status AudioPolicyService::queryDefaultPreProcessing( return Status::ok(); } -Status AudioPolicyService::addSourceDefaultEffect(const media::AudioUuid& typeAidl, +Status AudioPolicyService::addSourceDefaultEffect(const AudioUuid& typeAidl, const std::string& opPackageNameAidl, - const media::AudioUuid& uuidAidl, + const AudioUuid& uuidAidl, int32_t priority, - media::AudioSourceType sourceAidl, + AudioSource sourceAidl, int32_t* _aidl_return) { effect_uuid_t type = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioUuid_audio_uuid_t(typeAidl)); @@ -1315,7 +1318,7 @@ Status AudioPolicyService::addSourceDefaultEffect(const media::AudioUuid& typeAi effect_uuid_t uuid = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioUuid_audio_uuid_t(uuidAidl)); audio_source_t source = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(sourceAidl)); + aidl2legacy_AudioSource_audio_source_t(sourceAidl)); audio_unique_id_t id; spaudioPolicyEffects; @@ -1329,9 +1332,9 @@ Status AudioPolicyService::addSourceDefaultEffect(const media::AudioUuid& typeAi return Status::ok(); } -Status AudioPolicyService::addStreamDefaultEffect(const media::AudioUuid& typeAidl, +Status AudioPolicyService::addStreamDefaultEffect(const AudioUuid& typeAidl, const std::string& opPackageNameAidl, - const media::AudioUuid& uuidAidl, + const AudioUuid& uuidAidl, int32_t priority, AudioUsage usageAidl, int32_t* _aidl_return) { effect_uuid_t type = VALUE_OR_RETURN_BINDER_STATUS( @@ -2124,11 +2127,11 @@ Status AudioPolicyService::registerSoundTriggerCaptureStateListener( } Status AudioPolicyService::setDevicesRoleForCapturePreset( - media::AudioSourceType audioSourceAidl, + AudioSource audioSourceAidl, media::DeviceRole roleAidl, const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(audioSourceAidl)); + aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_DeviceRole_device_role_t(roleAidl)); AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( @@ -2144,11 +2147,11 @@ Status AudioPolicyService::setDevicesRoleForCapturePreset( } Status AudioPolicyService::addDevicesRoleForCapturePreset( - media::AudioSourceType audioSourceAidl, + AudioSource audioSourceAidl, media::DeviceRole roleAidl, const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(audioSourceAidl)); + aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_DeviceRole_device_role_t(roleAidl)); AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( @@ -2164,11 +2167,11 @@ Status AudioPolicyService::addDevicesRoleForCapturePreset( } Status AudioPolicyService::removeDevicesRoleForCapturePreset( - media::AudioSourceType audioSourceAidl, + AudioSource audioSourceAidl, media::DeviceRole roleAidl, const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(audioSourceAidl)); + aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_DeviceRole_device_role_t(roleAidl)); AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( @@ -2183,10 +2186,10 @@ Status AudioPolicyService::removeDevicesRoleForCapturePreset( mAudioPolicyManager->removeDevicesRoleForCapturePreset(audioSource, role, devices)); } -Status AudioPolicyService::clearDevicesRoleForCapturePreset(media::AudioSourceType audioSourceAidl, +Status AudioPolicyService::clearDevicesRoleForCapturePreset(AudioSource audioSourceAidl, media::DeviceRole roleAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(audioSourceAidl)); + aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_DeviceRole_device_role_t(roleAidl)); @@ -2199,11 +2202,11 @@ Status AudioPolicyService::clearDevicesRoleForCapturePreset(media::AudioSourceTy } Status AudioPolicyService::getDevicesForRoleAndCapturePreset( - media::AudioSourceType audioSourceAidl, + AudioSource audioSourceAidl, media::DeviceRole roleAidl, std::vector* _aidl_return) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioSourceType_audio_source_t(audioSourceAidl)); + aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_DeviceRole_device_role_t(roleAidl)); AudioDeviceTypeAddrVector devices; diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index db646335be..86ebe98f00 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -511,8 +511,8 @@ void AudioPolicyService::NotificationClient::onRecordingConfigurationUpdate( legacy2aidl_effect_descriptor_t_EffectDescriptor)); int32_t patchHandleAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_patch_handle_t_int32_t(patchHandle)); - media::AudioSourceType sourceAidl = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_source_t_AudioSourceType(source)); + media::audio::common::AudioSource sourceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_source_t_AudioSource(source)); return aidl_utils::statusTFromBinderStatus( mAudioPolicyServiceClient->onRecordingConfigurationUpdate(eventAidl, clientInfoAidl, diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index a6237bc7f1..b98dacbbf2 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -52,8 +52,11 @@ using content::AttributionSourceState; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioMode; +using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; +using media::audio::common::AudioUuid; // ---------------------------------------------------------------------------- @@ -86,7 +89,7 @@ public: const media::AudioDevice& device, const std::string& deviceName, const AudioFormatDescription& encodedFormat) override; - binder::Status setPhoneState(media::AudioMode state, int32_t uid) override; + binder::Status setPhoneState(AudioMode state, int32_t uid) override; binder::Status setForceUse(media::AudioPolicyForceUse usage, media::AudioPolicyForcedConfig config) override; binder::Status getForceUse(media::AudioPolicyForceUse usage, @@ -145,18 +148,18 @@ public: bool* _aidl_return) override; binder::Status isStreamActiveRemotely(AudioStreamType stream, int32_t inPastMs, bool* _aidl_return) override; - binder::Status isSourceActive(media::AudioSourceType source, bool* _aidl_return) override; + binder::Status isSourceActive(AudioSource source, bool* _aidl_return) override; binder::Status queryDefaultPreProcessing( int32_t audioSession, media::Int* count, std::vector* _aidl_return) override; - binder::Status addSourceDefaultEffect(const media::AudioUuid& type, + binder::Status addSourceDefaultEffect(const AudioUuid& type, const std::string& opPackageName, - const media::AudioUuid& uuid, int32_t priority, - media::AudioSourceType source, + const AudioUuid& uuid, int32_t priority, + AudioSource source, int32_t* _aidl_return) override; - binder::Status addStreamDefaultEffect(const media::AudioUuid& type, + binder::Status addStreamDefaultEffect(const AudioUuid& type, const std::string& opPackageName, - const media::AudioUuid& uuid, int32_t priority, + const AudioUuid& uuid, int32_t priority, AudioUsage usage, int32_t* _aidl_return) override; binder::Status removeSourceDefaultEffect(int32_t id) override; binder::Status removeStreamDefaultEffect(int32_t id) override; @@ -184,7 +187,7 @@ public: binder::Status setAudioVolumeGroupCallbacksEnabled(bool enabled) override; binder::Status acquireSoundTriggerSession(media::SoundTriggerSession* _aidl_return) override; binder::Status releaseSoundTriggerSession(int32_t session) override; - binder::Status getPhoneState(media::AudioMode* _aidl_return) override; + binder::Status getPhoneState(AudioMode* _aidl_return) override; binder::Status registerPolicyMixes(const std::vector& mixes, bool registration) override; binder::Status setUidDeviceAffinities(int32_t uid, @@ -237,21 +240,21 @@ public: int32_t strategy, media::DeviceRole role, std::vector* _aidl_return) override; binder::Status setDevicesRoleForCapturePreset( - media::AudioSourceType audioSource, + AudioSource audioSource, media::DeviceRole role, const std::vector& devices) override; binder::Status addDevicesRoleForCapturePreset( - media::AudioSourceType audioSource, + AudioSource audioSource, media::DeviceRole role, const std::vector& devices) override; binder::Status removeDevicesRoleForCapturePreset( - media::AudioSourceType audioSource, + AudioSource audioSource, media::DeviceRole role, const std::vector& devices) override; - binder::Status clearDevicesRoleForCapturePreset(media::AudioSourceType audioSource, + binder::Status clearDevicesRoleForCapturePreset(AudioSource audioSource, media::DeviceRole role) override; binder::Status getDevicesForRoleAndCapturePreset( - media::AudioSourceType audioSource, + AudioSource audioSource, media::DeviceRole role, std::vector* _aidl_return) override; binder::Status registerSoundTriggerCaptureStateListener( -- GitLab From f45fb0e59fc57a6c8f669d4ea718f18760c32313 Mon Sep 17 00:00:00 2001 From: Ember Rose Date: Sat, 4 Sep 2021 00:20:00 +0000 Subject: [PATCH 125/694] Revert "Add interface to query the mmap support." This reverts commit 57c44c002666bf75d73f09c844295aac80e45dfc. Bug: 198836727 Reason for revert: DroidMonitor-triggered revert due to breakage https://android-build.googleplex.com/builds/quarterdeck?branch=git_master&target=adt3-userdebug&lkgb=7703400&lkbb=7703573&fkbb=7703552 Change-Id: I82b9b99f8ab31134873157819fdb341cfa65ac80 --- media/audioserver/Android.bp | 2 +- media/audioserver/main_audioserver.cpp | 28 +------ .../libaaudio/src/core/AudioStreamBuilder.cpp | 55 ++----------- media/libaudioclient/Android.bp | 3 - media/libaudioclient/AudioSystem.cpp | 10 --- media/libaudioclient/IAudioFlinger.cpp | 15 ---- .../aidl/android/media/AudioMMapPolicy.aidl | 40 --------- .../android/media/AudioMMapPolicyInfo.aidl | 29 ------- .../android/media/AudioMMapPolicyType.aidl | 34 -------- .../android/media/IAudioFlingerService.aidl | 4 - .../include/media/AudioSystem.h | 6 -- .../include/media/IAudioFlinger.h | 14 ---- media/libaudiohal/Android.bp | 1 - media/libaudiohal/impl/Android.bp | 3 - media/libaudiohal/impl/DeviceHalHidl.cpp | 10 --- media/libaudiohal/impl/DeviceHalHidl.h | 4 - media/libaudiohal/impl/DeviceHalLocal.cpp | 7 -- media/libaudiohal/impl/DeviceHalLocal.h | 4 - media/libaudiohal/impl/PropertyUtils.cpp | 82 ------------------- media/libaudiohal/impl/PropertyUtils.h | 32 -------- .../media/audiohal/DeviceHalInterface.h | 6 -- services/audioflinger/AudioFlinger.cpp | 23 ------ services/audioflinger/AudioFlinger.h | 6 -- services/audioflinger/AudioHwDevice.cpp | 6 -- services/audioflinger/AudioHwDevice.h | 4 - 25 files changed, 11 insertions(+), 417 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl delete mode 100644 media/libaudiohal/impl/PropertyUtils.cpp delete mode 100644 media/libaudiohal/impl/PropertyUtils.h diff --git a/media/audioserver/Android.bp b/media/audioserver/Android.bp index e4fc4ded59..be25ffbe38 100644 --- a/media/audioserver/Android.bp +++ b/media/audioserver/Android.bp @@ -26,7 +26,6 @@ cc_binary { shared_libs: [ "libaaudioservice", - "libaudioclient", "libaudioflinger", "libaudiopolicyservice", "libaudioprocessing", @@ -42,6 +41,7 @@ cc_binary { "libpowermanager", "libutils", "libvibrator", + ], // TODO check if we still need all of these include directories diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp index e0740de6a9..8ee1efb2f3 100644 --- a/media/audioserver/main_audioserver.cpp +++ b/media/audioserver/main_audioserver.cpp @@ -17,26 +17,20 @@ #define LOG_TAG "audioserver" //#define LOG_NDEBUG 0 -#include - #include #include #include #include -#include -#include -#include -#include #include #include #include -#include #include #include #include // from include_dirs +#include "aaudio/AAudioTesting.h" // aaudio_policy_t, AAUDIO_PROP_MMAP_POLICY, AAUDIO_POLICY_* #include "AudioFlinger.h" #include "AudioPolicyService.h" #include "AAudioService.h" @@ -152,24 +146,10 @@ int main(int argc __unused, char **argv) // AAudioService should only be used in OC-MR1 and later. // And only enable the AAudioService if the system MMAP policy explicitly allows it. // This prevents a client from misusing AAudioService when it is not supported. - // If we cannot get audio flinger here, there must be some serious problems. In that case, - // attempting to call audio flinger on a null pointer could make the process crash - // and attract attentions. - sp af = AudioSystem::get_audio_flinger(); - std::vector policyInfos; - status_t status = af->getMmapPolicyInfos( - media::AudioMMapPolicyType::DEFAULT, &policyInfos); - // Initialize aaudio service when querying mmap policy succeeds and - // any of the policy supports MMAP. - if (status == NO_ERROR || - std::any_of(policyInfos.begin(), policyInfos.end(), [](const auto& info) { - return info.mmapPolicy == media::AudioMMapPolicy::AUTO || - info.mmapPolicy == media::AudioMMapPolicy::ALWAYS; - })) { + aaudio_policy_t mmapPolicy = property_get_int32(AAUDIO_PROP_MMAP_POLICY, + AAUDIO_POLICY_NEVER); + if (mmapPolicy == AAUDIO_POLICY_AUTO || mmapPolicy == AAUDIO_POLICY_ALWAYS) { AAudioService::instantiate(); - } else { - ALOGD("Do not init aaudio service, status %d, policy info size %zu", - status, policyInfos.size()); } ProcessState::self()->startThreadPool(); diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp index 2a6b23524a..a8fd0d91c4 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.cpp +++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp @@ -20,14 +20,9 @@ #include #include -#include #include #include -#include -#include -#include -#include #include "binding/AAudioBinderClient.h" #include "client/AudioStreamInternalCapture.h" @@ -91,37 +86,6 @@ static aaudio_result_t builder_createStream(aaudio_direction_t direction, return result; } -namespace { - -aaudio_policy_t aidl2legacy_aaudio_policy(android::media::AudioMMapPolicy aidl) { - switch (aidl) { - case android::media::AudioMMapPolicy::NEVER: - return AAUDIO_POLICY_NEVER; - case android::media::AudioMMapPolicy::AUTO: - return AAUDIO_POLICY_AUTO; - case android::media::AudioMMapPolicy::ALWAYS: - return AAUDIO_POLICY_ALWAYS; - case android::media::AudioMMapPolicy::UNSPECIFIED: - default: - return AAUDIO_UNSPECIFIED; - } -} - -// The aaudio policy will be ALWAYS, NEVER, UNSPECIFIED only when all policy info are -// ALWAYS, NEVER or UNSPECIFIED. Otherwise, the aaudio policy will be AUTO. -aaudio_policy_t getAAudioPolicy( - const std::vector& policyInfos) { - if (policyInfos.empty()) return AAUDIO_POLICY_AUTO; - for (size_t i = 1; i < policyInfos.size(); ++i) { - if (policyInfos.at(i).mmapPolicy != policyInfos.at(0).mmapPolicy) { - return AAUDIO_POLICY_AUTO; - } - } - return aidl2legacy_aaudio_policy(policyInfos.at(0).mmapPolicy); -} - -} // namespace - // Try to open using MMAP path if that is allowed. // Fall back to Legacy path if MMAP not available. // Exact behavior is controlled by MMapPolicy. @@ -140,32 +104,25 @@ aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) { return result; } - std::vector policyInfos; // The API setting is the highest priority. aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy(); // If not specified then get from a system property. - if (mmapPolicy == AAUDIO_UNSPECIFIED && android::AudioSystem::getMmapPolicyInfo( - android::media::AudioMMapPolicyType::DEFAULT, &policyInfos) == NO_ERROR) { - mmapPolicy = getAAudioPolicy(policyInfos); + if (mmapPolicy == AAUDIO_UNSPECIFIED) { + mmapPolicy = AAudioProperty_getMMapPolicy(); } // If still not specified then use the default. if (mmapPolicy == AAUDIO_UNSPECIFIED) { mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT; } - policyInfos.clear(); - aaudio_policy_t mmapExclusivePolicy = AAUDIO_UNSPECIFIED; - if (android::AudioSystem::getMmapPolicyInfo( - android::media::AudioMMapPolicyType::EXCLUSIVE, &policyInfos) == NO_ERROR) { - mmapExclusivePolicy = getAAudioPolicy(policyInfos); - } - if (mmapExclusivePolicy == AAUDIO_UNSPECIFIED) { - mmapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; + int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy(); + if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) { + mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; } aaudio_sharing_mode_t sharingMode = getSharingMode(); if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE) - && (mmapExclusivePolicy == AAUDIO_POLICY_NEVER)) { + && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) { ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__); sharingMode = AAUDIO_SHARING_MODE_SHARED; setSharingMode(sharingMode); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 921e2d2ba4..0a260514a7 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -331,9 +331,6 @@ aidl_interface { "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", - "aidl/android/media/AudioMMapPolicy.aidl", - "aidl/android/media/AudioMMapPolicyInfo.aidl", - "aidl/android/media/AudioMMapPolicyType.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioMode.aidl", "aidl/android/media/AudioOffloadInfo.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index be0dff8c25..057befdc4d 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -2353,16 +2353,6 @@ status_t AudioSystem::setVibratorInfos( return af->setVibratorInfos(vibratorInfos); } -status_t AudioSystem::getMmapPolicyInfo( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - const sp& af = AudioSystem::get_audio_flinger(); - if (af == nullptr) { - return PERMISSION_DENIED; - } - return af->getMmapPolicyInfos(policyType, policyInfos); -} - // --------------------------------------------------------------------------- int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index 566f77c26c..ee6489430b 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -17,9 +17,6 @@ #define LOG_TAG "IAudioFlinger" //#define LOG_NDEBUG 0 - -#include - #include #include @@ -780,12 +777,6 @@ status_t AudioFlingerClientAdapter::updateSecondaryOutputs( return statusTFromBinderStatus(mDelegate->updateSecondaryOutputs(trackSecondaryOutputInfos)); } -status_t AudioFlingerClientAdapter::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - return statusTFromBinderStatus(mDelegate->getMmapPolicyInfos(policyType, policyInfos)); -} - //////////////////////////////////////////////////////////////////////////////////////////////////// // AudioFlingerServerAdapter @@ -1258,10 +1249,4 @@ Status AudioFlingerServerAdapter::updateSecondaryOutputs( return Status::fromStatusT(mDelegate->updateSecondaryOutputs(trackSecondaryOutputs)); } -Status AudioFlingerServerAdapter::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *_aidl_return) { - return Status::fromStatusT(mDelegate->getMmapPolicyInfos(policyType, _aidl_return)); -} - } // namespace android diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl deleted file mode 100644 index e3fa951390..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * Audio MMAP policy describe how the aaudio MMAP feature is used. - * {@hide} - */ -@Backing(type="int") -enum AudioMMapPolicy { - /** - * The policy is unspecified. - */ - UNSPECIFIED = 0, - /** - * The MMAP feature is disabled and never used. - */ - NEVER = 1, - /** - * If MMAP feature works then uses it. Otherwise, fall back to something else. - */ - AUTO = 2, - /** - * The MMAP feature must be used. If not available then fail. - */ - ALWAYS = 3, -} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl deleted file mode 100644 index ad7bd45312..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -import android.media.AudioDevice; -import android.media.AudioMMapPolicy; - -/** - * Audio MMAP policy info describes how an aaudio MMAP feature can be - * used on a particular device. - * {@hide} - */ -parcelable AudioMMapPolicyInfo { - AudioDevice device; - AudioMMapPolicy mmapPolicy = AudioMMapPolicy.UNSPECIFIED; -} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl deleted file mode 100644 index d6acd2cca3..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * The aaudio MMAP policy type. - * {@hide} - */ -@Backing(type="int") -enum AudioMMapPolicyType { - /** - * Default aaudio mmap policy. It is used to query whether the - * aaudio MMAP could be used or not. - */ - DEFAULT = 1, - /** - * Exclusive aaudio mmap policy. It is used to query whether the - * aaudio MMAP could be used in exclusive mode or not. - */ - EXCLUSIVE = 2, -} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index de859b8ad7..7b02a9db7a 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,8 +16,6 @@ package android.media; -import android.media.AudioMMapPolicyInfo; -import android.media.AudioMMapPolicyType; import android.media.AudioMode; import android.media.AudioPatch; import android.media.AudioPort; @@ -219,6 +217,4 @@ interface IAudioFlingerService { // This usually happens when there is a dynamic policy registered. void updateSecondaryOutputs( in TrackSecondaryOutputInfo[] trackSecondaryOutputInfos); - - AudioMMapPolicyInfo[] getMmapPolicyInfos(AudioMMapPolicyType policyType); } diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 0da8186586..50ab42ab50 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -19,8 +19,6 @@ #include -#include -#include #include #include #include @@ -615,10 +613,6 @@ public: static status_t setVibratorInfos(const std::vector& vibratorInfos); - static status_t getMmapPolicyInfo( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); - private: class AudioFlingerClient: public IBinder::DeathRecipient, public media::BnAudioFlingerClient diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 03ad9b0569..a74661acfb 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -37,8 +37,6 @@ #include #include -#include -#include #include #include #include @@ -350,10 +348,6 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; - - virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) = 0; }; /** @@ -451,10 +445,6 @@ public: status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; - status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) override; - private: const sp mDelegate; }; @@ -539,7 +529,6 @@ public: SET_AUDIO_HAL_PIDS = media::BnAudioFlingerService::TRANSACTION_setAudioHalPids, SET_VIBRATOR_INFOS = media::BnAudioFlingerService::TRANSACTION_setVibratorInfos, UPDATE_SECONDARY_OUTPUTS = media::BnAudioFlingerService::TRANSACTION_updateSecondaryOutputs, - GET_MMAP_POLICY_INFOS = media::BnAudioFlingerService::TRANSACTION_getMmapPolicyInfos, }; /** @@ -652,9 +641,6 @@ public: Status setVibratorInfos(const std::vector& vibratorInfos) override; Status updateSecondaryOutputs( const std::vector& trackSecondaryOutputInfos) override; - Status getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *_aidl_return) override; private: const sp mDelegate; diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp index 5fe74f9d71..bd24c84dbc 100644 --- a/media/libaudiohal/Android.bp +++ b/media/libaudiohal/Android.bp @@ -30,7 +30,6 @@ cc_library_shared { ], shared_libs: [ - "audioclient-types-aidl-cpp", "libdl", "libhidlbase", "liblog", diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp index ed39231efd..a2c6e8aeba 100644 --- a/media/libaudiohal/impl/Android.bp +++ b/media/libaudiohal/impl/Android.bp @@ -23,8 +23,6 @@ cc_defaults { "EffectHalHidl.cpp", "EffectsFactoryHalHidl.cpp", "StreamHalHidl.cpp", - - "PropertyUtils.cpp", ], cflags: [ @@ -52,7 +50,6 @@ cc_defaults { "libmedia_helper", "libmediautils", "libutils", - "audioclient-types-aidl-cpp", ], header_libs: [ "android.hardware.audio.common.util@all-versions", diff --git a/media/libaudiohal/impl/DeviceHalHidl.cpp b/media/libaudiohal/impl/DeviceHalHidl.cpp index e4ab46f4c9..aa94eeaf16 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.cpp +++ b/media/libaudiohal/impl/DeviceHalHidl.cpp @@ -20,7 +20,6 @@ //#define LOG_NDEBUG 0 #include -#include #include #include #include @@ -33,7 +32,6 @@ #include "DeviceHalHidl.h" #include "EffectHalHidl.h" #include "ParameterUtils.h" -#include "PropertyUtils.h" #include "StreamHalHidl.h" using ::android::hardware::audio::common::CPP_VERSION::implementation::HidlUtils; @@ -459,14 +457,6 @@ status_t DeviceHalHidl::removeDeviceEffect( } #endif -status_t DeviceHalHidl::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - // TODO: this is just for test, faking a data by querying the system property. - // When AIDL HAL is ready, this should query AIDL HAL when possible. - return utils::getMmapPolicyInfosFromSystemProperty(policyType, policyInfos); -} - status_t DeviceHalHidl::dump(int fd, const Vector& args) { if (mDevice == 0) return NO_INIT; native_handle_t* hidlHandle = native_handle_create(1, 0); diff --git a/media/libaudiohal/impl/DeviceHalHidl.h b/media/libaudiohal/impl/DeviceHalHidl.h index b93390b2ae..2694ab3a12 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.h +++ b/media/libaudiohal/impl/DeviceHalHidl.h @@ -119,10 +119,6 @@ class DeviceHalHidl : public DeviceHalInterface, public ConversionHelperHidl status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; - status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) override; - status_t dump(int fd, const Vector& args) override; private: diff --git a/media/libaudiohal/impl/DeviceHalLocal.cpp b/media/libaudiohal/impl/DeviceHalLocal.cpp index bc37886e8c..e0304afd54 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.cpp +++ b/media/libaudiohal/impl/DeviceHalLocal.cpp @@ -20,7 +20,6 @@ #include #include "DeviceHalLocal.h" -#include "PropertyUtils.h" #include "StreamHalLocal.h" namespace android { @@ -234,12 +233,6 @@ status_t DeviceHalLocal::removeDeviceEffect( return INVALID_OPERATION; } -status_t DeviceHalLocal::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - return utils::getMmapPolicyInfosFromSystemProperty(policyType, policyInfos); -} - status_t DeviceHalLocal::dump(int fd, const Vector& /* args */) { return mDev->dump(mDev, fd); } diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h index 869b1b7606..2fde936b36 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.h +++ b/media/libaudiohal/impl/DeviceHalLocal.h @@ -112,10 +112,6 @@ class DeviceHalLocal : public DeviceHalInterface status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; - status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) override; - status_t dump(int fd, const Vector& args) override; void closeOutputStream(struct audio_stream_out *stream_out); diff --git a/media/libaudiohal/impl/PropertyUtils.cpp b/media/libaudiohal/impl/PropertyUtils.cpp deleted file mode 100644 index 55eec2ba7b..0000000000 --- a/media/libaudiohal/impl/PropertyUtils.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "PropertyUtils.h" - -namespace android { -namespace CPP_VERSION { -namespace utils { - -std::string getMmapPolicyProperty(media::AudioMMapPolicyType policyType) { - switch (policyType) { - case media::AudioMMapPolicyType::DEFAULT: - return "aaudio.mmap_policy"; - case media::AudioMMapPolicyType::EXCLUSIVE: - return "aaudio.mmap_exclusive_policy"; - default: - return ""; - } -} - -#define MMAP_POLICY_UNSPECIFIED 0 -#define MMAP_POLICY_NEVER 1 -#define MMAP_POLICY_AUTO 2 -#define MMAP_POLICY_ALWAYS 3 - -int getDefaultPolicyFromType(media::AudioMMapPolicyType policyType) { - switch (policyType) { - case media::AudioMMapPolicyType::EXCLUSIVE: - return MMAP_POLICY_UNSPECIFIED; - case media::AudioMMapPolicyType::DEFAULT: - default: - return MMAP_POLICY_NEVER; - } -} - -media::AudioMMapPolicy legacy2aidlAudioMMapPolicy(int legacy) { - switch (legacy) { - case MMAP_POLICY_NEVER: - return media::AudioMMapPolicy::NEVER; - case MMAP_POLICY_AUTO: - return media::AudioMMapPolicy::AUTO; - case MMAP_POLICY_ALWAYS: - return media::AudioMMapPolicy::ALWAYS; - case MMAP_POLICY_UNSPECIFIED: - default: - return media::AudioMMapPolicy::UNSPECIFIED; - } -} - -status_t getMmapPolicyInfosFromSystemProperty( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - media::AudioMMapPolicyInfo policyInfo; - const std::string propertyStr = getMmapPolicyProperty(policyType); - if (propertyStr.empty()) { - return BAD_VALUE; - } - policyInfo.mmapPolicy = utils::legacy2aidlAudioMMapPolicy( - property_get_int32(propertyStr.c_str(), utils::getDefaultPolicyFromType(policyType))); - policyInfos->push_back(policyInfo); - return NO_ERROR; -} - -} // namespace utils -} // namespace CPP_VERSION -} // namespace android \ No newline at end of file diff --git a/media/libaudiohal/impl/PropertyUtils.h b/media/libaudiohal/impl/PropertyUtils.h deleted file mode 100644 index b9d0057af4..0000000000 --- a/media/libaudiohal/impl/PropertyUtils.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include - -namespace android { -namespace CPP_VERSION { -namespace utils { - -status_t getMmapPolicyInfosFromSystemProperty( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); - -} // namespace utils -} // namespace CPP_VERSION -} // namespace android diff --git a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h index b93c8d26af..69cbcecf14 100644 --- a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h @@ -17,8 +17,6 @@ #ifndef ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H #define ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H -#include -#include #include #include #include @@ -122,10 +120,6 @@ class DeviceHalInterface : public RefBase virtual status_t removeDeviceEffect( audio_port_handle_t device, sp effect) = 0; - virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) = 0; - virtual status_t dump(int fd, const Vector& args) = 0; protected: diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index e34b58e5db..33b71c55f0 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -335,29 +335,6 @@ status_t AudioFlinger::updateSecondaryOutputs( return NO_ERROR; } -status_t AudioFlinger::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - AutoMutex lock(mHardwareLock); - if (mPolicyInfos.find(policyType) != mPolicyInfos.end()) { - *policyInfos = mPolicyInfos[policyType]; - return NO_ERROR; - } - for (size_t i = 0; i < mAudioHwDevs.size(); ++i) { - AudioHwDevice *dev = mAudioHwDevs.valueAt(i); - std::vector infos; - status_t status = dev->getMmapPolicyInfos(policyType, &infos); - if (status != NO_ERROR) { - ALOGE("Failed to query mmap policy info of %d, error %d", - mAudioHwDevs.keyAt(i), status); - continue; - } - policyInfos->insert(policyInfos->end(), infos.begin(), infos.end()); - } - mPolicyInfos[policyType] = *policyInfos; - return NO_ERROR; -} - // getDefaultVibratorInfo_l must be called with AudioFlinger lock held. std::optional AudioFlinger::getDefaultVibratorInfo_l() { if (mAudioVibratorInfos.empty()) { diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index b5d587bd8e..d6bf0ae29a 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -282,10 +282,6 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs); - virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); - status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -1008,8 +1004,6 @@ private: // Keep in sync with java definition in media/java/android/media/AudioRecord.java static constexpr int32_t kMaxSharedAudioHistoryMs = 5000; - - std::map> mPolicyInfos; }; #undef INCLUDING_FROM_AUDIOFLINGER_H diff --git a/services/audioflinger/AudioHwDevice.cpp b/services/audioflinger/AudioHwDevice.cpp index f70840f626..16b25f6828 100644 --- a/services/audioflinger/AudioHwDevice.cpp +++ b/services/audioflinger/AudioHwDevice.cpp @@ -102,11 +102,5 @@ status_t AudioHwDevice::getAudioPort(struct audio_port_v7 *port) const { return mHwDevice->getAudioPort(port); } -status_t AudioHwDevice::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) const { - return mHwDevice->getMmapPolicyInfos(policyType, policyInfos); -} - }; // namespace android diff --git a/services/audioflinger/AudioHwDevice.h b/services/audioflinger/AudioHwDevice.h index b72072f656..fc2c693ed5 100644 --- a/services/audioflinger/AudioHwDevice.h +++ b/services/audioflinger/AudioHwDevice.h @@ -85,10 +85,6 @@ public: status_t getAudioPort(struct audio_port_v7 *port) const; - status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) const; - private: const audio_module_handle_t mHandle; const char * const mModuleName; -- GitLab From 218ede7ec394062ddf73b00cfff007a175197c02 Mon Sep 17 00:00:00 2001 From: Francois Gaffie Date: Mon, 6 Sep 2021 10:33:56 +0200 Subject: [PATCH 126/694] audiopolicy: engine: anticipate usage deprecation USAGE_NOTIFICATION_COMMUNICATION_ will be deprecated in android T. USAGE_NOTIFICATION_EVENT will be kept and audio hal visible (removing the issue of convertion if AUDIO_NO_SYSTEM_DECLARATIONS is set. This CL removes the deprecated usage in hardcoded and XML configuration of audio policy engine. Bug: 199193042 Test: m Signed-off-by: Francois Gaffie Change-Id: I6a2d581357d71662800f0059fa501f6752247867 --- .../audiopolicy/engine/common/src/EngineDefaultConfig.h | 6 ------ .../phone/audio_policy_engine_product_strategies.xml | 3 --- .../phone/audio_policy_engine_product_strategies.xml | 3 --- 3 files changed, 12 deletions(-) diff --git a/services/audiopolicy/engine/common/src/EngineDefaultConfig.h b/services/audiopolicy/engine/common/src/EngineDefaultConfig.h index d39eff6537..665c2ddbcb 100644 --- a/services/audiopolicy/engine/common/src/EngineDefaultConfig.h +++ b/services/audiopolicy/engine/common/src/EngineDefaultConfig.h @@ -69,12 +69,6 @@ const engineConfig::ProductStrategies gOrderedStrategies = { { {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}, - {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST, - AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}, - {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT, - AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}, - {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED, - AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""}, {AUDIO_CONTENT_TYPE_UNKNOWN, AUDIO_USAGE_NOTIFICATION_EVENT, AUDIO_SOURCE_DEFAULT, AUDIO_FLAG_NONE, ""} } diff --git a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml index bc32416b3e..0ddf66d3af 100644 --- a/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml +++ b/services/audiopolicy/engineconfigurable/config/example/phone/audio_policy_engine_product_strategies.xml @@ -57,9 +57,6 @@ - - - diff --git a/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml b/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml index bc32416b3e..0ddf66d3af 100644 --- a/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml +++ b/services/audiopolicy/enginedefault/config/example/phone/audio_policy_engine_product_strategies.xml @@ -57,9 +57,6 @@ - - - -- GitLab From 028163982a898721e48c15c8cf93e7626f2a0586 Mon Sep 17 00:00:00 2001 From: Santiago Seifert Date: Wed, 8 Sep 2021 15:44:05 +0100 Subject: [PATCH 127/694] Add SafetyNet logging for security fix Bug: 188893559 Test: atest CtsMediaTestCases:MediaPlayerTest Change-Id: I073cc7d91fab35d07248d789244d121ca7bd0cb3 --- media/extractors/mp4/MPEG4Extractor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/media/extractors/mp4/MPEG4Extractor.cpp b/media/extractors/mp4/MPEG4Extractor.cpp index 9e4fbd578f..8836c471fd 100644 --- a/media/extractors/mp4/MPEG4Extractor.cpp +++ b/media/extractors/mp4/MPEG4Extractor.cpp @@ -6477,6 +6477,7 @@ media_status_t MPEG4Source::read( } else { // We are trying to read a sample larger than the expected max sample size. // Fall through and let the failure be handled by the following if. + android_errorWriteLog(0x534e4554, "188893559"); } if (num_bytes_read < (ssize_t)size) { -- GitLab From 894fca7cca36d24c18adb418b22bbe7ef2e65a5e Mon Sep 17 00:00:00 2001 From: Ryan Savitski Date: Fri, 27 Aug 2021 16:25:15 +0100 Subject: [PATCH 128/694] framework media seccomp: allow syscalls made by dynamic profilers within the process context There are potential memory leaks in at least media.swcodec, which heap profiling can help with (see linked bug). However the profiling requires making some socket-related syscalls from within the process, which are currently blocked by the media seccomp policy. This patch adds the necessary extra syscalls to allow for profiling of select media processes on arm64 devices. Note that several socket operations have always been allowed, even when not explicitly listed in these policy files. This is because external/minijail/util.c allowlists logging-related syscalls by default, which on Android requires the use of sockets (connect, fcntl, sendto, socket, writev). Even if this wasn't the case, some of these syscalls would still be needed for crash_dump to work. I've edited the framework files directly for the short term, and will look at a more maintainable solution for the future (likely moving to @include-able files as with crash_dump and code_coverage). Tested and verified on sc-dev userdebug device (with MODULE_BUILD_FROM_SOURCE=true): * arm64 media.extractor profileable and doesn't crash * arm64 media.swcodec profileable and doesn't crash Limitations: * not addressing arm32 or x86 policies as I don't have the appropriate devices to test with, and I'm assuming that arm64 is of main interest for the profiling investigation in the short term anyway. * not addressing media.codec (/vendor/bin/hw/android.hardware.media.omx@1.0-service) as I don't understand why its arm64 policy is a copypaste of arm32, as well as being unable to test the process in practice (unsure how to trigger allocations in it for the heap profiler). * this doesn't cover other media processes, including some vendor things. I'm happy to reduce the scope of the patch to just swcodec, or otherwise cover more architectures if they're considered critical. Looking for reviewer input on that, as I'm not familiar with these processes. Bug: 197184220 Bug: 198421643 Merged-In: I7815e9e00514e20ff41d4eabeb779113b0519a87 Change-Id: I7815e9e00514e20ff41d4eabeb779113b0519a87 --- .../seccomp_policy/mediaswcodec-arm64.policy | 10 ++++++++++ .../seccomp_policy/mediaextractor-arm64.policy | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy b/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy index 4c51a9c47b..7ff858b662 100644 --- a/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy +++ b/services/mediacodec/seccomp_policy/mediaswcodec-arm64.policy @@ -79,4 +79,14 @@ getgid: 1 getegid: 1 getgroups: 1 +# Android profiler (heapprofd, traced_perf) additions, where not already +# covered by the rest of the file, or by builtin minijail allow-listing of +# logging-related syscalls. +# TODO(b/197184220): this is a targeted addition for a specific investigation, +# and addresses just the arm64 framework av service policies. In the future, we +# should make this more general (e.g. a central file that can be @included in +# other policy files). +setsockopt: 1 +sendmsg: 1 + @include /apex/com.android.media.swcodec/etc/seccomp_policy/code_coverage.arm64.policy diff --git a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy index 9bbd53b5e2..e54c9187e7 100644 --- a/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy +++ b/services/mediaextractor/seccomp_policy/mediaextractor-arm64.policy @@ -46,5 +46,16 @@ mremap: 1 # Required by Sanitizers sched_yield: 1 +# Android profiler (heapprofd, traced_perf) additions, where not already +# covered by the rest of the file, or by builtin minijail allow-listing of +# logging-related syscalls. +# TODO(b/197184220): this is a targeted addition for a specific investigation, +# and addresses just the arm64 framework av service policies. In the future, we +# should make this more general (e.g. a central file that can be @included in +# other policy files). +setsockopt: 1 +sendmsg: 1 +set_tid_address: 1 + @include /apex/com.android.media/etc/seccomp_policy/crash_dump.arm64.policy @include /apex/com.android.media/etc/seccomp_policy/code_coverage.arm64.policy -- GitLab From e1a64b9f9a5b6de80ad8b320bb2e5e0acf76f5fb Mon Sep 17 00:00:00 2001 From: Aayush Soni Date: Fri, 18 Jun 2021 19:16:34 +0530 Subject: [PATCH 129/694] mpeg4enc: update resolution check Updated resolution check to limit encoder to 2048x2048 Bug: 190435883 Test: POC in bug descriptions Change-Id: I749a9a3fda0924c17b3a4ddfb1c6402d2ce8552f --- media/codecs/m4v_h263/enc/src/mp4enc_api.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp index 234faefbf7..00b2ab694f 100644 --- a/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp +++ b/media/codecs/m4v_h263/enc/src/mp4enc_api.cpp @@ -610,18 +610,19 @@ OSCL_EXPORT_REF Bool PVInitVideoEncoder(VideoEncControls *encoderControl, Vid /* Find the maximum width*height for memory allocation of the VOPs */ for (idx = 0; idx < nLayers; idx++) { - temp_w = video->encParams->LayerWidth[idx]; - temp_h = video->encParams->LayerHeight[idx]; + temp_w = ((video->encParams->LayerWidth[idx] + 15) >> 4) << 4; + temp_h = ((video->encParams->LayerHeight[idx] + 15) >> 4) << 4; + + if (temp_w > 2048 || temp_h > 2048) { + goto CLEAN_UP; + } if ((temp_w*temp_h) > max) { max = temp_w * temp_h; - max_width = ((temp_w + 15) >> 4) << 4; - max_height = ((temp_h + 15) >> 4) << 4; - if (((uint64_t)max_width * max_height) > (uint64_t)INT32_MAX - || temp_w > INT32_MAX - 15 || temp_h > INT32_MAX - 15) { - goto CLEAN_UP; - } + max_width = temp_w; + max_height = temp_h; + nTotalMB = ((max_width * max_height) >> 8); } -- GitLab From daf7b2460440d73b8fbbfac86dca288d6ba10d81 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Tue, 7 Sep 2021 18:32:04 +0000 Subject: [PATCH 130/694] Fix race condition for stream open When the stream goes to a weird state during a stream open, don't return ERROR_OK. Bug: 193071260 Test: OboeTester works fine Change-Id: I32932ce9b4782f19455b54b4b121c4c2c683aa36 --- media/libaaudio/src/legacy/AudioStreamTrack.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/media/libaaudio/src/legacy/AudioStreamTrack.cpp b/media/libaaudio/src/legacy/AudioStreamTrack.cpp index 118c004b79..8e58949727 100644 --- a/media/libaaudio/src/legacy/AudioStreamTrack.cpp +++ b/media/libaaudio/src/legacy/AudioStreamTrack.cpp @@ -215,7 +215,6 @@ aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder) mBlockAdapter = nullptr; } - setState(AAUDIO_STREAM_STATE_OPEN); setDeviceId(mAudioTrack->getRoutedDeviceId()); aaudio_session_id_t actualSessionId = @@ -248,6 +247,19 @@ aaudio_result_t AudioStreamTrack::open(const AudioStreamBuilder& builder) "open() perfMode changed from %d to %d", perfMode, actualPerformanceMode); + if (getState() != AAUDIO_STREAM_STATE_UNINITIALIZED) { + ALOGE("%s - Open canceled since state = %d", __func__, getState()); + if (getState() == AAUDIO_STREAM_STATE_DISCONNECTED) + { + ALOGE("%s - Opening while state is disconnected", __func__); + safeReleaseClose(); + return AAUDIO_ERROR_DISCONNECTED; + } + safeReleaseClose(); + return AAUDIO_ERROR_INVALID_STATE; + } + + setState(AAUDIO_STREAM_STATE_OPEN); return AAUDIO_OK; } -- GitLab From b5cf9ea7394d6b66b950df8a6bd317033508de21 Mon Sep 17 00:00:00 2001 From: qiang yin Date: Tue, 31 Aug 2021 10:13:29 +0800 Subject: [PATCH 131/694] Add for Dolby thubmnail There are many Dolby components. If the right component is at the back of the codec list, it will take much time to show thumbnail. Test: Dolby thumbnail show in time. Bug: 197069927 Change-Id: Id196493ccbdc0a67764458cf14de651b8935d363 --- .../StagefrightMetadataRetriever.cpp | 14 +++++++++++ media/libstagefright/MediaCodecList.cpp | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp b/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp index 2aabd534cc..a372b7fe78 100644 --- a/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp +++ b/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp @@ -225,10 +225,17 @@ sp StagefrightMetadataRetriever::getImageInternal( "media.stagefright.thumbnail.prefer_hw_codecs", false); uint32_t flags = preferhw ? 0 : MediaCodecList::kPreferSoftwareCodecs; Vector matchingCodecs; + sp format = new AMessage; + status_t err = convertMetaDataToMessage(trackMeta, &format); + if (err != OK) { + format = NULL; + } + MediaCodecList::findMatchingCodecs( mime, false, /* encoder */ flags, + format, &matchingCodecs); for (size_t i = 0; i < matchingCodecs.size(); ++i) { @@ -348,11 +355,18 @@ sp StagefrightMetadataRetriever::getFrameInternal( bool preferhw = property_get_bool( "media.stagefright.thumbnail.prefer_hw_codecs", false); uint32_t flags = preferhw ? 0 : MediaCodecList::kPreferSoftwareCodecs; + sp format = new AMessage; + status_t err = convertMetaDataToMessage(trackMeta, &format); + if (err != OK) { + format = NULL; + } + Vector matchingCodecs; MediaCodecList::findMatchingCodecs( mime, false, /* encoder */ flags, + format, &matchingCodecs); for (size_t i = 0; i < matchingCodecs.size(); ++i) { diff --git a/media/libstagefright/MediaCodecList.cpp b/media/libstagefright/MediaCodecList.cpp index 6243828e42..2ffe728696 100644 --- a/media/libstagefright/MediaCodecList.cpp +++ b/media/libstagefright/MediaCodecList.cpp @@ -509,6 +509,29 @@ bool MediaCodecList::codecHandlesFormat(const char *mime, sp inf } } } + + int32_t profile = -1; + if (format->findInt32("profile", &profile)) { + int32_t level = -1; + format->findInt32("level", &level); + Vector profileLevels; + capabilities->getSupportedProfileLevels(&profileLevels); + auto it = profileLevels.begin(); + for (; it != profileLevels.end(); ++it) { + if (profile != it->mProfile) { + continue; + } + if (level > -1 && level > it->mLevel) { + continue; + } + break; + } + + if (it == profileLevels.end()) { + ALOGV("Codec does not support profile %d with level %d", profile, level); + return false; + } + } } // haven't found a reason to discard this one -- GitLab From ebe64105be4f395433a0d34b2668c9cc62a086f8 Mon Sep 17 00:00:00 2001 From: Jiabin Huang Date: Tue, 7 Sep 2021 20:01:07 +0000 Subject: [PATCH 132/694] Add interface to query the mmap support. Currently, the mmap support is defined in system property. But the system property only indicates if the mmap is supported or not. It doesn't indicate on which device mmap is supported. In that case, adding an interface to query the mmap support can help make things clear. Test: atest AAudioTests Test: Run OboeTester TEST OUTPUT Test: Verify that MMAP is showed as enabled if supported Test: Try toggling MMAP on and off when opening streams Bug: 193275465 Change-Id: Iac289c1a02e6e2ab4076ab6f2b5045efecad97ac --- media/audioserver/Android.bp | 2 +- media/audioserver/main_audioserver.cpp | 27 ++++++- .../libaaudio/src/core/AudioStreamBuilder.cpp | 55 +++++++++++-- media/libaudioclient/Android.bp | 3 + media/libaudioclient/AudioSystem.cpp | 10 +++ media/libaudioclient/IAudioFlinger.cpp | 13 ++++ .../aidl/android/media/AudioMMapPolicy.aidl | 40 ++++++++++ .../android/media/AudioMMapPolicyInfo.aidl | 29 +++++++ .../android/media/AudioMMapPolicyType.aidl | 34 ++++++++ .../android/media/IAudioFlingerService.aidl | 4 + .../include/media/AudioSystem.h | 6 ++ .../include/media/IAudioFlinger.h | 14 ++++ media/libaudiohal/Android.bp | 1 + media/libaudiohal/impl/Android.bp | 1 + media/libaudiohal/impl/DeviceHalHidl.cpp | 1 + media/libaudiohal/impl/DeviceHalHidl.h | 7 ++ media/libaudiohal/impl/DeviceHalLocal.h | 7 ++ .../libaudiohal/impl/DevicesFactoryHalHidl.h | 2 + .../impl/DevicesFactoryHalHybrid.h | 4 + .../libaudiohal/impl/DevicesFactoryHalLocal.h | 4 + .../media/audiohal/DeviceHalInterface.h | 6 ++ .../audiohal/DevicesFactoryHalInterface.h | 2 + services/audioflinger/Android.bp | 2 + services/audioflinger/AudioFlinger.cpp | 31 ++++++++ services/audioflinger/AudioFlinger.h | 6 ++ services/audioflinger/AudioHwDevice.cpp | 8 ++ services/audioflinger/AudioHwDevice.h | 4 + services/audioflinger/PropertyUtils.cpp | 77 +++++++++++++++++++ services/audioflinger/PropertyUtils.h | 28 +++++++ 29 files changed, 417 insertions(+), 11 deletions(-) create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl create mode 100644 services/audioflinger/PropertyUtils.cpp create mode 100644 services/audioflinger/PropertyUtils.h diff --git a/media/audioserver/Android.bp b/media/audioserver/Android.bp index be25ffbe38..e4fc4ded59 100644 --- a/media/audioserver/Android.bp +++ b/media/audioserver/Android.bp @@ -26,6 +26,7 @@ cc_binary { shared_libs: [ "libaaudioservice", + "libaudioclient", "libaudioflinger", "libaudiopolicyservice", "libaudioprocessing", @@ -41,7 +42,6 @@ cc_binary { "libpowermanager", "libutils", "libvibrator", - ], // TODO check if we still need all of these include directories diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp index 8ee1efb2f3..fd665735f4 100644 --- a/media/audioserver/main_audioserver.cpp +++ b/media/audioserver/main_audioserver.cpp @@ -17,11 +17,17 @@ #define LOG_TAG "audioserver" //#define LOG_NDEBUG 0 +#include + #include #include #include #include +#include +#include +#include +#include #include #include #include @@ -30,7 +36,6 @@ #include // from include_dirs -#include "aaudio/AAudioTesting.h" // aaudio_policy_t, AAUDIO_PROP_MMAP_POLICY, AAUDIO_POLICY_* #include "AudioFlinger.h" #include "AudioPolicyService.h" #include "AAudioService.h" @@ -146,10 +151,24 @@ int main(int argc __unused, char **argv) // AAudioService should only be used in OC-MR1 and later. // And only enable the AAudioService if the system MMAP policy explicitly allows it. // This prevents a client from misusing AAudioService when it is not supported. - aaudio_policy_t mmapPolicy = property_get_int32(AAUDIO_PROP_MMAP_POLICY, - AAUDIO_POLICY_NEVER); - if (mmapPolicy == AAUDIO_POLICY_AUTO || mmapPolicy == AAUDIO_POLICY_ALWAYS) { + // If we cannot get audio flinger here, there must be some serious problems. In that case, + // attempting to call audio flinger on a null pointer could make the process crash + // and attract attentions. + sp af = AudioSystem::get_audio_flinger(); + std::vector policyInfos; + status_t status = af->getMmapPolicyInfos( + media::AudioMMapPolicyType::DEFAULT, &policyInfos); + // Initialize aaudio service when querying mmap policy succeeds and + // any of the policy supports MMAP. + if (status == NO_ERROR && + std::any_of(policyInfos.begin(), policyInfos.end(), [](const auto& info) { + return info.mmapPolicy == media::AudioMMapPolicy::AUTO || + info.mmapPolicy == media::AudioMMapPolicy::ALWAYS; + })) { AAudioService::instantiate(); + } else { + ALOGD("Do not init aaudio service, status %d, policy info size %zu", + status, policyInfos.size()); } ProcessState::self()->startThreadPool(); diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp index a8fd0d91c4..2a6b23524a 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.cpp +++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp @@ -20,9 +20,14 @@ #include #include +#include #include #include +#include +#include +#include +#include #include "binding/AAudioBinderClient.h" #include "client/AudioStreamInternalCapture.h" @@ -86,6 +91,37 @@ static aaudio_result_t builder_createStream(aaudio_direction_t direction, return result; } +namespace { + +aaudio_policy_t aidl2legacy_aaudio_policy(android::media::AudioMMapPolicy aidl) { + switch (aidl) { + case android::media::AudioMMapPolicy::NEVER: + return AAUDIO_POLICY_NEVER; + case android::media::AudioMMapPolicy::AUTO: + return AAUDIO_POLICY_AUTO; + case android::media::AudioMMapPolicy::ALWAYS: + return AAUDIO_POLICY_ALWAYS; + case android::media::AudioMMapPolicy::UNSPECIFIED: + default: + return AAUDIO_UNSPECIFIED; + } +} + +// The aaudio policy will be ALWAYS, NEVER, UNSPECIFIED only when all policy info are +// ALWAYS, NEVER or UNSPECIFIED. Otherwise, the aaudio policy will be AUTO. +aaudio_policy_t getAAudioPolicy( + const std::vector& policyInfos) { + if (policyInfos.empty()) return AAUDIO_POLICY_AUTO; + for (size_t i = 1; i < policyInfos.size(); ++i) { + if (policyInfos.at(i).mmapPolicy != policyInfos.at(0).mmapPolicy) { + return AAUDIO_POLICY_AUTO; + } + } + return aidl2legacy_aaudio_policy(policyInfos.at(0).mmapPolicy); +} + +} // namespace + // Try to open using MMAP path if that is allowed. // Fall back to Legacy path if MMAP not available. // Exact behavior is controlled by MMapPolicy. @@ -104,25 +140,32 @@ aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) { return result; } + std::vector policyInfos; // The API setting is the highest priority. aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy(); // If not specified then get from a system property. - if (mmapPolicy == AAUDIO_UNSPECIFIED) { - mmapPolicy = AAudioProperty_getMMapPolicy(); + if (mmapPolicy == AAUDIO_UNSPECIFIED && android::AudioSystem::getMmapPolicyInfo( + android::media::AudioMMapPolicyType::DEFAULT, &policyInfos) == NO_ERROR) { + mmapPolicy = getAAudioPolicy(policyInfos); } // If still not specified then use the default. if (mmapPolicy == AAUDIO_UNSPECIFIED) { mmapPolicy = AAUDIO_MMAP_POLICY_DEFAULT; } - int32_t mapExclusivePolicy = AAudioProperty_getMMapExclusivePolicy(); - if (mapExclusivePolicy == AAUDIO_UNSPECIFIED) { - mapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; + policyInfos.clear(); + aaudio_policy_t mmapExclusivePolicy = AAUDIO_UNSPECIFIED; + if (android::AudioSystem::getMmapPolicyInfo( + android::media::AudioMMapPolicyType::EXCLUSIVE, &policyInfos) == NO_ERROR) { + mmapExclusivePolicy = getAAudioPolicy(policyInfos); + } + if (mmapExclusivePolicy == AAUDIO_UNSPECIFIED) { + mmapExclusivePolicy = AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT; } aaudio_sharing_mode_t sharingMode = getSharingMode(); if ((sharingMode == AAUDIO_SHARING_MODE_EXCLUSIVE) - && (mapExclusivePolicy == AAUDIO_POLICY_NEVER)) { + && (mmapExclusivePolicy == AAUDIO_POLICY_NEVER)) { ALOGD("%s() EXCLUSIVE sharing mode not supported. Use SHARED.", __func__); sharingMode = AAUDIO_SHARING_MODE_SHARED; setSharingMode(sharingMode); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 322f360b5b..8ea3f32aa8 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -325,6 +325,9 @@ aidl_interface { "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", + "aidl/android/media/AudioMMapPolicy.aidl", + "aidl/android/media/AudioMMapPolicyInfo.aidl", + "aidl/android/media/AudioMMapPolicyType.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioOutputFlags.aidl", "aidl/android/media/AudioPatch.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 46ad296e74..97cb9af7f0 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -2359,6 +2359,16 @@ status_t AudioSystem::setVibratorInfos( return af->setVibratorInfos(vibratorInfos); } +status_t AudioSystem::getMmapPolicyInfo( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + const sp& af = AudioSystem::get_audio_flinger(); + if (af == nullptr) { + return PERMISSION_DENIED; + } + return af->getMmapPolicyInfos(policyType, policyInfos); +} + // --------------------------------------------------------------------------- int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index b67f1f76bb..fdec918fe0 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -17,6 +17,7 @@ #define LOG_TAG "IAudioFlinger" //#define LOG_NDEBUG 0 + #include #include @@ -780,6 +781,12 @@ status_t AudioFlingerClientAdapter::updateSecondaryOutputs( return statusTFromBinderStatus(mDelegate->updateSecondaryOutputs(trackSecondaryOutputInfos)); } +status_t AudioFlingerClientAdapter::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + return statusTFromBinderStatus(mDelegate->getMmapPolicyInfos(policyType, policyInfos)); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // AudioFlingerServerAdapter @@ -1252,4 +1259,10 @@ Status AudioFlingerServerAdapter::updateSecondaryOutputs( return Status::fromStatusT(mDelegate->updateSecondaryOutputs(trackSecondaryOutputs)); } +Status AudioFlingerServerAdapter::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *_aidl_return) { + return Status::fromStatusT(mDelegate->getMmapPolicyInfos(policyType, _aidl_return)); +} + } // namespace android diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl new file mode 100644 index 0000000000..e3fa951390 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +/** + * Audio MMAP policy describe how the aaudio MMAP feature is used. + * {@hide} + */ +@Backing(type="int") +enum AudioMMapPolicy { + /** + * The policy is unspecified. + */ + UNSPECIFIED = 0, + /** + * The MMAP feature is disabled and never used. + */ + NEVER = 1, + /** + * If MMAP feature works then uses it. Otherwise, fall back to something else. + */ + AUTO = 2, + /** + * The MMAP feature must be used. If not available then fail. + */ + ALWAYS = 3, +} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl new file mode 100644 index 0000000000..ad7bd45312 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +import android.media.AudioDevice; +import android.media.AudioMMapPolicy; + +/** + * Audio MMAP policy info describes how an aaudio MMAP feature can be + * used on a particular device. + * {@hide} + */ +parcelable AudioMMapPolicyInfo { + AudioDevice device; + AudioMMapPolicy mmapPolicy = AudioMMapPolicy.UNSPECIFIED; +} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl new file mode 100644 index 0000000000..d6acd2cca3 --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package android.media; + +/** + * The aaudio MMAP policy type. + * {@hide} + */ +@Backing(type="int") +enum AudioMMapPolicyType { + /** + * Default aaudio mmap policy. It is used to query whether the + * aaudio MMAP could be used or not. + */ + DEFAULT = 1, + /** + * Exclusive aaudio mmap policy. It is used to query whether the + * aaudio MMAP could be used in exclusive mode or not. + */ + EXCLUSIVE = 2, +} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 0f84af639f..7a46f4899c 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,6 +16,8 @@ package android.media; +import android.media.AudioMMapPolicyInfo; +import android.media.AudioMMapPolicyType; import android.media.AudioPatch; import android.media.AudioPort; import android.media.AudioPortConfig; @@ -217,4 +219,6 @@ interface IAudioFlingerService { // This usually happens when there is a dynamic policy registered. void updateSecondaryOutputs( in TrackSecondaryOutputInfo[] trackSecondaryOutputInfos); + + AudioMMapPolicyInfo[] getMmapPolicyInfos(AudioMMapPolicyType policyType); } diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index 3c610afa66..c546dfb2b6 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -22,6 +22,8 @@ #include #include +#include +#include #include #include #include @@ -614,6 +616,10 @@ public: static status_t setVibratorInfos(const std::vector& vibratorInfos); + static status_t getMmapPolicyInfo( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + private: class AudioFlingerClient: public IBinder::DeathRecipient, public media::BnAudioFlingerClient diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 25ded3851e..774e907917 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -37,6 +37,8 @@ #include #include +#include +#include #include #include #include @@ -348,6 +350,10 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; + + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; }; /** @@ -445,6 +451,10 @@ public: status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) override; + private: const sp mDelegate; }; @@ -529,6 +539,7 @@ public: SET_AUDIO_HAL_PIDS = media::BnAudioFlingerService::TRANSACTION_setAudioHalPids, SET_VIBRATOR_INFOS = media::BnAudioFlingerService::TRANSACTION_setVibratorInfos, UPDATE_SECONDARY_OUTPUTS = media::BnAudioFlingerService::TRANSACTION_updateSecondaryOutputs, + GET_MMAP_POLICY_INFOS = media::BnAudioFlingerService::TRANSACTION_getMmapPolicyInfos, }; /** @@ -643,6 +654,9 @@ public: Status setVibratorInfos(const std::vector& vibratorInfos) override; Status updateSecondaryOutputs( const std::vector& trackSecondaryOutputInfos) override; + Status getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *_aidl_return) override; private: const sp mDelegate; diff --git a/media/libaudiohal/Android.bp b/media/libaudiohal/Android.bp index bd24c84dbc..5fe74f9d71 100644 --- a/media/libaudiohal/Android.bp +++ b/media/libaudiohal/Android.bp @@ -30,6 +30,7 @@ cc_library_shared { ], shared_libs: [ + "audioclient-types-aidl-cpp", "libdl", "libhidlbase", "liblog", diff --git a/media/libaudiohal/impl/Android.bp b/media/libaudiohal/impl/Android.bp index a2c6e8aeba..d6576f5fc9 100644 --- a/media/libaudiohal/impl/Android.bp +++ b/media/libaudiohal/impl/Android.bp @@ -50,6 +50,7 @@ cc_defaults { "libmedia_helper", "libmediautils", "libutils", + "audioclient-types-aidl-cpp", ], header_libs: [ "android.hardware.audio.common.util@all-versions", diff --git a/media/libaudiohal/impl/DeviceHalHidl.cpp b/media/libaudiohal/impl/DeviceHalHidl.cpp index aa94eeaf16..47acb19f11 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.cpp +++ b/media/libaudiohal/impl/DeviceHalHidl.cpp @@ -20,6 +20,7 @@ //#define LOG_NDEBUG 0 #include +#include #include #include #include diff --git a/media/libaudiohal/impl/DeviceHalHidl.h b/media/libaudiohal/impl/DeviceHalHidl.h index 2694ab3a12..7b4dd88f6e 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.h +++ b/media/libaudiohal/impl/DeviceHalHidl.h @@ -119,6 +119,13 @@ class DeviceHalHidl : public DeviceHalInterface, public ConversionHelperHidl status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType __unused, + std::vector *policyInfos __unused) override { + // TODO: Implement the HAL query when moving to AIDL HAL. + return INVALID_OPERATION; + } + status_t dump(int fd, const Vector& args) override; private: diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h index 2fde936b36..d4bb7a047e 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.h +++ b/media/libaudiohal/impl/DeviceHalLocal.h @@ -112,6 +112,13 @@ class DeviceHalLocal : public DeviceHalInterface status_t addDeviceEffect(audio_port_handle_t device, sp effect) override; status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType __unused, + std::vector *policyInfos __unused) override { + // This function will only be available on AIDL HAL. + return INVALID_OPERATION; + } + status_t dump(int fd, const Vector& args) override; void closeOutputStream(struct audio_stream_out *stream_out); diff --git a/media/libaudiohal/impl/DevicesFactoryHalHidl.h b/media/libaudiohal/impl/DevicesFactoryHalHidl.h index 6f84efeacc..b46259b9f3 100644 --- a/media/libaudiohal/impl/DevicesFactoryHalHidl.h +++ b/media/libaudiohal/impl/DevicesFactoryHalHidl.h @@ -46,6 +46,8 @@ class DevicesFactoryHalHidl : public DevicesFactoryHalInterface status_t setCallbackOnce(sp callback) override; + float getHalVersion() const override { return MAJOR_VERSION + (float)MINOR_VERSION / 10; } + private: friend class ServiceNotificationListener; void addDeviceFactory(sp factory, bool needToNotify); diff --git a/media/libaudiohal/impl/DevicesFactoryHalHybrid.h b/media/libaudiohal/impl/DevicesFactoryHalHybrid.h index 568a1fbaeb..5baefa4b2b 100644 --- a/media/libaudiohal/impl/DevicesFactoryHalHybrid.h +++ b/media/libaudiohal/impl/DevicesFactoryHalHybrid.h @@ -40,6 +40,10 @@ class DevicesFactoryHalHybrid : public DevicesFactoryHalInterface status_t setCallbackOnce(sp callback) override; + float getHalVersion() const override { + return MAJOR_VERSION + (float)MINOR_VERSION / 10; + } + private: sp mLocalFactory; sp mHidlFactory; diff --git a/media/libaudiohal/impl/DevicesFactoryHalLocal.h b/media/libaudiohal/impl/DevicesFactoryHalLocal.h index 32bf362001..d2b9104dbe 100644 --- a/media/libaudiohal/impl/DevicesFactoryHalLocal.h +++ b/media/libaudiohal/impl/DevicesFactoryHalLocal.h @@ -41,6 +41,10 @@ class DevicesFactoryHalLocal : public DevicesFactoryHalInterface return INVALID_OPERATION; } + float getHalVersion() const override { + return MAJOR_VERSION + (float)MINOR_VERSION / 10; + } + private: friend class DevicesFactoryHalHybrid; diff --git a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h index 69cbcecf14..b93c8d26af 100644 --- a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h @@ -17,6 +17,8 @@ #ifndef ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H #define ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H +#include +#include #include #include #include @@ -120,6 +122,10 @@ class DeviceHalInterface : public RefBase virtual status_t removeDeviceEffect( audio_port_handle_t device, sp effect) = 0; + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; + virtual status_t dump(int fd, const Vector& args) = 0; protected: diff --git a/media/libaudiohal/include/media/audiohal/DevicesFactoryHalInterface.h b/media/libaudiohal/include/media/audiohal/DevicesFactoryHalInterface.h index 5091558ce4..17010e6800 100644 --- a/media/libaudiohal/include/media/audiohal/DevicesFactoryHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DevicesFactoryHalInterface.h @@ -43,6 +43,8 @@ class DevicesFactoryHalInterface : public RefBase // The callback can be only set once. virtual status_t setCallbackOnce(sp callback) = 0; + virtual float getHalVersion() const = 0; + static sp create(); protected: diff --git a/services/audioflinger/Android.bp b/services/audioflinger/Android.bp index ea85d04bc8..f401fff073 100644 --- a/services/audioflinger/Android.bp +++ b/services/audioflinger/Android.bp @@ -41,6 +41,7 @@ cc_library_shared { "FastThreadState.cpp", "NBAIO_Tee.cpp", "PatchPanel.cpp", + "PropertyUtils.cpp", "SpdifStreamOut.cpp", "StateQueue.cpp", "Threads.cpp", @@ -92,6 +93,7 @@ cc_library_shared { ], header_libs: [ + "libaaudio_headers", "libaudioclient_headers", "libaudiohal_headers", "libmedia_headers", diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index 1bfacd570c..c8d753b703 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -57,6 +57,7 @@ #include "AudioFlinger.h" #include "NBAIO_Tee.h" +#include "PropertyUtils.h" #include @@ -335,6 +336,36 @@ status_t AudioFlinger::updateSecondaryOutputs( return NO_ERROR; } +#define MAX_MMAP_PROPERTY_DEVICE_HAL_VERSION 7.0 + +status_t AudioFlinger::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) { + *policyInfos = it->second; + return NO_ERROR; + } + if (mDevicesFactoryHal->getHalVersion() > MAX_MMAP_PROPERTY_DEVICE_HAL_VERSION) { + AutoMutex lock(mHardwareLock); + for (size_t i = 0; i < mAudioHwDevs.size(); ++i) { + AudioHwDevice *dev = mAudioHwDevs.valueAt(i); + std::vector infos; + status_t status = dev->getMmapPolicyInfos(policyType, &infos); + if (status != NO_ERROR) { + ALOGE("Failed to query mmap policy info of %d, error %d", + mAudioHwDevs.keyAt(i), status); + continue; + } + policyInfos->insert(policyInfos->end(), infos.begin(), infos.end()); + } + mPolicyInfos[policyType] = *policyInfos; + } else { + getMmapPolicyInfosFromSystemProperty(policyType, policyInfos); + mPolicyInfos[policyType] = *policyInfos; + } + return NO_ERROR; +} + // getDefaultVibratorInfo_l must be called with AudioFlinger lock held. std::optional AudioFlinger::getDefaultVibratorInfo_l() { if (mAudioVibratorInfos.empty()) { diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index d6bf0ae29a..b5d587bd8e 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -282,6 +282,10 @@ public: virtual status_t updateSecondaryOutputs( const TrackSecondaryOutputsMap& trackSecondaryOutputs); + virtual status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -1004,6 +1008,8 @@ private: // Keep in sync with java definition in media/java/android/media/AudioRecord.java static constexpr int32_t kMaxSharedAudioHistoryMs = 5000; + + std::map> mPolicyInfos; }; #undef INCLUDING_FROM_AUDIOFLINGER_H diff --git a/services/audioflinger/AudioHwDevice.cpp b/services/audioflinger/AudioHwDevice.cpp index 16b25f6828..b996c6c97a 100644 --- a/services/audioflinger/AudioHwDevice.cpp +++ b/services/audioflinger/AudioHwDevice.cpp @@ -103,4 +103,12 @@ status_t AudioHwDevice::getAudioPort(struct audio_port_v7 *port) const { } + +status_t AudioHwDevice::getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) const { + return mHwDevice->getMmapPolicyInfos(policyType, policyInfos); +} + + }; // namespace android diff --git a/services/audioflinger/AudioHwDevice.h b/services/audioflinger/AudioHwDevice.h index fc2c693ed5..b72072f656 100644 --- a/services/audioflinger/AudioHwDevice.h +++ b/services/audioflinger/AudioHwDevice.h @@ -85,6 +85,10 @@ public: status_t getAudioPort(struct audio_port_v7 *port) const; + status_t getMmapPolicyInfos( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) const; + private: const audio_module_handle_t mHandle; const char * const mModuleName; diff --git a/services/audioflinger/PropertyUtils.cpp b/services/audioflinger/PropertyUtils.cpp new file mode 100644 index 0000000000..b8abb8edaf --- /dev/null +++ b/services/audioflinger/PropertyUtils.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "PropertyUtils.h" + +namespace android { + +std::string getMmapPolicyProperty(media::AudioMMapPolicyType policyType) { + switch (policyType) { + case media::AudioMMapPolicyType::DEFAULT: + return "aaudio.mmap_policy"; + case media::AudioMMapPolicyType::EXCLUSIVE: + return "aaudio.mmap_exclusive_policy"; + default: + return ""; + } +} + +int getDefaultPolicyFromType(media::AudioMMapPolicyType policyType) { + switch (policyType) { + case media::AudioMMapPolicyType::EXCLUSIVE: + return AAUDIO_UNSPECIFIED; + case media::AudioMMapPolicyType::DEFAULT: + default: + return AAUDIO_POLICY_NEVER; + } +} + +media::AudioMMapPolicy legacy2aidl_aaudio_policy_t_AudioMMapPolicy(aaudio_policy_t legacy) { + switch (legacy) { + case AAUDIO_POLICY_NEVER: + return media::AudioMMapPolicy::NEVER; + case AAUDIO_POLICY_AUTO: + return media::AudioMMapPolicy::AUTO; + case AAUDIO_POLICY_ALWAYS: + return media::AudioMMapPolicy::ALWAYS; + case AAUDIO_UNSPECIFIED: + return media::AudioMMapPolicy::UNSPECIFIED; + default: + ALOGE("%s unknown aaudio policy: %d", __func__, legacy); + return media::AudioMMapPolicy::UNSPECIFIED; + } +} + +status_t getMmapPolicyInfosFromSystemProperty( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos) { + media::AudioMMapPolicyInfo policyInfo; + const std::string propertyStr = getMmapPolicyProperty(policyType); + if (propertyStr.empty()) { + return BAD_VALUE; + } + policyInfo.mmapPolicy = legacy2aidl_aaudio_policy_t_AudioMMapPolicy( + property_get_int32(propertyStr.c_str(), getDefaultPolicyFromType(policyType))); + policyInfos->push_back(policyInfo); + return NO_ERROR; +} + +} // namespace android diff --git a/services/audioflinger/PropertyUtils.h b/services/audioflinger/PropertyUtils.h new file mode 100644 index 0000000000..38cbf92a17 --- /dev/null +++ b/services/audioflinger/PropertyUtils.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +namespace android { + +status_t getMmapPolicyInfosFromSystemProperty( + media::AudioMMapPolicyType policyType, + std::vector *policyInfos); + +} // namespace android -- GitLab From 55a4ae70bd98bc8559829a87e41c9b83892a245d Mon Sep 17 00:00:00 2001 From: Aayush Soni Date: Tue, 20 Jul 2021 17:55:30 +0530 Subject: [PATCH 133/694] mpeg4enc: Ignore integer overflow in encoder idct functions Bug: 191546873 Test: Revert fix for b/186859418 and test with POC generated by fuzzer Change-Id: I27132e3af1a7212debdfdba9b7812cab3c901169 --- media/codecs/m4v_h263/enc/src/fastidct.cpp | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/media/codecs/m4v_h263/enc/src/fastidct.cpp b/media/codecs/m4v_h263/enc/src/fastidct.cpp index 688effc4e5..ec1b28f9d7 100644 --- a/media/codecs/m4v_h263/enc/src/fastidct.cpp +++ b/media/codecs/m4v_h263/enc/src/fastidct.cpp @@ -76,6 +76,8 @@ void idct_col1(Short *blk) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col2(Short *blk) { int32 x0, x1, x3, x5, x7;//, x8; @@ -102,6 +104,8 @@ void idct_col2(Short *blk) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col3(Short *blk) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -137,6 +141,8 @@ void idct_col3(Short *blk) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col4(Short *blk) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -180,6 +186,8 @@ void idct_col4(Short *blk) } #ifndef SMALL_DCT +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col0x40(Short *blk) { int32 x1, x3, x5, x7;//, x8; @@ -230,6 +238,8 @@ void idct_col0x20(Short *blk) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col0x10(Short *blk) { int32 x1, x3, x5, x7; @@ -256,6 +266,8 @@ void idct_col0x10(Short *blk) #endif /* SMALL_DCT */ +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_col(Short *blk) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -368,6 +380,8 @@ void idct_row1Inter(Short *blk, UChar *rec, Int lx) return; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row2Inter(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x4, x5; @@ -427,6 +441,8 @@ void idct_row2Inter(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row3Inter(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -497,6 +513,8 @@ void idct_row3Inter(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row4Inter(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -573,6 +591,8 @@ void idct_row4Inter(Short *blk, UChar *rec, Int lx) } #ifndef SMALL_DCT +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x40Inter(Short *blk, UChar *rec, Int lx) { int32 x1, x2, x4, x5; @@ -686,6 +706,8 @@ void idct_row0x20Inter(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x10Inter(Short *blk, UChar *rec, Int lx) { int32 x1, x3, x5, x7; @@ -741,6 +763,8 @@ void idct_row0x10Inter(Short *blk, UChar *rec, Int lx) #endif /* SMALL_DCT */ +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_rowInter(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -864,6 +888,8 @@ void idct_row1Intra(Short *blk, UChar *rec, Int lx) return; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row2Intra(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x4, x5; @@ -919,6 +945,8 @@ void idct_row2Intra(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row3Intra(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -985,6 +1013,8 @@ void idct_row3Intra(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row4Intra(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -1058,6 +1088,8 @@ void idct_row4Intra(Short *blk, UChar *rec, Int lx) } #ifndef SMALL_DCT +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x40Intra(Short *blk, UChar *rec, Int lx) { int32 x1, x2, x4, x5; @@ -1166,6 +1198,8 @@ void idct_row0x20Intra(Short *blk, UChar *rec, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x10Intra(Short *blk, UChar *rec, Int lx) { int32 x1, x3, x5, x7; @@ -1218,6 +1252,8 @@ void idct_row0x10Intra(Short *blk, UChar *rec, Int lx) } #endif /* SMALL_DCT */ +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_rowIntra(Short *blk, UChar *rec, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -1364,6 +1400,8 @@ void idct_row1zmv(Short *blk, UChar *rec, UChar *pred, Int lx) return; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row2zmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x0, x1, x2, x4, x5; @@ -1424,6 +1462,8 @@ void idct_row2zmv(Short *blk, UChar *rec, UChar *pred, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row3zmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -1495,6 +1535,8 @@ void idct_row3zmv(Short *blk, UChar *rec, UChar *pred, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row4zmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; @@ -1572,6 +1614,8 @@ void idct_row4zmv(Short *blk, UChar *rec, UChar *pred, Int lx) } #ifndef SMALL_DCT +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x40zmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x1, x2, x4, x5; @@ -1687,6 +1731,8 @@ void idct_row0x20zmv(Short *blk, UChar *rec, UChar *pred, Int lx) return ; } +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_row0x10zmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x1, x3, x5, x7; @@ -1743,6 +1789,8 @@ void idct_row0x10zmv(Short *blk, UChar *rec, UChar *pred, Int lx) #endif /* SMALL_DCT */ +/* Ignoring overflows as idct function expects and uses overflows */ +__attribute__((no_sanitize("signed-integer-overflow"))) void idct_rowzmv(Short *blk, UChar *rec, UChar *pred, Int lx) { int32 x0, x1, x2, x3, x4, x5, x6, x7, x8; -- GitLab From 693ffd3f3fd97634a5a88b03c3dde457aa504460 Mon Sep 17 00:00:00 2001 From: Lais Andrade Date: Fri, 10 Sep 2021 18:33:41 +0100 Subject: [PATCH 134/694] Remove unused libvibrator dependency from libaudioclient Bug: 124501721 Test: builds Change-Id: I7ea66f0e8d7fc96bb0065ed31b5932b617dc8115 --- media/libaudioclient/Android.bp | 1 - 1 file changed, 1 deletion(-) diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 5b60a40561..5eeae786ca 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -137,7 +137,6 @@ cc_library { "libprocessgroup", "libshmemcompat", "libutils", - "libvibrator", "framework-permission-aidl-cpp", ], export_shared_lib_headers: [ -- GitLab From bf8cead83c4db1aca9536a0fd264eeeb34af7f5d Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Tue, 14 Sep 2021 16:04:00 +0200 Subject: [PATCH 135/694] Spatializer: process callbacks in separate thread Add a Looper and Handler to process events from the engine and pose controler callback to avoid cross mutex deadlocks. Bug: 188502620 Test: manual test with mock spatializer Change-Id: I1342602259b147727c704ad7bbeb1b3a68c7b231 --- services/audiopolicy/service/Android.bp | 1 + services/audiopolicy/service/Spatializer.cpp | 147 +++++++++++++++++-- services/audiopolicy/service/Spatializer.h | 20 ++- 3 files changed, 158 insertions(+), 10 deletions(-) diff --git a/services/audiopolicy/service/Android.bp b/services/audiopolicy/service/Android.bp index 3723a69e00..99085e2263 100644 --- a/services/audiopolicy/service/Android.bp +++ b/services/audiopolicy/service/Android.bp @@ -49,6 +49,7 @@ cc_library_shared { "libsensorprivacy", "libshmemcompat", "libutils", + "libstagefright_foundation", "android.media.audio.common.types-V1-cpp", "audioclient-types-aidl-cpp", "audioflinger-aidl-cpp", diff --git a/services/audiopolicy/service/Spatializer.cpp b/services/audiopolicy/service/Spatializer.cpp index c5506a3d6f..7d49ea2bab 100644 --- a/services/audiopolicy/service/Spatializer.cpp +++ b/services/audiopolicy/service/Spatializer.cpp @@ -29,8 +29,10 @@ #include #include #include -#include #include +#include +#include +#include #include #include @@ -49,7 +51,6 @@ using media::SpatializationMode; using media::SpatializerHeadTrackingMode; using media::SensorPoseProvider; - using namespace std::chrono_literals; #define VALUE_OR_RETURN_BINDER_STATUS(x) \ @@ -65,6 +66,90 @@ using namespace std::chrono_literals; // --------------------------------------------------------------------------- +class Spatializer::EngineCallbackHandler : public AHandler { +public: + EngineCallbackHandler(wp spatializer) + : mSpatializer(spatializer) { + } + + enum { + // Device state callbacks + kWhatOnFramesProcessed, // AudioEffect::EVENT_FRAMES_PROCESSED + kWhatOnHeadToStagePose, // SpatializerPoseController::Listener::onHeadToStagePose + kWhatOnActualModeChange, // SpatializerPoseController::Listener::onActualModeChange + }; + static constexpr const char *kNumFramesKey = "numFrames"; + static constexpr const char *kModeKey = "mode"; + static constexpr const char *kTranslation0Key = "translation0"; + static constexpr const char *kTranslation1Key = "translation1"; + static constexpr const char *kTranslation2Key = "translation2"; + static constexpr const char *kRotation0Key = "rotation0"; + static constexpr const char *kRotation1Key = "rotation1"; + static constexpr const char *kRotation2Key = "rotation2"; + + void onMessageReceived(const sp &msg) override { + switch (msg->what()) { + case kWhatOnFramesProcessed: { + sp spatializer = mSpatializer.promote(); + if (spatializer == nullptr) { + ALOGW("%s: Cannot promote spatializer", __func__); + return; + } + int numFrames; + if (!msg->findInt32(kNumFramesKey, &numFrames)) { + ALOGE("%s: Cannot find num frames!", __func__); + return; + } + if (numFrames > 0) { + spatializer->calculateHeadPose(); + } + } break; + case kWhatOnHeadToStagePose: { + sp spatializer = mSpatializer.promote(); + if (spatializer == nullptr) { + ALOGW("%s: Cannot promote spatializer", __func__); + return; + } + std::vector headToStage(sHeadPoseKeys.size()); + for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) { + if (!msg->findFloat(sHeadPoseKeys[i], &headToStage[i])) { + ALOGE("%s: Cannot find kTranslation0Key!", __func__); + return; + } + } + spatializer->onHeadToStagePoseMsg(headToStage); + } break; + case kWhatOnActualModeChange: { + sp spatializer = mSpatializer.promote(); + if (spatializer == nullptr) { + ALOGW("%s: Cannot promote spatializer", __func__); + return; + } + int mode; + if (!msg->findInt32(EngineCallbackHandler::kModeKey, &mode)) { + ALOGE("%s: Cannot find actualMode!", __func__); + return; + } + spatializer->onActualModeChangeMsg(static_cast(mode)); + } break; + default: + LOG_ALWAYS_FATAL("Invalid callback message %d", msg->what()); + } + } +private: + wp mSpatializer; +}; + +const std::vector Spatializer::sHeadPoseKeys = { + Spatializer::EngineCallbackHandler::kTranslation0Key, + Spatializer::EngineCallbackHandler::kTranslation1Key, + Spatializer::EngineCallbackHandler::kTranslation2Key, + Spatializer::EngineCallbackHandler::kRotation0Key, + Spatializer::EngineCallbackHandler::kRotation1Key, + Spatializer::EngineCallbackHandler::kRotation2Key, +}; + +// --------------------------------------------------------------------------- sp Spatializer::create(SpatializerPolicyCallback *callback) { sp spatializer; @@ -107,8 +192,26 @@ Spatializer::Spatializer(effect_descriptor_t engineDescriptor, SpatializerPolicy ALOGV("%s", __func__); } +void Spatializer::onFirstRef() { + mLooper = new ALooper; + mLooper->setName("Spatializer-looper"); + mLooper->start( + /*runOnCallingThread*/false, + /*canCallJava*/ false, + PRIORITY_AUDIO); + + mHandler = new EngineCallbackHandler(this); + mLooper->registerHandler(mHandler); +} + Spatializer::~Spatializer() { ALOGV("%s", __func__); + if (mLooper != nullptr) { + mLooper->stop(); + mLooper->unregisterHandler(mHandler->id()); + } + mLooper.clear(); + mHandler.clear(); } status_t Spatializer::loadEngineConfiguration(sp effect) { @@ -391,23 +494,44 @@ Status Spatializer::getSupportedModes(std::vector *modes) { // SpatializerPoseController::Listener void Spatializer::onHeadToStagePose(const Pose3f& headToStage) { ALOGV("%s", __func__); - sp callback; auto vec = headToStage.toVector(); + LOG_ALWAYS_FATAL_IF(vec.size() != sHeadPoseKeys.size(), + "%s invalid head to stage vector size %zu", __func__, vec.size()); + + sp msg = + new AMessage(EngineCallbackHandler::kWhatOnHeadToStagePose, mHandler); + for (size_t i = 0 ; i < sHeadPoseKeys.size(); i++) { + msg->setFloat(sHeadPoseKeys[i], vec[i]); + } + msg->post(); +} + +void Spatializer::onHeadToStagePoseMsg(const std::vector& headToStage) { + ALOGV("%s", __func__); + sp callback; { std::lock_guard lock(mLock); callback = mSpatializerCallback; if (mEngine != nullptr) { - setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, vec); + setEffectParameter_l(SPATIALIZER_PARAM_HEAD_TO_STAGE, headToStage); } } if (callback != nullptr) { - callback->onHeadToSoundStagePoseUpdated(vec); + callback->onHeadToSoundStagePoseUpdated(headToStage); } } void Spatializer::onActualModeChange(HeadTrackingMode mode) { - ALOGV("onActualModeChange(%d)", (int) mode); + ALOGV("%s(%d)", __func__, (int)mode); + sp msg = + new AMessage(EngineCallbackHandler::kWhatOnActualModeChange, mHandler); + msg->setInt32(EngineCallbackHandler::kModeKey, static_cast(mode)); + msg->post(); +} + +void Spatializer::onActualModeChangeMsg(HeadTrackingMode mode) { + ALOGV("%s(%d)", __func__, (int) mode); sp callback; SpatializerHeadTrackingMode spatializerMode; { @@ -534,9 +658,7 @@ void Spatializer::engineCallback(int32_t event, void *user, void *info) { case AudioEffect::EVENT_FRAMES_PROCESSED: { int frames = info == nullptr ? 0 : *(int*)info; ALOGD("%s frames processed %d for me %p", __func__, frames, me); - if (frames > 0) { - me->calculateHeadPose(); - } + me->postFramesProcessedMsg(frames); } break; default: ALOGD("%s event %d", __func__, event); @@ -544,6 +666,13 @@ void Spatializer::engineCallback(int32_t event, void *user, void *info) { } } +void Spatializer::postFramesProcessedMsg(int frames) { + sp msg = + new AMessage(EngineCallbackHandler::kWhatOnFramesProcessed, mHandler); + msg->setInt32(EngineCallbackHandler::kNumFramesKey, frames); + msg->post(); +} + // --------------------------------------------------------------------------- Spatializer::EffectClient::EffectClient(const sp& effectClient, diff --git a/services/audiopolicy/service/Spatializer.h b/services/audiopolicy/service/Spatializer.h index a45290bea2..ae7ded86ce 100644 --- a/services/audiopolicy/service/Spatializer.h +++ b/services/audiopolicy/service/Spatializer.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -91,6 +92,9 @@ class Spatializer : public media::BnSpatializer, ~Spatializer() override; + /** RefBase */ + void onFirstRef(); + /** ISpatializer, see ISpatializer.aidl */ binder::Status release() override; binder::Status getSupportedLevels(std::vector* levels) override; @@ -138,6 +142,8 @@ class Spatializer : public media::BnSpatializer, /** Gets the channel mask, sampling rate and format set for the spatializer input. */ audio_config_base_t getAudioInConfig() const; + void calculateHeadPose(); + /** An implementation of an IEffect interface that can be used to pass advanced parameters to * the spatializer engine. All APis are noop (i.e. the interface cannot be used to control * the effect) except for passing parameters via the command() API. */ @@ -176,7 +182,9 @@ private: void onHeadToStagePose(const media::Pose3f& headToStage) override; void onActualModeChange(media::HeadTrackingMode mode) override; - void calculateHeadPose(); + void onHeadToStagePoseMsg(const std::vector& headToStage); + void onActualModeChangeMsg(media::HeadTrackingMode mode); + static ConversionResult getSensorFromHandle(int handle); @@ -251,6 +259,8 @@ private: return mEngine->setParameter(p); } + void postFramesProcessedMsg(int frames); + /** Effect engine descriptor */ const effect_descriptor_t mEngineDescriptor; /** Callback interface to parent audio policy service */ @@ -298,6 +308,14 @@ private: std::vector mSpatializationModes; std::vector mChannelMasks; bool mSupportsHeadTracking; + + // Looper thread for mEngine callbacks + class EngineCallbackHandler; + + sp mLooper; + sp mHandler; + + static const std::vector sHeadPoseKeys; }; -- GitLab From 925a27febcc2be81cb6960b5d0c1bc7d06f502e9 Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Mon, 13 Sep 2021 16:25:07 -0700 Subject: [PATCH 136/694] cameraserver hidl: Skip vendor ids with tag count <=0 for getCameraVendorTagSections. Bug: 199420805 Test: Use getCameraVendorTagSections on devices where a provider returns -1 for getTagCount via vndk Change-Id: I29f23b6771168ec19c693b2a443f1c9a3fe4c13d Signed-off-by: Jayant Chowdhary --- services/camera/libcameraservice/hidl/HidlCameraService.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/camera/libcameraservice/hidl/HidlCameraService.cpp b/services/camera/libcameraservice/hidl/HidlCameraService.cpp index 7d1b3cf0ad..a812587c24 100644 --- a/services/camera/libcameraservice/hidl/HidlCameraService.cpp +++ b/services/camera/libcameraservice/hidl/HidlCameraService.cpp @@ -279,6 +279,9 @@ Return HidlCameraService::getCameraVendorTagSections(getCameraVendorTagSec size_t numSections = sectionNames->size(); std::vector> tagsBySection(numSections); int tagCount = desc->getTagCount(); + if (tagCount <= 0) { + continue; + } std::vector tags(tagCount); desc->getTagArray(tags.data()); for (int i = 0; i < tagCount; i++) { -- GitLab From f4a75367c834a502c40de0d0793b3f83aaca829a Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 16 Sep 2021 00:02:54 +0000 Subject: [PATCH 137/694] Move AudioDevice* from android.media -> a.m.audio.common SAIDL Bug: 198812639 Test: m Test: atest audio_aidl_conversion_tests Change-Id: I9193593bf17634e9bf05dc7cf56ac826c4755443 --- media/libaudioclient/AidlConversion.cpp | 148 ++++++++-------- media/libaudioclient/Android.bp | 3 - media/libaudioclient/AudioSystem.cpp | 66 ++++---- .../aidl/android/media/AudioDevice.aidl | 27 --- .../android/media/AudioDeviceDescription.aidl | 101 ----------- .../aidl/android/media/AudioDeviceType.aidl | 158 ------------------ .../android/media/AudioMMapPolicyInfo.aidl | 4 +- .../aidl/android/media/AudioMix.aidl | 2 +- .../media/AudioPortConfigDeviceExt.aidl | 2 +- .../android/media/AudioPortDeviceExt.aidl | 2 +- .../android/media/CreateEffectRequest.aidl | 4 +- .../android/media/IAudioPolicyService.aidl | 4 +- .../aidl/android/media/OpenInputRequest.aidl | 2 +- .../aidl/android/media/OpenInputResponse.aidl | 2 +- .../android/media/SoundTriggerSession.aidl | 2 +- .../include/media/AidlConversion.h | 12 +- .../include/media/AudioCommonTypes.h | 9 +- .../audio_aidl_legacy_conversion_tests.cpp | 36 ++-- .../AudioDeviceTypeAddr.cpp | 11 +- .../include/media/AudioDeviceTypeAddr.h | 6 +- .../service/AudioPolicyInterfaceImpl.cpp | 56 ++++--- .../audiopolicy/service/AudioPolicyService.h | 40 ++--- 22 files changed, 211 insertions(+), 486 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioDevice.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioDeviceType.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index b499cfadd9..b0426fa780 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -38,6 +38,8 @@ using media::audio::common::AudioChannelLayout; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioContentType; +using media::audio::common::AudioDeviceDescription; +using media::audio::common::AudioDeviceType; using media::audio::common::AudioEncapsulationMetadataType; using media::audio::common::AudioEncapsulationMode; using media::audio::common::AudioEncapsulationType; @@ -406,7 +408,7 @@ namespace { namespace detail { using AudioChannelPair = std::pair; using AudioChannelPairs = std::vector; -using AudioDevicePair = std::pair; +using AudioDevicePair = std::pair; using AudioDevicePairs = std::vector; using AudioFormatPair = std::pair; using AudioFormatPairs = std::vector; @@ -494,9 +496,9 @@ const detail::AudioChannelPairs& getVoiceAudioChannelPairs() { return pairs; } -media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, +AudioDeviceDescription make_AudioDeviceDescription(AudioDeviceType type, const std::string& connection = "") { - media::AudioDeviceDescription result; + AudioDeviceDescription result; result.type = type; result.connection = connection; return result; @@ -504,7 +506,7 @@ media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType void append_AudioDeviceDescription(detail::AudioDevicePairs& pairs, audio_devices_t inputType, audio_devices_t outputType, - media::AudioDeviceType inType, media::AudioDeviceType outType, + AudioDeviceType inType, AudioDeviceType outType, const std::string& connection = "") { pairs.push_back(std::make_pair(inputType, make_AudioDeviceDescription(inType, connection))); pairs.push_back(std::make_pair(outputType, make_AudioDeviceDescription(outType, connection))); @@ -514,174 +516,174 @@ const detail::AudioDevicePairs& getAudioDevicePairs() { static const detail::AudioDevicePairs pairs = []() { detail::AudioDevicePairs pairs = {{ { - AUDIO_DEVICE_NONE, media::AudioDeviceDescription{} + AUDIO_DEVICE_NONE, AudioDeviceDescription{} }, { AUDIO_DEVICE_OUT_EARPIECE, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_SPEAKER_EARPIECE) + AudioDeviceType::OUT_SPEAKER_EARPIECE) }, { AUDIO_DEVICE_OUT_SPEAKER, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_SPEAKER) + AudioDeviceType::OUT_SPEAKER) }, { AUDIO_DEVICE_OUT_WIRED_HEADPHONE, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_HEADPHONE, - media::AudioDeviceDescription::CONNECTION_ANALOG()) + AudioDeviceType::OUT_HEADPHONE, + AudioDeviceDescription::CONNECTION_ANALOG()) }, { AUDIO_DEVICE_OUT_BLUETOOTH_SCO, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_BT_SCO()) + AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_BT_SCO()) }, { AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_CARKIT, - media::AudioDeviceDescription::CONNECTION_BT_SCO()) + AudioDeviceType::OUT_CARKIT, + AudioDeviceDescription::CONNECTION_BT_SCO()) }, { AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_HEADPHONE, - media::AudioDeviceDescription::CONNECTION_BT_A2DP()) + AudioDeviceType::OUT_HEADPHONE, + AudioDeviceDescription::CONNECTION_BT_A2DP()) }, { AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_SPEAKER, - media::AudioDeviceDescription::CONNECTION_BT_A2DP()) + AudioDeviceType::OUT_SPEAKER, + AudioDeviceDescription::CONNECTION_BT_A2DP()) }, { AUDIO_DEVICE_OUT_TELEPHONY_TX, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_TELEPHONY_TX) + AudioDeviceType::OUT_TELEPHONY_TX) }, { AUDIO_DEVICE_OUT_AUX_LINE, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_LINE_AUX) + AudioDeviceType::OUT_LINE_AUX) }, { AUDIO_DEVICE_OUT_SPEAKER_SAFE, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_SPEAKER_SAFE) + AudioDeviceType::OUT_SPEAKER_SAFE) }, { AUDIO_DEVICE_OUT_HEARING_AID, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_HEARING_AID, - media::AudioDeviceDescription::CONNECTION_WIRELESS()) + AudioDeviceType::OUT_HEARING_AID, + AudioDeviceDescription::CONNECTION_WIRELESS()) }, { AUDIO_DEVICE_OUT_ECHO_CANCELLER, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_ECHO_CANCELLER) + AudioDeviceType::OUT_ECHO_CANCELLER) }, { AUDIO_DEVICE_OUT_BLE_SPEAKER, make_AudioDeviceDescription( - media::AudioDeviceType::OUT_SPEAKER, - media::AudioDeviceDescription::CONNECTION_BT_LE()) + AudioDeviceType::OUT_SPEAKER, + AudioDeviceDescription::CONNECTION_BT_LE()) }, // AUDIO_DEVICE_IN_AMBIENT and IN_COMMUNICATION are removed since they were deprecated. { AUDIO_DEVICE_IN_BUILTIN_MIC, make_AudioDeviceDescription( - media::AudioDeviceType::IN_MICROPHONE) + AudioDeviceType::IN_MICROPHONE) }, { AUDIO_DEVICE_IN_BACK_MIC, make_AudioDeviceDescription( - media::AudioDeviceType::IN_MICROPHONE_BACK) + AudioDeviceType::IN_MICROPHONE_BACK) }, { AUDIO_DEVICE_IN_TELEPHONY_RX, make_AudioDeviceDescription( - media::AudioDeviceType::IN_TELEPHONY_RX) + AudioDeviceType::IN_TELEPHONY_RX) }, { AUDIO_DEVICE_IN_TV_TUNER, make_AudioDeviceDescription( - media::AudioDeviceType::IN_TV_TUNER) + AudioDeviceType::IN_TV_TUNER) }, { AUDIO_DEVICE_IN_LOOPBACK, make_AudioDeviceDescription( - media::AudioDeviceType::IN_LOOPBACK) + AudioDeviceType::IN_LOOPBACK) }, { AUDIO_DEVICE_IN_BLUETOOTH_BLE, make_AudioDeviceDescription( - media::AudioDeviceType::IN_DEVICE, - media::AudioDeviceDescription::CONNECTION_BT_LE()) + AudioDeviceType::IN_DEVICE, + AudioDeviceDescription::CONNECTION_BT_LE()) }, { AUDIO_DEVICE_IN_ECHO_REFERENCE, make_AudioDeviceDescription( - media::AudioDeviceType::IN_ECHO_REFERENCE) + AudioDeviceType::IN_ECHO_REFERENCE) } }}; append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_DEFAULT, AUDIO_DEVICE_OUT_DEFAULT, - media::AudioDeviceType::IN_DEFAULT, media::AudioDeviceType::OUT_DEFAULT); + AudioDeviceType::IN_DEFAULT, AudioDeviceType::OUT_DEFAULT); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_ANALOG()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_ANALOG()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_BT_SCO()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_BT_SCO()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_HDMI, AUDIO_DEVICE_OUT_HDMI, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_HDMI()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_HDMI()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX, - media::AudioDeviceType::IN_SUBMIX, media::AudioDeviceType::OUT_SUBMIX); + AudioDeviceType::IN_SUBMIX, AudioDeviceType::OUT_SUBMIX); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_ANALOG_DOCK()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_ANALOG_DOCK()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_DIGITAL_DOCK()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_DIGITAL_DOCK()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_USB_ACCESSORY, AUDIO_DEVICE_OUT_USB_ACCESSORY, - media::AudioDeviceType::IN_ACCESSORY, media::AudioDeviceType::OUT_ACCESSORY, - media::AudioDeviceDescription::CONNECTION_USB()); + AudioDeviceType::IN_ACCESSORY, AudioDeviceType::OUT_ACCESSORY, + AudioDeviceDescription::CONNECTION_USB()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_USB_DEVICE, AUDIO_DEVICE_OUT_USB_DEVICE, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_USB()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_USB()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_FM_TUNER, AUDIO_DEVICE_OUT_FM, - media::AudioDeviceType::IN_FM_TUNER, media::AudioDeviceType::OUT_FM); + AudioDeviceType::IN_FM_TUNER, AudioDeviceType::OUT_FM); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_LINE, AUDIO_DEVICE_OUT_LINE, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_ANALOG()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_ANALOG()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_SPDIF, AUDIO_DEVICE_OUT_SPDIF, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_SPDIF()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_SPDIF()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_BT_A2DP()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_BT_A2DP()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_IP, AUDIO_DEVICE_OUT_IP, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_IP_V4()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_IP_V4()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_OUT_BUS, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_BUS()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_BUS()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_PROXY, AUDIO_DEVICE_OUT_PROXY, - media::AudioDeviceType::IN_AFE_PROXY, media::AudioDeviceType::OUT_AFE_PROXY); + AudioDeviceType::IN_AFE_PROXY, AudioDeviceType::OUT_AFE_PROXY); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_USB_HEADSET, AUDIO_DEVICE_OUT_USB_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_USB()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_USB()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_ARC, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_HDMI_ARC()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_HDMI_ARC()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_HDMI_EARC, AUDIO_DEVICE_OUT_HDMI_EARC, - media::AudioDeviceType::IN_DEVICE, media::AudioDeviceType::OUT_DEVICE, - media::AudioDeviceDescription::CONNECTION_HDMI_EARC()); + AudioDeviceType::IN_DEVICE, AudioDeviceType::OUT_DEVICE, + AudioDeviceDescription::CONNECTION_HDMI_EARC()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_BLE_HEADSET, AUDIO_DEVICE_OUT_BLE_HEADSET, - media::AudioDeviceType::IN_HEADSET, media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_BT_LE()); + AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_BT_LE()); return pairs; }(); return pairs; @@ -1135,8 +1137,8 @@ ConversionResult legacy2aidl_audio_channel_mask_t_AudioChann } ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( - const media::AudioDeviceDescription& aidl) { - static const std::unordered_map m = + const AudioDeviceDescription& aidl) { + static const std::unordered_map m = make_ReverseMap(getAudioDevicePairs()); if (auto it = m.find(aidl); it != m.end()) { return it->second; @@ -1146,9 +1148,9 @@ ConversionResult aidl2legacy_AudioDeviceDescription_audio_devic } } -ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( +ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( audio_devices_t legacy) { - static const std::unordered_map m = + static const std::unordered_map m = make_DirectMap(getAudioDevicePairs()); if (auto it = m.find(legacy); it != m.end()) { return it->second; diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index f1df084107..7475e5f7dc 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -312,9 +312,6 @@ aidl_interface { srcs: [ "aidl/android/media/AudioAttributesInternal.aidl", "aidl/android/media/AudioClient.aidl", - "aidl/android/media/AudioDevice.aidl", - "aidl/android/media/AudioDeviceDescription.aidl", - "aidl/android/media/AudioDeviceType.aidl", "aidl/android/media/AudioDualMonoMode.aidl", "aidl/android/media/AudioFlag.aidl", "aidl/android/media/AudioGain.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 97cb9af7f0..afc65d74ff 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -55,6 +55,8 @@ using content::AttributionSourceState; using media::IAudioPolicyService; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; +using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioOffloadInfo; using media::audio::common::AudioSource; @@ -853,7 +855,7 @@ status_t AudioSystem::setDeviceConnectionState(audio_devices_t device, name = device_name; } - media::AudioDevice deviceAidl; + AudioDevice deviceAidl; deviceAidl.type = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = address; @@ -874,7 +876,7 @@ audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t d if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; auto result = [&]() -> ConversionResult { - media::AudioDevice deviceAidl; + AudioDevice deviceAidl; deviceAidl.type = VALUE_OR_RETURN( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = device_address; @@ -905,7 +907,7 @@ status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device, name = device_name; } - media::AudioDevice deviceAidl; + AudioDevice deviceAidl; deviceAidl.type = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); deviceAidl.address = address; @@ -1177,7 +1179,7 @@ status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream, AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral(index)); - media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); return statusTFromBinderStatus( aps->setStreamVolumeIndex(streamAidl, deviceAidl, indexAidl)); @@ -1191,7 +1193,7 @@ status_t AudioSystem::getStreamVolumeIndex(audio_stream_type_t stream, AudioStreamType streamAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); - media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); int32_t indexAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( @@ -1211,7 +1213,7 @@ status_t AudioSystem::setVolumeIndexForAttributes(const audio_attributes_t& attr media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); int32_t indexAidl = VALUE_OR_RETURN_STATUS(convertIntegral(index)); - media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); return statusTFromBinderStatus( aps->setVolumeIndexForAttributes(attrAidl, deviceAidl, indexAidl)); @@ -1225,7 +1227,7 @@ status_t AudioSystem::getVolumeIndexForAttributes(const audio_attributes_t& attr media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr)); - media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( + AudioDeviceDescription deviceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); int32_t indexAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( @@ -1282,7 +1284,7 @@ DeviceTypeSet AudioSystem::getDevicesForStream(audio_stream_type_t stream) { auto result = [&]() -> ConversionResult { AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); - std::vector resultAidl; + std::vector resultAidl; RETURN_IF_ERROR(statusTFromBinderStatus( aps->getDevicesForStream(streamAidl, &resultAidl))); return convertContainer(resultAidl, @@ -1301,7 +1303,7 @@ status_t AudioSystem::getDevicesForAttributes(const AudioAttributes& aa, media::AudioAttributesEx aaAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioAttributes_AudioAttributesEx(aa)); - std::vector retAidl; + std::vector retAidl; RETURN_STATUS_IF_ERROR( statusTFromBinderStatus(aps->getDevicesForAttributes(aaAidl, &retAidl))); *devices = VALUE_OR_RETURN_STATUS( @@ -1750,8 +1752,8 @@ status_t AudioSystem::setUidDeviceAffinities(uid_t uid, const AudioDeviceTypeAdd if (aps == 0) return PERMISSION_DENIED; int32_t uidAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_uid_t_int32_t(uid)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus(aps->setUidDeviceAffinities(uidAidl, devicesAidl)); } @@ -1770,9 +1772,9 @@ status_t AudioSystem::setUserIdDeviceAffinities(int userId, if (aps == 0) return PERMISSION_DENIED; int32_t userIdAidl = VALUE_OR_RETURN_STATUS(convertReinterpret(userId)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus( aps->setUserIdDeviceAffinities(userIdAidl, devicesAidl)); } @@ -1848,7 +1850,7 @@ AudioSystem::getStreamVolumeDB(audio_stream_type_t stream, int index, audio_devi AudioStreamType streamAidl = VALUE_OR_RETURN( legacy2aidl_audio_stream_type_t_AudioStreamType(stream)); int32_t indexAidl = VALUE_OR_RETURN(convertIntegral(index)); - media::AudioDeviceDescription deviceAidl = VALUE_OR_RETURN( + AudioDeviceDescription deviceAidl = VALUE_OR_RETURN( legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); float retAidl; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -2134,9 +2136,9 @@ status_t AudioSystem::setDevicesRoleForStrategy(product_strategy_t strategy, int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus( aps->setDevicesRoleForStrategy(strategyAidl, roleAidl, devicesAidl)); } @@ -2162,7 +2164,7 @@ status_t AudioSystem::getDevicesForRoleAndStrategy(product_strategy_t strategy, } int32_t strategyAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_product_strategy_t_int32_t(strategy)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl; + std::vector devicesAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getDevicesForRoleAndStrategy(strategyAidl, roleAidl, &devicesAidl))); devices = VALUE_OR_RETURN_STATUS( @@ -2182,9 +2184,9 @@ status_t AudioSystem::setDevicesRoleForCapturePreset(audio_source_t audioSource, AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus( aps->setDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl)); } @@ -2199,9 +2201,9 @@ status_t AudioSystem::addDevicesRoleForCapturePreset(audio_source_t audioSource, AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus( aps->addDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl)); } @@ -2215,9 +2217,9 @@ status_t AudioSystem::removeDevicesRoleForCapturePreset( AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return statusTFromBinderStatus( aps->removeDevicesRoleForCapturePreset(audioSourceAidl, roleAidl, devicesAidl)); } @@ -2245,7 +2247,7 @@ status_t AudioSystem::getDevicesForRoleAndCapturePreset(audio_source_t audioSour AudioSource audioSourceAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_source_t_AudioSource(audioSource)); media::DeviceRole roleAidl = VALUE_OR_RETURN_STATUS(legacy2aidl_device_role_t_DeviceRole(role)); - std::vector devicesAidl; + std::vector devicesAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->getDevicesForRoleAndCapturePreset(audioSourceAidl, roleAidl, &devicesAidl))); devices = VALUE_OR_RETURN_STATUS( @@ -2286,9 +2288,9 @@ status_t AudioSystem::canBeSpatialized(const audio_attributes_t *attr, legacy2aidl_audio_attributes_t_AudioAttributesInternal(attributes)); std::optional configAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_config_t_AudioConfig(configuration, false /*isInput*/)); - std::vector devicesAidl = VALUE_OR_RETURN_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + std::vector devicesAidl = VALUE_OR_RETURN_STATUS( + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( aps->canBeSpatialized(attrAidl, configAidl, devicesAidl, canBeSpatialized))); return OK; diff --git a/media/libaudioclient/aidl/android/media/AudioDevice.aidl b/media/libaudioclient/aidl/android/media/AudioDevice.aidl deleted file mode 100644 index a815874491..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioDevice.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioDeviceDescription; - -/** - * {@hide} - */ -parcelable AudioDevice { - AudioDeviceDescription type; - @utf8InCpp String address; -} diff --git a/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl b/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl deleted file mode 100644 index f7548b957f..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioDeviceDescription.aidl +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioDeviceType; - -parcelable AudioDeviceDescription { - /** - * Type and directionality of the device. For bidirectional audio devices - * two descriptions need to be created, having the same value for - * the 'connection' field. - * - * See 'AudioDeviceType' for the list of supported values. - */ - AudioDeviceType type = AudioDeviceType.NONE; - /** - * Specifies the type of the connection of the device to the audio system. - * Usually it's some kind of a communication protocol, e.g. Bluetooth SCO or - * USB. There is a list of connection types recognized by the framework, - * defined using 'CONNECTION_' constants. Vendors can add their own - * connection types with "vx.." prefix. - * - * When the 'connection' field is left empty and 'type != NONE | DEFAULT', - * it is assumed that the device is permanently attached to the audio - * system, e.g. a built-in speaker or microphone. - * - * The 'connection' field must be left empty if 'type' is 'NONE' or - * '{IN|OUT}_DEFAULT'. - */ - @utf8InCpp String connection; - /** - * Analog connection, for example, via 3.5 mm analog jack. - */ - const @utf8InCpp String CONNECTION_ANALOG = "analog"; - /** - * Low-End (Analog) Desk Dock. - */ - const @utf8InCpp String CONNECTION_ANALOG_DOCK = "analog-dock"; - /** - * Bluetooth A2DP connection. - */ - const @utf8InCpp String CONNECTION_BT_A2DP = "bt-a2dp"; - /** - * Bluetooth Low Energy (LE) connection. - */ - const @utf8InCpp String CONNECTION_BT_LE = "bt-le"; - /** - * Bluetooth SCO connection. - */ - const @utf8InCpp String CONNECTION_BT_SCO = "bt-sco"; - /** - * Bus connection. Mostly used in automotive scenarios. - */ - const @utf8InCpp String CONNECTION_BUS = "bus"; - /** - * High-End (Digital) Desk Dock. - */ - const @utf8InCpp String CONNECTION_DIGITAL_DOCK = "digital-dock"; - /** - * HDMI connection. - */ - const @utf8InCpp String CONNECTION_HDMI = "hdmi"; - /** - * HDMI ARC connection. - */ - const @utf8InCpp String CONNECTION_HDMI_ARC = "hdmi-arc"; - /** - * HDMI eARC connection. - */ - const @utf8InCpp String CONNECTION_HDMI_EARC = "hdmi-earc"; - /** - * IP v4 connection. - */ - const @utf8InCpp String CONNECTION_IP_V4 = "ip-v4"; - /** - * SPDIF connection. - */ - const @utf8InCpp String CONNECTION_SPDIF = "spdif"; - /** - * A wireless connection when the actual protocol is unspecified. - */ - const @utf8InCpp String CONNECTION_WIRELESS = "wireless"; - /** - * USB connection. - */ - const @utf8InCpp String CONNECTION_USB = "usb"; -} diff --git a/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl b/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl deleted file mode 100644 index 4da9fd66c3..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioDeviceType.aidl +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * The type of the audio device. Only used as part of 'AudioDeviceDescription' - * structure. - * - * Types are divided into "input" and "output" categories. Audio devices that - * have both audio input and output, for example, headsets, are represented by a - * pair of input and output device types. - * - * The 'AudioDeviceType' intentionally binds together directionality and 'kind' - * of the device to avoid making them fully orthogonal. This is because not all - * types of devices are bidirectional, for example, speakers can only be used - * for output and microphones can only be used for input (at least, in the - * context of the audio framework). - */ -@Backing(type="int") -enum AudioDeviceType { - /** - * "None" type is a "null" value. All fields of 'AudioDeviceDescription' - * must have default / empty / null values. - */ - NONE = 0, - /** - * The "default" device is used when the client does not have any - * preference for a particular device. - */ - IN_DEFAULT = 1, - /** - * A device implementing Android Open Accessory protocol. - */ - IN_ACCESSORY = 2, - /** - * Input from a DSP front-end proxy device. - */ - IN_AFE_PROXY = 3, - /** - * Used when only the connection protocol is known, e.g. a "HDMI Device." - */ - IN_DEVICE = 4, - /** - * A device providing reference input for echo canceller. - */ - IN_ECHO_REFERENCE = 5, - /** - * FM Tuner input. - */ - IN_FM_TUNER = 6, - /** - * A microphone of a headset. - */ - IN_HEADSET = 7, - /** - * Loopback input. - */ - IN_LOOPBACK = 8, - /** - * The main microphone (the frontal mic on mobile devices). - */ - IN_MICROPHONE = 9, - /** - * The secondary microphone (the back mic on mobile devices). - */ - IN_MICROPHONE_BACK = 10, - /** - * Input from a submix of other streams. - */ - IN_SUBMIX = 11, - /** - * Audio received via the telephone line. - */ - IN_TELEPHONY_RX = 12, - /** - * TV Tuner audio input. - */ - IN_TV_TUNER = 13, - /** - * The "default" device is used when the client does not have any - * preference for a particular device. - */ - OUT_DEFAULT = 129, - /** - * A device implementing Android Open Accessory protocol. - */ - OUT_ACCESSORY = 130, - /** - * Output from a DSP front-end proxy device. - */ - OUT_AFE_PROXY = 131, - /** - * Car audio system. - */ - OUT_CARKIT = 132, - /** - * Used when only the connection protocol is known, e.g. a "HDMI Device." - */ - OUT_DEVICE = 133, - /** - * The echo canceller device. - */ - OUT_ECHO_CANCELLER = 134, - /** - * The FM Tuner device. - */ - OUT_FM = 135, - /** - * Headphones. - */ - OUT_HEADPHONE = 136, - /** - * Headphones of a headset. - */ - OUT_HEADSET = 137, - /** - * Hearing aid. - */ - OUT_HEARING_AID = 138, - /** - * Secondary line level output. - */ - OUT_LINE_AUX = 139, - /** - * The main speaker. - */ - OUT_SPEAKER = 140, - /** - * The speaker of a mobile device in the case when it is close to the ear. - */ - OUT_SPEAKER_EARPIECE = 141, - /** - * The main speaker with overload / overheating protection. - */ - OUT_SPEAKER_SAFE = 142, - /** - * Output into a submix. - */ - OUT_SUBMIX = 143, - /** - * Output into a telephone line. - */ - OUT_TELEPHONY_TX = 144, -} diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl index ad7bd45312..3e1f9cb25e 100644 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl +++ b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl @@ -15,8 +15,8 @@ */ package android.media; -import android.media.AudioDevice; import android.media.AudioMMapPolicy; +import android.media.audio.common.AudioDevice; /** * Audio MMAP policy info describes how an aaudio MMAP feature can be @@ -26,4 +26,4 @@ import android.media.AudioMMapPolicy; parcelable AudioMMapPolicyInfo { AudioDevice device; AudioMMapPolicy mmapPolicy = AudioMMapPolicy.UNSPECIFIED; -} \ No newline at end of file +} diff --git a/media/libaudioclient/aidl/android/media/AudioMix.aidl b/media/libaudioclient/aidl/android/media/AudioMix.aidl index 6a8980f43f..88b04501a9 100644 --- a/media/libaudioclient/aidl/android/media/AudioMix.aidl +++ b/media/libaudioclient/aidl/android/media/AudioMix.aidl @@ -16,12 +16,12 @@ package android.media; -import android.media.AudioDevice; import android.media.AudioMixCallbackFlag; import android.media.AudioMixMatchCriterion; import android.media.AudioMixRouteFlag; import android.media.AudioMixType; import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioDevice; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl index 31e5330d9f..82e1baef1b 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioDeviceDescription; +import android.media.audio.common.AudioDeviceDescription; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl index b758f23cd3..c28d688e81 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioDevice; +import android.media.audio.common.AudioDevice; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl b/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl index 35a56eba26..bcca04aa6c 100644 --- a/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl +++ b/media/libaudioclient/aidl/android/media/CreateEffectRequest.aidl @@ -16,10 +16,10 @@ package android.media; -import android.media.AudioDevice; +import android.content.AttributionSourceState; import android.media.EffectDescriptor; import android.media.IEffectClient; -import android.content.AttributionSourceState; +import android.media.audio.common.AudioDevice; /** * Input arguments of the createEffect() method. diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 528a432ba7..282bce1b0c 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -20,8 +20,6 @@ import android.content.AttributionSourceState; import android.media.AudioAttributesEx; import android.media.AudioAttributesInternal; -import android.media.AudioDevice; -import android.media.AudioDeviceDescription; import android.media.AudioMix; import android.media.AudioOffloadMode; import android.media.AudioPatch; @@ -46,6 +44,8 @@ import android.media.Int; import android.media.SoundTriggerSession; import android.media.audio.common.AudioConfig; import android.media.audio.common.AudioConfigBase; +import android.media.audio.common.AudioDevice; +import android.media.audio.common.AudioDeviceDescription; import android.media.audio.common.AudioFormatDescription; import android.media.audio.common.AudioMode; import android.media.audio.common.AudioOffloadInfo; diff --git a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl index fe3c2f9f8f..75ff8e926c 100644 --- a/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl +++ b/media/libaudioclient/aidl/android/media/OpenInputRequest.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioDevice; import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioDevice; import android.media.audio.common.AudioSource; /** diff --git a/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl b/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl index b4de4048de..41bc38a147 100644 --- a/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl +++ b/media/libaudioclient/aidl/android/media/OpenInputResponse.aidl @@ -16,8 +16,8 @@ package android.media; -import android.media.AudioDevice; import android.media.audio.common.AudioConfig; +import android.media.audio.common.AudioDevice; /** * {@hide} diff --git a/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl b/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl index b9708b2c97..4b540a9124 100644 --- a/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl +++ b/media/libaudioclient/aidl/android/media/SoundTriggerSession.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.AudioDeviceDescription; +import android.media.audio.common.AudioDeviceDescription; /** * {@hide} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 0671dd709d..d4069d4626 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -23,7 +23,6 @@ #include #include -#include #include #include #include @@ -50,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -137,14 +137,14 @@ ConversionResult legacy2aidl_audio_port_type_t_AudioPortTy audio_port_type_t legacy); ConversionResult aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - const android::media::audio::common::AudioChannelLayout& aidl, bool isInput); -ConversionResult + const media::audio::common::AudioChannelLayout& aidl, bool isInput); +ConversionResult legacy2aidl_audio_channel_mask_t_AudioChannelLayout(audio_channel_mask_t legacy, bool isInput); ConversionResult aidl2legacy_AudioDeviceDescription_audio_devices_t( - const media::AudioDeviceDescription& aidl); -ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription( - audio_devices_t legacy); + const media::audio::common::AudioDeviceDescription& aidl); +ConversionResult +legacy2aidl_audio_devices_t_AudioDeviceDescription(audio_devices_t legacy); ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( const media::audio::common::AudioFormatDescription& aidl); diff --git a/media/libaudioclient/include/media/AudioCommonTypes.h b/media/libaudioclient/include/media/AudioCommonTypes.h index b63f3897ae..862a0f9ca3 100644 --- a/media/libaudioclient/include/media/AudioCommonTypes.h +++ b/media/libaudioclient/include/media/AudioCommonTypes.h @@ -19,8 +19,8 @@ #include -#include #include +#include #include #include #include @@ -64,11 +64,12 @@ template<> struct hash } }; -template<> struct hash +template<> struct hash { - std::size_t operator()(const android::media::AudioDeviceDescription& add) const noexcept { + std::size_t operator()( + const android::media::audio::common::AudioDeviceDescription& add) const noexcept { return hash_combine( - std::hash{}(add.type), + std::hash{}(add.type), std::hash{}(add.connection)); } }; diff --git a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp index 253ccac26a..f963e68016 100644 --- a/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp +++ b/media/libaudioclient/tests/audio_aidl_legacy_conversion_tests.cpp @@ -23,6 +23,8 @@ using namespace android; using namespace android::aidl_utils; using media::audio::common::AudioChannelLayout; +using media::audio::common::AudioDeviceDescription; +using media::audio::common::AudioDeviceType; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioFormatType; using media::audio::common::PcmType; @@ -61,34 +63,34 @@ AudioChannelLayout make_ACL_VoiceCall() { AudioChannelLayout::VOICE_CALL_MONO); } -media::AudioDeviceDescription make_AudioDeviceDescription(media::AudioDeviceType type, +AudioDeviceDescription make_AudioDeviceDescription(AudioDeviceType type, const std::string& connection = "") { - media::AudioDeviceDescription result; + AudioDeviceDescription result; result.type = type; result.connection = connection; return result; } -media::AudioDeviceDescription make_ADD_None() { - return media::AudioDeviceDescription{}; +AudioDeviceDescription make_ADD_None() { + return AudioDeviceDescription{}; } -media::AudioDeviceDescription make_ADD_DefaultIn() { - return make_AudioDeviceDescription(media::AudioDeviceType::IN_DEFAULT); +AudioDeviceDescription make_ADD_DefaultIn() { + return make_AudioDeviceDescription(AudioDeviceType::IN_DEFAULT); } -media::AudioDeviceDescription make_ADD_DefaultOut() { - return make_AudioDeviceDescription(media::AudioDeviceType::OUT_DEFAULT); +AudioDeviceDescription make_ADD_DefaultOut() { + return make_AudioDeviceDescription(AudioDeviceType::OUT_DEFAULT); } -media::AudioDeviceDescription make_ADD_WiredHeadset() { - return make_AudioDeviceDescription(media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_ANALOG()); +AudioDeviceDescription make_ADD_WiredHeadset() { + return make_AudioDeviceDescription(AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_ANALOG()); } -media::AudioDeviceDescription make_ADD_BtScoHeadset() { - return make_AudioDeviceDescription(media::AudioDeviceType::OUT_HEADSET, - media::AudioDeviceDescription::CONNECTION_BT_SCO()); +AudioDeviceDescription make_ADD_BtScoHeadset() { + return make_AudioDeviceDescription(AudioDeviceType::OUT_HEADSET, + AudioDeviceDescription::CONNECTION_BT_SCO()); } AudioFormatDescription make_AudioFormatDescription(AudioFormatType type) { @@ -171,7 +173,7 @@ TEST_F(HashIdentityTest, AudioChannelLayoutHashIdentity) { } TEST_F(HashIdentityTest, AudioDeviceDescriptionHashIdentity) { - verifyHashIdentity({ + verifyHashIdentity({ make_ADD_None, make_ADD_DefaultIn, make_ADD_DefaultOut, make_ADD_WiredHeadset, make_ADD_BtScoHeadset}); } @@ -206,7 +208,7 @@ INSTANTIATE_TEST_SUITE_P(AudioChannelVoiceRoundTrip, testing::Combine(testing::Values(make_ACL_VoiceCall()), testing::Values(true))); class AudioDeviceDescriptionRoundTripTest : - public testing::TestWithParam {}; + public testing::TestWithParam {}; TEST_P(AudioDeviceDescriptionRoundTripTest, Aidl2Legacy2Aidl) { const auto initial = GetParam(); auto conv = aidl2legacy_AudioDeviceDescription_audio_devices_t(initial); @@ -217,7 +219,7 @@ TEST_P(AudioDeviceDescriptionRoundTripTest, Aidl2Legacy2Aidl) { } INSTANTIATE_TEST_SUITE_P(AudioDeviceDescriptionRoundTrip, AudioDeviceDescriptionRoundTripTest, - testing::Values(media::AudioDeviceDescription{}, make_ADD_DefaultIn(), + testing::Values(AudioDeviceDescription{}, make_ADD_DefaultIn(), make_ADD_DefaultOut(), make_ADD_WiredHeadset(), make_ADD_BtScoHeadset())); class AudioFormatDescriptionRoundTripTest : diff --git a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp index 7f54474ea2..2c087d98d7 100644 --- a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp +++ b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp @@ -25,6 +25,8 @@ namespace android { +using media::audio::common::AudioDevice; + namespace { static const std::string SUPPRESSED = "SUPPRESSED"; @@ -157,16 +159,17 @@ std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& devic } ConversionResult -aidl2legacy_AudioDeviceTypeAddress(const media::AudioDevice& aidl) { +aidl2legacy_AudioDeviceTypeAddress(const AudioDevice& aidl) { audio_devices_t type = VALUE_OR_RETURN( aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); return AudioDeviceTypeAddr(type, aidl.address); } -ConversionResult +ConversionResult legacy2aidl_AudioDeviceTypeAddress(const AudioDeviceTypeAddr& legacy) { - media::AudioDevice aidl; - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mType)); + AudioDevice aidl; + aidl.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mType)); aidl.address = legacy.getAddress(); return aidl; } diff --git a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h index 8edcc58ca5..6660f3b1bd 100644 --- a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h +++ b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include #include @@ -88,8 +88,8 @@ std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& devic // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioDeviceTypeAddress(const media::AudioDevice& aidl); -ConversionResult +aidl2legacy_AudioDeviceTypeAddress(const media::audio::common::AudioDevice& aidl); +ConversionResult legacy2aidl_AudioDeviceTypeAddress(const AudioDeviceTypeAddr& legacy); } // namespace android diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index fa47c9e8b8..55917bc407 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -46,6 +46,8 @@ using aidl_utils::binderStatusFromStatusT; using content::AttributionSourceState; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; +using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; @@ -105,7 +107,7 @@ void AudioPolicyService::doOnNewAudioModulesAvailable() } Status AudioPolicyService::setDeviceConnectionState( - const media::AudioDevice& deviceAidl, + const AudioDevice& deviceAidl, media::AudioPolicyDeviceState stateAidl, const std::string& deviceNameAidl, const AudioFormatDescription& encodedFormatAidl) { @@ -140,7 +142,7 @@ Status AudioPolicyService::setDeviceConnectionState( return binderStatusFromStatusT(status); } -Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& deviceAidl, +Status AudioPolicyService::getDeviceConnectionState(const AudioDevice& deviceAidl, media::AudioPolicyDeviceState* _aidl_return) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); @@ -159,7 +161,7 @@ Status AudioPolicyService::getDeviceConnectionState(const media::AudioDevice& de } Status AudioPolicyService::handleDeviceConfigChange( - const media::AudioDevice& deviceAidl, + const AudioDevice& deviceAidl, const std::string& deviceNameAidl, const AudioFormatDescription& encodedFormatAidl) { audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( @@ -942,7 +944,7 @@ Status AudioPolicyService::initStreamVolume(AudioStreamType streamAidl, } Status AudioPolicyService::setStreamVolumeIndex(AudioStreamType streamAidl, - const media::AudioDeviceDescription& deviceAidl, + const AudioDeviceDescription& deviceAidl, int32_t indexAidl) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -967,7 +969,7 @@ Status AudioPolicyService::setStreamVolumeIndex(AudioStreamType streamAidl, } Status AudioPolicyService::getStreamVolumeIndex(AudioStreamType streamAidl, - const media::AudioDeviceDescription& deviceAidl, + const AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); @@ -991,7 +993,7 @@ Status AudioPolicyService::getStreamVolumeIndex(AudioStreamType streamAidl, Status AudioPolicyService::setVolumeIndexForAttributes( const media::AudioAttributesInternal& attrAidl, - const media::AudioDeviceDescription& deviceAidl, int32_t indexAidl) { + const AudioDeviceDescription& deviceAidl, int32_t indexAidl) { audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attrAidl)); int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(indexAidl)); @@ -1014,7 +1016,7 @@ Status AudioPolicyService::setVolumeIndexForAttributes( Status AudioPolicyService::getVolumeIndexForAttributes( const media::AudioAttributesInternal& attrAidl, - const media::AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) { + const AudioDeviceDescription& deviceAidl, int32_t* _aidl_return) { audio_attributes_t attributes = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesInternal_audio_attributes_t(attrAidl)); audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( @@ -1098,12 +1100,12 @@ Status AudioPolicyService::getStrategyForStream(AudioStreamType streamAidl, Status AudioPolicyService::getDevicesForStream( AudioStreamType streamAidl, - std::vector* _aidl_return) { + std::vector* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); if (uint32_t(stream) >= AUDIO_STREAM_PUBLIC_CNT) { - *_aidl_return = std::vector{}; + *_aidl_return = std::vector{}; return Status::ok(); } if (mAudioPolicyManager == NULL) { @@ -1112,14 +1114,14 @@ Status AudioPolicyService::getDevicesForStream( Mutex::Autolock _l(mLock); AutoCallerClear acc; *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>( + convertContainer>( mAudioPolicyManager->getDevicesForStream(stream), legacy2aidl_audio_devices_t_AudioDeviceDescription)); return Status::ok(); } Status AudioPolicyService::getDevicesForAttributes(const media::AudioAttributesEx& attrAidl, - std::vector* _aidl_return) + std::vector* _aidl_return) { AudioAttributes aa = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioAttributesEx_AudioAttributes(attrAidl)); @@ -1133,8 +1135,8 @@ Status AudioPolicyService::getDevicesForAttributes(const media::AudioAttributesE RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getDevicesForAttributes(aa.getAttributes(), &devices))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return Status::ok(); } @@ -1695,7 +1697,7 @@ Status AudioPolicyService::registerPolicyMixes(const std::vector& devicesAidl) { + const std::vector& devicesAidl) { uid_t uid = VALUE_OR_RETURN_BINDER_STATUS(aidl2legacy_int32_t_uid_t(uidAidl)); AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( convertContainer(devicesAidl, @@ -1728,7 +1730,7 @@ Status AudioPolicyService::removeUidDeviceAffinities(int32_t uidAidl) { Status AudioPolicyService::setUserIdDeviceAffinities( int32_t userIdAidl, - const std::vector& devicesAidl) { + const std::vector& devicesAidl) { int userId = VALUE_OR_RETURN_BINDER_STATUS(convertReinterpret(userIdAidl)); AudioDeviceTypeAddrVector devices = VALUE_OR_RETURN_BINDER_STATUS( convertContainer(devicesAidl, @@ -1827,7 +1829,7 @@ Status AudioPolicyService::getMasterMono(bool* _aidl_return) Status AudioPolicyService::getStreamVolumeDB( AudioStreamType streamAidl, int32_t indexAidl, - const media::AudioDeviceDescription& deviceAidl, float* _aidl_return) { + const AudioDeviceDescription& deviceAidl, float* _aidl_return) { audio_stream_type_t stream = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioStreamType_audio_stream_type_t(streamAidl)); int index = VALUE_OR_RETURN_BINDER_STATUS(convertIntegral(indexAidl)); @@ -2075,7 +2077,7 @@ Status AudioPolicyService::isCallScreenModeSupported(bool* _aidl_return) Status AudioPolicyService::setDevicesRoleForStrategy( int32_t strategyAidl, media::DeviceRole roleAidl, - const std::vector& devicesAidl) { + const std::vector& devicesAidl) { product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_product_strategy_t(strategyAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2115,7 +2117,7 @@ Status AudioPolicyService::removeDevicesRoleForStrategy(int32_t strategyAidl, Status AudioPolicyService::getDevicesForRoleAndStrategy( int32_t strategyAidl, media::DeviceRole roleAidl, - std::vector* _aidl_return) { + std::vector* _aidl_return) { product_strategy_t strategy = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_product_strategy_t(strategyAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2129,8 +2131,8 @@ Status AudioPolicyService::getDevicesForRoleAndStrategy( RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getDevicesForRoleAndStrategy(strategy, role, devices))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return Status::ok(); } @@ -2143,7 +2145,7 @@ Status AudioPolicyService::registerSoundTriggerCaptureStateListener( Status AudioPolicyService::setDevicesRoleForCapturePreset( AudioSource audioSourceAidl, media::DeviceRole roleAidl, - const std::vector& devicesAidl) { + const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2163,7 +2165,7 @@ Status AudioPolicyService::setDevicesRoleForCapturePreset( Status AudioPolicyService::addDevicesRoleForCapturePreset( AudioSource audioSourceAidl, media::DeviceRole roleAidl, - const std::vector& devicesAidl) { + const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2183,7 +2185,7 @@ Status AudioPolicyService::addDevicesRoleForCapturePreset( Status AudioPolicyService::removeDevicesRoleForCapturePreset( AudioSource audioSourceAidl, media::DeviceRole roleAidl, - const std::vector& devicesAidl) { + const std::vector& devicesAidl) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2218,7 +2220,7 @@ Status AudioPolicyService::clearDevicesRoleForCapturePreset(AudioSource audioSou Status AudioPolicyService::getDevicesForRoleAndCapturePreset( AudioSource audioSourceAidl, media::DeviceRole roleAidl, - std::vector* _aidl_return) { + std::vector* _aidl_return) { audio_source_t audioSource = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioSource_audio_source_t(audioSourceAidl)); device_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -2232,8 +2234,8 @@ Status AudioPolicyService::getDevicesForRoleAndCapturePreset( RETURN_IF_BINDER_ERROR(binderStatusFromStatusT( mAudioPolicyManager->getDevicesForRoleAndCapturePreset(audioSource, role, devices))); *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( - convertContainer>(devices, - legacy2aidl_AudioDeviceTypeAddress)); + convertContainer>(devices, + legacy2aidl_AudioDeviceTypeAddress)); return Status::ok(); } @@ -2255,7 +2257,7 @@ Status AudioPolicyService::getSpatializer( Status AudioPolicyService::canBeSpatialized( const std::optional& attrAidl, const std::optional& configAidl, - const std::vector& devicesAidl, + const std::vector& devicesAidl, bool* _aidl_return) { if (mAudioPolicyManager == nullptr) { return binderStatusFromStatusT(NO_INIT); diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index ed766b0936..92e1bb9696 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -51,6 +51,8 @@ namespace android { using content::AttributionSourceState; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; +using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioMode; using media::audio::common::AudioSource; @@ -79,14 +81,14 @@ public: // binder::Status onNewAudioModulesAvailable() override; binder::Status setDeviceConnectionState( - const media::AudioDevice& device, + const AudioDevice& device, media::AudioPolicyDeviceState state, const std::string& deviceName, const AudioFormatDescription& encodedFormat) override; - binder::Status getDeviceConnectionState(const media::AudioDevice& device, + binder::Status getDeviceConnectionState(const AudioDevice& device, media::AudioPolicyDeviceState* _aidl_return) override; binder::Status handleDeviceConfigChange( - const media::AudioDevice& device, + const AudioDevice& device, const std::string& deviceName, const AudioFormatDescription& encodedFormat) override; binder::Status setPhoneState(AudioMode state, int32_t uid) override; @@ -115,16 +117,16 @@ public: binder::Status initStreamVolume(AudioStreamType stream, int32_t indexMin, int32_t indexMax) override; binder::Status setStreamVolumeIndex(AudioStreamType stream, - const media::AudioDeviceDescription& device, + const AudioDeviceDescription& device, int32_t index) override; binder::Status getStreamVolumeIndex(AudioStreamType stream, - const media::AudioDeviceDescription& device, + const AudioDeviceDescription& device, int32_t* _aidl_return) override; binder::Status setVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, - const media::AudioDeviceDescription& device, + const AudioDeviceDescription& device, int32_t index) override; binder::Status getVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, - const media::AudioDeviceDescription& device, + const AudioDeviceDescription& device, int32_t* _aidl_return) override; binder::Status getMaxVolumeIndexForAttributes(const media::AudioAttributesInternal& attr, int32_t* _aidl_return) override; @@ -134,9 +136,9 @@ public: int32_t* _aidl_return) override; binder::Status getDevicesForStream( AudioStreamType stream, - std::vector* _aidl_return) override; + std::vector* _aidl_return) override; binder::Status getDevicesForAttributes(const media::AudioAttributesEx& attr, - std::vector* _aidl_return) override; + std::vector* _aidl_return) override; binder::Status getOutputForEffect(const media::EffectDescriptor& desc, int32_t* _aidl_return) override; binder::Status registerEffect(const media::EffectDescriptor& desc, int32_t io, int32_t strategy, @@ -191,11 +193,11 @@ public: binder::Status registerPolicyMixes(const std::vector& mixes, bool registration) override; binder::Status setUidDeviceAffinities(int32_t uid, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status removeUidDeviceAffinities(int32_t uid) override; binder::Status setUserIdDeviceAffinities( int32_t userId, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status removeUserIdDeviceAffinities(int32_t userId) override; binder::Status startAudioSource(const media::AudioPortConfig& source, const media::AudioAttributesInternal& attributes, @@ -204,7 +206,7 @@ public: binder::Status setMasterMono(bool mono) override; binder::Status getMasterMono(bool* _aidl_return) override; binder::Status getStreamVolumeDB(AudioStreamType stream, int32_t index, - const media::AudioDeviceDescription& device, + const AudioDeviceDescription& device, float* _aidl_return) override; binder::Status getSurroundFormats(media::Int* count, std::vector* formats, @@ -234,29 +236,29 @@ public: binder::Status isCallScreenModeSupported(bool* _aidl_return) override; binder::Status setDevicesRoleForStrategy( int32_t strategy, media::DeviceRole role, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status removeDevicesRoleForStrategy(int32_t strategy, media::DeviceRole role) override; binder::Status getDevicesForRoleAndStrategy( int32_t strategy, media::DeviceRole role, - std::vector* _aidl_return) override; + std::vector* _aidl_return) override; binder::Status setDevicesRoleForCapturePreset( AudioSource audioSource, media::DeviceRole role, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status addDevicesRoleForCapturePreset( AudioSource audioSource, media::DeviceRole role, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status removeDevicesRoleForCapturePreset( AudioSource audioSource, media::DeviceRole role, - const std::vector& devices) override; + const std::vector& devices) override; binder::Status clearDevicesRoleForCapturePreset(AudioSource audioSource, media::DeviceRole role) override; binder::Status getDevicesForRoleAndCapturePreset( AudioSource audioSource, media::DeviceRole role, - std::vector* _aidl_return) override; + std::vector* _aidl_return) override; binder::Status registerSoundTriggerCaptureStateListener( const sp& listener, bool* _aidl_return) override; @@ -265,7 +267,7 @@ public: binder::Status canBeSpatialized( const std::optional& attr, const std::optional& config, - const std::vector& devices, + const std::vector& devices, bool* _aidl_return) override; status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override; -- GitLab From 932cb9627ebc3a2c1438655d94f2a5065969faa1 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 16 Sep 2021 01:05:27 +0000 Subject: [PATCH 138/694] Use android.media.audio.common.AudioDeviceAddress Make sure that pairs of 'AudioDeviceDescription' (aka type) and the device address are always represented in AIDL as AudioDevice. Move all the AIDL<->legacy conversions into AidlConversion so it is possible to switch to structured device address representations in a subsequent CL. Bug: 198812639 Test: m Change-Id: If4300e411d76c90d42939f07298535ebdb4185f4 --- media/libaudioclient/AidlConversion.cpp | 75 +++++++++++++++---- media/libaudioclient/AudioSystem.cpp | 19 ++--- media/libaudioclient/PolicyAidlConversion.cpp | 12 +-- .../media/AudioPortConfigDeviceExt.aidl | 8 +- .../include/media/AidlConversion.h | 16 ++++ .../AudioDeviceTypeAddr.cpp | 14 ++-- .../include/media/AudioDeviceTypeAddr.h | 1 + .../service/AudioPolicyInterfaceImpl.cpp | 34 +++++---- 8 files changed, 122 insertions(+), 57 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index b0426fa780..9928b7df81 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -38,6 +38,8 @@ using media::audio::common::AudioChannelLayout; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioContentType; +using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceAddress; using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioDeviceType; using media::audio::common::AudioEncapsulationMetadataType; @@ -1161,6 +1163,58 @@ ConversionResult legacy2aidl_audio_devices_t_AudioDevice } } +status_t aidl2legacy_AudioDevice_audio_device( + const AudioDevice& aidl, + audio_devices_t* legacyType, char* legacyAddress) { + *legacyType = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); + return aidl2legacy_string( + aidl.address.get(), + legacyAddress, AUDIO_DEVICE_MAX_ADDRESS_LEN); +} + +status_t aidl2legacy_AudioDevice_audio_device( + const AudioDevice& aidl, + audio_devices_t* legacyType, String8* legacyAddress) { + *legacyType = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); + *legacyAddress = VALUE_OR_RETURN_STATUS(aidl2legacy_string_view_String8( + aidl.address.get())); + return OK; +} + +status_t aidl2legacy_AudioDevice_audio_device( + const AudioDevice& aidl, + audio_devices_t* legacyType, std::string* legacyAddress) { + *legacyType = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); + *legacyAddress = aidl.address.get(); + return OK; +} + +ConversionResult legacy2aidl_audio_device_AudioDevice( + audio_devices_t legacyType, const char* legacyAddress) { + AudioDevice aidl; + aidl.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(legacyType)); + const std::string aidl_id = VALUE_OR_RETURN( + legacy2aidl_string(legacyAddress, AUDIO_DEVICE_MAX_ADDRESS_LEN)); + aidl.address = AudioDeviceAddress::make(aidl_id); + return aidl; +} + +ConversionResult +legacy2aidl_audio_device_AudioDevice( + audio_devices_t legacyType, const String8& legacyAddress) { + AudioDevice aidl; + aidl.type = VALUE_OR_RETURN( + legacy2aidl_audio_devices_t_AudioDeviceDescription(legacyType)); + const std::string aidl_id = VALUE_OR_RETURN( + legacy2aidl_String8_string(legacyAddress)); + aidl.address = AudioDeviceAddress::make(aidl_id); + return aidl; +} + ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( const AudioFormatDescription& aidl) { static const std::unordered_map m = @@ -1491,8 +1545,8 @@ aidl2legacy_AudioPortConfigDeviceExt_audio_port_config_device_ext( const media::AudioPortConfigDeviceExt& aidl) { audio_port_config_device_ext legacy; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); - RETURN_IF_ERROR(aidl2legacy_string(aidl.address, legacy.address, AUDIO_DEVICE_MAX_ADDRESS_LEN)); + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device( + aidl.device, &legacy.type, legacy.address)); return legacy; } @@ -1501,9 +1555,8 @@ legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( const audio_port_config_device_ext& legacy) { media::AudioPortConfigDeviceExt aidl; aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.type)); - aidl.address = VALUE_OR_RETURN( - legacy2aidl_string(legacy.address, AUDIO_DEVICE_MAX_ADDRESS_LEN)); + aidl.device = VALUE_OR_RETURN(legacy2aidl_audio_device_AudioDevice( + legacy.type, legacy.address)); return aidl; } @@ -2578,10 +2631,8 @@ ConversionResult aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl) { audio_port_device_ext legacy; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - legacy.type = VALUE_OR_RETURN( - aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.device.type)); - RETURN_IF_ERROR( - aidl2legacy_string(aidl.device.address, legacy.address, sizeof(legacy.address))); + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device( + aidl.device, &legacy.type, legacy.address)); legacy.encapsulation_modes = VALUE_OR_RETURN( aidl2legacy_AudioEncapsulationMode_mask(aidl.encapsulationModes)); legacy.encapsulation_metadata_types = VALUE_OR_RETURN( @@ -2593,10 +2644,8 @@ ConversionResult legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(const audio_port_device_ext& legacy) { media::AudioPortDeviceExt aidl; aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.device.type = VALUE_OR_RETURN( - legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.type)); - aidl.device.address = VALUE_OR_RETURN( - legacy2aidl_string(legacy.address, sizeof(legacy.address))); + aidl.device = VALUE_OR_RETURN(legacy2aidl_audio_device_AudioDevice( + legacy.type, legacy.address)); aidl.encapsulationModes = VALUE_OR_RETURN( legacy2aidl_AudioEncapsulationMode_mask(legacy.encapsulation_modes)); aidl.encapsulationMetadataTypes = VALUE_OR_RETURN( diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index afc65d74ff..2557482d3c 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -56,6 +56,7 @@ using media::IAudioPolicyService; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceAddress; using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioOffloadInfo; @@ -855,10 +856,8 @@ status_t AudioSystem::setDeviceConnectionState(audio_devices_t device, name = device_name; } - AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); - deviceAidl.address = address; + AudioDevice deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_device_AudioDevice(device, address)); return statusTFromBinderStatus( aps->setDeviceConnectionState( @@ -876,10 +875,8 @@ audio_policy_dev_state_t AudioSystem::getDeviceConnectionState(audio_devices_t d if (aps == 0) return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE; auto result = [&]() -> ConversionResult { - AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN( - legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); - deviceAidl.address = device_address; + AudioDevice deviceAidl = VALUE_OR_RETURN( + legacy2aidl_audio_device_AudioDevice(device, device_address)); media::AudioPolicyDeviceState result; RETURN_IF_ERROR(statusTFromBinderStatus( @@ -907,10 +904,8 @@ status_t AudioSystem::handleDeviceConfigChange(audio_devices_t device, name = device_name; } - AudioDevice deviceAidl; - deviceAidl.type = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_devices_t_AudioDeviceDescription(device)); - deviceAidl.address = address; + AudioDevice deviceAidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_device_AudioDevice(device, address)); return statusTFromBinderStatus( aps->handleDeviceConfigChange(deviceAidl, name, VALUE_OR_RETURN_STATUS( diff --git a/media/libaudioclient/PolicyAidlConversion.cpp b/media/libaudioclient/PolicyAidlConversion.cpp index c3b7ce7cdb..fd945686e2 100644 --- a/media/libaudioclient/PolicyAidlConversion.cpp +++ b/media/libaudioclient/PolicyAidlConversion.cpp @@ -25,6 +25,7 @@ namespace android { using base::unexpected; +using media::audio::common::AudioDeviceAddress; ConversionResult aidl2legacy_int32_t_volume_group_t(int32_t aidl) { @@ -238,9 +239,8 @@ aidl2legacy_AudioMix(const media::AudioMix& aidl) { aidl.format, false /*isInput*/)); legacy.mRouteFlags = VALUE_OR_RETURN( aidl2legacy_AudioMixRouteFlag_uint32_t_mask(aidl.routeFlags)); - legacy.mDeviceType = VALUE_OR_RETURN( - aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.device.type)); - legacy.mDeviceAddress = VALUE_OR_RETURN(aidl2legacy_string_view_String8(aidl.device.address)); + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device( + aidl.device, &legacy.mDeviceType, &legacy.mDeviceAddress)); legacy.mCbFlags = VALUE_OR_RETURN(aidl2legacy_AudioMixCallbackFlag_uint32_t_mask(aidl.cbFlags)); legacy.mAllowPrivilegedMediaPlaybackCapture = aidl.allowPrivilegedMediaPlaybackCapture; legacy.mVoiceCommunicationCaptureAllowed = aidl.voiceCommunicationCaptureAllowed; @@ -261,9 +261,9 @@ legacy2aidl_AudioMix(const AudioMix& legacy) { legacy.mFormat, false /*isInput*/)); aidl.routeFlags = VALUE_OR_RETURN( legacy2aidl_uint32_t_AudioMixRouteFlag_mask(legacy.mRouteFlags)); - aidl.device.type = VALUE_OR_RETURN( - legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mDeviceType)); - aidl.device.address = VALUE_OR_RETURN(legacy2aidl_String8_string(legacy.mDeviceAddress)); + aidl.device = VALUE_OR_RETURN( + legacy2aidl_audio_device_AudioDevice( + legacy.mDeviceType, legacy.mDeviceAddress)); aidl.cbFlags = VALUE_OR_RETURN(legacy2aidl_uint32_t_AudioMixCallbackFlag_mask(legacy.mCbFlags)); aidl.allowPrivilegedMediaPlaybackCapture = legacy.mAllowPrivilegedMediaPlaybackCapture; aidl.voiceCommunicationCaptureAllowed = legacy.mVoiceCommunicationCaptureAllowed; diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl index 82e1baef1b..640a63b545 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl @@ -16,7 +16,7 @@ package android.media; -import android.media.audio.common.AudioDeviceDescription; +import android.media.audio.common.AudioDevice; /** * {@hide} @@ -28,9 +28,7 @@ parcelable AudioPortConfigDeviceExt { */ int hwModule; /** - * Device type. + * Audio device instance. */ - AudioDeviceDescription type; - /** Device address. "" if N/A. */ - @utf8InCpp String address; + AudioDevice device; } diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index d4069d4626..3bdd11c1d6 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -146,6 +146,22 @@ ConversionResult aidl2legacy_AudioDeviceDescription_audio_devic ConversionResult legacy2aidl_audio_devices_t_AudioDeviceDescription(audio_devices_t legacy); +status_t aidl2legacy_AudioDevice_audio_device( + const media::audio::common::AudioDevice& aidl, + audio_devices_t* legacyType, char* legacyAddress); +status_t aidl2legacy_AudioDevice_audio_device( + const media::audio::common::AudioDevice& aidl, + audio_devices_t* legacyType, String8* legacyAddress); +status_t aidl2legacy_AudioDevice_audio_device( + const media::audio::common::AudioDevice& aidl, + audio_devices_t* legacyType, std::string* legacyAddress); +ConversionResult +legacy2aidl_audio_device_AudioDevice( + audio_devices_t legacyType, const char* legacyAddress); +ConversionResult +legacy2aidl_audio_device_AudioDevice( + audio_devices_t legacyType, const String8& legacyAddress); + ConversionResult aidl2legacy_AudioFormatDescription_audio_format_t( const media::audio::common::AudioFormatDescription& aidl); ConversionResult diff --git a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp index 2c087d98d7..26eea874c8 100644 --- a/media/libaudiofoundation/AudioDeviceTypeAddr.cpp +++ b/media/libaudiofoundation/AudioDeviceTypeAddr.cpp @@ -26,6 +26,7 @@ namespace android { using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceAddress; namespace { @@ -160,18 +161,15 @@ std::string dumpAudioDeviceTypeAddrVector(const AudioDeviceTypeAddrVector& devic ConversionResult aidl2legacy_AudioDeviceTypeAddress(const AudioDevice& aidl) { - audio_devices_t type = VALUE_OR_RETURN( - aidl2legacy_AudioDeviceDescription_audio_devices_t(aidl.type)); - return AudioDeviceTypeAddr(type, aidl.address); + audio_devices_t type; + std::string address; + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device(aidl, &type, &address)); + return AudioDeviceTypeAddr(type, address); } ConversionResult legacy2aidl_AudioDeviceTypeAddress(const AudioDeviceTypeAddr& legacy) { - AudioDevice aidl; - aidl.type = VALUE_OR_RETURN( - legacy2aidl_audio_devices_t_AudioDeviceDescription(legacy.mType)); - aidl.address = legacy.getAddress(); - return aidl; + return legacy2aidl_audio_device_AudioDevice(legacy.mType, legacy.getAddress()); } } // namespace android diff --git a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h index 6660f3b1bd..11aa222a79 100644 --- a/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h +++ b/media/libaudiofoundation/include/media/AudioDeviceTypeAddr.h @@ -32,6 +32,7 @@ namespace android { class AudioDeviceTypeAddr : public Parcelable { public: AudioDeviceTypeAddr() = default; + AudioDeviceTypeAddr(const AudioDeviceTypeAddr&) = default; AudioDeviceTypeAddr(audio_devices_t type, const std::string& address); diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index 55917bc407..d01037d98d 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -32,6 +32,9 @@ if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \ std::move(_tmp.value()); }) +#define RETURN_BINDER_STATUS_IF_ERROR(x) \ + if (status_t _tmp = (x); _tmp != OK) return aidl_utils::binderStatusFromStatusT(_tmp); + #define RETURN_IF_BINDER_ERROR(x) \ { \ binder::Status _tmp = (x); \ @@ -47,6 +50,7 @@ using content::AttributionSourceState; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioDevice; +using media::audio::common::AudioDeviceAddress; using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioMode; @@ -111,8 +115,10 @@ Status AudioPolicyService::setDeviceConnectionState( media::AudioPolicyDeviceState stateAidl, const std::string& deviceNameAidl, const AudioFormatDescription& encodedFormatAidl) { - audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); + audio_devices_t device; + std::string address; + RETURN_BINDER_STATUS_IF_ERROR( + aidl2legacy_AudioDevice_audio_device(deviceAidl, &device, &address)); audio_policy_dev_state_t state = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioPolicyDeviceState_audio_policy_dev_state_t(stateAidl)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( @@ -132,10 +138,8 @@ Status AudioPolicyService::setDeviceConnectionState( ALOGV("setDeviceConnectionState()"); Mutex::Autolock _l(mLock); AutoCallerClear acc; - status_t status = mAudioPolicyManager->setDeviceConnectionState(device, state, - deviceAidl.address.c_str(), - deviceNameAidl.c_str(), - encodedFormat); + status_t status = mAudioPolicyManager->setDeviceConnectionState( + device, state, address.c_str(), deviceNameAidl.c_str(), encodedFormat); if (status == NO_ERROR) { onCheckSpatializer_l(); } @@ -144,8 +148,10 @@ Status AudioPolicyService::setDeviceConnectionState( Status AudioPolicyService::getDeviceConnectionState(const AudioDevice& deviceAidl, media::AudioPolicyDeviceState* _aidl_return) { - audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); + audio_devices_t device; + std::string address; + RETURN_BINDER_STATUS_IF_ERROR( + aidl2legacy_AudioDevice_audio_device(deviceAidl, &device, &address)); if (mAudioPolicyManager == NULL) { *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState( @@ -155,8 +161,8 @@ Status AudioPolicyService::getDeviceConnectionState(const AudioDevice& deviceAid AutoCallerClear acc; *_aidl_return = VALUE_OR_RETURN_BINDER_STATUS( legacy2aidl_audio_policy_dev_state_t_AudioPolicyDeviceState( - mAudioPolicyManager->getDeviceConnectionState(device, - deviceAidl.address.c_str()))); + mAudioPolicyManager->getDeviceConnectionState( + device, address.c_str()))); return Status::ok(); } @@ -164,8 +170,10 @@ Status AudioPolicyService::handleDeviceConfigChange( const AudioDevice& deviceAidl, const std::string& deviceNameAidl, const AudioFormatDescription& encodedFormatAidl) { - audio_devices_t device = VALUE_OR_RETURN_BINDER_STATUS( - aidl2legacy_AudioDeviceDescription_audio_devices_t(deviceAidl.type)); + audio_devices_t device; + std::string address; + RETURN_BINDER_STATUS_IF_ERROR( + aidl2legacy_AudioDevice_audio_device(deviceAidl, &device, &address)); audio_format_t encodedFormat = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_AudioFormatDescription_audio_format_t(encodedFormatAidl)); @@ -180,7 +188,7 @@ Status AudioPolicyService::handleDeviceConfigChange( Mutex::Autolock _l(mLock); AutoCallerClear acc; status_t status = mAudioPolicyManager->handleDeviceConfigChange( - device, deviceAidl.address.c_str(), deviceNameAidl.c_str(), encodedFormat); + device, address.c_str(), deviceNameAidl.c_str(), encodedFormat); if (status == NO_ERROR) { onCheckSpatializer_l(); -- GitLab From e99d08844983773f44fd43f0dc8b4982f77eabb0 Mon Sep 17 00:00:00 2001 From: jiabin Date: Fri, 17 Sep 2021 05:21:25 +0000 Subject: [PATCH 139/694] Move AudioMMapPolicy* from android.media to a.m.audio.common SAIDL Bug: 193275465 Test: make Change-Id: I79ea167fe4a0035a13873a641428305e1209c3cf --- media/audioserver/main_audioserver.cpp | 18 +++++---- .../libaaudio/src/core/AudioStreamBuilder.cpp | 28 +++++++------ media/libaudioclient/Android.bp | 3 -- media/libaudioclient/AudioSystem.cpp | 5 ++- media/libaudioclient/IAudioFlinger.cpp | 8 ++-- .../aidl/android/media/AudioMMapPolicy.aidl | 40 ------------------- .../android/media/AudioMMapPolicyInfo.aidl | 29 -------------- .../android/media/AudioMMapPolicyType.aidl | 34 ---------------- .../android/media/IAudioFlingerService.aidl | 4 +- .../include/media/AudioSystem.h | 10 ++--- .../include/media/IAudioFlinger.h | 18 ++++----- media/libaudiohal/impl/DeviceHalHidl.h | 4 +- media/libaudiohal/impl/DeviceHalLocal.h | 4 +- .../media/audiohal/DeviceHalInterface.h | 8 ++-- services/audioflinger/AudioFlinger.cpp | 7 ++-- services/audioflinger/AudioFlinger.h | 7 ++-- services/audioflinger/AudioHwDevice.cpp | 8 ++-- services/audioflinger/AudioHwDevice.h | 6 ++- services/audioflinger/PropertyUtils.cpp | 35 ++++++++-------- services/audioflinger/PropertyUtils.h | 8 ++-- 20 files changed, 97 insertions(+), 187 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl diff --git a/media/audioserver/main_audioserver.cpp b/media/audioserver/main_audioserver.cpp index fd665735f4..726a6be095 100644 --- a/media/audioserver/main_audioserver.cpp +++ b/media/audioserver/main_audioserver.cpp @@ -24,9 +24,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include #include #include @@ -44,6 +44,10 @@ using namespace android; +using android::media::audio::common::AudioMMapPolicy; +using android::media::audio::common::AudioMMapPolicyInfo; +using android::media::audio::common::AudioMMapPolicyType; + int main(int argc __unused, char **argv) { // TODO: update with refined parameters @@ -155,15 +159,15 @@ int main(int argc __unused, char **argv) // attempting to call audio flinger on a null pointer could make the process crash // and attract attentions. sp af = AudioSystem::get_audio_flinger(); - std::vector policyInfos; + std::vector policyInfos; status_t status = af->getMmapPolicyInfos( - media::AudioMMapPolicyType::DEFAULT, &policyInfos); + AudioMMapPolicyType::DEFAULT, &policyInfos); // Initialize aaudio service when querying mmap policy succeeds and // any of the policy supports MMAP. if (status == NO_ERROR && std::any_of(policyInfos.begin(), policyInfos.end(), [](const auto& info) { - return info.mmapPolicy == media::AudioMMapPolicy::AUTO || - info.mmapPolicy == media::AudioMMapPolicy::ALWAYS; + return info.mmapPolicy == AudioMMapPolicy::AUTO || + info.mmapPolicy == AudioMMapPolicy::ALWAYS; })) { AAudioService::instantiate(); } else { diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp index 2a6b23524a..2be3d65719 100644 --- a/media/libaaudio/src/core/AudioStreamBuilder.cpp +++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp @@ -24,9 +24,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include #include "binding/AAudioBinderClient.h" @@ -40,6 +40,10 @@ using namespace aaudio; +using android::media::audio::common::AudioMMapPolicy; +using android::media::audio::common::AudioMMapPolicyInfo; +using android::media::audio::common::AudioMMapPolicyType; + #define AAUDIO_MMAP_POLICY_DEFAULT AAUDIO_POLICY_NEVER #define AAUDIO_MMAP_EXCLUSIVE_POLICY_DEFAULT AAUDIO_POLICY_NEVER @@ -93,15 +97,15 @@ static aaudio_result_t builder_createStream(aaudio_direction_t direction, namespace { -aaudio_policy_t aidl2legacy_aaudio_policy(android::media::AudioMMapPolicy aidl) { +aaudio_policy_t aidl2legacy_aaudio_policy(AudioMMapPolicy aidl) { switch (aidl) { - case android::media::AudioMMapPolicy::NEVER: + case AudioMMapPolicy::NEVER: return AAUDIO_POLICY_NEVER; - case android::media::AudioMMapPolicy::AUTO: + case AudioMMapPolicy::AUTO: return AAUDIO_POLICY_AUTO; - case android::media::AudioMMapPolicy::ALWAYS: + case AudioMMapPolicy::ALWAYS: return AAUDIO_POLICY_ALWAYS; - case android::media::AudioMMapPolicy::UNSPECIFIED: + case AudioMMapPolicy::UNSPECIFIED: default: return AAUDIO_UNSPECIFIED; } @@ -110,7 +114,7 @@ aaudio_policy_t aidl2legacy_aaudio_policy(android::media::AudioMMapPolicy aidl) // The aaudio policy will be ALWAYS, NEVER, UNSPECIFIED only when all policy info are // ALWAYS, NEVER or UNSPECIFIED. Otherwise, the aaudio policy will be AUTO. aaudio_policy_t getAAudioPolicy( - const std::vector& policyInfos) { + const std::vector& policyInfos) { if (policyInfos.empty()) return AAUDIO_POLICY_AUTO; for (size_t i = 1; i < policyInfos.size(); ++i) { if (policyInfos.at(i).mmapPolicy != policyInfos.at(0).mmapPolicy) { @@ -140,12 +144,12 @@ aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) { return result; } - std::vector policyInfos; + std::vector policyInfos; // The API setting is the highest priority. aaudio_policy_t mmapPolicy = AudioGlobal_getMMapPolicy(); // If not specified then get from a system property. if (mmapPolicy == AAUDIO_UNSPECIFIED && android::AudioSystem::getMmapPolicyInfo( - android::media::AudioMMapPolicyType::DEFAULT, &policyInfos) == NO_ERROR) { + AudioMMapPolicyType::DEFAULT, &policyInfos) == NO_ERROR) { mmapPolicy = getAAudioPolicy(policyInfos); } // If still not specified then use the default. @@ -156,7 +160,7 @@ aaudio_result_t AudioStreamBuilder::build(AudioStream** streamPtr) { policyInfos.clear(); aaudio_policy_t mmapExclusivePolicy = AAUDIO_UNSPECIFIED; if (android::AudioSystem::getMmapPolicyInfo( - android::media::AudioMMapPolicyType::EXCLUSIVE, &policyInfos) == NO_ERROR) { + AudioMMapPolicyType::EXCLUSIVE, &policyInfos) == NO_ERROR) { mmapExclusivePolicy = getAAudioPolicy(policyInfos); } if (mmapExclusivePolicy == AAUDIO_UNSPECIFIED) { diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 7475e5f7dc..4cb531a4d1 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -321,9 +321,6 @@ aidl_interface { "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", - "aidl/android/media/AudioMMapPolicy.aidl", - "aidl/android/media/AudioMMapPolicyInfo.aidl", - "aidl/android/media/AudioMMapPolicyType.aidl", "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioOutputFlags.aidl", "aidl/android/media/AudioPatch.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 2557482d3c..17557e7896 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -59,6 +59,8 @@ using media::audio::common::AudioDevice; using media::audio::common::AudioDeviceAddress; using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioMMapPolicyInfo; +using media::audio::common::AudioMMapPolicyType; using media::audio::common::AudioOffloadInfo; using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; @@ -2357,8 +2359,7 @@ status_t AudioSystem::setVibratorInfos( } status_t AudioSystem::getMmapPolicyInfo( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { + AudioMMapPolicyType policyType, std::vector *policyInfos) { const sp& af = AudioSystem::get_audio_flinger(); if (af == nullptr) { return PERMISSION_DENIED; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index fdec918fe0..e1e44fc228 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -33,6 +33,8 @@ using aidl_utils::statusTFromBinderStatus; using binder::Status; using media::audio::common::AudioChannelLayout; using media::audio::common::AudioFormatDescription; +using media::audio::common::AudioMMapPolicyInfo; +using media::audio::common::AudioMMapPolicyType; using media::audio::common::AudioMode; using media::audio::common::AudioStreamType; using media::audio::common::AudioUuid; @@ -782,8 +784,7 @@ status_t AudioFlingerClientAdapter::updateSecondaryOutputs( } status_t AudioFlingerClientAdapter::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { + AudioMMapPolicyType policyType, std::vector *policyInfos) { return statusTFromBinderStatus(mDelegate->getMmapPolicyInfos(policyType, policyInfos)); } @@ -1260,8 +1261,7 @@ Status AudioFlingerServerAdapter::updateSecondaryOutputs( } Status AudioFlingerServerAdapter::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *_aidl_return) { + AudioMMapPolicyType policyType, std::vector *_aidl_return) { return Status::fromStatusT(mDelegate->getMmapPolicyInfos(policyType, _aidl_return)); } diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl deleted file mode 100644 index e3fa951390..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicy.aidl +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * Audio MMAP policy describe how the aaudio MMAP feature is used. - * {@hide} - */ -@Backing(type="int") -enum AudioMMapPolicy { - /** - * The policy is unspecified. - */ - UNSPECIFIED = 0, - /** - * The MMAP feature is disabled and never used. - */ - NEVER = 1, - /** - * If MMAP feature works then uses it. Otherwise, fall back to something else. - */ - AUTO = 2, - /** - * The MMAP feature must be used. If not available then fail. - */ - ALWAYS = 3, -} \ No newline at end of file diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl deleted file mode 100644 index 3e1f9cb25e..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicyInfo.aidl +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -import android.media.AudioMMapPolicy; -import android.media.audio.common.AudioDevice; - -/** - * Audio MMAP policy info describes how an aaudio MMAP feature can be - * used on a particular device. - * {@hide} - */ -parcelable AudioMMapPolicyInfo { - AudioDevice device; - AudioMMapPolicy mmapPolicy = AudioMMapPolicy.UNSPECIFIED; -} diff --git a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl b/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl deleted file mode 100644 index d6acd2cca3..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMMapPolicyType.aidl +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * The aaudio MMAP policy type. - * {@hide} - */ -@Backing(type="int") -enum AudioMMapPolicyType { - /** - * Default aaudio mmap policy. It is used to query whether the - * aaudio MMAP could be used or not. - */ - DEFAULT = 1, - /** - * Exclusive aaudio mmap policy. It is used to query whether the - * aaudio MMAP could be used in exclusive mode or not. - */ - EXCLUSIVE = 2, -} diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index 7a46f4899c..d8d40a984d 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -16,8 +16,6 @@ package android.media; -import android.media.AudioMMapPolicyInfo; -import android.media.AudioMMapPolicyType; import android.media.AudioPatch; import android.media.AudioPort; import android.media.AudioPortConfig; @@ -42,6 +40,8 @@ import android.media.RenderPosition; import android.media.TrackSecondaryOutputInfo; import android.media.audio.common.AudioChannelLayout; import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioMMapPolicyInfo; +import android.media.audio.common.AudioMMapPolicyType; import android.media.audio.common.AudioMode; import android.media.audio.common.AudioStreamType; import android.media.audio.common.AudioUuid; diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index c546dfb2b6..a4e2cc1a6b 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -22,14 +22,14 @@ #include #include -#include -#include +#include #include #include #include #include #include -#include +#include +#include #include #include #include @@ -617,8 +617,8 @@ public: static status_t setVibratorInfos(const std::vector& vibratorInfos); static status_t getMmapPolicyInfo( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos); private: diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 774e907917..9aacdf963a 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -37,12 +37,12 @@ #include #include -#include -#include +#include #include #include #include -#include +#include +#include #include "android/media/CreateEffectRequest.h" #include "android/media/CreateEffectResponse.h" #include "android/media/CreateRecordRequest.h" @@ -352,8 +352,8 @@ public: const TrackSecondaryOutputsMap& trackSecondaryOutputs) = 0; virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) = 0; + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; }; /** @@ -452,8 +452,8 @@ public: const TrackSecondaryOutputsMap& trackSecondaryOutputs) override; status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) override; + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos) override; private: const sp mDelegate; @@ -655,8 +655,8 @@ public: Status updateSecondaryOutputs( const std::vector& trackSecondaryOutputInfos) override; Status getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *_aidl_return) override; + media::audio::common::AudioMMapPolicyType policyType, + std::vector *_aidl_return) override; private: const sp mDelegate; diff --git a/media/libaudiohal/impl/DeviceHalHidl.h b/media/libaudiohal/impl/DeviceHalHidl.h index 7b4dd88f6e..6065b40064 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.h +++ b/media/libaudiohal/impl/DeviceHalHidl.h @@ -120,8 +120,8 @@ class DeviceHalHidl : public DeviceHalInterface, public ConversionHelperHidl status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType __unused, - std::vector *policyInfos __unused) override { + media::audio::common::AudioMMapPolicyType policyType __unused, + std::vector *policyInfos __unused) override { // TODO: Implement the HAL query when moving to AIDL HAL. return INVALID_OPERATION; } diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h index d4bb7a047e..6bc7a8023d 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.h +++ b/media/libaudiohal/impl/DeviceHalLocal.h @@ -113,8 +113,8 @@ class DeviceHalLocal : public DeviceHalInterface status_t removeDeviceEffect(audio_port_handle_t device, sp effect) override; status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType __unused, - std::vector *policyInfos __unused) override { + media::audio::common::AudioMMapPolicyType policyType __unused, + std::vector *policyInfos __unused) override { // This function will only be available on AIDL HAL. return INVALID_OPERATION; } diff --git a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h index b93c8d26af..376f37bef9 100644 --- a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h @@ -17,8 +17,8 @@ #ifndef ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H #define ANDROID_HARDWARE_DEVICE_HAL_INTERFACE_H -#include -#include +#include +#include #include #include #include @@ -123,8 +123,8 @@ class DeviceHalInterface : public RefBase audio_port_handle_t device, sp effect) = 0; virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) = 0; + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos) = 0; virtual status_t dump(int fd, const Vector& args) = 0; diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index c8d753b703..87964d1056 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -104,6 +104,8 @@ namespace android { using media::IEffectClient; +using media::audio::common::AudioMMapPolicyInfo; +using media::audio::common::AudioMMapPolicyType; using android::content::AttributionSourceState; static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n"; @@ -339,8 +341,7 @@ status_t AudioFlinger::updateSecondaryOutputs( #define MAX_MMAP_PROPERTY_DEVICE_HAL_VERSION 7.0 status_t AudioFlinger::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { + AudioMMapPolicyType policyType, std::vector *policyInfos) { if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) { *policyInfos = it->second; return NO_ERROR; @@ -349,7 +350,7 @@ status_t AudioFlinger::getMmapPolicyInfos( AutoMutex lock(mHardwareLock); for (size_t i = 0; i < mAudioHwDevs.size(); ++i) { AudioHwDevice *dev = mAudioHwDevs.valueAt(i); - std::vector infos; + std::vector infos; status_t status = dev->getMmapPolicyInfos(policyType, &infos); if (status != NO_ERROR) { ALOGE("Failed to query mmap policy info of %d, error %d", diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index b5d587bd8e..d0a9ea83df 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -283,8 +283,8 @@ public: const TrackSecondaryOutputsMap& trackSecondaryOutputs); virtual status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos); status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -1009,7 +1009,8 @@ private: // Keep in sync with java definition in media/java/android/media/AudioRecord.java static constexpr int32_t kMaxSharedAudioHistoryMs = 5000; - std::map> mPolicyInfos; + std::map> mPolicyInfos; }; #undef INCLUDING_FROM_AUDIOFLINGER_H diff --git a/services/audioflinger/AudioHwDevice.cpp b/services/audioflinger/AudioHwDevice.cpp index b996c6c97a..12f8272d7d 100644 --- a/services/audioflinger/AudioHwDevice.cpp +++ b/services/audioflinger/AudioHwDevice.cpp @@ -29,6 +29,9 @@ namespace android { +using media::audio::common::AudioMMapPolicyInfo; +using media::audio::common::AudioMMapPolicyType; + // ---------------------------------------------------------------------------- status_t AudioHwDevice::openOutputStream( @@ -102,11 +105,8 @@ status_t AudioHwDevice::getAudioPort(struct audio_port_v7 *port) const { return mHwDevice->getAudioPort(port); } - - status_t AudioHwDevice::getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) const { + AudioMMapPolicyType policyType, std::vector *policyInfos) const { return mHwDevice->getMmapPolicyInfos(policyType, policyInfos); } diff --git a/services/audioflinger/AudioHwDevice.h b/services/audioflinger/AudioHwDevice.h index b72072f656..0715e55a20 100644 --- a/services/audioflinger/AudioHwDevice.h +++ b/services/audioflinger/AudioHwDevice.h @@ -22,6 +22,8 @@ #include #include +#include +#include #include #include #include @@ -86,8 +88,8 @@ public: status_t getAudioPort(struct audio_port_v7 *port) const; status_t getMmapPolicyInfos( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) const; + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos) const; private: const audio_module_handle_t mHandle; diff --git a/services/audioflinger/PropertyUtils.cpp b/services/audioflinger/PropertyUtils.cpp index b8abb8edaf..341d5bb6a9 100644 --- a/services/audioflinger/PropertyUtils.cpp +++ b/services/audioflinger/PropertyUtils.cpp @@ -16,54 +16,57 @@ #include #include -#include +#include #include #include "PropertyUtils.h" namespace android { -std::string getMmapPolicyProperty(media::AudioMMapPolicyType policyType) { +using media::audio::common::AudioMMapPolicy; +using media::audio::common::AudioMMapPolicyType; +using media::audio::common::AudioMMapPolicyInfo; + +std::string getMmapPolicyProperty(AudioMMapPolicyType policyType) { switch (policyType) { - case media::AudioMMapPolicyType::DEFAULT: + case AudioMMapPolicyType::DEFAULT: return "aaudio.mmap_policy"; - case media::AudioMMapPolicyType::EXCLUSIVE: + case AudioMMapPolicyType::EXCLUSIVE: return "aaudio.mmap_exclusive_policy"; default: return ""; } } -int getDefaultPolicyFromType(media::AudioMMapPolicyType policyType) { +int getDefaultPolicyFromType(AudioMMapPolicyType policyType) { switch (policyType) { - case media::AudioMMapPolicyType::EXCLUSIVE: + case AudioMMapPolicyType::EXCLUSIVE: return AAUDIO_UNSPECIFIED; - case media::AudioMMapPolicyType::DEFAULT: + case AudioMMapPolicyType::DEFAULT: default: return AAUDIO_POLICY_NEVER; } } -media::AudioMMapPolicy legacy2aidl_aaudio_policy_t_AudioMMapPolicy(aaudio_policy_t legacy) { +AudioMMapPolicy legacy2aidl_aaudio_policy_t_AudioMMapPolicy(aaudio_policy_t legacy) { switch (legacy) { case AAUDIO_POLICY_NEVER: - return media::AudioMMapPolicy::NEVER; + return AudioMMapPolicy::NEVER; case AAUDIO_POLICY_AUTO: - return media::AudioMMapPolicy::AUTO; + return AudioMMapPolicy::AUTO; case AAUDIO_POLICY_ALWAYS: - return media::AudioMMapPolicy::ALWAYS; + return AudioMMapPolicy::ALWAYS; case AAUDIO_UNSPECIFIED: - return media::AudioMMapPolicy::UNSPECIFIED; + return AudioMMapPolicy::UNSPECIFIED; default: ALOGE("%s unknown aaudio policy: %d", __func__, legacy); - return media::AudioMMapPolicy::UNSPECIFIED; + return AudioMMapPolicy::UNSPECIFIED; } } status_t getMmapPolicyInfosFromSystemProperty( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos) { - media::AudioMMapPolicyInfo policyInfo; + AudioMMapPolicyType policyType, std::vector *policyInfos) { + AudioMMapPolicyInfo policyInfo; const std::string propertyStr = getMmapPolicyProperty(policyType); if (propertyStr.empty()) { return BAD_VALUE; diff --git a/services/audioflinger/PropertyUtils.h b/services/audioflinger/PropertyUtils.h index 38cbf92a17..3bb6fa2f3b 100644 --- a/services/audioflinger/PropertyUtils.h +++ b/services/audioflinger/PropertyUtils.h @@ -16,13 +16,13 @@ #pragma once -#include -#include +#include +#include namespace android { status_t getMmapPolicyInfosFromSystemProperty( - media::AudioMMapPolicyType policyType, - std::vector *policyInfos); + media::audio::common::AudioMMapPolicyType policyType, + std::vector *policyInfos); } // namespace android -- GitLab From 27b252fa7a785ae2b5ee49d371c8f7eac5f2f27e Mon Sep 17 00:00:00 2001 From: Aayush Soni Date: Wed, 28 Jul 2021 14:36:58 +0530 Subject: [PATCH 140/694] C2SoftMpeg4Dec: Fix memory leak in onRelease Test: POC in bug description atest VtsHalMediaC2V1_0TargetVideoDecTest atest -c CtsMediaV2TestCases:CodecDecoderTest Bug: 193759243 Merged-In: I1b4511e733d02a2f573bcb5475b778beccaccbae Change-Id: I1b4511e733d02a2f573bcb5475b778beccaccbae --- .../components/mpeg4_h263/C2SoftMpeg4Dec.cpp | 23 +++++-------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp index ddd312ffce..60d6b44c68 100644 --- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp +++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp @@ -243,11 +243,13 @@ c2_status_t C2SoftMpeg4Dec::onInit() { } c2_status_t C2SoftMpeg4Dec::onStop() { - if (mInitialized) { - if (mDecHandle) { + if (mDecHandle) { + if (mInitialized) { PVCleanUpVideoDecoder(mDecHandle); + mInitialized = false; } - mInitialized = false; + delete mDecHandle; + mDecHandle = nullptr; } for (int32_t i = 0; i < kNumOutputBuffers; ++i) { if (mOutputBuffer[i]) { @@ -269,23 +271,10 @@ void C2SoftMpeg4Dec::onReset() { } void C2SoftMpeg4Dec::onRelease() { - if (mInitialized) { - if (mDecHandle) { - PVCleanUpVideoDecoder(mDecHandle); - delete mDecHandle; - mDecHandle = nullptr; - } - mInitialized = false; - } + (void)onStop(); if (mOutBlock) { mOutBlock.reset(); } - for (int32_t i = 0; i < kNumOutputBuffers; ++i) { - if (mOutputBuffer[i]) { - free(mOutputBuffer[i]); - mOutputBuffer[i] = nullptr; - } - } } c2_status_t C2SoftMpeg4Dec::onFlush_sm() { -- GitLab From ae1b824c7de7aa9f63dde1f7d4eab4e1ec79d80d Mon Sep 17 00:00:00 2001 From: Aayush Soni Date: Thu, 26 Aug 2021 13:21:31 +0530 Subject: [PATCH 141/694] C2SoftMpeg4Dec: fix null pointer dereference issue Test: atest CtsMediaTestCases:android.media.cts.AdaptivePlaybackTest Test: atest CtsMediaV2TestCases -- --module-arg \ CtsMediaV2TestCases:instrumentation-arg:codec-prefix:=\ c2.android.mpeg4.decoder Test: atest CtsMediaV2TestCases -- --module-arg \ CtsMediaV2TestCases:instrumentation-arg:codec-prefix:=\ c2.android.h263.decoder Test: atest VtsHalMediaC2V1_0TargetVideoDecTest Bug: 197359760 Bug: 197525621 Change-Id: I0bfafc8731c073dd0a38d607b23443338ca58459 --- .../components/mpeg4_h263/C2SoftMpeg4Dec.cpp | 52 +++++++------------ .../components/mpeg4_h263/C2SoftMpeg4Dec.h | 4 +- 2 files changed, 21 insertions(+), 35 deletions(-) diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp index 60d6b44c68..81f4679ed6 100644 --- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp +++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.cpp @@ -228,7 +228,6 @@ C2SoftMpeg4Dec::C2SoftMpeg4Dec( const std::shared_ptr &intfImpl) : SimpleC2Component(std::make_shared>(name, id, intfImpl)), mIntf(intfImpl), - mDecHandle(nullptr), mOutputBuffer{}, mInitialized(false) { } @@ -243,13 +242,9 @@ c2_status_t C2SoftMpeg4Dec::onInit() { } c2_status_t C2SoftMpeg4Dec::onStop() { - if (mDecHandle) { - if (mInitialized) { - PVCleanUpVideoDecoder(mDecHandle); - mInitialized = false; - } - delete mDecHandle; - mDecHandle = nullptr; + if (mInitialized) { + PVCleanUpVideoDecoder(&mVideoDecControls); + mInitialized = false; } for (int32_t i = 0; i < kNumOutputBuffers; ++i) { if (mOutputBuffer[i]) { @@ -279,7 +274,7 @@ void C2SoftMpeg4Dec::onRelease() { c2_status_t C2SoftMpeg4Dec::onFlush_sm() { if (mInitialized) { - if (PV_TRUE != PVResetVideoDecoder(mDecHandle)) { + if (PV_TRUE != PVResetVideoDecoder(&mVideoDecControls)) { return C2_CORRUPTED; } } @@ -294,14 +289,8 @@ status_t C2SoftMpeg4Dec::initDecoder() { #else mIsMpeg4 = false; #endif - if (!mDecHandle) { - mDecHandle = new tagvideoDecControls; - } - if (!mDecHandle) { - ALOGE("mDecHandle is null"); - return NO_MEMORY; - } - memset(mDecHandle, 0, sizeof(tagvideoDecControls)); + + memset(&mVideoDecControls, 0, sizeof(tagvideoDecControls)); /* TODO: bring these values to 352 and 288. It cannot be done as of now * because, h263 doesn't seem to allow port reconfiguration. In OMX, the @@ -357,10 +346,6 @@ void C2SoftMpeg4Dec::finishWork(uint64_t index, const std::unique_ptr &w } c2_status_t C2SoftMpeg4Dec::ensureDecoderState(const std::shared_ptr &pool) { - if (!mDecHandle) { - ALOGE("not supposed to be here, invalid decoder context"); - return C2_CORRUPTED; - } mOutputBufferSize = align(mIntf->getMaxWidth(), 16) * align(mIntf->getMaxHeight(), 16) * 3 / 2; for (int32_t i = 0; i < kNumOutputBuffers; ++i) { @@ -391,10 +376,10 @@ c2_status_t C2SoftMpeg4Dec::ensureDecoderState(const std::shared_ptr &work) { uint32_t disp_width, disp_height; - PVGetVideoDimensions(mDecHandle, (int32 *)&disp_width, (int32 *)&disp_height); + PVGetVideoDimensions(&mVideoDecControls, (int32 *)&disp_width, (int32 *)&disp_height); uint32_t buf_width, buf_height; - PVGetBufferDimensions(mDecHandle, (int32 *)&buf_width, (int32 *)&buf_height); + PVGetBufferDimensions(&mVideoDecControls, (int32 *)&buf_width, (int32 *)&buf_height); CHECK_LE(disp_width, buf_width); CHECK_LE(disp_height, buf_height); @@ -415,13 +400,14 @@ bool C2SoftMpeg4Dec::handleResChange(const std::unique_ptr &work) { } if (!mIsMpeg4) { - PVCleanUpVideoDecoder(mDecHandle); + PVCleanUpVideoDecoder(&mVideoDecControls); uint8_t *vol_data[1]{}; int32_t vol_size = 0; if (!PVInitVideoDecoder( - mDecHandle, vol_data, &vol_size, 1, mIntf->getMaxWidth(), mIntf->getMaxHeight(), H263_MODE)) { + &mVideoDecControls, vol_data, &vol_size, 1, mIntf->getMaxWidth(), + mIntf->getMaxHeight(), H263_MODE)) { ALOGE("Error in PVInitVideoDecoder H263_MODE while resChanged was set to true"); mSignalledError = true; work->result = C2_CORRUPTED; @@ -511,7 +497,7 @@ void C2SoftMpeg4Dec::process( uint32_t *start_code = (uint32_t *)bitstream; bool volHeader = *start_code == 0xB0010000; if (volHeader) { - PVCleanUpVideoDecoder(mDecHandle); + PVCleanUpVideoDecoder(&mVideoDecControls); mInitialized = false; } @@ -526,7 +512,7 @@ void C2SoftMpeg4Dec::process( } MP4DecodingMode mode = (mIsMpeg4) ? MPEG4_MODE : H263_MODE; if (!PVInitVideoDecoder( - mDecHandle, vol_data, &vol_size, 1, + &mVideoDecControls, vol_data, &vol_size, 1, mIntf->getMaxWidth(), mIntf->getMaxHeight(), mode)) { ALOGE("PVInitVideoDecoder failed. Unsupported content?"); mSignalledError = true; @@ -534,7 +520,7 @@ void C2SoftMpeg4Dec::process( return; } mInitialized = true; - MP4DecodingMode actualMode = PVGetDecBitstreamMode(mDecHandle); + MP4DecodingMode actualMode = PVGetDecBitstreamMode(&mVideoDecControls); if (mode != actualMode) { ALOGE("Decoded mode not same as actual mode of the decoder"); mSignalledError = true; @@ -542,7 +528,7 @@ void C2SoftMpeg4Dec::process( return; } - PVSetPostProcType(mDecHandle, 0); + PVSetPostProcType(&mVideoDecControls, 0); if (handleResChange(work)) { ALOGI("Setting width and height"); C2StreamPictureSizeInfo::output size(0u, mWidth, mHeight); @@ -579,7 +565,7 @@ void C2SoftMpeg4Dec::process( return; } - uint32_t yFrameSize = sizeof(uint8) * mDecHandle->size; + uint32_t yFrameSize = sizeof(uint8) * mVideoDecControls.size; if (mOutputBufferSize < yFrameSize * 3 / 2){ ALOGE("Too small output buffer: %zu bytes", mOutputBufferSize); mSignalledError = true; @@ -588,7 +574,7 @@ void C2SoftMpeg4Dec::process( } if (!mFramesConfigured) { - PVSetReferenceYUV(mDecHandle,mOutputBuffer[1]); + PVSetReferenceYUV(&mVideoDecControls,mOutputBuffer[1]); mFramesConfigured = true; } @@ -599,7 +585,7 @@ void C2SoftMpeg4Dec::process( uint8_t *bitstreamTmp = bitstream; uint32_t timestamp = workIndex; if (PVDecodeVopHeader( - mDecHandle, &bitstreamTmp, ×tamp, &tmpInSize, + &mVideoDecControls, &bitstreamTmp, ×tamp, &tmpInSize, &header_info, &useExtTimestamp, mOutputBuffer[mNumSamplesOutput & 1]) != PV_TRUE) { ALOGE("failed to decode vop header."); @@ -631,7 +617,7 @@ void C2SoftMpeg4Dec::process( continue; } - if (PVDecodeVopBody(mDecHandle, &tmpInSize) != PV_TRUE) { + if (PVDecodeVopBody(&mVideoDecControls, &tmpInSize) != PV_TRUE) { ALOGE("failed to decode video frame."); mSignalledError = true; work->result = C2_CORRUPTED; diff --git a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.h b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.h index 716a0951b2..fed04c9c57 100644 --- a/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.h +++ b/media/codec2/components/mpeg4_h263/C2SoftMpeg4Dec.h @@ -19,8 +19,8 @@ #include +#include -struct tagvideoDecControls; namespace android { @@ -54,7 +54,7 @@ struct C2SoftMpeg4Dec : public SimpleC2Component { bool handleResChange(const std::unique_ptr &work); std::shared_ptr mIntf; - tagvideoDecControls *mDecHandle; + tagvideoDecControls mVideoDecControls; std::shared_ptr mOutBlock; uint8_t *mOutputBuffer[kNumOutputBuffers]; size_t mOutputBufferSize; -- GitLab From 2eb1482a7c3dad6c53fbd381afe42abf3e1baa29 Mon Sep 17 00:00:00 2001 From: Manisha Jajoo Date: Wed, 21 Jul 2021 17:51:04 +0530 Subject: [PATCH 142/694] C2SoftMp3Dec: fix floating point exception outTimeStamp and mProcessedSamples are calculated from samplingRate and numChannels respectively. If either of them is 0, it will lead to divide by zero error. This patch adds a check on both these parameters. Test: clusterfuzz generated poc in bug Test: atest android.mediav2.cts.CodecDecoderTest Test: atest VtsHalMediaC2V1_0TargetAudioDecTest Bug: 193363472 Change-Id: Ib268d63fa28b2b4d83165c2e3deccbb2bac2d92b --- media/codec2/components/mp3/C2SoftMp3Dec.cpp | 29 ++++++++++++-------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/media/codec2/components/mp3/C2SoftMp3Dec.cpp b/media/codec2/components/mp3/C2SoftMp3Dec.cpp index 30d7394b04..50690afa41 100644 --- a/media/codec2/components/mp3/C2SoftMp3Dec.cpp +++ b/media/codec2/components/mp3/C2SoftMp3Dec.cpp @@ -321,6 +321,13 @@ c2_status_t C2SoftMP3::drain( return C2_OK; } +static void fillEmptyWork(const std::unique_ptr &work) { + work->worklets.front()->output.flags = work->input.flags; + work->worklets.front()->output.buffers.clear(); + work->worklets.front()->output.ordinal = work->input.ordinal; + work->workletsProcessed = 1u; +} + // TODO: Can overall error checking be improved? As in the check for validity of // work, pool ptr, work->input.buffers.size() == 1, ... // TODO: Blind removal of 529 samples from the output may not work. Because @@ -486,17 +493,17 @@ void C2SoftMP3::process( } } - int64_t outTimeStamp = mProcessedSamples * 1000000ll / samplingRate; - mProcessedSamples += ((outSize - outOffset) / (numChannels * sizeof(int16_t))); - ALOGV("out buffer attr. offset %d size %d timestamp %" PRId64 " ", outOffset, - outSize - outOffset, mAnchorTimeStamp + outTimeStamp); - decodedSizes.clear(); - work->worklets.front()->output.flags = work->input.flags; - work->worklets.front()->output.buffers.clear(); - work->worklets.front()->output.buffers.push_back( - createLinearBuffer(block, outOffset, outSize - outOffset)); - work->worklets.front()->output.ordinal = work->input.ordinal; - work->worklets.front()->output.ordinal.timestamp = mAnchorTimeStamp + outTimeStamp; + fillEmptyWork(work); + if (samplingRate && numChannels) { + int64_t outTimeStamp = mProcessedSamples * 1000000ll / samplingRate; + mProcessedSamples += ((outSize - outOffset) / (numChannels * sizeof(int16_t))); + ALOGV("out buffer attr. offset %d size %d timestamp %" PRId64 " ", outOffset, + outSize - outOffset, mAnchorTimeStamp + outTimeStamp); + decodedSizes.clear(); + work->worklets.front()->output.buffers.push_back( + createLinearBuffer(block, outOffset, outSize - outOffset)); + work->worklets.front()->output.ordinal.timestamp = mAnchorTimeStamp + outTimeStamp; + } if (eos) { mSignalledOutputEos = true; ALOGV("signalled EOS"); -- GitLab From c8dd629269cfa00d59632f5eaa51660bb4a927de Mon Sep 17 00:00:00 2001 From: Phil Burk Date: Wed, 8 Sep 2021 16:04:22 +0000 Subject: [PATCH 143/694] aaudio test: add close option to test_steal_exclusive This can be used to simulate apps that fail to close the stream when it is disconnected. Test: adb root Test: adb remount -R Test: mmm frameworks/av/media/libaaudio/tests/ Test: adb push $OUT/data/nativetest64/test_steal_exclusive/test_steal_exclusive /system/bin/. Test: test_steal_exclusive -c0 # do NOT close Test: test_steal_exclusive -c1 # close enabled Bug: 199285450 Change-Id: I0930eda1c8e2258b22f71d786c7b3d092cf4daa4 --- .../libaaudio/tests/test_steal_exclusive.cpp | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/media/libaaudio/tests/test_steal_exclusive.cpp b/media/libaaudio/tests/test_steal_exclusive.cpp index 05c560dd60..5cb005c39c 100644 --- a/media/libaaudio/tests/test_steal_exclusive.cpp +++ b/media/libaaudio/tests/test_steal_exclusive.cpp @@ -110,6 +110,10 @@ public: mOpenDelayMillis = openDelayMillis; } + void setCloseEnabled(bool enabled) { + mCloseEnabled = enabled; + } + void restartStream() { int retriesLeft = mMaxRetries; aaudio_result_t result; @@ -189,10 +193,12 @@ public: std::lock_guard lock(mLock); aaudio_result_t result = AAUDIO_OK; if (mStream != nullptr) { - result = AAudioStream_close(mStream); - if (result != AAUDIO_OK) { - printf("AAudioStream_close returned %s\n", - AAudio_convertResultToText(result)); + if (mCloseEnabled) { + result = AAudioStream_close(mStream); + printf("AAudioStream_close() returned %s\n", + AAudio_convertResultToText(result)); + } else { + printf("AAudioStream_close() DISABLED!\n"); } mStream = nullptr; } @@ -287,6 +293,7 @@ private: std::string mName; int mMaxRetries = 1; int mOpenDelayMillis = 0; + bool mCloseEnabled = true; }; // Callback function that fills the audio output buffer. @@ -319,11 +326,12 @@ static void s_myErrorCallbackProc( } static void s_usage() { - printf("test_steal_exclusive [-i] [-r{maxRetries}] [-d{delay}] -s\n"); + printf("test_steal_exclusive [-i] [-r{maxRetries}] [-d{delay}] -s -c{flag}\n"); printf(" -i direction INPUT, otherwise OUTPUT\n"); - printf(" -d delay open by milliseconds, default = 0\n"); - printf(" -r max retries in the error callback, default = 1\n"); + printf(" -d Delay open by milliseconds, default = 0\n"); + printf(" -r max Retries in the error callback, default = 1\n"); printf(" -s try to open in SHARED mode\n"); + printf(" -c enable or disabling Closing of the stream with 0/1, default = 1\n"); } int main(int argc, char ** argv) { @@ -334,6 +342,7 @@ int main(int argc, char ** argv) { int errorCount = 0; int maxRetries = 1; int openDelayMillis = 0; + bool closeEnabled = true; aaudio_sharing_mode_t requestedSharingMode = AAUDIO_SHARING_MODE_EXCLUSIVE; // Make printf print immediately so that debug info is not stuck @@ -348,6 +357,9 @@ int main(int argc, char ** argv) { if (arg[0] == '-') { char option = arg[1]; switch (option) { + case 'c': + closeEnabled = atoi(&arg[2]) != 0; + break; case 'd': openDelayMillis = atoi(&arg[2]); break; @@ -376,6 +388,8 @@ int main(int argc, char ** argv) { thief.setOpenDelayMillis(openDelayMillis); victim.setMaxRetries(maxRetries); thief.setMaxRetries(maxRetries); + victim.setCloseEnabled(closeEnabled); + thief.setCloseEnabled(closeEnabled); result = victim.openAudioStream(direction, requestedSharingMode); if (result != AAUDIO_OK) { @@ -442,7 +456,7 @@ int main(int argc, char ** argv) { } LOGI("Both streams running. Ask user to plug in headset. ===="); - printf("\n====\nPlease PLUG IN A HEADSET now!\n====\n\n"); + printf("\n====\nPlease PLUG IN A HEADSET now! - OPTIONAL\n====\n\n"); if (result == AAUDIO_OK) { const int watchLoops = DUET_DURATION_MSEC / SLEEP_DURATION_MSEC; -- GitLab From d3bb86e692f92ef08c25f1ddb2601a623df7b6f4 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Mon, 20 Sep 2021 12:10:14 -0700 Subject: [PATCH 144/694] Update AidlConversion for AudioDevices Bug: 198812639 Test: m Change-Id: I68eb74872f88957672f89e05b212cb8044e71712 --- media/libaudioclient/AidlConversion.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 9928b7df81..eb8c03fa02 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -630,12 +630,12 @@ const detail::AudioDevicePairs& getAudioDevicePairs() { AudioDeviceType::IN_SUBMIX, AudioDeviceType::OUT_SUBMIX); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET, AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET, - AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_ANALOG_DOCK()); + AudioDeviceType::IN_DOCK, AudioDeviceType::OUT_DOCK, + AudioDeviceDescription::CONNECTION_ANALOG()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET, - AudioDeviceType::IN_HEADSET, AudioDeviceType::OUT_HEADSET, - AudioDeviceDescription::CONNECTION_DIGITAL_DOCK()); + AudioDeviceType::IN_DOCK, AudioDeviceType::OUT_DOCK, + AudioDeviceDescription::CONNECTION_USB()); append_AudioDeviceDescription(pairs, AUDIO_DEVICE_IN_USB_ACCESSORY, AUDIO_DEVICE_OUT_USB_ACCESSORY, AudioDeviceType::IN_ACCESSORY, AudioDeviceType::OUT_ACCESSORY, -- GitLab From dca60f36399e63c05e91943bf1611aa3da71593a Mon Sep 17 00:00:00 2001 From: Phil Burk Date: Tue, 21 Sep 2021 21:48:16 +0000 Subject: [PATCH 145/694] aaudio tests: fix test_attributes Remove illegal SYSTEM_USAGEs. Fix bad test variable. Bug: 200632807 Test: atest test_attributes Change-Id: Ia42d8778adeb44898d7756277948edb9bd36583b --- media/libaaudio/tests/test_attributes.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/media/libaaudio/tests/test_attributes.cpp b/media/libaaudio/tests/test_attributes.cpp index d540866c09..b88d5627ef 100644 --- a/media/libaaudio/tests/test_attributes.cpp +++ b/media/libaaudio/tests/test_attributes.cpp @@ -16,6 +16,10 @@ // Test AAudio attributes such as Usage, ContentType and InputPreset. +// TODO Many of these tests are duplicates of CTS tests in +// "test_aaudio_attributes.cpp". That other file is more current. +// So these tests could be deleted. + #include #include @@ -91,7 +95,7 @@ static void checkAttributes(aaudio_performance_mode_t perfMode, aaudio_allowed_capture_policy_t expectedCapturePolicy = (capturePolicy == DONT_SET || capturePolicy == AAUDIO_UNSPECIFIED) ? AAUDIO_ALLOW_CAPTURE_BY_ALL // default - : preset; + : capturePolicy; EXPECT_EQ(expectedCapturePolicy, AAudioStream_getAllowedCapturePolicy(aaudioStream)); bool expectedPrivacyMode = @@ -132,10 +136,7 @@ static const aaudio_usage_t sUsages[] = { AAUDIO_USAGE_ASSISTANCE_SONIFICATION, AAUDIO_USAGE_GAME, AAUDIO_USAGE_ASSISTANT, - AAUDIO_SYSTEM_USAGE_EMERGENCY, - AAUDIO_SYSTEM_USAGE_SAFETY, - AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS, - AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT + // Note that the AAUDIO_SYSTEM_USAGE_* values requires special permission. }; static const aaudio_content_type_t sContentypes[] = { -- GitLab From e504e7b785de72b27aa52fda7b4be4694aa57ff1 Mon Sep 17 00:00:00 2001 From: jiabin Date: Sat, 18 Sep 2021 00:27:08 +0000 Subject: [PATCH 146/694] Add HAL interface to replace aaudio system property. Using the HAL interface instead of reading system property is a better option when moving to AIDL HAL. The replaced property includes: - aaudio.mixer_bursts - aaudio.hw_burst_min_usec Test: atest AAudioTests Bug: 193275465 Change-Id: I9c9a04296e56ff083babcfa089fcdddc6b89ed94 --- .../src/client/AudioStreamInternal.cpp | 3 +- media/libaudioclient/AudioSystem.cpp | 16 +++++++++ media/libaudioclient/IAudioFlinger.cpp | 33 +++++++++++++++++++ .../android/media/IAudioFlingerService.aidl | 4 +++ .../include/media/AudioSystem.h | 4 +++ .../include/media/IAudioFlinger.h | 12 +++++++ media/libaudiohal/impl/DeviceHalHidl.h | 10 ++++++ media/libaudiohal/impl/DeviceHalLocal.h | 10 ++++++ .../media/audiohal/DeviceHalInterface.h | 2 ++ services/audioflinger/AudioFlinger.cpp | 33 +++++++++++++++++-- services/audioflinger/AudioFlinger.h | 6 ++++ services/audioflinger/AudioHwDevice.cpp | 8 +++++ services/audioflinger/AudioHwDevice.h | 4 +++ services/audioflinger/PropertyUtils.cpp | 24 ++++++++++++++ services/audioflinger/PropertyUtils.h | 4 +++ .../oboeservice/AAudioServiceEndpointPlay.cpp | 3 +- 16 files changed, 171 insertions(+), 5 deletions(-) diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp index 8284be5e12..efd6598df9 100644 --- a/media/libaaudio/src/client/AudioStreamInternal.cpp +++ b/media/libaaudio/src/client/AudioStreamInternal.cpp @@ -27,6 +27,7 @@ #include #include +#include #include #include @@ -95,7 +96,7 @@ aaudio_result_t AudioStreamInternal::open(const AudioStreamBuilder &builder) { return result; } - const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros(); + const int32_t burstMinMicros = android::AudioSystem::getAAudioHardwareBurstMinUsec(); int32_t burstMicros = 0; const audio_format_t requestedFormat = getFormat(); diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 17557e7896..317ad1e957 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -2367,6 +2367,22 @@ status_t AudioSystem::getMmapPolicyInfo( return af->getMmapPolicyInfos(policyType, policyInfos); } +int32_t AudioSystem::getAAudioMixerBurstCount() { + const sp& af = AudioSystem::get_audio_flinger(); + if (af == nullptr) { + return PERMISSION_DENIED; + } + return af->getAAudioMixerBurstCount(); +} + +int32_t AudioSystem::getAAudioHardwareBurstMinUsec() { + const sp& af = AudioSystem::get_audio_flinger(); + if (af == nullptr) { + return PERMISSION_DENIED; + } + return af->getAAudioHardwareBurstMinUsec(); +} + // --------------------------------------------------------------------------- int AudioSystem::AudioPolicyServiceClient::addAudioPortCallback( diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index e1e44fc228..d3098b8938 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -788,6 +788,27 @@ status_t AudioFlingerClientAdapter::getMmapPolicyInfos( return statusTFromBinderStatus(mDelegate->getMmapPolicyInfos(policyType, policyInfos)); } +int32_t AudioFlingerClientAdapter::getAAudioMixerBurstCount() { + auto result = [&]() -> ConversionResult { + int32_t aidlRet; + RETURN_IF_ERROR(statusTFromBinderStatus(mDelegate->getAAudioMixerBurstCount(&aidlRet))); + return convertIntegral(aidlRet); + }(); + // Failure is ignored. + return result.value_or(0); +} + +int32_t AudioFlingerClientAdapter::getAAudioHardwareBurstMinUsec() { + auto result = [&]() -> ConversionResult { + int32_t aidlRet; + RETURN_IF_ERROR(statusTFromBinderStatus( + mDelegate->getAAudioHardwareBurstMinUsec(&aidlRet))); + return convertIntegral(aidlRet); + }(); + // Failure is ignored. + return result.value_or(0); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // AudioFlingerServerAdapter @@ -1265,4 +1286,16 @@ Status AudioFlingerServerAdapter::getMmapPolicyInfos( return Status::fromStatusT(mDelegate->getMmapPolicyInfos(policyType, _aidl_return)); } +Status AudioFlingerServerAdapter::getAAudioMixerBurstCount(int32_t* _aidl_return) { + *_aidl_return = VALUE_OR_RETURN_BINDER( + convertIntegral(mDelegate->getAAudioMixerBurstCount())); + return Status::ok(); +} + +Status AudioFlingerServerAdapter::getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) { + *_aidl_return = VALUE_OR_RETURN_BINDER( + convertIntegral(mDelegate->getAAudioHardwareBurstMinUsec())); + return Status::ok(); +} + } // namespace android diff --git a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl index d8d40a984d..c55c66e4f8 100644 --- a/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioFlingerService.aidl @@ -221,4 +221,8 @@ interface IAudioFlingerService { in TrackSecondaryOutputInfo[] trackSecondaryOutputInfos); AudioMMapPolicyInfo[] getMmapPolicyInfos(AudioMMapPolicyType policyType); + + int getAAudioMixerBurstCount(); + + int getAAudioHardwareBurstMinUsec(); } diff --git a/media/libaudioclient/include/media/AudioSystem.h b/media/libaudioclient/include/media/AudioSystem.h index a4e2cc1a6b..45ee8bdae7 100644 --- a/media/libaudioclient/include/media/AudioSystem.h +++ b/media/libaudioclient/include/media/AudioSystem.h @@ -620,6 +620,10 @@ public: media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos); + static int32_t getAAudioMixerBurstCount(); + + static int32_t getAAudioHardwareBurstMinUsec(); + private: class AudioFlingerClient: public IBinder::DeathRecipient, public media::BnAudioFlingerClient diff --git a/media/libaudioclient/include/media/IAudioFlinger.h b/media/libaudioclient/include/media/IAudioFlinger.h index 9aacdf963a..485648d7ed 100644 --- a/media/libaudioclient/include/media/IAudioFlinger.h +++ b/media/libaudioclient/include/media/IAudioFlinger.h @@ -354,6 +354,10 @@ public: virtual status_t getMmapPolicyInfos( media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos) = 0; + + virtual int32_t getAAudioMixerBurstCount() = 0; + + virtual int32_t getAAudioHardwareBurstMinUsec() = 0; }; /** @@ -455,6 +459,10 @@ public: media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos) override; + int32_t getAAudioMixerBurstCount() override; + + int32_t getAAudioHardwareBurstMinUsec() override; + private: const sp mDelegate; }; @@ -540,6 +548,8 @@ public: SET_VIBRATOR_INFOS = media::BnAudioFlingerService::TRANSACTION_setVibratorInfos, UPDATE_SECONDARY_OUTPUTS = media::BnAudioFlingerService::TRANSACTION_updateSecondaryOutputs, GET_MMAP_POLICY_INFOS = media::BnAudioFlingerService::TRANSACTION_getMmapPolicyInfos, + GET_AAUDIO_MIXER_BURST_COUNT = media::BnAudioFlingerService::TRANSACTION_getAAudioMixerBurstCount, + GET_AAUDIO_HARDWARE_BURST_MIN_USEC = media::BnAudioFlingerService::TRANSACTION_getAAudioHardwareBurstMinUsec, }; /** @@ -657,6 +667,8 @@ public: Status getMmapPolicyInfos( media::audio::common::AudioMMapPolicyType policyType, std::vector *_aidl_return) override; + Status getAAudioMixerBurstCount(int32_t* _aidl_return) override; + Status getAAudioHardwareBurstMinUsec(int32_t* _aidl_return) override; private: const sp mDelegate; diff --git a/media/libaudiohal/impl/DeviceHalHidl.h b/media/libaudiohal/impl/DeviceHalHidl.h index 6065b40064..9fd0ac0059 100644 --- a/media/libaudiohal/impl/DeviceHalHidl.h +++ b/media/libaudiohal/impl/DeviceHalHidl.h @@ -126,6 +126,16 @@ class DeviceHalHidl : public DeviceHalInterface, public ConversionHelperHidl return INVALID_OPERATION; } + int32_t getAAudioMixerBurstCount() override { + // TODO: Implement the HAL query when moving to AIDL HAL. + return INVALID_OPERATION; + } + + int32_t getAAudioHardwareBurstMinUsec() override { + // TODO: Implement the HAL query when moving to AIDL HAL. + return INVALID_OPERATION; + } + status_t dump(int fd, const Vector& args) override; private: diff --git a/media/libaudiohal/impl/DeviceHalLocal.h b/media/libaudiohal/impl/DeviceHalLocal.h index 6bc7a8023d..ee1d2c561e 100644 --- a/media/libaudiohal/impl/DeviceHalLocal.h +++ b/media/libaudiohal/impl/DeviceHalLocal.h @@ -119,6 +119,16 @@ class DeviceHalLocal : public DeviceHalInterface return INVALID_OPERATION; } + int32_t getAAudioMixerBurstCount() override { + // This function will only be available on AIDL HAL. + return INVALID_OPERATION; + } + + int32_t getAAudioHardwareBurstMinUsec() override { + // This function will only be available on AIDL HAL. + return INVALID_OPERATION; + } + status_t dump(int fd, const Vector& args) override; void closeOutputStream(struct audio_stream_out *stream_out); diff --git a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h index 376f37bef9..70c3199901 100644 --- a/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h +++ b/media/libaudiohal/include/media/audiohal/DeviceHalInterface.h @@ -125,6 +125,8 @@ class DeviceHalInterface : public RefBase virtual status_t getMmapPolicyInfos( media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos) = 0; + virtual int32_t getAAudioMixerBurstCount() = 0; + virtual int32_t getAAudioHardwareBurstMinUsec() = 0; virtual status_t dump(int fd, const Vector& args) = 0; diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp index a75e4276b9..b359331e60 100644 --- a/services/audioflinger/AudioFlinger.cpp +++ b/services/audioflinger/AudioFlinger.cpp @@ -104,6 +104,8 @@ namespace android { +#define MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION 7.0 + using media::IEffectClient; using media::audio::common::AudioMMapPolicyInfo; using media::audio::common::AudioMMapPolicyType; @@ -304,6 +306,11 @@ void AudioFlinger::onFirstRef() mDevicesFactoryHalCallback = new DevicesFactoryHalCallbackImpl; mDevicesFactoryHal->setCallbackOnce(mDevicesFactoryHalCallback); + + if (mDevicesFactoryHal->getHalVersion() <= MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) { + mAAudioBurstsPerBuffer = getAAudioMixerBurstCountFromSystemProperty(); + mAAudioHwBurstMinMicros = getAAudioHardwareBurstMinUsecFromSystemProperty(); + } } status_t AudioFlinger::setAudioHalPids(const std::vector& pids) { @@ -339,15 +346,14 @@ status_t AudioFlinger::updateSecondaryOutputs( return NO_ERROR; } -#define MAX_MMAP_PROPERTY_DEVICE_HAL_VERSION 7.0 - status_t AudioFlinger::getMmapPolicyInfos( AudioMMapPolicyType policyType, std::vector *policyInfos) { + Mutex::Autolock _l(mLock); if (const auto it = mPolicyInfos.find(policyType); it != mPolicyInfos.end()) { *policyInfos = it->second; return NO_ERROR; } - if (mDevicesFactoryHal->getHalVersion() > MAX_MMAP_PROPERTY_DEVICE_HAL_VERSION) { + if (mDevicesFactoryHal->getHalVersion() > MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) { AutoMutex lock(mHardwareLock); for (size_t i = 0; i < mAudioHwDevs.size(); ++i) { AudioHwDevice *dev = mAudioHwDevs.valueAt(i); @@ -368,6 +374,16 @@ status_t AudioFlinger::getMmapPolicyInfos( return NO_ERROR; } +int32_t AudioFlinger::getAAudioMixerBurstCount() { + Mutex::Autolock _l(mLock); + return mAAudioBurstsPerBuffer; +} + +int32_t AudioFlinger::getAAudioHardwareBurstMinUsec() { + Mutex::Autolock _l(mLock); + return mAAudioHwBurstMinMicros; +} + // getDefaultVibratorInfo_l must be called with AudioFlinger lock held. std::optional AudioFlinger::getDefaultVibratorInfo_l() { if (mAudioVibratorInfos.empty()) { @@ -2322,6 +2338,17 @@ audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name) mHardwareStatus = AUDIO_HW_IDLE; } + if (mDevicesFactoryHal->getHalVersion() > MAX_AAUDIO_PROPERTY_DEVICE_HAL_VERSION) { + if (int32_t mixerBursts = dev->getAAudioMixerBurstCount(); + mixerBursts > mAAudioBurstsPerBuffer) { + mAAudioBurstsPerBuffer = mixerBursts; + } + if (int32_t hwBurstMinMicros = dev->getAAudioHardwareBurstMinUsec(); + hwBurstMinMicros < mAAudioHwBurstMinMicros || mAAudioHwBurstMinMicros == 0) { + mAAudioHwBurstMinMicros = hwBurstMinMicros; + } + } + mAudioHwDevs.add(handle, audioDevice); ALOGI("loadHwModule() Loaded %s audio interface, handle %d", name, handle); diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h index d0a9ea83df..8c546cc354 100644 --- a/services/audioflinger/AudioFlinger.h +++ b/services/audioflinger/AudioFlinger.h @@ -286,6 +286,10 @@ public: media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos); + virtual int32_t getAAudioMixerBurstCount(); + + virtual int32_t getAAudioHardwareBurstMinUsec(); + status_t onTransactWrapper(TransactionCode code, const Parcel& data, uint32_t flags, const std::function& delegate) override; @@ -1011,6 +1015,8 @@ private: std::map> mPolicyInfos; + int32_t mAAudioBurstsPerBuffer = 0; + int32_t mAAudioHwBurstMinMicros = 0; }; #undef INCLUDING_FROM_AUDIOFLINGER_H diff --git a/services/audioflinger/AudioHwDevice.cpp b/services/audioflinger/AudioHwDevice.cpp index 12f8272d7d..dee6161c3f 100644 --- a/services/audioflinger/AudioHwDevice.cpp +++ b/services/audioflinger/AudioHwDevice.cpp @@ -110,5 +110,13 @@ status_t AudioHwDevice::getMmapPolicyInfos( return mHwDevice->getMmapPolicyInfos(policyType, policyInfos); } +int32_t AudioHwDevice::getAAudioMixerBurstCount() const { + return mHwDevice->getAAudioMixerBurstCount(); +} + +int32_t AudioHwDevice::getAAudioHardwareBurstMinUsec() const { + return mHwDevice->getAAudioHardwareBurstMinUsec(); +} + }; // namespace android diff --git a/services/audioflinger/AudioHwDevice.h b/services/audioflinger/AudioHwDevice.h index 0715e55a20..8c5d239bcb 100644 --- a/services/audioflinger/AudioHwDevice.h +++ b/services/audioflinger/AudioHwDevice.h @@ -91,6 +91,10 @@ public: media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos) const; + int32_t getAAudioMixerBurstCount() const; + + int32_t getAAudioHardwareBurstMinUsec() const; + private: const audio_module_handle_t mHandle; const char * const mModuleName; diff --git a/services/audioflinger/PropertyUtils.cpp b/services/audioflinger/PropertyUtils.cpp index 341d5bb6a9..65e2533bc8 100644 --- a/services/audioflinger/PropertyUtils.cpp +++ b/services/audioflinger/PropertyUtils.cpp @@ -77,4 +77,28 @@ status_t getMmapPolicyInfosFromSystemProperty( return NO_ERROR; } +int32_t getAAudioMixerBurstCountFromSystemProperty() { + static const int32_t sDefaultBursts = 2; // arbitrary, use 2 for double buffered + static const int32_t sMaxBursts = 1024; // arbitrary + static const char* sPropMixerBursts = "aaudio.mixer_bursts"; + int32_t prop = property_get_int32(sPropMixerBursts, sDefaultBursts); + if (prop <= 0 || prop > sMaxBursts) { + ALOGE("%s: invalid value %d, use default %d", __func__, prop, sDefaultBursts); + prop = sDefaultBursts; + } + return prop; +} + +int32_t getAAudioHardwareBurstMinUsecFromSystemProperty() { + static const int32_t sDefaultMicros = 1000; // arbitrary + static const int32_t sMaxMicros = 1000 * 1000; // arbitrary + static const char* sPropHwBurstMinUsec = "aaudio.hw_burst_min_usec"; + int32_t prop = property_get_int32(sPropHwBurstMinUsec, sDefaultMicros); + if (prop <= 0 || prop > sMaxMicros) { + ALOGE("%s invalid value %d, use default %d", __func__, prop, sDefaultMicros); + prop = sDefaultMicros; + } + return prop; +} + } // namespace android diff --git a/services/audioflinger/PropertyUtils.h b/services/audioflinger/PropertyUtils.h index 3bb6fa2f3b..fbf651ae1f 100644 --- a/services/audioflinger/PropertyUtils.h +++ b/services/audioflinger/PropertyUtils.h @@ -25,4 +25,8 @@ status_t getMmapPolicyInfosFromSystemProperty( media::audio::common::AudioMMapPolicyType policyType, std::vector *policyInfos); +int32_t getAAudioMixerBurstCountFromSystemProperty(); + +int32_t getAAudioHardwareBurstMinUsecFromSystemProperty(); + } // namespace android diff --git a/services/oboeservice/AAudioServiceEndpointPlay.cpp b/services/oboeservice/AAudioServiceEndpointPlay.cpp index 4e46033171..f590fc8987 100644 --- a/services/oboeservice/AAudioServiceEndpointPlay.cpp +++ b/services/oboeservice/AAudioServiceEndpointPlay.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include "AAudioEndpointManager.h" @@ -51,7 +52,7 @@ aaudio_result_t AAudioServiceEndpointPlay::open(const aaudio::AAudioStreamReques mMixer.allocate(getStreamInternal()->getSamplesPerFrame(), getStreamInternal()->getFramesPerBurst()); - int32_t burstsPerBuffer = AAudioProperty_getMixerBursts(); + int32_t burstsPerBuffer = AudioSystem::getAAudioMixerBurstCount(); if (burstsPerBuffer == 0) { mLatencyTuningEnabled = true; burstsPerBuffer = BURSTS_PER_BUFFER_DEFAULT; -- GitLab From 637bd201585679aded3175b1c280b06e0173729f Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Wed, 22 Sep 2021 11:17:11 +0200 Subject: [PATCH 147/694] audio policy: update permission check for REMOTE_SUBMIX audio source. Do not request RECORD_AUDIO permission when capturing from audio source REMOTE_SUBMIX as this is not capturing from an actual microphone but from a redirection if the audio output instead. Now enforce either MODIFY_AUDIO_ROUTING (aligned with dynamic audio policy registration). Also fix a similar issue with audio source ECHO_REFERENCE where RECORD_AUDIO permission was requested in addition to CAPTURE_AUDIO_OUTPUT. Bug: 186581697 Test: GTS AudioCaptureTest#testFixedVolumeRemoteSubmixSetup, RemoteSubmixTest#testRecordFromRemoteSubmix, AudioPolicyTest Test: CTS AudioRecordTest#testRestrictedAudioSourcePermissions, NoCaptureAudioOutputPermissionTest#testCreateAudioRecord, AudioPlaybackCaptureTest Change-Id: Icfaa60af99bb5813ec4572e092c94a94090b7d8d --- .../MediaRecorderClient.cpp | 7 +++- .../service/AudioPolicyInterfaceImpl.cpp | 37 ++++++++++++------- .../service/AudioPolicyService.cpp | 1 + 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp index a914006294..4aa80beacf 100644 --- a/media/libmediaplayerservice/MediaRecorderClient.cpp +++ b/media/libmediaplayerservice/MediaRecorderClient.cpp @@ -126,8 +126,13 @@ status_t MediaRecorderClient::setAudioSource(int as) } if ((as == AUDIO_SOURCE_FM_TUNER - && !(captureAudioOutputAllowed(mAttributionSource) + && !(captureAudioOutputAllowed(mAttributionSource) || captureTunerAudioInputAllowed(mAttributionSource))) + || (as == AUDIO_SOURCE_REMOTE_SUBMIX + && !(captureAudioOutputAllowed(mAttributionSource) + || modifyAudioRoutingAllowed(mAttributionSource))) + || (as == AUDIO_SOURCE_ECHO_REFERENCE + && !captureAudioOutputAllowed(mAttributionSource)) || !recordingAllowed(mAttributionSource, (audio_source_t)as)) { return PERMISSION_DENIED; } diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index d01037d98d..23111e4c84 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -608,28 +608,35 @@ Status AudioPolicyService::getInputForAttr(const media::AudioAttributesInternal& adjAttributionSource))); // check calling permissions. - // Capturing from FM_TUNER source is controlled by captureTunerAudioInputAllowed() and - // captureAudioOutputAllowed() (deprecated) as this does not affect users privacy - // as does capturing from an actual microphone. - if (!(recordingAllowed(adjAttributionSource, attr.source) - || attr.source == AUDIO_SOURCE_FM_TUNER)) { + // Capturing from the following sources does not require permission RECORD_AUDIO + // as the captured audio does not come from a microphone: + // - FM_TUNER source is controlled by captureTunerAudioInputAllowed() or + // captureAudioOutputAllowed() (deprecated). + // - REMOTE_SUBMIX source is controlled by captureAudioOutputAllowed() if the input + // type is API_INPUT_MIX_EXT_POLICY_REROUTE and by AudioService if a media projection + // is used and input type is API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK + // - ECHO_REFERENCE source is controlled by captureAudioOutputAllowed() + if (!(recordingAllowed(adjAttributionSource, inputSource) + || inputSource == AUDIO_SOURCE_FM_TUNER + || inputSource == AUDIO_SOURCE_REMOTE_SUBMIX + || inputSource == AUDIO_SOURCE_ECHO_REFERENCE)) { ALOGE("%s permission denied: recording not allowed for %s", __func__, adjAttributionSource.toString().c_str()); return binderStatusFromStatusT(PERMISSION_DENIED); } bool canCaptureOutput = captureAudioOutputAllowed(adjAttributionSource); - if ((inputSource == AUDIO_SOURCE_VOICE_UPLINK || - inputSource == AUDIO_SOURCE_VOICE_DOWNLINK || - inputSource == AUDIO_SOURCE_VOICE_CALL || - inputSource == AUDIO_SOURCE_ECHO_REFERENCE) - && !canCaptureOutput) { + if ((inputSource == AUDIO_SOURCE_VOICE_UPLINK + || inputSource == AUDIO_SOURCE_VOICE_DOWNLINK + || inputSource == AUDIO_SOURCE_VOICE_CALL + || inputSource == AUDIO_SOURCE_ECHO_REFERENCE) + && !canCaptureOutput) { return binderStatusFromStatusT(PERMISSION_DENIED); } if (inputSource == AUDIO_SOURCE_FM_TUNER - && !captureTunerAudioInputAllowed(adjAttributionSource) - && !canCaptureOutput) { + && !canCaptureOutput + && !captureTunerAudioInputAllowed(adjAttributionSource)) { return binderStatusFromStatusT(PERMISSION_DENIED); } @@ -757,8 +764,10 @@ Status AudioPolicyService::startInput(int32_t portIdAidl) // check calling permissions if (!(startRecording(client->attributionSource, String16(msg.str().c_str()), - client->attributes.source) - || client->attributes.source == AUDIO_SOURCE_FM_TUNER)) { + client->attributes.source) + || client->attributes.source == AUDIO_SOURCE_FM_TUNER + || client->attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX + || client->attributes.source == AUDIO_SOURCE_ECHO_REFERENCE)) { ALOGE("%s permission denied: recording not allowed for attribution source %s", __func__, client->attributionSource.toString().c_str()); return binderStatusFromStatusT(PERMISSION_DENIED); diff --git a/services/audiopolicy/service/AudioPolicyService.cpp b/services/audiopolicy/service/AudioPolicyService.cpp index c21be1ede3..d0efac0fba 100644 --- a/services/audiopolicy/service/AudioPolicyService.cpp +++ b/services/audiopolicy/service/AudioPolicyService.cpp @@ -904,6 +904,7 @@ bool AudioPolicyService::isAppOpSource(audio_source_t source) switch (source) { case AUDIO_SOURCE_FM_TUNER: case AUDIO_SOURCE_ECHO_REFERENCE: + case AUDIO_SOURCE_REMOTE_SUBMIX: return false; default: break; -- GitLab From a16785fda4f699cc7168e318cc440eaaafde8ccc Mon Sep 17 00:00:00 2001 From: Gopalakrishnan Nallasamy Date: Sat, 18 Sep 2021 06:52:23 -0700 Subject: [PATCH 148/694] FrameDecoder:Handle grid vars multiply overflow Potential integer overflow on Grid variable is handled using builtin multiply overflow macros, appropriate log printed and value returned. Bug: 180200830 Test: atest android.media.cts.MediaMetadataRetrieverTest Change-Id: Ia570d0222ea1d97f232aa2ffc2bd50b56c5e794c --- media/libstagefright/FrameDecoder.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/media/libstagefright/FrameDecoder.cpp b/media/libstagefright/FrameDecoder.cpp index 94a0424e39..6e55f079c7 100644 --- a/media/libstagefright/FrameDecoder.cpp +++ b/media/libstagefright/FrameDecoder.cpp @@ -793,8 +793,16 @@ sp MediaImageDecoder::onGetFormatAndSeekOptions( if (overrideMeta == NULL) { // check if we're dealing with a tiled heif int32_t tileWidth, tileHeight, gridRows, gridCols; + int32_t widthColsProduct = 0; + int32_t heightRowsProduct = 0; if (findGridInfo(trackMeta(), &tileWidth, &tileHeight, &gridRows, &gridCols)) { - if (mWidth <= tileWidth * gridCols && mHeight <= tileHeight * gridRows) { + if (__builtin_mul_overflow(tileWidth, gridCols, &widthColsProduct) || + __builtin_mul_overflow(tileHeight, gridRows, &heightRowsProduct)) { + ALOGE("Multiplication overflowed Grid size: %dx%d, Picture size: %dx%d", + gridCols, gridRows, tileWidth, tileHeight); + return nullptr; + } + if (mWidth <= widthColsProduct && mHeight <= heightRowsProduct) { ALOGV("grid: %dx%d, tile size: %dx%d, picture size: %dx%d", gridCols, gridRows, tileWidth, tileHeight, mWidth, mHeight); -- GitLab From c4d2cfee72e5da66f8531ecfd5d1f61186eb4400 Mon Sep 17 00:00:00 2001 From: jiabin Date: Thu, 23 Sep 2021 21:11:54 +0000 Subject: [PATCH 149/694] Remove unnecessary property query. With adding HAL interface to replace aaudio system property, the functions of querying system property is useless. The removed functions include: - AAudioProperty_getMMapPolicy - AAudioProperty_getMMapExclusivePolicy - AAudioProperty_getMixerBursts - AAudioProperty_getHardwareBurstMinMicros Test: atest AAudioTests Bug: 193275465 Change-Id: Ia7b6c8bc00498c87d68307657761753e0c383b57 --- .../libaaudio/src/utility/AAudioUtilities.cpp | 51 ------------------- media/libaaudio/src/utility/AAudioUtilities.h | 34 ------------- 2 files changed, 85 deletions(-) diff --git a/media/libaaudio/src/utility/AAudioUtilities.cpp b/media/libaaudio/src/utility/AAudioUtilities.cpp index e44cceec22..a0952fed6a 100644 --- a/media/libaaudio/src/utility/AAudioUtilities.cpp +++ b/media/libaaudio/src/utility/AAudioUtilities.cpp @@ -544,45 +544,6 @@ int32_t AAudioConvert_framesToBytes(int32_t numFrames, return AAUDIO_OK; } -static int32_t AAudioProperty_getMMapProperty(const char *propName, - int32_t defaultValue, - const char * caller) { - int32_t prop = property_get_int32(propName, defaultValue); - switch (prop) { - case AAUDIO_UNSPECIFIED: - case AAUDIO_POLICY_NEVER: - case AAUDIO_POLICY_ALWAYS: - case AAUDIO_POLICY_AUTO: - break; - default: - ALOGE("%s: invalid = %d", caller, prop); - prop = defaultValue; - break; - } - return prop; -} - -int32_t AAudioProperty_getMMapPolicy() { - return AAudioProperty_getMMapProperty(AAUDIO_PROP_MMAP_POLICY, - AAUDIO_UNSPECIFIED, __func__); -} - -int32_t AAudioProperty_getMMapExclusivePolicy() { - return AAudioProperty_getMMapProperty(AAUDIO_PROP_MMAP_EXCLUSIVE_POLICY, - AAUDIO_UNSPECIFIED, __func__); -} - -int32_t AAudioProperty_getMixerBursts() { - const int32_t defaultBursts = 2; // arbitrary, use 2 for double buffered - const int32_t maxBursts = 1024; // arbitrary - int32_t prop = property_get_int32(AAUDIO_PROP_MIXER_BURSTS, defaultBursts); - if (prop < 1 || prop > maxBursts) { - ALOGE("AAudioProperty_getMixerBursts: invalid = %d", prop); - prop = defaultBursts; - } - return prop; -} - int32_t AAudioProperty_getWakeupDelayMicros() { const int32_t minMicros = 0; // arbitrary const int32_t defaultMicros = 200; // arbitrary, based on some observed jitter @@ -613,18 +574,6 @@ int32_t AAudioProperty_getMinimumSleepMicros() { return prop; } -int32_t AAudioProperty_getHardwareBurstMinMicros() { - const int32_t defaultMicros = 1000; // arbitrary - const int32_t maxMicros = 1000 * 1000; // arbitrary - int32_t prop = property_get_int32(AAUDIO_PROP_HW_BURST_MIN_USEC, defaultMicros); - if (prop < 1 || prop > maxMicros) { - ALOGE("AAudioProperty_getHardwareBurstMinMicros: invalid = %d, use %d", - prop, defaultMicros); - prop = defaultMicros; - } - return prop; -} - static int32_t AAudioProperty_getMMapOffsetMicros(const char *functionName, const char *propertyName) { const int32_t minMicros = -20000; // arbitrary diff --git a/media/libaaudio/src/utility/AAudioUtilities.h b/media/libaaudio/src/utility/AAudioUtilities.h index 4a6e05d03c..b59ce1cd87 100644 --- a/media/libaaudio/src/utility/AAudioUtilities.h +++ b/media/libaaudio/src/utility/AAudioUtilities.h @@ -127,27 +127,6 @@ audio_channel_mask_t AAudio_getChannelMaskForOpen( // Note that this code may be replaced by Settings or by some other system configuration tool. -/** - * Read system property. - * @return AAUDIO_UNSPECIFIED, AAUDIO_POLICY_NEVER or AAUDIO_POLICY_AUTO or AAUDIO_POLICY_ALWAYS - */ -int32_t AAudioProperty_getMMapPolicy(); -#define AAUDIO_PROP_MMAP_POLICY "aaudio.mmap_policy" - -/** - * Read system property. - * @return AAUDIO_UNSPECIFIED, AAUDIO_POLICY_NEVER or AAUDIO_POLICY_AUTO or AAUDIO_POLICY_ALWAYS - */ -int32_t AAudioProperty_getMMapExclusivePolicy(); -#define AAUDIO_PROP_MMAP_EXCLUSIVE_POLICY "aaudio.mmap_exclusive_policy" - -/** - * Read system property. - * @return number of bursts per AAudio service mixer cycle - */ -int32_t AAudioProperty_getMixerBursts(); -#define AAUDIO_PROP_MIXER_BURSTS "aaudio.mixer_bursts" - /** * Read a system property that specifies the number of extra microseconds that a thread * should sleep when waiting for another thread to service a FIFO. This is used @@ -168,19 +147,6 @@ int32_t AAudioProperty_getWakeupDelayMicros(); int32_t AAudioProperty_getMinimumSleepMicros(); #define AAUDIO_PROP_MINIMUM_SLEEP_USEC "aaudio.minimum_sleep_usec" -/** - * Read system property. - * This is handy in case the DMA is bursting too quickly for the CPU to keep up. - * For example, there may be a DMA burst every 100 usec but you only - * want to feed the MMAP buffer every 2000 usec. - * - * This will affect the framesPerBurst for an MMAP stream. - * - * @return minimum number of microseconds for a MMAP HW burst - */ -int32_t AAudioProperty_getHardwareBurstMinMicros(); -#define AAUDIO_PROP_HW_BURST_MIN_USEC "aaudio.hw_burst_min_usec" - /** * Read a system property that specifies an offset that will be added to MMAP timestamps. * This can be used to correct bias in the timestamp. -- GitLab From 443d5f10e3e8bf19e7feee5c6b5e282e34ea7a14 Mon Sep 17 00:00:00 2001 From: Jayant Chowdhary Date: Fri, 24 Sep 2021 13:13:59 -0700 Subject: [PATCH 150/694] Add arakesh@ to camera framework OWNERS. Test: N/A Change-Id: Ib5cb54e28064a95a4573da44f13d6f6c6e4d5778 Signed-off-by: Jayant Chowdhary --- camera/OWNERS | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/camera/OWNERS b/camera/OWNERS index 47d1d19b02..a4ab616c14 100644 --- a/camera/OWNERS +++ b/camera/OWNERS @@ -1,8 +1,8 @@ + +# Bug component: 41727 +arakesh@google.com epeev@google.com etalvala@google.com jchowdhary@google.com shuzhenwang@google.com ruchamk@google.com -# backup owner -cychen@google.com -zhijunhe@google.com -- GitLab From 89818ba4747263dbe86ca86bf9eb997e04bb0da4 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 21 Sep 2021 20:37:13 +0000 Subject: [PATCH 151/694] Split AudioProfile between fwk and android.media.audio.common a.m.a.c adds a version of AudioProfile struct which is similar to Audio HIDL HAL V7. It lacks some bits used only by the framework. These are carried in AudioProfileSys. AudioProfileSys does not contain AudioProfile. This is done to simplify further splitting of other types like AudioPort. Updated to/from AIDL conversions in libaudiofondation. They encapsulate the fact that there are two AIDL structures per AudioProfile class instance. Bug: 198812639 Test: atest audiofoundation_parcelable_test Change-Id: I6834650f9406c552b6dfa42b120769eb38d6f588 --- media/libaudioclient/AidlConversion.cpp | 18 +++--- media/libaudioclient/Android.bp | 2 +- .../aidl/android/media/AudioPort.aidl | 5 +- ...AudioProfile.aidl => AudioProfileSys.aidl} | 16 ++---- .../include/media/AidlConversion.h | 7 ++- .../include/media/AidlConversionUtil.h | 41 ++++++++++++++ media/libaudiofoundation/AudioPort.cpp | 8 ++- media/libaudiofoundation/AudioProfile.cpp | 55 +++++++++++-------- .../include/media/AudioProfile.h | 22 +++++--- .../tests/audiofoundation_parcelable_test.cpp | 18 ++++++ 10 files changed, 135 insertions(+), 57 deletions(-) rename media/libaudioclient/aidl/android/media/{AudioProfile.aidl => AudioProfileSys.aidl} (62%) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index eb8c03fa02..ed9268113a 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -49,6 +49,7 @@ using media::audio::common::AudioFormatDescription; using media::audio::common::AudioFormatType; using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioProfile; using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; @@ -2743,17 +2744,17 @@ ConversionResult legacy2aidl_AudioPortExt( } ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput) { +aidl2legacy_AudioProfile_audio_profile(const AudioProfile& aidl, bool isInput) { audio_profile legacy; legacy.format = VALUE_OR_RETURN(aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); - if (aidl.samplingRates.size() > std::size(legacy.sample_rates)) { + if (aidl.sampleRates.size() > std::size(legacy.sample_rates)) { return unexpected(BAD_VALUE); } RETURN_IF_ERROR( - convertRange(aidl.samplingRates.begin(), aidl.samplingRates.end(), legacy.sample_rates, + convertRange(aidl.sampleRates.begin(), aidl.sampleRates.end(), legacy.sample_rates, convertIntegral)); - legacy.num_sample_rates = aidl.samplingRates.size(); + legacy.num_sample_rates = aidl.sampleRates.size(); if (aidl.channelMasks.size() > std::size(legacy.channel_masks)) { return unexpected(BAD_VALUE); @@ -2770,9 +2771,9 @@ aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isI return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput) { - media::AudioProfile aidl; + AudioProfile aidl; aidl.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); if (legacy.num_sample_rates > std::size(legacy.sample_rates)) { @@ -2780,7 +2781,7 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput } RETURN_IF_ERROR( convertRange(legacy.sample_rates, legacy.sample_rates + legacy.num_sample_rates, - std::back_inserter(aidl.samplingRates), + std::back_inserter(aidl.sampleRates), convertIntegral)); if (legacy.num_channel_masks > std::size(legacy.channel_masks)) { @@ -2843,7 +2844,7 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { } const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; RETURN_IF_ERROR(convertRange(aidl.profiles.begin(), aidl.profiles.end(), legacy.audio_profiles, - [isInput](const media::AudioProfile& p) { + [isInput](const AudioProfile& p) { return aidl2legacy_AudioProfile_audio_profile(p, isInput); })); legacy.num_audio_profiles = aidl.profiles.size(); @@ -2892,6 +2893,7 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { if (legacy.num_extra_audio_descriptors > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); } + aidl.profilesSys.resize(legacy.num_audio_profiles); RETURN_IF_ERROR( convertRange(legacy.extra_audio_descriptors, legacy.extra_audio_descriptors + legacy.num_extra_audio_descriptors, diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 4cb531a4d1..f150d88253 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -339,7 +339,7 @@ aidl_interface { "aidl/android/media/AudioPortRole.aidl", "aidl/android/media/AudioPortSessionExt.aidl", "aidl/android/media/AudioPortType.aidl", - "aidl/android/media/AudioProfile.aidl", + "aidl/android/media/AudioProfileSys.aidl", "aidl/android/media/AudioStandard.aidl", "aidl/android/media/AudioTimestampInternal.aidl", "aidl/android/media/AudioUniqueIdUse.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioPort.aidl b/media/libaudioclient/aidl/android/media/AudioPort.aidl index bf0e5b792c..0f98ea18bf 100644 --- a/media/libaudioclient/aidl/android/media/AudioPort.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPort.aidl @@ -21,8 +21,9 @@ import android.media.AudioPortConfig; import android.media.AudioPortExt; import android.media.AudioPortRole; import android.media.AudioPortType; -import android.media.AudioProfile; +import android.media.AudioProfileSys; import android.media.ExtraAudioDescriptor; +import android.media.audio.common.AudioProfile; /** * {@hide} @@ -37,6 +38,8 @@ parcelable AudioPort { @utf8InCpp String name; /** AudioProfiles supported by this port (format, Rates, Channels). */ AudioProfile[] profiles; + /** System-only parameters for each AudioProfile. */ + AudioProfileSys[] profilesSys; /** * ExtraAudioDescriptors supported by this port. The format is not unrecognized to the * platform. The audio capability is described by a hardware descriptor. diff --git a/media/libaudioclient/aidl/android/media/AudioProfile.aidl b/media/libaudioclient/aidl/android/media/AudioProfileSys.aidl similarity index 62% rename from media/libaudioclient/aidl/android/media/AudioProfile.aidl rename to media/libaudioclient/aidl/android/media/AudioProfileSys.aidl index 9378ab39b6..329c9d56b6 100644 --- a/media/libaudioclient/aidl/android/media/AudioProfile.aidl +++ b/media/libaudioclient/aidl/android/media/AudioProfileSys.aidl @@ -16,21 +16,15 @@ package android.media; -import android.media.audio.common.AudioEncapsulationType; -import android.media.audio.common.AudioFormatDescription; -import android.media.audio.common.AudioChannelLayout; - /** + * Provides indication whether the parameters of the AudioProfiles in the + * AudioPort are dynamic. Each instance of AudioProfileSys corresponds + * to an instance of AudioProfile. + * * {@hide} */ -parcelable AudioProfile { - @utf8InCpp String name; - /** The format for an audio profile should only be set when initialized. */ - AudioFormatDescription format; - AudioChannelLayout[] channelMasks; - int[] samplingRates; +parcelable AudioProfileSys { boolean isDynamicFormat; boolean isDynamicChannels; boolean isDynamicRate; - AudioEncapsulationType encapsulationType; } diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 3bdd11c1d6..1afb2c5ee1 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -39,7 +39,6 @@ #include #include #include -#include #include #include #include @@ -56,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -372,8 +372,9 @@ ConversionResult legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy); ConversionResult -aidl2legacy_AudioProfile_audio_profile(const media::AudioProfile& aidl, bool isInput); -ConversionResult +aidl2legacy_AudioProfile_audio_profile( + const media::audio::common::AudioProfile& aidl, bool isInput); +ConversionResult legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput); ConversionResult diff --git a/media/libaudioclient/include/media/AidlConversionUtil.h b/media/libaudioclient/include/media/AidlConversionUtil.h index c1a2be33fc..f9446adc0a 100644 --- a/media/libaudioclient/include/media/AidlConversionUtil.h +++ b/media/libaudioclient/include/media/AidlConversionUtil.h @@ -119,6 +119,47 @@ convertContainer(const InputContainer& input, const Func& itemConversion) { return output; } +/** + * A generic template that helps to "zip" two input containers of the same size + * into a single vector of converted types. The conversion function must + * thus accept two arguments. + */ +template +ConversionResult +convertContainers(const InputContainer1& input1, const InputContainer2& input2, + const Func& itemConversion) { + auto iter2 = input2.begin(); + OutputContainer output; + auto ins = std::inserter(output, output.begin()); + for (const auto& item1 : input1) { + RETURN_IF_ERROR(iter2 != input2.end() ? OK : BAD_VALUE); + *ins = VALUE_OR_RETURN(itemConversion(item1, *iter2++)); + } + return output; +} + +/** + * A generic template that helps to "unzip" a per-element conversion into + * a pair of elements into a pair of containers. The conversion function + * must emit a pair of elements. + */ +template +ConversionResult> +convertContainerSplit(const InputContainer& input, const Func& itemConversion) { + OutputContainer1 output1; + OutputContainer2 output2; + auto ins1 = std::inserter(output1, output1.begin()); + auto ins2 = std::inserter(output2, output2.begin()); + for (const auto& item : input) { + auto out_pair = VALUE_OR_RETURN(itemConversion(item)); + *ins1 = out_pair.first; + *ins2 = out_pair.second; + } + return std::make_pair(output1, output2); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // The code below establishes: // IntegralTypeOf, which works for either integral types (in which case it evaluates to T), or diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index c70a6c2f8b..74c9b10113 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -210,8 +210,10 @@ status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { parcelable->name = mName; parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); - parcelable->profiles = VALUE_OR_RETURN_STATUS( + auto aidl = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); + parcelable->profiles = aidl.first; + parcelable->profilesSys = aidl.second; parcelable->extraAudioDescriptors = mExtraAudioDescriptors; parcelable->gains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); return OK; @@ -228,7 +230,9 @@ status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { mType = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortType_audio_port_type_t(parcelable.type)); mRole = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.role)); mProfiles = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioProfileVector(parcelable.profiles, useInputChannelMask())); + aidl2legacy_AudioProfileVector( + std::make_pair(parcelable.profiles, parcelable.profilesSys), + useInputChannelMask())); mExtraAudioDescriptors = parcelable.extraAudioDescriptors; mGains = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioGains(parcelable.gains)); return OK; diff --git a/media/libaudiofoundation/AudioProfile.cpp b/media/libaudiofoundation/AudioProfile.cpp index 2d44f4a0c6..15f2d68b4f 100644 --- a/media/libaudiofoundation/AudioProfile.cpp +++ b/media/libaudiofoundation/AudioProfile.cpp @@ -156,31 +156,38 @@ AudioProfile& AudioProfile::operator=(const AudioProfile& other) { return *this; } -ConversionResult +ConversionResult AudioProfile::toParcelable(bool isInput) const { - media::AudioProfile parcelable; + media::audio::common::AudioProfile parcelable; parcelable.name = mName; - parcelable.format = VALUE_OR_RETURN(legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); + parcelable.format = VALUE_OR_RETURN( + legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); + // Note: legacy 'audio_profile' imposes a limit on the number of + // channel masks and sampling rates. That's why it's not used here + // and conversions are performed directly on the fields instead + // of using 'legacy2aidl_audio_profile_AudioProfile' from AidlConversion. parcelable.channelMasks = VALUE_OR_RETURN( convertContainer>( mChannelMasks, [isInput](audio_channel_mask_t m) { return legacy2aidl_audio_channel_mask_t_AudioChannelLayout(m, isInput); })); - parcelable.samplingRates = VALUE_OR_RETURN( + parcelable.sampleRates = VALUE_OR_RETURN( convertContainer>(mSamplingRates, convertIntegral)); - parcelable.isDynamicFormat = mIsDynamicFormat; - parcelable.isDynamicChannels = mIsDynamicChannels; - parcelable.isDynamicRate = mIsDynamicRate; parcelable.encapsulationType = VALUE_OR_RETURN( legacy2aidl_audio_encapsulation_type_t_AudioEncapsulationType(mEncapsulationType)); - return parcelable; + media::AudioProfileSys parcelableSys; + parcelableSys.isDynamicFormat = mIsDynamicFormat; + parcelableSys.isDynamicChannels = mIsDynamicChannels; + parcelableSys.isDynamicRate = mIsDynamicRate; + return std::make_pair(parcelable, parcelableSys); } -ConversionResult> -AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput) { +ConversionResult> AudioProfile::fromParcelable( + const AudioProfile::Aidl& aidl, bool isInput) { sp legacy = new AudioProfile(); + const auto& parcelable = aidl.first; legacy->mName = parcelable.name; legacy->mFormat = VALUE_OR_RETURN( aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); @@ -190,23 +197,24 @@ AudioProfile::fromParcelable(const media::AudioProfile& parcelable, bool isInput return aidl2legacy_AudioChannelLayout_audio_channel_mask_t(l, isInput); })); legacy->mSamplingRates = VALUE_OR_RETURN( - convertContainer(parcelable.samplingRates, + convertContainer(parcelable.sampleRates, convertIntegral)); - legacy->mIsDynamicFormat = parcelable.isDynamicFormat; - legacy->mIsDynamicChannels = parcelable.isDynamicChannels; - legacy->mIsDynamicRate = parcelable.isDynamicRate; legacy->mEncapsulationType = VALUE_OR_RETURN( aidl2legacy_AudioEncapsulationType_audio_encapsulation_type_t( parcelable.encapsulationType)); + const auto& parcelableSys = aidl.second; + legacy->mIsDynamicFormat = parcelableSys.isDynamicFormat; + legacy->mIsDynamicChannels = parcelableSys.isDynamicChannels; + legacy->mIsDynamicRate = parcelableSys.isDynamicRate; return legacy; } ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput) { +aidl2legacy_AudioProfile(const AudioProfile::Aidl& aidl, bool isInput) { return AudioProfile::fromParcelable(aidl, isInput); } -ConversionResult +ConversionResult legacy2aidl_AudioProfile(const sp& legacy, bool isInput) { return legacy->toParcelable(isInput); } @@ -331,16 +339,19 @@ bool AudioProfileVector::equals(const AudioProfileVector& other) const } ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput) { - return convertContainer(aidl, - [isInput](const media::AudioProfile& p) { - return aidl2legacy_AudioProfile(p, isInput); +aidl2legacy_AudioProfileVector(const AudioProfileVector::Aidl& aidl, bool isInput) { + return convertContainers(aidl.first, aidl.second, + [isInput](const media::audio::common::AudioProfile& p, + const media::AudioProfileSys& ps) { + return aidl2legacy_AudioProfile(std::make_pair(p, ps), isInput); }); } -ConversionResult> +ConversionResult legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput) { - return convertContainer>(legacy, + return convertContainerSplit< + std::vector, + std::vector>(legacy, [isInput](const sp& p) { return legacy2aidl_AudioProfile(p, isInput); }); diff --git a/media/libaudiofoundation/include/media/AudioProfile.h b/media/libaudiofoundation/include/media/AudioProfile.h index e34a49f32b..62670e4c57 100644 --- a/media/libaudiofoundation/include/media/AudioProfile.h +++ b/media/libaudiofoundation/include/media/AudioProfile.h @@ -17,11 +17,10 @@ #pragma once #include +#include #include -#include -#include -#include +#include #include #include #include @@ -81,9 +80,10 @@ public: bool equals(const sp& other) const; - ConversionResult toParcelable(bool isInput) const; + using Aidl = std::pair; + ConversionResult toParcelable(bool isInput) const; static ConversionResult> fromParcelable( - const media::AudioProfile& parcelable, bool isInput); + const Aidl& aidl, bool isInput); private: @@ -104,8 +104,8 @@ private: // Conversion routines, according to AidlConversion.h conventions. ConversionResult> -aidl2legacy_AudioProfile(const media::AudioProfile& aidl, bool isInput); -ConversionResult +aidl2legacy_AudioProfile(const AudioProfile::Aidl& aidl, bool isInput); +ConversionResult legacy2aidl_AudioProfile(const sp& legacy, bool isInput); class AudioProfileVector : public std::vector> @@ -134,14 +134,18 @@ public: virtual void dump(std::string *dst, int spaces) const; bool equals(const AudioProfileVector& other) const; + + using Aidl = std::pair< + std::vector, + std::vector>; }; bool operator == (const AudioProfile &left, const AudioProfile &right); // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioProfileVector(const std::vector& aidl, bool isInput); -ConversionResult> +aidl2legacy_AudioProfileVector(const AudioProfileVector::Aidl& aidl, bool isInput); +ConversionResult legacy2aidl_AudioProfileVector(const AudioProfileVector& legacy, bool isInput); AudioProfileVector intersectAudioProfiles(const AudioProfileVector& profiles1, diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 169698042a..abafff1168 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -75,6 +75,24 @@ AudioProfileVector getAudioProfileVectorForTest() { return audioProfiles; } +TEST(AudioFoundationParcelableTest, ParcelingAudioProfile) { + sp profile = getAudioProfileVectorForTest()[0]; + auto conv = legacy2aidl_AudioProfile(profile, false /*isInput*/); + ASSERT_TRUE(conv.ok()); + auto convBack = aidl2legacy_AudioProfile(conv.value(), false /*isInput*/); + ASSERT_TRUE(convBack.ok()); + ASSERT_TRUE(profile->equals(convBack.value())); +} + +TEST(AudioFoundationParcelableTest, ParcelingAudioProfileVector) { + AudioProfileVector profiles = getAudioProfileVectorForTest(); + auto conv = legacy2aidl_AudioProfileVector(profiles, false /*isInput*/); + ASSERT_TRUE(conv.ok()); + auto convBack = aidl2legacy_AudioProfileVector(conv.value(), false /*isInput*/); + ASSERT_TRUE(convBack.ok()); + ASSERT_TRUE(profiles.equals(convBack.value())); +} + TEST(AudioFoundationParcelableTest, ParcelingAudioGain) { Parcel data; AudioGains audioGains = getAudioGainsForTest(); -- GitLab From 7d0b36bf54a5d83be6e744864e87049072546165 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 22 Sep 2021 23:58:41 +0000 Subject: [PATCH 152/694] Split AudioGain* between fwk and android.media.audio.common AudioGainMode and AudioGainConfig are moved as is. The version of AudioGain in a.m.a.c is similar to the one from Audio HIDL HAL V7. It lacks some bits used only by the framework. These are carried in AudioGainSys. AudioGainSys does not contain AudioGain. This is done to simplify further splitting of other types like AudioPort. Updated to/from AIDL conversions in libaudiofondation. They encapsulate the fact that there are two AIDL structures per AudioGain class instance. The AudioGain class is simplified by stripping off no more required implementation of Parcelable, and reusing conversion functions from AidlConversion. Bug: 198812639 Test: atest audiofoundation_parcelable_test Change-Id: Ic8fa34f6d873e026c785497bb48c4a12fa90a442 --- media/libaudioclient/AidlConversion.cpp | 51 ++++--- media/libaudioclient/Android.bp | 4 +- .../aidl/android/media/AudioGain.aidl | 37 ----- .../aidl/android/media/AudioGainConfig.aidl | 45 ------ .../{AudioGainMode.aidl => AudioGainSys.aidl} | 12 +- .../aidl/android/media/AudioPort.aidl | 5 +- .../aidl/android/media/AudioPortConfig.aidl | 4 +- .../include/media/AidlConversion.h | 20 +-- media/libaudiofoundation/AudioGain.cpp | 128 +++++------------- media/libaudiofoundation/AudioPort.cpp | 13 +- .../include/media/AudioGain.h | 41 +++--- .../tests/audiofoundation_parcelable_test.cpp | 21 ++- 12 files changed, 129 insertions(+), 252 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioGain.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioGainConfig.aidl rename media/libaudioclient/aidl/android/media/{AudioGainMode.aidl => AudioGainSys.aidl} (79%) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index ed9268113a..7ee78e0529 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -47,6 +47,9 @@ using media::audio::common::AudioEncapsulationMode; using media::audio::common::AudioEncapsulationType; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioFormatType; +using media::audio::common::AudioGain; +using media::audio::common::AudioGainConfig; +using media::audio::common::AudioGainMode; using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; using media::audio::common::AudioProfile; @@ -1241,57 +1244,59 @@ ConversionResult legacy2aidl_audio_format_t_AudioFormatD } } -ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl) { +ConversionResult aidl2legacy_AudioGainMode_audio_gain_mode_t( + AudioGainMode aidl) { switch (aidl) { - case media::AudioGainMode::JOINT: + case AudioGainMode::JOINT: return AUDIO_GAIN_MODE_JOINT; - case media::AudioGainMode::CHANNELS: + case AudioGainMode::CHANNELS: return AUDIO_GAIN_MODE_CHANNELS; - case media::AudioGainMode::RAMP: + case AudioGainMode::RAMP: return AUDIO_GAIN_MODE_RAMP; } return unexpected(BAD_VALUE); } -ConversionResult legacy2aidl_audio_gain_mode_t_AudioGainMode(audio_gain_mode_t legacy) { +ConversionResult legacy2aidl_audio_gain_mode_t_AudioGainMode( + audio_gain_mode_t legacy) { switch (legacy) { case AUDIO_GAIN_MODE_JOINT: - return media::AudioGainMode::JOINT; + return AudioGainMode::JOINT; case AUDIO_GAIN_MODE_CHANNELS: - return media::AudioGainMode::CHANNELS; + return AudioGainMode::CHANNELS; case AUDIO_GAIN_MODE_RAMP: - return media::AudioGainMode::RAMP; + return AudioGainMode::RAMP; } return unexpected(BAD_VALUE); } ConversionResult aidl2legacy_int32_t_audio_gain_mode_t_mask(int32_t aidl) { - return convertBitmask( + return convertBitmask( aidl, aidl2legacy_AudioGainMode_audio_gain_mode_t, // AudioGainMode is index-based. - indexToEnum_index, + indexToEnum_index, // AUDIO_GAIN_MODE_* constants are mask-based. enumToMask_bitmask); } ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_mode_t legacy) { - return convertBitmask( + return convertBitmask( legacy, legacy2aidl_audio_gain_mode_t_AudioGainMode, // AUDIO_GAIN_MODE_* constants are mask-based. indexToEnum_bitmask, // AudioGainMode is index-based. - enumToMask_index); + enumToMask_index); } ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( - const media::AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type) { + const AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type) { audio_gain_config legacy; legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); - const bool isJoint = bitmaskIsSet(aidl.mode, media::AudioGainMode::JOINT); + const bool isJoint = bitmaskIsSet(aidl.mode, AudioGainMode::JOINT); size_t numValues = isJoint ? 1 : isInput ? audio_channel_count_from_in_mask(legacy.channel_mask) : audio_channel_count_from_out_mask(legacy.channel_mask); @@ -1305,9 +1310,9 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi return legacy; } -ConversionResult legacy2aidl_audio_gain_config_AudioGainConfig( +ConversionResult legacy2aidl_audio_gain_config_AudioGainConfig( const audio_gain_config& legacy, audio_port_role_t role, audio_port_type_t type) { - media::AudioGainConfig aidl; + AudioGainConfig aidl; aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; @@ -2801,11 +2806,11 @@ legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput } ConversionResult -aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { +aidl2legacy_AudioGain_audio_gain(const AudioGain& aidl, bool isInput) { audio_gain legacy; legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); legacy.channel_mask = VALUE_OR_RETURN(aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, aidl.isInput)); + aidl.channelMask, isInput)); legacy.min_value = VALUE_OR_RETURN(convertIntegral(aidl.minValue)); legacy.max_value = VALUE_OR_RETURN(convertIntegral(aidl.maxValue)); legacy.default_value = VALUE_OR_RETURN(convertIntegral(aidl.defaultValue)); @@ -2815,11 +2820,10 @@ aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl) { return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { - media::AudioGain aidl; + AudioGain aidl; aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - aidl.isInput = isInput; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); aidl.minValue = VALUE_OR_RETURN(convertIntegral(legacy.min_value)); @@ -2862,7 +2866,9 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { return unexpected(BAD_VALUE); } RETURN_IF_ERROR(convertRange(aidl.gains.begin(), aidl.gains.end(), legacy.gains, - aidl2legacy_AudioGain_audio_gain)); + [isInput](const AudioGain& g) { + return aidl2legacy_AudioGain_audio_gain(g, isInput); + })); legacy.num_gains = aidl.gains.size(); legacy.active_config = VALUE_OR_RETURN( @@ -2909,6 +2915,7 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { [isInput](const audio_gain& g) { return legacy2aidl_audio_gain_AudioGain(g, isInput); })); + aidl.gainsSys.resize(legacy.num_gains); aidl.activeConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index f150d88253..739b982db8 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -314,9 +314,7 @@ aidl_interface { "aidl/android/media/AudioClient.aidl", "aidl/android/media/AudioDualMonoMode.aidl", "aidl/android/media/AudioFlag.aidl", - "aidl/android/media/AudioGain.aidl", - "aidl/android/media/AudioGainConfig.aidl", - "aidl/android/media/AudioGainMode.aidl", + "aidl/android/media/AudioGainSys.aidl", "aidl/android/media/AudioInputFlags.aidl", "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioGain.aidl b/media/libaudioclient/aidl/android/media/AudioGain.aidl deleted file mode 100644 index ff85b50399..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioGain.aidl +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.audio.common.AudioChannelLayout; - -/** - * {@hide} - */ -parcelable AudioGain { - int index; - boolean isInput; - boolean useForVolume; - /** Bitmask, indexed by AudioGainMode. */ - int mode; - AudioChannelLayout channelMask; - int minValue; - int maxValue; - int defaultValue; - int stepValue; - int minRampMs; - int maxRampMs; -} diff --git a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl b/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl deleted file mode 100644 index f60c461318..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioGainConfig.aidl +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.audio.common.AudioChannelLayout; - -/** - * {@hide} - */ -parcelable AudioGainConfig { - /** Index of the corresponding audio_gain in the audio_port gains[] table. */ - int index; - - /** Mode requested for this command. Bitfield indexed by AudioGainMode. */ - int mode; - - /** - * Channels which gain value follows. N/A in joint mode. - */ - AudioChannelLayout channelMask; - - /** - * Gain values in millibels. - * For each channel ordered from LSb to MSb in channel mask. The number of values is 1 in joint - * mode, otherwise equals the number of bits implied by channelMask. - */ - int[] values; - - /** Ramp duration in ms. */ - int rampDurationMs; -} diff --git a/media/libaudioclient/aidl/android/media/AudioGainMode.aidl b/media/libaudioclient/aidl/android/media/AudioGainSys.aidl similarity index 79% rename from media/libaudioclient/aidl/android/media/AudioGainMode.aidl rename to media/libaudioclient/aidl/android/media/AudioGainSys.aidl index e1b9f0b65d..9ec839046e 100644 --- a/media/libaudioclient/aidl/android/media/AudioGainMode.aidl +++ b/media/libaudioclient/aidl/android/media/AudioGainSys.aidl @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package android.media; /** + * Provides additional runtime information for AudioGain, used by the framework. + * * {@hide} */ -@Backing(type="int") -enum AudioGainMode { - JOINT = 0, - CHANNELS = 1, - RAMP = 2, +parcelable AudioGainSys { + int index; + boolean isInput; + boolean useForVolume; } diff --git a/media/libaudioclient/aidl/android/media/AudioPort.aidl b/media/libaudioclient/aidl/android/media/AudioPort.aidl index 0f98ea18bf..92b88ed283 100644 --- a/media/libaudioclient/aidl/android/media/AudioPort.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPort.aidl @@ -16,13 +16,14 @@ package android.media; -import android.media.AudioGain; +import android.media.AudioGainSys; import android.media.AudioPortConfig; import android.media.AudioPortExt; import android.media.AudioPortRole; import android.media.AudioPortType; import android.media.AudioProfileSys; import android.media.ExtraAudioDescriptor; +import android.media.audio.common.AudioGain; import android.media.audio.common.AudioProfile; /** @@ -47,6 +48,8 @@ parcelable AudioPort { ExtraAudioDescriptor[] extraAudioDescriptors; /** Gain controllers. */ AudioGain[] gains; + /** System-only parameters for each AudioGain. */ + AudioGainSys[] gainsSys; /** Current audio port configuration. */ AudioPortConfig activeConfig; AudioPortExt ext; diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index 3908cb1a5d..07e4480055 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,14 +16,14 @@ package android.media; -import android.media.AudioGainConfig; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; import android.media.AudioPortConfigType; import android.media.AudioPortRole; import android.media.AudioPortType; -import android.media.audio.common.AudioFormatDescription; import android.media.audio.common.AudioChannelLayout; +import android.media.audio.common.AudioFormatDescription; +import android.media.audio.common.AudioGainConfig; /** * {@hide} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 1afb2c5ee1..74a3520560 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -25,8 +25,6 @@ #include #include #include -#include -#include #include #include #include @@ -53,6 +51,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -168,16 +169,18 @@ ConversionResult legacy2aidl_audio_format_t_AudioFormatDescription(audio_format_t legacy); ConversionResult -aidl2legacy_AudioGainMode_audio_gain_mode_t(media::AudioGainMode aidl); -ConversionResult +aidl2legacy_AudioGainMode_audio_gain_mode_t(media::audio::common::AudioGainMode aidl); +ConversionResult legacy2aidl_audio_gain_mode_t_AudioGainMode(audio_gain_mode_t legacy); ConversionResult aidl2legacy_int32_t_audio_gain_mode_t_mask(int32_t aidl); ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_mode_t legacy); ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( - const media::AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type); -ConversionResult legacy2aidl_audio_gain_config_AudioGainConfig( + const media::audio::common::AudioGainConfig& aidl, + media::AudioPortRole role, media::AudioPortType type); +ConversionResult +legacy2aidl_audio_gain_config_AudioGainConfig( const audio_gain_config& legacy, audio_port_role_t role, audio_port_type_t type); ConversionResult aidl2legacy_AudioInputFlags_audio_input_flags_t( @@ -378,9 +381,8 @@ ConversionResult legacy2aidl_audio_profile_AudioProfile(const audio_profile& legacy, bool isInput); ConversionResult -aidl2legacy_AudioGain_audio_gain(const media::AudioGain& aidl); -// The AIDL structure provides a flag for direction indication while the legacy type doesn't. -ConversionResult +aidl2legacy_AudioGain_audio_gain(const media::audio::common::AudioGain& aidl, bool isInput); +ConversionResult legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput); ConversionResult diff --git a/media/libaudiofoundation/AudioGain.cpp b/media/libaudiofoundation/AudioGain.cpp index ea0258a1d1..1a8fbf0955 100644 --- a/media/libaudiofoundation/AudioGain.cpp +++ b/media/libaudiofoundation/AudioGain.cpp @@ -24,22 +24,18 @@ #define ALOGVV(a...) do { } while(0) #endif +#include + #include #include #include #include -#include - namespace android { AudioGain::AudioGain(int index, bool isInput) -{ - mIndex = index; - mIsInput = isInput; - memset(&mGain, 0, sizeof(struct audio_gain)); -} + : mIndex(index), mIsInput(isInput) {} void AudioGain::getDefaultConfig(struct audio_gain_config *config) { @@ -123,53 +119,24 @@ bool AudioGain::equals(const sp& other) const mGain.max_ramp_ms == other->mGain.max_ramp_ms; } -status_t AudioGain::writeToParcel(android::Parcel *parcel) const { - media::AudioGain parcelable; - return writeToParcelable(&parcelable) - ?: parcelable.writeToParcel(parcel); +ConversionResult AudioGain::toParcelable() const { + media::audio::common::AudioGain aidl = VALUE_OR_RETURN( + legacy2aidl_audio_gain_AudioGain(mGain, mIsInput)); + media::AudioGainSys aidlSys; + aidlSys.index = VALUE_OR_RETURN(convertIntegral(mIndex)); + aidlSys.isInput = mIsInput; + aidlSys.useForVolume = mUseForVolume; + return std::make_pair(aidl, aidlSys); } -status_t AudioGain::writeToParcelable(media::AudioGain* parcelable) const { - parcelable->index = VALUE_OR_RETURN_STATUS(convertIntegral(mIndex)); - parcelable->isInput = mIsInput; - parcelable->useForVolume = mUseForVolume; - parcelable->mode = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); - parcelable->channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout( - mGain.channel_mask, mIsInput)); - parcelable->minValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_value)); - parcelable->maxValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_value)); - parcelable->defaultValue = VALUE_OR_RETURN_STATUS( - convertIntegral(mGain.default_value)); - parcelable->stepValue = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.step_value)); - parcelable->minRampMs = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.min_ramp_ms)); - parcelable->maxRampMs = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.max_ramp_ms)); - return OK; -} - -status_t AudioGain::readFromParcel(const android::Parcel *parcel) { - media::AudioGain parcelable; - return parcelable.readFromParcel(parcel) - ?: readFromParcelable(parcelable); -} - -status_t AudioGain::readFromParcelable(const media::AudioGain& parcelable) { - mIndex = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.index)); - mIsInput = parcelable.isInput; - mUseForVolume = parcelable.useForVolume; - mGain.mode = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.mode)); - mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.channelMask, parcelable.isInput)); - mGain.min_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minValue)); - mGain.max_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxValue)); - mGain.default_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.defaultValue)); - mGain.step_value = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.stepValue)); - mGain.min_ramp_ms = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.minRampMs)); - mGain.max_ramp_ms = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.maxRampMs)); - return OK; +ConversionResult> AudioGain::fromParcelable(const AudioGain::Aidl& aidl) { + const media::AudioGainSys& sys = aidl.second; + auto index = VALUE_OR_RETURN(convertIntegral(sys.index)); + sp legacy = sp::make(index, sys.isInput); + legacy->mGain = VALUE_OR_RETURN( + aidl2legacy_AudioGain_audio_gain(aidl.first, sys.isInput)); + legacy->mUseForVolume = sys.useForVolume; + return legacy; } bool AudioGains::equals(const AudioGains &other) const @@ -180,59 +147,30 @@ bool AudioGains::equals(const AudioGains &other) const }); } -status_t AudioGains::writeToParcel(android::Parcel *parcel) const { - status_t status = NO_ERROR; - if ((status = parcel->writeVectorSize(*this)) != NO_ERROR) return status; - for (const auto &audioGain : *this) { - if ((status = parcel->writeParcelable(*audioGain)) != NO_ERROR) { - break; - } - } - return status; -} - -status_t AudioGains::readFromParcel(const android::Parcel *parcel) { - status_t status = NO_ERROR; - this->clear(); - if ((status = parcel->resizeOutVector(this)) != NO_ERROR) return status; - for (size_t i = 0; i < this->size(); i++) { - this->at(i) = new AudioGain(0, false); - if ((status = parcel->readParcelable(this->at(i).get())) != NO_ERROR) { - this->clear(); - break; - } - } - return status; -} - ConversionResult> -aidl2legacy_AudioGain(const media::AudioGain& aidl) { - sp legacy = new AudioGain(0, false); - status_t status = legacy->readFromParcelable(aidl); - if (status != OK) { - return base::unexpected(status); - } - return legacy; +aidl2legacy_AudioGain(const AudioGain::Aidl& aidl) { + return AudioGain::fromParcelable(aidl); } -ConversionResult +ConversionResult legacy2aidl_AudioGain(const sp& legacy) { - media::AudioGain aidl; - status_t status = legacy->writeToParcelable(&aidl); - if (status != OK) { - return base::unexpected(status); - } - return aidl; + return legacy->toParcelable(); } ConversionResult -aidl2legacy_AudioGains(const std::vector& aidl) { - return convertContainer(aidl, aidl2legacy_AudioGain); +aidl2legacy_AudioGains(const AudioGains::Aidl& aidl) { + return convertContainers(aidl.first, aidl.second, + [](const media::audio::common::AudioGain& g, + const media::AudioGainSys& gs) { + return aidl2legacy_AudioGain(std::make_pair(g, gs)); + }); } -ConversionResult> +ConversionResult legacy2aidl_AudioGains(const AudioGains& legacy) { - return convertContainer>(legacy, legacy2aidl_AudioGain); + return convertContainerSplit< + std::vector, + std::vector>(legacy, legacy2aidl_AudioGain); } } // namespace android diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index 74c9b10113..905a0caa5d 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -210,12 +210,14 @@ status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { parcelable->name = mName; parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); - auto aidl = VALUE_OR_RETURN_STATUS( + auto aidlProfiles = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); - parcelable->profiles = aidl.first; - parcelable->profilesSys = aidl.second; + parcelable->profiles = aidlProfiles.first; + parcelable->profilesSys = aidlProfiles.second; parcelable->extraAudioDescriptors = mExtraAudioDescriptors; - parcelable->gains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); + auto aidlGains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); + parcelable->gains = aidlGains.first; + parcelable->gainsSys = aidlGains.second; return OK; } @@ -234,7 +236,8 @@ status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { std::make_pair(parcelable.profiles, parcelable.profilesSys), useInputChannelMask())); mExtraAudioDescriptors = parcelable.extraAudioDescriptors; - mGains = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioGains(parcelable.gains)); + mGains = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioGains(std::make_pair(parcelable.gains, parcelable.gainsSys))); return OK; } diff --git a/media/libaudiofoundation/include/media/AudioGain.h b/media/libaudiofoundation/include/media/AudioGain.h index 28769d26ba..10088f28f0 100644 --- a/media/libaudiofoundation/include/media/AudioGain.h +++ b/media/libaudiofoundation/include/media/AudioGain.h @@ -16,23 +16,23 @@ #pragma once -#include -#include -#include +#include +#include +#include + +#include #include #include #include #include -#include -#include namespace android { -class AudioGain: public RefBase, public Parcelable +class AudioGain: public RefBase { public: AudioGain(int index, bool isInput); - virtual ~AudioGain() {} + virtual ~AudioGain() = default; void setMode(audio_gain_mode_t mode) { mGain.mode = mode; } const audio_gain_mode_t &getMode() const { return mGain.mode; } @@ -71,26 +71,24 @@ public: bool equals(const sp& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; - - status_t writeToParcelable(media::AudioGain* parcelable) const; - status_t readFromParcelable(const media::AudioGain& parcelable); + using Aidl = std::pair; + ConversionResult toParcelable() const; + static ConversionResult> fromParcelable(const Aidl& aidl); private: int mIndex; - struct audio_gain mGain; bool mIsInput; + struct audio_gain mGain = {}; bool mUseForVolume = false; }; // Conversion routines, according to AidlConversion.h conventions. ConversionResult> -aidl2legacy_AudioGain(const media::AudioGain& aidl); -ConversionResult +aidl2legacy_AudioGain(const AudioGain::Aidl& aidl); +ConversionResult legacy2aidl_AudioGain(const sp& legacy); -class AudioGains : public std::vector >, public Parcelable +class AudioGains : public std::vector> { public: bool canUseForVolume() const @@ -103,7 +101,7 @@ public: return false; } - int32_t add(const sp gain) + int32_t add(const sp& gain) { push_back(gain); return 0; @@ -111,14 +109,15 @@ public: bool equals(const AudioGains& other) const; - status_t writeToParcel(Parcel* parcel) const override; - status_t readFromParcel(const Parcel* parcel) override; + using Aidl = std::pair< + std::vector, + std::vector>; }; // Conversion routines, according to AidlConversion.h conventions. ConversionResult -aidl2legacy_AudioGains(const std::vector& aidl); -ConversionResult> +aidl2legacy_AudioGains(const AudioGains::Aidl& aidl); +ConversionResult legacy2aidl_AudioGains(const AudioGains& legacy); } // namespace android diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index abafff1168..3a7ddd7280 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -94,14 +94,21 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioProfileVector) { } TEST(AudioFoundationParcelableTest, ParcelingAudioGain) { - Parcel data; - AudioGains audioGains = getAudioGainsForTest(); + sp audioGain = getAudioGainsForTest()[0]; + auto conv = legacy2aidl_AudioGain(audioGain); + ASSERT_TRUE(conv.ok()); + auto convBack = aidl2legacy_AudioGain(conv.value()); + ASSERT_TRUE(convBack.ok()); + ASSERT_TRUE(audioGain->equals(convBack.value())); +} - ASSERT_EQ(data.writeParcelable(audioGains), NO_ERROR); - data.setDataPosition(0); - AudioGains audioGainsFromParcel; - ASSERT_EQ(data.readParcelable(&audioGainsFromParcel), NO_ERROR); - ASSERT_TRUE(audioGainsFromParcel.equals(audioGains)); +TEST(AudioFoundationParcelableTest, ParcelingAudioGains) { + AudioGains audioGains = getAudioGainsForTest(); + auto conv = legacy2aidl_AudioGains(audioGains); + ASSERT_TRUE(conv.ok()); + auto convBack = aidl2legacy_AudioGains(conv.value()); + ASSERT_TRUE(convBack.ok()); + ASSERT_TRUE(audioGains.equals(convBack.value())); } TEST(AudioFoundationParcelableTest, ParcelingAudioPort) { -- GitLab From f33fd94d49c8a3a7f4fdbe17514e7f1c619b66ad Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 29 Sep 2021 17:10:30 +0000 Subject: [PATCH 153/694] Dedupe RETURN_STATUS_IF_ERROR macro Move the definition to 'AidlConversionUtil.h' and get rid of the copies. Bug: 198812639 Test: m Change-Id: I373c4449721b69aa104d45a599ba1aa1304bcb4d --- media/libaudioclient/AudioAttributes.cpp | 3 --- media/libaudioclient/AudioEffect.cpp | 6 ------ media/libaudioclient/AudioProductStrategy.cpp | 3 --- media/libaudioclient/AudioSystem.cpp | 6 ------ media/libaudioclient/AudioVolumeGroup.cpp | 3 --- media/libaudioclient/IAudioFlinger.cpp | 6 ------ media/libaudioclient/include/media/AidlConversionUtil.h | 3 +++ 7 files changed, 3 insertions(+), 27 deletions(-) diff --git a/media/libaudioclient/AudioAttributes.cpp b/media/libaudioclient/AudioAttributes.cpp index 83bf5a7f2f..260c06c521 100644 --- a/media/libaudioclient/AudioAttributes.cpp +++ b/media/libaudioclient/AudioAttributes.cpp @@ -24,9 +24,6 @@ #include #include -#define RETURN_STATUS_IF_ERROR(x) \ - { auto _tmp = (x); if (_tmp != OK) return _tmp; } - namespace android { status_t AudioAttributes::readFromParcel(const Parcel* parcel) { diff --git a/media/libaudioclient/AudioEffect.cpp b/media/libaudioclient/AudioEffect.cpp index 65daa3c644..3a979456c1 100644 --- a/media/libaudioclient/AudioEffect.cpp +++ b/media/libaudioclient/AudioEffect.cpp @@ -32,12 +32,6 @@ #include #include -#define RETURN_STATUS_IF_ERROR(x) \ - { \ - auto _tmp = (x); \ - if (_tmp != OK) return _tmp; \ - } - namespace android { using aidl_utils::statusTFromBinderStatus; using binder::Status; diff --git a/media/libaudioclient/AudioProductStrategy.cpp b/media/libaudioclient/AudioProductStrategy.cpp index f98027aa17..ecd423a05b 100644 --- a/media/libaudioclient/AudioProductStrategy.cpp +++ b/media/libaudioclient/AudioProductStrategy.cpp @@ -21,9 +21,6 @@ #include #include -#define RETURN_STATUS_IF_ERROR(x) \ - { auto _tmp = (x); if (_tmp != OK) return _tmp; } - namespace android { status_t AudioProductStrategy::readFromParcel(const Parcel* parcel) { diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 317ad1e957..377af28f42 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -40,12 +40,6 @@ if (!_tmp.ok()) return aidl_utils::binderStatusFromStatusT(_tmp.error()); \ std::move(_tmp.value()); }) -#define RETURN_STATUS_IF_ERROR(x) \ - { \ - auto _tmp = (x); \ - if (_tmp != OK) return _tmp; \ - } - // ---------------------------------------------------------------------------- namespace android { diff --git a/media/libaudioclient/AudioVolumeGroup.cpp b/media/libaudioclient/AudioVolumeGroup.cpp index 36696cdedc..ab95246150 100644 --- a/media/libaudioclient/AudioVolumeGroup.cpp +++ b/media/libaudioclient/AudioVolumeGroup.cpp @@ -26,9 +26,6 @@ #include #include -#define RETURN_STATUS_IF_ERROR(x) \ - { auto _tmp = (x); if (_tmp != OK) return _tmp; } - namespace android { using media::audio::common::AudioStreamType; diff --git a/media/libaudioclient/IAudioFlinger.cpp b/media/libaudioclient/IAudioFlinger.cpp index d3098b8938..88e7396130 100644 --- a/media/libaudioclient/IAudioFlinger.cpp +++ b/media/libaudioclient/IAudioFlinger.cpp @@ -48,12 +48,6 @@ using media::audio::common::AudioUuid; std::move(_tmp.value()); \ }) -#define RETURN_STATUS_IF_ERROR(x) \ - { \ - auto _tmp = (x); \ - if (_tmp != OK) return _tmp; \ - } - #define RETURN_BINDER_IF_ERROR(x) \ { \ auto _tmp = (x); \ diff --git a/media/libaudioclient/include/media/AidlConversionUtil.h b/media/libaudioclient/include/media/AidlConversionUtil.h index f9446adc0a..dfabd55ff8 100644 --- a/media/libaudioclient/include/media/AidlConversionUtil.h +++ b/media/libaudioclient/include/media/AidlConversionUtil.h @@ -41,6 +41,9 @@ using ConversionResult = base::expected; #define RETURN_IF_ERROR(result) \ if (status_t _tmp = (result); _tmp != OK) return base::unexpected(_tmp); +#define RETURN_STATUS_IF_ERROR(result) \ + if (status_t _tmp = (result); _tmp != OK) return _tmp; + #define VALUE_OR_RETURN_STATUS(x) \ ({ \ auto _tmp = (x); \ -- GitLab From 9255d4da829bec021675e35f61c96bf4c1e23c6a Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 23 Sep 2021 18:39:38 +0000 Subject: [PATCH 154/694] Remove AudioPortConfigType from AIDL interfaces Switch to the canonical approach of making a field '@nullable' if the value for it is not required. This makes AudioPortConfigType redundant. Refactor affected parceling code in libaudiofoundation to reuse functions from AidlConversion. Bug: 198812639 Test: atest audiofoundation_parcelable_test Change-Id: If02a9d788e7aed21bca917ac193cf71598804b83 --- media/libaudioclient/AidlConversion.cpp | 106 +++++------------- media/libaudioclient/Android.bp | 3 +- .../aidl/android/media/AudioPortConfig.aidl | 28 ++--- .../android/media/AudioPortConfigType.aidl | 28 ----- .../include/media/AidlConversion.h | 14 +-- media/libaudiofoundation/AudioPort.cpp | 50 ++++----- 6 files changed, 64 insertions(+), 165 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortConfigType.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 7ee78e0529..45788e79ea 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -249,60 +249,6 @@ ConversionResult legacy2aidl_String8_string(const String8& legacy) return std::string(legacy.c_str()); } -// The legacy enum is unnamed. Thus, we use int32_t. -ConversionResult aidl2legacy_AudioPortConfigType_int32_t( - media::AudioPortConfigType aidl) { - switch (aidl) { - case media::AudioPortConfigType::SAMPLE_RATE: - return AUDIO_PORT_CONFIG_SAMPLE_RATE; - case media::AudioPortConfigType::CHANNEL_MASK: - return AUDIO_PORT_CONFIG_CHANNEL_MASK; - case media::AudioPortConfigType::FORMAT: - return AUDIO_PORT_CONFIG_FORMAT; - case media::AudioPortConfigType::GAIN: - return AUDIO_PORT_CONFIG_GAIN; - case media::AudioPortConfigType::FLAGS: - return AUDIO_PORT_CONFIG_FLAGS; - } - return unexpected(BAD_VALUE); -} - -// The legacy enum is unnamed. Thus, we use int32_t. -ConversionResult legacy2aidl_int32_t_AudioPortConfigType( - int32_t legacy) { - switch (legacy) { - case AUDIO_PORT_CONFIG_SAMPLE_RATE: - return media::AudioPortConfigType::SAMPLE_RATE; - case AUDIO_PORT_CONFIG_CHANNEL_MASK: - return media::AudioPortConfigType::CHANNEL_MASK; - case AUDIO_PORT_CONFIG_FORMAT: - return media::AudioPortConfigType::FORMAT; - case AUDIO_PORT_CONFIG_GAIN: - return media::AudioPortConfigType::GAIN; - case AUDIO_PORT_CONFIG_FLAGS: - return media::AudioPortConfigType::FLAGS; - } - return unexpected(BAD_VALUE); -} - -ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl) { - return convertBitmask( - aidl, aidl2legacy_AudioPortConfigType_int32_t, - // AudioPortConfigType enum is index-based. - indexToEnum_index, - // AUDIO_PORT_CONFIG_* flags are mask-based. - enumToMask_bitmask); -} - -ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy) { - return convertBitmask( - legacy, legacy2aidl_int32_t_AudioPortConfigType, - // AUDIO_PORT_CONFIG_* flags are mask-based. - indexToEnum_bitmask, - // AudioPortConfigType enum is index-based. - enumToMask_index); -} - ConversionResult aidl2legacy_AudioIoConfigEvent_audio_io_config_event_t( media::AudioIoConfigEvent aidl) { switch (aidl) { @@ -1289,11 +1235,10 @@ ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_ } ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( - const AudioGainConfig& aidl, media::AudioPortRole role, media::AudioPortType type) { + const AudioGainConfig& aidl, bool isInput) { audio_gain_config legacy; legacy.index = VALUE_OR_RETURN(convertIntegral(aidl.index)); legacy.mode = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_gain_mode_t_mask(aidl.mode)); - const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelLayout_audio_channel_mask_t(aidl.channelMask, isInput)); const bool isJoint = bitmaskIsSet(aidl.mode, AudioGainMode::JOINT); @@ -1311,11 +1256,10 @@ ConversionResult aidl2legacy_AudioGainConfig_audio_gain_confi } ConversionResult legacy2aidl_audio_gain_config_AudioGainConfig( - const audio_gain_config& legacy, audio_port_role_t role, audio_port_type_t type) { + const audio_gain_config& legacy, bool isInput) { AudioGainConfig aidl; aidl.index = VALUE_OR_RETURN(convertIntegral(legacy.index)); aidl.mode = VALUE_OR_RETURN(legacy2aidl_audio_gain_mode_t_int32_t_mask(legacy.mode)); - const bool isInput = VALUE_OR_RETURN(direction(role, type)) == Direction::INPUT; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); const bool isJoint = (legacy.mode & AUDIO_GAIN_MODE_JOINT) != 0; @@ -1873,32 +1817,37 @@ ConversionResult legacy2aidl_AudioPortConfigExt( ConversionResult aidl2legacy_AudioPortConfig_audio_port_config( const media::AudioPortConfig& aidl) { - audio_port_config legacy; + audio_port_config legacy{}; legacy.id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.id)); legacy.role = VALUE_OR_RETURN(aidl2legacy_AudioPortRole_audio_port_role_t(aidl.role)); legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioPortType_audio_port_type_t(aidl.type)); - legacy.config_mask = VALUE_OR_RETURN(aidl2legacy_int32_t_config_mask(aidl.configMask)); - if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::SAMPLE_RATE)) { - legacy.sample_rate = VALUE_OR_RETURN(convertIntegral(aidl.sampleRate)); + const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; + if (aidl.sampleRate.has_value()) { + legacy.sample_rate = VALUE_OR_RETURN( + convertIntegral(aidl.sampleRate.value().value)); + legacy.config_mask |= AUDIO_PORT_CONFIG_SAMPLE_RATE; } - if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::CHANNEL_MASK)) { - const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; + if (aidl.channelMask.has_value()) { legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask, isInput)); + aidl.channelMask.value(), isInput)); + legacy.config_mask |= AUDIO_PORT_CONFIG_CHANNEL_MASK; } - if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FORMAT)) { + if (aidl.format.has_value()) { legacy.format = VALUE_OR_RETURN( - aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format)); + aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format.value())); + legacy.config_mask |= AUDIO_PORT_CONFIG_FORMAT; } - if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::GAIN)) { - legacy.gain = VALUE_OR_RETURN( - aidl2legacy_AudioGainConfig_audio_gain_config(aidl.gain, aidl.role, aidl.type)); + if (aidl.gain.has_value()) { + legacy.gain = VALUE_OR_RETURN(aidl2legacy_AudioGainConfig_audio_gain_config( + aidl.gain.value(), isInput)); + legacy.config_mask |= AUDIO_PORT_CONFIG_GAIN; } - if (bitmaskIsSet(aidl.configMask, media::AudioPortConfigType::FLAGS)) { + if (aidl.flags.has_value()) { legacy.flags = VALUE_OR_RETURN( - aidl2legacy_AudioIoFlags_audio_io_flags(aidl.flags, aidl.role, aidl.type)); + aidl2legacy_AudioIoFlags_audio_io_flags(aidl.flags.value(), aidl.role, aidl.type)); + legacy.config_mask |= AUDIO_PORT_CONFIG_FLAGS; } legacy.ext = VALUE_OR_RETURN(aidl2legacy_AudioPortConfigExt(aidl.ext, aidl.type, aidl.role)); return legacy; @@ -1910,13 +1859,14 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort aidl.id = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.id)); aidl.role = VALUE_OR_RETURN(legacy2aidl_audio_port_role_t_AudioPortRole(legacy.role)); aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_port_type_t_AudioPortType(legacy.type)); - aidl.configMask = VALUE_OR_RETURN(legacy2aidl_config_mask_int32_t(legacy.config_mask)); + const bool isInput = VALUE_OR_RETURN( + direction(legacy.role, legacy.type)) == Direction::INPUT; if (legacy.config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) { - aidl.sampleRate = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); + media::Int aidl_sampleRate; + aidl_sampleRate.value = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); + aidl.sampleRate = aidl_sampleRate; } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { - const bool isInput = VALUE_OR_RETURN( - direction(legacy.role, legacy.type)) == Direction::INPUT; aidl.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); } @@ -1925,8 +1875,8 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_GAIN) { - aidl.gain = VALUE_OR_RETURN(legacy2aidl_audio_gain_config_AudioGainConfig( - legacy.gain, legacy.role, legacy.type)); + aidl.gain = VALUE_OR_RETURN( + legacy2aidl_audio_gain_config_AudioGainConfig(legacy.gain, isInput)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FLAGS) { aidl.flags = VALUE_OR_RETURN( diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 739b982db8..04b1b93100 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -325,7 +325,6 @@ aidl_interface { "aidl/android/media/AudioPlaybackRate.aidl", "aidl/android/media/AudioPort.aidl", "aidl/android/media/AudioPortConfig.aidl", - "aidl/android/media/AudioPortConfigType.aidl", "aidl/android/media/AudioPortConfigDeviceExt.aidl", "aidl/android/media/AudioPortConfigExt.aidl", "aidl/android/media/AudioPortConfigMixExt.aidl", @@ -344,6 +343,7 @@ aidl_interface { "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", "aidl/android/media/ExtraAudioDescriptor.aidl", + "aidl/android/media/Int.aidl", "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ @@ -466,7 +466,6 @@ aidl_interface { "aidl/android/media/GetInputForAttrResponse.aidl", "aidl/android/media/GetOutputForAttrResponse.aidl", "aidl/android/media/GetSpatializerResponse.aidl", - "aidl/android/media/Int.aidl", "aidl/android/media/RecordClientInfo.aidl", "aidl/android/media/IAudioPolicyService.aidl", "aidl/android/media/IAudioPolicyServiceClient.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index 07e4480055..4e1520ccd2 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -18,9 +18,9 @@ package android.media; import android.media.AudioIoFlags; import android.media.AudioPortConfigExt; -import android.media.AudioPortConfigType; import android.media.AudioPortRole; import android.media.AudioPortType; +import android.media.Int; import android.media.audio.common.AudioChannelLayout; import android.media.audio.common.AudioFormatDescription; import android.media.audio.common.AudioGainConfig; @@ -38,21 +38,15 @@ parcelable AudioPortConfig { AudioPortRole role; /** Device, mix ... */ AudioPortType type; - /** Bitmask, indexed by AudioPortConfigType. */ - int configMask; - /** Sampling rate in Hz. */ - int sampleRate; - /** - * Channel mask, if applicable. - */ - AudioChannelLayout channelMask; - /** - * Format, if applicable. - */ - AudioFormatDescription format; - /** Gain to apply, if applicable. */ - AudioGainConfig gain; - /** Framework only: HW_AV_SYNC, DIRECT, ... */ - AudioIoFlags flags; + /** Sampling rate in Hz. Can be left unspecified. */ + @nullable Int sampleRate; + /** Channel mask. Can be left unspecified. */ + @nullable AudioChannelLayout channelMask; + /** Format. Can be left unspecified. */ + @nullable AudioFormatDescription format; + /** Gain to apply. Can be left unspecified. */ + @nullable AudioGainConfig gain; + /** Framework only: HW_AV_SYNC, DIRECT, ... Can be left unspecified. */ + @nullable AudioIoFlags flags; AudioPortConfigExt ext; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigType.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigType.aidl deleted file mode 100644 index 6e22b8d4fa..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigType.aidl +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioPortConfigType { - SAMPLE_RATE = 0, - CHANNEL_MASK = 1, - FORMAT = 2, - GAIN = 3, - FLAGS = 4, -} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 74a3520560..1095766515 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include @@ -95,13 +94,6 @@ ConversionResult legacy2aidl_audio_unique_id_t_int32_t(audio_unique_id_ ConversionResult aidl2legacy_int32_t_audio_hw_sync_t(int32_t aidl); ConversionResult legacy2aidl_audio_hw_sync_t_int32_t(audio_hw_sync_t legacy); -// The legacy enum is unnamed. Thus, we use int32_t. -ConversionResult aidl2legacy_AudioPortConfigType_int32_t( - media::AudioPortConfigType aidl); -// The legacy enum is unnamed. Thus, we use int32_t. -ConversionResult legacy2aidl_int32_t_AudioPortConfigType( - int32_t legacy); - ConversionResult aidl2legacy_int32_t_config_mask(int32_t aidl); ConversionResult legacy2aidl_config_mask_int32_t(unsigned int legacy); @@ -177,11 +169,9 @@ ConversionResult aidl2legacy_int32_t_audio_gain_mode_t_mask(i ConversionResult legacy2aidl_audio_gain_mode_t_int32_t_mask(audio_gain_mode_t legacy); ConversionResult aidl2legacy_AudioGainConfig_audio_gain_config( - const media::audio::common::AudioGainConfig& aidl, - media::AudioPortRole role, media::AudioPortType type); + const media::audio::common::AudioGainConfig& aidl, bool isInput); ConversionResult -legacy2aidl_audio_gain_config_AudioGainConfig( - const audio_gain_config& legacy, audio_port_role_t role, audio_port_type_t type); +legacy2aidl_audio_gain_config_AudioGainConfig(const audio_gain_config& legacy, bool isInput); ConversionResult aidl2legacy_AudioInputFlags_audio_input_flags_t( media::AudioInputFlags aidl); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index 905a0caa5d..329ff9a76e 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -341,45 +341,39 @@ bool AudioPortConfig::equals(const sp &other) const status_t AudioPortConfig::writeToParcelable( media::AudioPortConfig* parcelable, bool isInput) const { - parcelable->sampleRate = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); + media::Int aidl_sampleRate; + aidl_sampleRate.value = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); + parcelable->sampleRate = aidl_sampleRate; parcelable->format = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_format_t_AudioFormatDescription(mFormat)); parcelable->channelMask = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mChannelMask, isInput)); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); - parcelable->gain.index = VALUE_OR_RETURN_STATUS(convertIntegral(mGain.index)); - parcelable->gain.mode = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_gain_mode_t_int32_t_mask(mGain.mode)); - parcelable->gain.channelMask = VALUE_OR_RETURN_STATUS( - legacy2aidl_audio_channel_mask_t_AudioChannelLayout(mGain.channel_mask, isInput)); - parcelable->gain.rampDurationMs = VALUE_OR_RETURN_STATUS( - convertIntegral(mGain.ramp_duration_ms)); - parcelable->gain.values = VALUE_OR_RETURN_STATUS(convertContainer>( - mGain.values, convertIntegral)); + media::audio::common::AudioGainConfig aidl_gain = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_gain_config_AudioGainConfig(mGain, isInput)); + parcelable->gain = aidl_gain; return OK; } status_t AudioPortConfig::readFromParcelable( const media::AudioPortConfig& parcelable, bool isInput) { - mSamplingRate = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.sampleRate)); - mFormat = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format)); - mChannelMask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t(parcelable.channelMask, isInput)); - mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); - mGain.index = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.index)); - mGain.mode = VALUE_OR_RETURN_STATUS( - aidl2legacy_int32_t_audio_gain_mode_t_mask(parcelable.gain.mode)); - mGain.channel_mask = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - parcelable.gain.channelMask, isInput)); - mGain.ramp_duration_ms = VALUE_OR_RETURN_STATUS( - convertIntegral(parcelable.gain.rampDurationMs)); - if (parcelable.gain.values.size() > std::size(mGain.values)) { - return BAD_VALUE; + if (parcelable.sampleRate.has_value()) { + mSamplingRate = VALUE_OR_RETURN_STATUS( + convertIntegral(parcelable.sampleRate.value().value)); + } + if (parcelable.format.has_value()) { + mFormat = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioFormatDescription_audio_format_t(parcelable.format.value())); } - for (size_t i = 0; i < parcelable.gain.values.size(); ++i) { - mGain.values[i] = VALUE_OR_RETURN_STATUS(convertIntegral(parcelable.gain.values[i])); + if (parcelable.channelMask.has_value()) { + mChannelMask = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioChannelLayout_audio_channel_mask_t( + parcelable.channelMask.value(), isInput)); + } + mId = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_audio_port_handle_t(parcelable.id)); + if (parcelable.gain.has_value()) { + mGain = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioGainConfig_audio_gain_config(parcelable.gain.value(), isInput)); } return OK; } -- GitLab From a4a926ff92fde2d2ce960695014b11f12db94355 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Wed, 29 Sep 2021 17:20:29 +0000 Subject: [PATCH 155/694] Remove AudioMixLatencyClass enum from AIDL interfaces The enum was only used for the 'AudioPortMixExt.latencyClass' field, which is "write only" on the framework side, and isn't used on the HAL side. Bug: 198812639 Test: m Change-Id: Ibf245027696e4df1df6f434b9553012461f90b7b --- media/libaudioclient/AidlConversion.cpp | 30 +------------------ media/libaudioclient/Android.bp | 1 - .../android/media/AudioMixLatencyClass.aidl | 25 ---------------- .../aidl/android/media/AudioPortMixExt.aidl | 4 --- .../include/media/AidlConversion.h | 8 ----- .../include/media/PolicyAidlConversion.h | 1 - 6 files changed, 1 insertion(+), 68 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioMixLatencyClass.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 45788e79ea..08036951a6 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -2559,30 +2559,6 @@ legacy2aidl_AudioEncapsulationMetadataType_mask(uint32_t legacy) { enumToMask_index); } -ConversionResult -aidl2legacy_AudioMixLatencyClass_audio_mix_latency_class_t( - media::AudioMixLatencyClass aidl) { - switch (aidl) { - case media::AudioMixLatencyClass::LOW: - return AUDIO_LATENCY_LOW; - case media::AudioMixLatencyClass::NORMAL: - return AUDIO_LATENCY_NORMAL; - } - return unexpected(BAD_VALUE); -} - -ConversionResult -legacy2aidl_audio_mix_latency_class_t_AudioMixLatencyClass( - audio_mix_latency_class_t legacy) { - switch (legacy) { - case AUDIO_LATENCY_LOW: - return media::AudioMixLatencyClass::LOW; - case AUDIO_LATENCY_NORMAL: - return media::AudioMixLatencyClass::NORMAL; - } - return unexpected(BAD_VALUE); -} - ConversionResult aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl) { audio_port_device_ext legacy; @@ -2611,11 +2587,9 @@ legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(const audio_port_device_ext ConversionResult aidl2legacy_AudioPortMixExt_audio_port_mix_ext(const media::AudioPortMixExt& aidl) { - audio_port_mix_ext legacy; + audio_port_mix_ext legacy{}; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); legacy.handle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.handle)); - legacy.latency_class = VALUE_OR_RETURN( - aidl2legacy_AudioMixLatencyClass_audio_mix_latency_class_t(aidl.latencyClass)); return legacy; } @@ -2624,8 +2598,6 @@ legacy2aidl_audio_port_mix_ext_AudioPortMixExt(const audio_port_mix_ext& legacy) media::AudioPortMixExt aidl; aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); aidl.handle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); - aidl.latencyClass = VALUE_OR_RETURN( - legacy2aidl_audio_mix_latency_class_t_AudioMixLatencyClass(legacy.latency_class)); return aidl; } diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 04b1b93100..3ba1fc25ee 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -319,7 +319,6 @@ aidl_interface { "aidl/android/media/AudioIoConfigEvent.aidl", "aidl/android/media/AudioIoDescriptor.aidl", "aidl/android/media/AudioIoFlags.aidl", - "aidl/android/media/AudioMixLatencyClass.aidl", "aidl/android/media/AudioOutputFlags.aidl", "aidl/android/media/AudioPatch.aidl", "aidl/android/media/AudioPlaybackRate.aidl", diff --git a/media/libaudioclient/aidl/android/media/AudioMixLatencyClass.aidl b/media/libaudioclient/aidl/android/media/AudioMixLatencyClass.aidl deleted file mode 100644 index d70b364376..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioMixLatencyClass.aidl +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * {@hide} - */ -@Backing(type="int") -enum AudioMixLatencyClass { - LOW = 0, - NORMAL = 1, -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl index 62cdb8ef2b..8362c4fc71 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl @@ -16,8 +16,6 @@ package android.media; -import android.media.AudioMixLatencyClass; - /** * {@hide} */ @@ -26,6 +24,4 @@ parcelable AudioPortMixExt { int hwModule; /** I/O handle of the input/output stream. Interpreted as audio_io_handle_t. */ int handle; - /** Latency class */ - AudioMixLatencyClass latencyClass; } diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 1095766515..7b5013d855 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -342,13 +341,6 @@ aidl2legacy_AudioEncapsulationMetadataType_mask(int32_t aidl); ConversionResult legacy2aidl_AudioEncapsulationMetadataType_mask(uint32_t legacy); -ConversionResult -aidl2legacy_AudioMixLatencyClass_audio_mix_latency_class_t( - media::AudioMixLatencyClass aidl); -ConversionResult -legacy2aidl_audio_mix_latency_class_t_AudioMixLatencyClass( - audio_mix_latency_class_t legacy); - ConversionResult aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl); ConversionResult diff --git a/media/libaudioclient/include/media/PolicyAidlConversion.h b/media/libaudioclient/include/media/PolicyAidlConversion.h index edecfeff31..2296fdb9de 100644 --- a/media/libaudioclient/include/media/PolicyAidlConversion.h +++ b/media/libaudioclient/include/media/PolicyAidlConversion.h @@ -23,7 +23,6 @@ #include #include -#include #include #include #include -- GitLab From ceb8bf98b9424ccdc09b1f91cec03f8127f97a28 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 23 Sep 2021 21:29:39 +0000 Subject: [PATCH 156/694] Refactor AudioPort and AudioPortConfig The goals are to split framework-only fields from common, and to simplify and unify structures where possible. What has got changed: 1. Removed 'AudioPort[Config]SessionExt' parcelables. These parcelables correspond to 'audio_port[_config]_session_ext', which is trivial--contains only 'session' field, and hasn't been extented since the inception. Remove AIDL types since each type requires its own file, which adds mental burden. 2. Removed 'AudioPort[Config]DeviceExt' parcelables. At the HAL level only the 'AudioDevice' field is needed. Moved remaining framework-only fields to 'AudioPortDeviceExtSys' which is reused between 'AudioPort' and 'AudioPortConfig'. 3. Merged 'AudioPortConfigMixExt' with 'AudioPortMixExt'. Moved remaining framework-only fields to 'AudioPortMixExtSys'. 4. The previous item allowed using 'AudioPortExt' instead of 'AudioPortConfigExt'. 5. 'AudioPortDeviceExtSys' and 'AudioPortMixExtSys' put into 'AudioPortExtSys' which is a system-only companion to 'AudioPortExt'. Bug: 198812639 Test: atest audiofoundation_parcelable_test Change-Id: I27306f7ce33b136860db6a9784d34960816987cd --- media/libaudioclient/AidlConversion.cpp | 282 ++++++++++-------- media/libaudioclient/Android.bp | 11 +- media/libaudioclient/AudioSystem.cpp | 1 - .../aidl/android/media/AudioPort.aidl | 2 + .../aidl/android/media/AudioPortConfig.aidl | 6 +- .../android/media/AudioPortConfigExt.aidl | 39 --- .../android/media/AudioPortConfigMixExt.aidl | 36 --- .../media/AudioPortConfigSessionExt.aidl | 24 -- ...iceExt.aidl => AudioPortDeviceExtSys.aidl} | 7 +- .../aidl/android/media/AudioPortExt.aidl | 11 +- ...figDeviceExt.aidl => AudioPortExtSys.aidl} | 20 +- .../aidl/android/media/AudioPortMixExt.aidl | 9 +- ...essionExt.aidl => AudioPortMixExtSys.aidl} | 8 +- ...eCase.aidl => AudioPortMixExtUseCase.aidl} | 2 +- .../include/media/AidlConversion.h | 58 ++-- .../DeviceDescriptorBase.cpp | 23 +- 16 files changed, 243 insertions(+), 296 deletions(-) delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortConfigExt.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortConfigMixExt.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortConfigSessionExt.aidl rename media/libaudioclient/aidl/android/media/{AudioPortDeviceExt.aidl => AudioPortDeviceExtSys.aidl} (84%) rename media/libaudioclient/aidl/android/media/{AudioPortConfigDeviceExt.aidl => AudioPortExtSys.aidl} (58%) rename media/libaudioclient/aidl/android/media/{AudioPortSessionExt.aidl => AudioPortMixExtSys.aidl} (76%) rename media/libaudioclient/aidl/android/media/{AudioPortConfigMixExtUseCase.aidl => AudioPortMixExtUseCase.aidl} (97%) diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 08036951a6..0107bd46f6 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -1491,23 +1491,23 @@ ConversionResult legacy2aidl_audio_io_flags_AudioIoFlags( } ConversionResult -aidl2legacy_AudioPortConfigDeviceExt_audio_port_config_device_ext( - const media::AudioPortConfigDeviceExt& aidl) { +aidl2legacy_AudioDevice_audio_port_config_device_ext( + const AudioDevice& aidl, const media::AudioPortDeviceExtSys& aidlDeviceExt) { audio_port_config_device_ext legacy; - legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device( - aidl.device, &legacy.type, legacy.address)); + legacy.hw_module = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_module_handle_t(aidlDeviceExt.hwModule)); + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device(aidl, &legacy.type, legacy.address)); return legacy; } -ConversionResult -legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( - const audio_port_config_device_ext& legacy) { - media::AudioPortConfigDeviceExt aidl; - aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.device = VALUE_OR_RETURN(legacy2aidl_audio_device_AudioDevice( - legacy.type, legacy.address)); - return aidl; +status_t legacy2aidl_audio_port_config_device_ext_AudioDevice( + const audio_port_config_device_ext& legacy, + AudioDevice* aidl, media::AudioPortDeviceExtSys* aidlDeviceExt) { + aidlDeviceExt->hwModule = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); + *aidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_device_AudioDevice(legacy.type, legacy.address)); + return OK; } ConversionResult aidl2legacy_AudioStreamType_audio_stream_type_t( @@ -1675,8 +1675,8 @@ ConversionResult legacy2aidl_audio_session_t_int32_t(audio_session_t le // This type is unnamed in the original definition, thus we name it here. using audio_port_config_mix_ext_usecase = decltype(audio_port_config_mix_ext::usecase); -ConversionResult aidl2legacy_AudioPortConfigMixExtUseCase( - const media::AudioPortConfigMixExtUseCase& aidl, media::AudioPortRole role) { +ConversionResult aidl2legacy_AudioPortMixExtUseCase( + const media::AudioPortMixExtUseCase& aidl, media::AudioPortRole role) { audio_port_config_mix_ext_usecase legacy; switch (role) { @@ -1700,9 +1700,9 @@ ConversionResult aidl2legacy_AudioPortConfigM LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } -ConversionResult legacy2aidl_AudioPortConfigMixExtUseCase( +ConversionResult legacy2aidl_AudioPortMixExtUseCase( const audio_port_config_mix_ext_usecase& legacy, audio_port_role_t role) { - media::AudioPortConfigMixExtUseCase aidl; + media::AudioPortMixExtUseCase aidl; switch (role) { case AUDIO_PORT_ROLE_NONE: @@ -1722,46 +1722,47 @@ ConversionResult legacy2aidl_AudioPortConfi LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } -ConversionResult aidl2legacy_AudioPortConfigMixExt( - const media::AudioPortConfigMixExt& aidl, media::AudioPortRole role) { +ConversionResult aidl2legacy_AudioPortMixExt( + const media::AudioPortMixExt& aidl, media::AudioPortRole role, + const media::AudioPortMixExtSys& aidlMixExt) { audio_port_config_mix_ext legacy; - legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); + legacy.hw_module = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_module_handle_t(aidlMixExt.hwModule)); legacy.handle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.handle)); - legacy.usecase = VALUE_OR_RETURN(aidl2legacy_AudioPortConfigMixExtUseCase(aidl.usecase, role)); + legacy.usecase = VALUE_OR_RETURN(aidl2legacy_AudioPortMixExtUseCase(aidl.usecase, role)); return legacy; } -ConversionResult legacy2aidl_AudioPortConfigMixExt( - const audio_port_config_mix_ext& legacy, audio_port_role_t role) { - media::AudioPortConfigMixExt aidl; - aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.handle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); - aidl.usecase = VALUE_OR_RETURN(legacy2aidl_AudioPortConfigMixExtUseCase(legacy.usecase, role)); - return aidl; +status_t legacy2aidl_AudioPortMixExt( + const audio_port_config_mix_ext& legacy, audio_port_role_t role, + media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { + aidlMixExt->hwModule = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); + aidl->handle = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); + aidl->usecase = VALUE_OR_RETURN_STATUS( + legacy2aidl_AudioPortMixExtUseCase(legacy.usecase, role)); + return OK; } ConversionResult -aidl2legacy_AudioPortConfigSessionExt_audio_port_config_session_ext( - const media::AudioPortConfigSessionExt& aidl) { +aidl2legacy_int32_t_audio_port_config_session_ext(int32_t aidl) { audio_port_config_session_ext legacy; - legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl.session)); + legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl)); return legacy; } -ConversionResult -legacy2aidl_audio_port_config_session_ext_AudioPortConfigSessionExt( +ConversionResult +legacy2aidl_audio_port_config_session_ext_int32_t( const audio_port_config_session_ext& legacy) { - media::AudioPortConfigSessionExt aidl; - aidl.session = VALUE_OR_RETURN(legacy2aidl_audio_session_t_int32_t(legacy.session)); - return aidl; + return legacy2aidl_audio_session_t_int32_t(legacy.session); } // This type is unnamed in the original definition, thus we name it here. using audio_port_config_ext = decltype(audio_port_config::ext); -ConversionResult aidl2legacy_AudioPortConfigExt( - const media::AudioPortConfigExt& aidl, media::AudioPortType type, - media::AudioPortRole role) { +ConversionResult aidl2legacy_AudioPortExt_audio_port_config_ext( + const media::AudioPortExt& aidl, media::AudioPortType type, + media::AudioPortRole role, const media::AudioPortExtSys& aidlSys) { audio_port_config_ext legacy; switch (type) { case media::AudioPortType::NONE: @@ -1770,16 +1771,19 @@ ConversionResult aidl2legacy_AudioPortConfigExt( return legacy; case media::AudioPortType::DEVICE: legacy.device = VALUE_OR_RETURN( - aidl2legacy_AudioPortConfigDeviceExt_audio_port_config_device_ext( - VALUE_OR_RETURN(UNION_GET(aidl, device)))); + aidl2legacy_AudioDevice_audio_port_config_device_ext( + VALUE_OR_RETURN(UNION_GET(aidl, device)), + VALUE_OR_RETURN(UNION_GET(aidlSys, device)))); return legacy; case media::AudioPortType::MIX: legacy.mix = VALUE_OR_RETURN( - aidl2legacy_AudioPortConfigMixExt(VALUE_OR_RETURN(UNION_GET(aidl, mix)), role)); + aidl2legacy_AudioPortMixExt( + VALUE_OR_RETURN(UNION_GET(aidl, mix)), role, + VALUE_OR_RETURN(UNION_GET(aidlSys, mix)))); return legacy; case media::AudioPortType::SESSION: legacy.session = VALUE_OR_RETURN( - aidl2legacy_AudioPortConfigSessionExt_audio_port_config_session_ext( + aidl2legacy_int32_t_audio_port_config_session_ext( VALUE_OR_RETURN(UNION_GET(aidl, session)))); return legacy; @@ -1787,30 +1791,37 @@ ConversionResult aidl2legacy_AudioPortConfigExt( LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } -ConversionResult legacy2aidl_AudioPortConfigExt( - const audio_port_config_ext& legacy, audio_port_type_t type, audio_port_role_t role) { - media::AudioPortConfigExt aidl; - +status_t legacy2aidl_AudioPortExt( + const audio_port_config_ext& legacy, audio_port_type_t type, audio_port_role_t role, + media::AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { switch (type) { case AUDIO_PORT_TYPE_NONE: - UNION_SET(aidl, unspecified, false); - return aidl; - case AUDIO_PORT_TYPE_DEVICE: - UNION_SET(aidl, device, - VALUE_OR_RETURN( - legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( - legacy.device))); - return aidl; - case AUDIO_PORT_TYPE_MIX: - UNION_SET(aidl, mix, - VALUE_OR_RETURN(legacy2aidl_AudioPortConfigMixExt(legacy.mix, role))); - return aidl; + UNION_SET(*aidl, unspecified, false); + UNION_SET(*aidlSys, unspecified, false); + return OK; + case AUDIO_PORT_TYPE_DEVICE: { + AudioDevice device; + media::AudioPortDeviceExtSys deviceSys; + RETURN_STATUS_IF_ERROR( + legacy2aidl_audio_port_config_device_ext_AudioDevice( + legacy.device, &device, &deviceSys)); + UNION_SET(*aidl, device, device); + UNION_SET(*aidlSys, device, deviceSys); + return OK; + } + case AUDIO_PORT_TYPE_MIX: { + media::AudioPortMixExt mix; + media::AudioPortMixExtSys mixSys; + RETURN_STATUS_IF_ERROR(legacy2aidl_AudioPortMixExt(legacy.mix, role, &mix, &mixSys)); + UNION_SET(*aidl, mix, mix); + UNION_SET(*aidlSys, mix, mixSys); + return OK; + } case AUDIO_PORT_TYPE_SESSION: - UNION_SET(aidl, session, - VALUE_OR_RETURN( - legacy2aidl_audio_port_config_session_ext_AudioPortConfigSessionExt( - legacy.session))); - return aidl; + UNION_SET(*aidl, session, VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_port_config_session_ext_int32_t(legacy.session))); + UNION_SET(*aidlSys, unspecified, false); + return OK; } LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } @@ -1849,7 +1860,9 @@ ConversionResult aidl2legacy_AudioPortConfig_audio_port_confi aidl2legacy_AudioIoFlags_audio_io_flags(aidl.flags.value(), aidl.role, aidl.type)); legacy.config_mask |= AUDIO_PORT_CONFIG_FLAGS; } - legacy.ext = VALUE_OR_RETURN(aidl2legacy_AudioPortConfigExt(aidl.ext, aidl.type, aidl.role)); + legacy.ext = VALUE_OR_RETURN( + aidl2legacy_AudioPortExt_audio_port_config_ext( + aidl.ext, aidl.type, aidl.role, aidl.extSys)); return legacy; } @@ -1882,8 +1895,8 @@ ConversionResult legacy2aidl_audio_port_config_AudioPort aidl.flags = VALUE_OR_RETURN( legacy2aidl_audio_io_flags_AudioIoFlags(legacy.flags, legacy.role, legacy.type)); } - aidl.ext = - VALUE_OR_RETURN(legacy2aidl_AudioPortConfigExt(legacy.ext, legacy.type, legacy.role)); + RETURN_IF_ERROR(legacy2aidl_AudioPortExt(legacy.ext, legacy.type, legacy.role, + &aidl.ext, &aidl.extSys)); return aidl; } @@ -2560,66 +2573,70 @@ legacy2aidl_AudioEncapsulationMetadataType_mask(uint32_t legacy) { } ConversionResult -aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl) { +aidl2legacy_AudioDevice_audio_port_device_ext( + const AudioDevice& aidl, const media::AudioPortDeviceExtSys& aidlSys) { audio_port_device_ext legacy; - legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); - RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device( - aidl.device, &legacy.type, legacy.address)); + legacy.hw_module = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_module_handle_t(aidlSys.hwModule)); + RETURN_IF_ERROR(aidl2legacy_AudioDevice_audio_device(aidl, &legacy.type, legacy.address)); legacy.encapsulation_modes = VALUE_OR_RETURN( - aidl2legacy_AudioEncapsulationMode_mask(aidl.encapsulationModes)); + aidl2legacy_AudioEncapsulationMode_mask(aidlSys.encapsulationModes)); legacy.encapsulation_metadata_types = VALUE_OR_RETURN( - aidl2legacy_AudioEncapsulationMetadataType_mask(aidl.encapsulationMetadataTypes)); + aidl2legacy_AudioEncapsulationMetadataType_mask( + aidlSys.encapsulationMetadataTypes)); return legacy; } -ConversionResult -legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(const audio_port_device_ext& legacy) { - media::AudioPortDeviceExt aidl; - aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.device = VALUE_OR_RETURN(legacy2aidl_audio_device_AudioDevice( - legacy.type, legacy.address)); - aidl.encapsulationModes = VALUE_OR_RETURN( +status_t legacy2aidl_audio_port_device_ext_AudioDevice( + const audio_port_device_ext& legacy, + AudioDevice* aidl, media::AudioPortDeviceExtSys* aidlDeviceExt) { + aidlDeviceExt->hwModule = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); + *aidl = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_device_AudioDevice(legacy.type, legacy.address)); + aidlDeviceExt->encapsulationModes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMode_mask(legacy.encapsulation_modes)); - aidl.encapsulationMetadataTypes = VALUE_OR_RETURN( + aidlDeviceExt->encapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMetadataType_mask(legacy.encapsulation_metadata_types)); - return aidl; + return OK; } ConversionResult -aidl2legacy_AudioPortMixExt_audio_port_mix_ext(const media::AudioPortMixExt& aidl) { +aidl2legacy_AudioPortMixExt_audio_port_mix_ext( + const media::AudioPortMixExt& aidl, const media::AudioPortMixExtSys& aidlSys) { audio_port_mix_ext legacy{}; - legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidl.hwModule)); + legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidlSys.hwModule)); legacy.handle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.handle)); return legacy; } -ConversionResult -legacy2aidl_audio_port_mix_ext_AudioPortMixExt(const audio_port_mix_ext& legacy) { - media::AudioPortMixExt aidl; - aidl.hwModule = VALUE_OR_RETURN(legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); - aidl.handle = VALUE_OR_RETURN(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); - return aidl; +status_t +legacy2aidl_audio_port_mix_ext_AudioPortMixExt(const audio_port_mix_ext& legacy, + media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { + aidlMixExt->hwModule = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); + aidl->handle = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); + return OK; } ConversionResult -aidl2legacy_AudioPortSessionExt_audio_port_session_ext(const media::AudioPortSessionExt& aidl) { +aidl2legacy_int32_t_audio_port_session_ext(int32_t aidl) { audio_port_session_ext legacy; - legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl.session)); + legacy.session = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_session_t(aidl)); return legacy; } -ConversionResult -legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy) { - media::AudioPortSessionExt aidl; - aidl.session = VALUE_OR_RETURN(legacy2aidl_audio_session_t_int32_t(legacy.session)); - return aidl; +ConversionResult +legacy2aidl_audio_port_session_ext_int32_t(const audio_port_session_ext& legacy) { + return legacy2aidl_audio_session_t_int32_t(legacy.session); } // This type is unnamed in the original definition, thus we name it here. using audio_port_v7_ext = decltype(audio_port_v7::ext); -ConversionResult aidl2legacy_AudioPortExt( - const media::AudioPortExt& aidl, media::AudioPortType type) { +ConversionResult aidl2legacy_AudioPortExt_audio_port_v7_ext( + const media::AudioPortExt& aidl, media::AudioPortType type, + const media::AudioPortExtSys& aidlSys) { audio_port_v7_ext legacy; switch (type) { case media::AudioPortType::NONE: @@ -2628,44 +2645,59 @@ ConversionResult aidl2legacy_AudioPortExt( return legacy; case media::AudioPortType::DEVICE: legacy.device = VALUE_OR_RETURN( - aidl2legacy_AudioPortDeviceExt_audio_port_device_ext( - VALUE_OR_RETURN(UNION_GET(aidl, device)))); + aidl2legacy_AudioDevice_audio_port_device_ext( + VALUE_OR_RETURN(UNION_GET(aidl, device)), + VALUE_OR_RETURN(UNION_GET(aidlSys, device)))); return legacy; case media::AudioPortType::MIX: legacy.mix = VALUE_OR_RETURN( aidl2legacy_AudioPortMixExt_audio_port_mix_ext( - VALUE_OR_RETURN(UNION_GET(aidl, mix)))); + VALUE_OR_RETURN(UNION_GET(aidl, mix)), + VALUE_OR_RETURN(UNION_GET(aidlSys, mix)))); return legacy; case media::AudioPortType::SESSION: - legacy.session = VALUE_OR_RETURN(aidl2legacy_AudioPortSessionExt_audio_port_session_ext( - VALUE_OR_RETURN(UNION_GET(aidl, session)))); + legacy.session = VALUE_OR_RETURN( + aidl2legacy_int32_t_audio_port_session_ext( + VALUE_OR_RETURN(UNION_GET(aidl, session)))); return legacy; } LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } -ConversionResult legacy2aidl_AudioPortExt( - const audio_port_v7_ext& legacy, audio_port_type_t type) { - media::AudioPortExt aidl; +status_t legacy2aidl_AudioPortExt( + const audio_port_v7_ext& legacy, audio_port_type_t type, + media::AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { switch (type) { case AUDIO_PORT_TYPE_NONE: - UNION_SET(aidl, unspecified, false); - return aidl; - case AUDIO_PORT_TYPE_DEVICE: - UNION_SET(aidl, device, - VALUE_OR_RETURN( - legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(legacy.device))); - return aidl; - case AUDIO_PORT_TYPE_MIX: - UNION_SET(aidl, mix, - VALUE_OR_RETURN(legacy2aidl_audio_port_mix_ext_AudioPortMixExt(legacy.mix))); - return aidl; + UNION_SET(*aidl, unspecified, false); + UNION_SET(*aidlSys, unspecified, false); + return OK; + case AUDIO_PORT_TYPE_DEVICE: { + AudioDevice device; + media::AudioPortDeviceExtSys deviceSys; + RETURN_STATUS_IF_ERROR( + legacy2aidl_audio_port_device_ext_AudioDevice( + legacy.device, &device, &deviceSys)); + UNION_SET(*aidl, device, device); + UNION_SET(*aidlSys, device, deviceSys); + return OK; + } + case AUDIO_PORT_TYPE_MIX: { + media::AudioPortMixExt mix; + media::AudioPortMixExtSys mixSys; + RETURN_STATUS_IF_ERROR( + legacy2aidl_audio_port_mix_ext_AudioPortMixExt( + legacy.mix, &mix, &mixSys)); + UNION_SET(*aidl, mix, mix); + UNION_SET(*aidlSys, mix, mixSys); + return OK; + } case AUDIO_PORT_TYPE_SESSION: - UNION_SET(aidl, session, - VALUE_OR_RETURN(legacy2aidl_audio_port_session_ext_AudioPortSessionExt( - legacy.session))); - return aidl; + UNION_SET(*aidl, session, VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_port_session_ext_int32_t(legacy.session))); + UNION_SET(*aidlSys, unspecified, false); + return OK; } LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } @@ -2795,7 +2827,8 @@ aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { legacy.active_config = VALUE_OR_RETURN( aidl2legacy_AudioPortConfig_audio_port_config(aidl.activeConfig)); - legacy.ext = VALUE_OR_RETURN(aidl2legacy_AudioPortExt(aidl.ext, aidl.type)); + legacy.ext = VALUE_OR_RETURN( + aidl2legacy_AudioPortExt_audio_port_v7_ext(aidl.ext, aidl.type, aidl.extSys)); return legacy; } @@ -2841,7 +2874,8 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { aidl.activeConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); - aidl.ext = VALUE_OR_RETURN(legacy2aidl_AudioPortExt(legacy.ext, legacy.type)); + RETURN_IF_ERROR( + legacy2aidl_AudioPortExt(legacy.ext, legacy.type, &aidl.ext, &aidl.extSys)); return aidl; } diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 3ba1fc25ee..3c8796e73b 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -324,16 +324,13 @@ aidl_interface { "aidl/android/media/AudioPlaybackRate.aidl", "aidl/android/media/AudioPort.aidl", "aidl/android/media/AudioPortConfig.aidl", - "aidl/android/media/AudioPortConfigDeviceExt.aidl", - "aidl/android/media/AudioPortConfigExt.aidl", - "aidl/android/media/AudioPortConfigMixExt.aidl", - "aidl/android/media/AudioPortConfigMixExtUseCase.aidl", - "aidl/android/media/AudioPortConfigSessionExt.aidl", - "aidl/android/media/AudioPortDeviceExt.aidl", + "aidl/android/media/AudioPortDeviceExtSys.aidl", "aidl/android/media/AudioPortExt.aidl", + "aidl/android/media/AudioPortExtSys.aidl", "aidl/android/media/AudioPortMixExt.aidl", + "aidl/android/media/AudioPortMixExtSys.aidl", + "aidl/android/media/AudioPortMixExtUseCase.aidl", "aidl/android/media/AudioPortRole.aidl", - "aidl/android/media/AudioPortSessionExt.aidl", "aidl/android/media/AudioPortType.aidl", "aidl/android/media/AudioProfileSys.aidl", "aidl/android/media/AudioStandard.aidl", diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index 377af28f42..d9b428588a 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -50,7 +50,6 @@ using media::IAudioPolicyService; using media::audio::common::AudioConfig; using media::audio::common::AudioConfigBase; using media::audio::common::AudioDevice; -using media::audio::common::AudioDeviceAddress; using media::audio::common::AudioDeviceDescription; using media::audio::common::AudioFormatDescription; using media::audio::common::AudioMMapPolicyInfo; diff --git a/media/libaudioclient/aidl/android/media/AudioPort.aidl b/media/libaudioclient/aidl/android/media/AudioPort.aidl index 92b88ed283..76e55b9c40 100644 --- a/media/libaudioclient/aidl/android/media/AudioPort.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPort.aidl @@ -19,6 +19,7 @@ package android.media; import android.media.AudioGainSys; import android.media.AudioPortConfig; import android.media.AudioPortExt; +import android.media.AudioPortExtSys; import android.media.AudioPortRole; import android.media.AudioPortType; import android.media.AudioProfileSys; @@ -53,4 +54,5 @@ parcelable AudioPort { /** Current audio port configuration. */ AudioPortConfig activeConfig; AudioPortExt ext; + AudioPortExtSys extSys; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index 4e1520ccd2..ffeb905587 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -17,7 +17,8 @@ package android.media; import android.media.AudioIoFlags; -import android.media.AudioPortConfigExt; +import android.media.AudioPortExt; +import android.media.AudioPortExtSys; import android.media.AudioPortRole; import android.media.AudioPortType; import android.media.Int; @@ -48,5 +49,6 @@ parcelable AudioPortConfig { @nullable AudioGainConfig gain; /** Framework only: HW_AV_SYNC, DIRECT, ... Can be left unspecified. */ @nullable AudioIoFlags flags; - AudioPortConfigExt ext; + AudioPortExt ext; + AudioPortExtSys extSys; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigExt.aidl deleted file mode 100644 index 5d635b6d09..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigExt.aidl +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioPortConfigDeviceExt; -import android.media.AudioPortConfigMixExt; -import android.media.AudioPortConfigSessionExt; - -/** - * {@hide} - */ -union AudioPortConfigExt { - /** - * This represents an empty union. Value is ignored. - * TODO(ytai): replace with the canonical representation for an empty union, as soon as it is - * established. - */ - boolean unspecified; - /** Device specific info. */ - AudioPortConfigDeviceExt device; - /** Mix specific info. */ - AudioPortConfigMixExt mix; - /** Session specific info. */ - AudioPortConfigSessionExt session; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigMixExt.aidl deleted file mode 100644 index d3226f2f2f..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExt.aidl +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioPortConfigMixExtUseCase; - -/** - * {@hide} - */ -parcelable AudioPortConfigMixExt { - /** - * Module the stream is attached to. - * Interpreted as audio_module_handle_t. - */ - int hwModule; - /** - * I/O handle of the input/output stream. - * Interpreted as audio_io_handle_t. - */ - int handle; - AudioPortConfigMixExtUseCase usecase; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigSessionExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigSessionExt.aidl deleted file mode 100644 index a2cbf62883..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigSessionExt.aidl +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * {@hide} - */ -parcelable AudioPortConfigSessionExt { - int session; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortDeviceExtSys.aidl similarity index 84% rename from media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl rename to media/libaudioclient/aidl/android/media/AudioPortDeviceExtSys.aidl index c28d688e81..0f5a9b67f6 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortDeviceExtSys.aidl @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,12 @@ package android.media; -import android.media.audio.common.AudioDevice; - /** * {@hide} */ -parcelable AudioPortDeviceExt { +parcelable AudioPortDeviceExtSys { /** Module the device is attached to. Interpreted as audio_module_handle_t. */ int hwModule; - AudioDevice device; /** Bitmask, indexed by AudioEncapsulationMode. */ int encapsulationModes; /** Bitmask, indexed by AudioEncapsulationMetadataType. */ diff --git a/media/libaudioclient/aidl/android/media/AudioPortExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortExt.aidl index 453784be66..27693b2886 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortExt.aidl @@ -16,9 +16,8 @@ package android.media; -import android.media.AudioPortDeviceExt; import android.media.AudioPortMixExt; -import android.media.AudioPortSessionExt; +import android.media.audio.common.AudioDevice; /** * {@hide} @@ -30,10 +29,10 @@ union AudioPortExt { * established. */ boolean unspecified; - /** Device specific info. */ - AudioPortDeviceExt device; + /** Audio device specification. */ + AudioDevice device; /** Mix specific info. */ AudioPortMixExt mix; - /** Session specific info. */ - AudioPortSessionExt session; + /** Audio session identifier. */ + int session; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortExtSys.aidl similarity index 58% rename from media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl rename to media/libaudioclient/aidl/android/media/AudioPortExtSys.aidl index 640a63b545..2cdf4f68ca 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigDeviceExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortExtSys.aidl @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,19 @@ package android.media; -import android.media.audio.common.AudioDevice; +import android.media.AudioPortDeviceExtSys; +import android.media.AudioPortMixExtSys; /** * {@hide} */ -parcelable AudioPortConfigDeviceExt { +union AudioPortExtSys { /** - * Module the device is attached to. - * Interpreted as audio_module_handle_t. + * This represents an empty union. Value is ignored. */ - int hwModule; - /** - * Audio device instance. - */ - AudioDevice device; + boolean unspecified; + /** System-only parameters when the port is an audio device. */ + AudioPortDeviceExtSys device; + /** System-only parameters when the port is an audio mix. */ + AudioPortMixExtSys mix; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl index 8362c4fc71..d222d0a18e 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl @@ -16,12 +16,15 @@ package android.media; +import android.media.AudioPortMixExtUseCase; + /** * {@hide} */ parcelable AudioPortMixExt { - /** Module the stream is attached to. Interpreted as audio_module_handle_t. */ - int hwModule; - /** I/O handle of the input/output stream. Interpreted as audio_io_handle_t. */ + /** + * I/O handle of the input/output stream. Interpreted as audio_io_handle_t. + */ int handle; + AudioPortMixExtUseCase usecase; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortSessionExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExtSys.aidl similarity index 76% rename from media/libaudioclient/aidl/android/media/AudioPortSessionExt.aidl rename to media/libaudioclient/aidl/android/media/AudioPortMixExtSys.aidl index dbca168988..599988586a 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortSessionExt.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortMixExtSys.aidl @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package android.media; /** * {@hide} */ -parcelable AudioPortSessionExt { - /** Audio session. Interpreted as audio_session_t. */ - int session; +parcelable AudioPortMixExtSys { + /** Module the stream is attached to. Interpreted as audio_module_handle_t. */ + int hwModule; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl similarity index 97% rename from media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl rename to media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl index 58bc1a56d3..77f2fbb673 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfigMixExtUseCase.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl @@ -22,7 +22,7 @@ import android.media.audio.common.AudioStreamType; /** * {@hide} */ -union AudioPortConfigMixExtUseCase { +union AudioPortMixExtUseCase { /** * This to be set if the containing config has the AudioPortRole::NONE role. * This represents an empty value (value is ignored). diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 7b5013d855..30fd309497 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -31,10 +31,9 @@ #include #include #include -#include +#include +#include #include -#include -#include #include #include #include @@ -198,11 +197,12 @@ ConversionResult legacy2aidl_audio_io_flags_AudioIoFlags( const audio_io_flags& legacy, audio_port_role_t role, audio_port_type_t type); ConversionResult -aidl2legacy_AudioPortConfigDeviceExt_audio_port_config_device_ext( - const media::AudioPortConfigDeviceExt& aidl); -ConversionResult -legacy2aidl_audio_port_config_device_ext_AudioPortConfigDeviceExt( - const audio_port_config_device_ext& legacy); +aidl2legacy_AudioDevice_audio_port_config_device_ext( + const media::audio::common::AudioDevice& aidl, + const media::AudioPortDeviceExtSys& aidlDeviceExt); +status_t legacy2aidl_audio_port_config_device_ext_AudioDevice( + const audio_port_config_device_ext& legacy, + media::audio::common::AudioDevice* aidl, media::AudioPortDeviceExtSys* aidlDeviceExt); ConversionResult aidl2legacy_AudioStreamType_audio_stream_type_t( media::audio::common::AudioStreamType aidl); @@ -218,16 +218,16 @@ ConversionResult ConversionResult aidl2legacy_int32_t_audio_session_t(int32_t aidl); ConversionResult legacy2aidl_audio_session_t_int32_t(audio_session_t legacy); -ConversionResult aidl2legacy_AudioPortConfigMixExt( - const media::AudioPortConfigMixExt& aidl, media::AudioPortRole role); -ConversionResult legacy2aidl_AudioPortConfigMixExt( - const audio_port_config_mix_ext& legacy, audio_port_role_t role); +ConversionResult aidl2legacy_AudioPortMixExt( + const media::AudioPortMixExt& aidl, media::AudioPortRole role, + const media::AudioPortMixExtSys& aidlMixExt); +status_t legacy2aidl_AudioPortMixExt( + const audio_port_config_mix_ext& legacy, audio_port_role_t role, + media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt); ConversionResult -aidl2legacy_AudioPortConfigSessionExt_audio_port_config_session_ext( - const media::AudioPortConfigSessionExt& aidl); -ConversionResult -legacy2aidl_audio_port_config_session_ext_AudioPortConfigSessionExt( +aidl2legacy_int32_t_audio_port_config_session_ext(int32_t aidl); +ConversionResult legacy2aidl_audio_port_config_session_ext_AudioPortConfigSessionExt( const audio_port_config_session_ext& legacy); ConversionResult aidl2legacy_AudioPortConfig_audio_port_config( @@ -342,19 +342,27 @@ ConversionResult legacy2aidl_AudioEncapsulationMetadataType_mask(uint32_t legacy); ConversionResult -aidl2legacy_AudioPortDeviceExt_audio_port_device_ext(const media::AudioPortDeviceExt& aidl); -ConversionResult -legacy2aidl_audio_port_device_ext_AudioPortDeviceExt(const audio_port_device_ext& legacy); +aidl2legacy_AudioDevice_audio_port_device_ext( + const media::audio::common::AudioDevice& aidl, + const media::AudioPortDeviceExtSys& aidlDeviceExt); +status_t legacy2aidl_audio_port_device_ext_AudioDevice( + const audio_port_device_ext& legacy, + media::audio::common::AudioDevice* aidl, + media::AudioPortDeviceExtSys* aidlDeviceExt); ConversionResult -aidl2legacy_AudioPortMixExt_audio_port_mix_ext(const media::AudioPortMixExt& aidl); -ConversionResult -legacy2aidl_audio_port_mix_ext_AudioPortMixExt(const audio_port_mix_ext& legacy); +aidl2legacy_AudioPortMixExt_audio_port_mix_ext( + const media::AudioPortMixExt& aidl, + const media::AudioPortMixExtSys& aidlMixExt); +status_t legacy2aidl_audio_port_mix_ext_AudioPortMixExt( + const audio_port_mix_ext& legacy, + media::AudioPortMixExt* aidl, + media::AudioPortMixExtSys* aidlMixExt); ConversionResult -aidl2legacy_AudioPortSessionExt_audio_port_session_ext(const media::AudioPortSessionExt& aidl); -ConversionResult -legacy2aidl_audio_port_session_ext_AudioPortSessionExt(const audio_port_session_ext& legacy); +aidl2legacy_int32_t_audio_port_session_ext(int32_t aidl); +ConversionResult +legacy2aidl_audio_port_session_ext_int32_t(const audio_port_session_ext& legacy); ConversionResult aidl2legacy_AudioProfile_audio_profile( diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp index 3cce722225..2e9b0053ac 100644 --- a/media/libaudiofoundation/DeviceDescriptorBase.cpp +++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp @@ -169,13 +169,15 @@ status_t DeviceDescriptorBase::writeToParcelable(media::AudioPort* parcelable) c AudioPortConfig::writeToParcelable(&parcelable->activeConfig, useInputChannelMask()); parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); - media::AudioPortDeviceExt ext; - ext.device = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioDeviceTypeAddress(mDeviceTypeAddr)); - ext.encapsulationModes = VALUE_OR_RETURN_STATUS( + media::audio::common::AudioDevice device = VALUE_OR_RETURN_STATUS( + legacy2aidl_AudioDeviceTypeAddress(mDeviceTypeAddr)); + UNION_SET(parcelable->ext, device, device); + media::AudioPortDeviceExtSys deviceSys; + deviceSys.encapsulationModes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMode_mask(mEncapsulationModes)); - ext.encapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( + deviceSys.encapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMetadataType_mask(mEncapsulationMetadataTypes)); - UNION_SET(parcelable->ext, device, std::move(ext)); + UNION_SET(parcelable->extSys, device, deviceSys); return OK; } @@ -195,13 +197,16 @@ status_t DeviceDescriptorBase::readFromParcelable(const media::AudioPort& parcel return status; } - media::AudioPortDeviceExt ext = VALUE_OR_RETURN_STATUS(UNION_GET(parcelable.ext, device)); + media::audio::common::AudioDevice device = VALUE_OR_RETURN_STATUS( + UNION_GET(parcelable.ext, device)); mDeviceTypeAddr = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioDeviceTypeAddress(ext.device)); + aidl2legacy_AudioDeviceTypeAddress(device)); + media::AudioPortDeviceExtSys deviceSys = VALUE_OR_RETURN_STATUS( + UNION_GET(parcelable.extSys, device)); mEncapsulationModes = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioEncapsulationMode_mask(ext.encapsulationModes)); + aidl2legacy_AudioEncapsulationMode_mask(deviceSys.encapsulationModes)); mEncapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioEncapsulationMetadataType_mask(ext.encapsulationMetadataTypes)); + aidl2legacy_AudioEncapsulationMetadataType_mask(deviceSys.encapsulationMetadataTypes)); return OK; } -- GitLab From 0078ee57547cae721a5e3fd1f03effb35a273df9 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Thu, 30 Sep 2021 23:06:20 +0000 Subject: [PATCH 157/694] Split AudioPort/Config between fwk and android.media.audio.common a.m.a.c adds versions of AudioPort/Config structs which are similar to Audio HIDL HAL V7. They lack some bits used only by the framework. These are carried in AudioPortSys/PortConfigSys. media::AudioPort/Config join the HAL part and the system part together. Updated to/from AIDL conversions in libaudiofondation. Bug: 198812639 Test: atest audiofoundation_parcelable_test Change-Id: I383cf2b07d9931dbea1ba0d10bb60cdd0b57039c --- media/libaudioclient/AidlConversion.cpp | 174 ++++++++++-------- media/libaudioclient/Android.bp | 8 +- media/libaudioclient/AudioEffect.cpp | 2 +- media/libaudioclient/AudioSystem.cpp | 9 +- .../aidl/android/media/AudioPort.aidl | 38 +--- .../aidl/android/media/AudioPortConfig.aidl | 34 +--- ...escriptor.aidl => AudioPortConfigSys.aidl} | 21 ++- .../aidl/android/media/AudioPortExt.aidl | 38 ---- .../aidl/android/media/AudioPortMixExt.aidl | 30 --- .../android/media/AudioPortMixExtUseCase.aidl | 37 ---- .../aidl/android/media/AudioPortSys.aidl | 42 +++++ .../aidl/android/media/AudioStandard.aidl | 27 --- .../android/media/IAudioPolicyService.aidl | 2 +- .../aidl/android/media/Int.aidl | 27 --- .../include/media/AidlConversion.h | 22 ++- media/libaudiofoundation/AudioPort.cpp | 39 ++-- .../DeviceDescriptorBase.cpp | 17 +- .../include/media/AudioPort.h | 14 +- .../tests/audiofoundation_parcelable_test.cpp | 4 +- .../service/AudioPolicyInterfaceImpl.cpp | 11 +- .../audiopolicy/service/AudioPolicyService.h | 11 +- 21 files changed, 230 insertions(+), 377 deletions(-) rename media/libaudioclient/aidl/android/media/{ExtraAudioDescriptor.aidl => AudioPortConfigSys.aidl} (62%) delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortExt.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl create mode 100644 media/libaudioclient/aidl/android/media/AudioPortSys.aidl delete mode 100644 media/libaudioclient/aidl/android/media/AudioStandard.aidl delete mode 100644 media/libaudioclient/aidl/android/media/Int.aidl diff --git a/media/libaudioclient/AidlConversion.cpp b/media/libaudioclient/AidlConversion.cpp index 0107bd46f6..5f63a69203 100644 --- a/media/libaudioclient/AidlConversion.cpp +++ b/media/libaudioclient/AidlConversion.cpp @@ -52,11 +52,17 @@ using media::audio::common::AudioGainConfig; using media::audio::common::AudioGainMode; using media::audio::common::AudioMode; using media::audio::common::AudioOffloadInfo; +using media::audio::common::AudioPortExt; +using media::audio::common::AudioPortMixExt; +using media::audio::common::AudioPortMixExtUseCase; using media::audio::common::AudioProfile; using media::audio::common::AudioSource; +using media::audio::common::AudioStandard; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; using media::audio::common::AudioUuid; +using media::audio::common::ExtraAudioDescriptor; +using media::audio::common::Int; using media::audio::common::PcmType; namespace { @@ -1676,7 +1682,7 @@ ConversionResult legacy2aidl_audio_session_t_int32_t(audio_session_t le using audio_port_config_mix_ext_usecase = decltype(audio_port_config_mix_ext::usecase); ConversionResult aidl2legacy_AudioPortMixExtUseCase( - const media::AudioPortMixExtUseCase& aidl, media::AudioPortRole role) { + const AudioPortMixExtUseCase& aidl, media::AudioPortRole role) { audio_port_config_mix_ext_usecase legacy; switch (role) { @@ -1700,9 +1706,9 @@ ConversionResult aidl2legacy_AudioPortMixExtU LOG_ALWAYS_FATAL("Shouldn't get here"); // with -Werror,-Wswitch may compile-time fail } -ConversionResult legacy2aidl_AudioPortMixExtUseCase( +ConversionResult legacy2aidl_AudioPortMixExtUseCase( const audio_port_config_mix_ext_usecase& legacy, audio_port_role_t role) { - media::AudioPortMixExtUseCase aidl; + AudioPortMixExtUseCase aidl; switch (role) { case AUDIO_PORT_ROLE_NONE: @@ -1723,7 +1729,7 @@ ConversionResult legacy2aidl_AudioPortMixExtUseCa } ConversionResult aidl2legacy_AudioPortMixExt( - const media::AudioPortMixExt& aidl, media::AudioPortRole role, + const AudioPortMixExt& aidl, media::AudioPortRole role, const media::AudioPortMixExtSys& aidlMixExt) { audio_port_config_mix_ext legacy; legacy.hw_module = VALUE_OR_RETURN( @@ -1735,7 +1741,7 @@ ConversionResult aidl2legacy_AudioPortMixExt( status_t legacy2aidl_AudioPortMixExt( const audio_port_config_mix_ext& legacy, audio_port_role_t role, - media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { + AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { aidlMixExt->hwModule = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); aidl->handle = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); @@ -1761,7 +1767,7 @@ legacy2aidl_audio_port_config_session_ext_int32_t( using audio_port_config_ext = decltype(audio_port_config::ext); ConversionResult aidl2legacy_AudioPortExt_audio_port_config_ext( - const media::AudioPortExt& aidl, media::AudioPortType type, + const AudioPortExt& aidl, media::AudioPortType type, media::AudioPortRole role, const media::AudioPortExtSys& aidlSys) { audio_port_config_ext legacy; switch (type) { @@ -1793,7 +1799,7 @@ ConversionResult aidl2legacy_AudioPortExt_audio_port_conf status_t legacy2aidl_AudioPortExt( const audio_port_config_ext& legacy, audio_port_type_t type, audio_port_role_t role, - media::AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { + AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { switch (type) { case AUDIO_PORT_TYPE_NONE: UNION_SET(*aidl, unspecified, false); @@ -1810,7 +1816,7 @@ status_t legacy2aidl_AudioPortExt( return OK; } case AUDIO_PORT_TYPE_MIX: { - media::AudioPortMixExt mix; + AudioPortMixExt mix; media::AudioPortMixExtSys mixSys; RETURN_STATUS_IF_ERROR(legacy2aidl_AudioPortMixExt(legacy.mix, role, &mix, &mixSys)); UNION_SET(*aidl, mix, mix); @@ -1829,74 +1835,76 @@ status_t legacy2aidl_AudioPortExt( ConversionResult aidl2legacy_AudioPortConfig_audio_port_config( const media::AudioPortConfig& aidl) { audio_port_config legacy{}; - legacy.id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.id)); - legacy.role = VALUE_OR_RETURN(aidl2legacy_AudioPortRole_audio_port_role_t(aidl.role)); - legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioPortType_audio_port_type_t(aidl.type)); - const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; - if (aidl.sampleRate.has_value()) { + legacy.id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.hal.id)); + legacy.role = VALUE_OR_RETURN(aidl2legacy_AudioPortRole_audio_port_role_t(aidl.sys.role)); + legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioPortType_audio_port_type_t(aidl.sys.type)); + const bool isInput = + VALUE_OR_RETURN(direction(aidl.sys.role, aidl.sys.type)) == Direction::INPUT; + if (aidl.hal.sampleRate.has_value()) { legacy.sample_rate = VALUE_OR_RETURN( - convertIntegral(aidl.sampleRate.value().value)); + convertIntegral(aidl.hal.sampleRate.value().value)); legacy.config_mask |= AUDIO_PORT_CONFIG_SAMPLE_RATE; } - if (aidl.channelMask.has_value()) { + if (aidl.hal.channelMask.has_value()) { legacy.channel_mask = VALUE_OR_RETURN( aidl2legacy_AudioChannelLayout_audio_channel_mask_t( - aidl.channelMask.value(), isInput)); + aidl.hal.channelMask.value(), isInput)); legacy.config_mask |= AUDIO_PORT_CONFIG_CHANNEL_MASK; } - if (aidl.format.has_value()) { + if (aidl.hal.format.has_value()) { legacy.format = VALUE_OR_RETURN( - aidl2legacy_AudioFormatDescription_audio_format_t(aidl.format.value())); + aidl2legacy_AudioFormatDescription_audio_format_t(aidl.hal.format.value())); legacy.config_mask |= AUDIO_PORT_CONFIG_FORMAT; } - if (aidl.gain.has_value()) { + if (aidl.hal.gain.has_value()) { legacy.gain = VALUE_OR_RETURN(aidl2legacy_AudioGainConfig_audio_gain_config( - aidl.gain.value(), isInput)); + aidl.hal.gain.value(), isInput)); legacy.config_mask |= AUDIO_PORT_CONFIG_GAIN; } - if (aidl.flags.has_value()) { + if (aidl.sys.flags.has_value()) { legacy.flags = VALUE_OR_RETURN( - aidl2legacy_AudioIoFlags_audio_io_flags(aidl.flags.value(), aidl.role, aidl.type)); + aidl2legacy_AudioIoFlags_audio_io_flags( + aidl.sys.flags.value(), aidl.sys.role, aidl.sys.type)); legacy.config_mask |= AUDIO_PORT_CONFIG_FLAGS; } legacy.ext = VALUE_OR_RETURN( aidl2legacy_AudioPortExt_audio_port_config_ext( - aidl.ext, aidl.type, aidl.role, aidl.extSys)); + aidl.hal.ext, aidl.sys.type, aidl.sys.role, aidl.sys.ext)); return legacy; } ConversionResult legacy2aidl_audio_port_config_AudioPortConfig( const audio_port_config& legacy) { media::AudioPortConfig aidl; - aidl.id = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.id)); - aidl.role = VALUE_OR_RETURN(legacy2aidl_audio_port_role_t_AudioPortRole(legacy.role)); - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_port_type_t_AudioPortType(legacy.type)); + aidl.hal.id = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.id)); + aidl.sys.role = VALUE_OR_RETURN(legacy2aidl_audio_port_role_t_AudioPortRole(legacy.role)); + aidl.sys.type = VALUE_OR_RETURN(legacy2aidl_audio_port_type_t_AudioPortType(legacy.type)); const bool isInput = VALUE_OR_RETURN( direction(legacy.role, legacy.type)) == Direction::INPUT; if (legacy.config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) { - media::Int aidl_sampleRate; + Int aidl_sampleRate; aidl_sampleRate.value = VALUE_OR_RETURN(convertIntegral(legacy.sample_rate)); - aidl.sampleRate = aidl_sampleRate; + aidl.hal.sampleRate = aidl_sampleRate; } if (legacy.config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) { - aidl.channelMask = VALUE_OR_RETURN( + aidl.hal.channelMask = VALUE_OR_RETURN( legacy2aidl_audio_channel_mask_t_AudioChannelLayout(legacy.channel_mask, isInput)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FORMAT) { - aidl.format = VALUE_OR_RETURN( + aidl.hal.format = VALUE_OR_RETURN( legacy2aidl_audio_format_t_AudioFormatDescription(legacy.format)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_GAIN) { - aidl.gain = VALUE_OR_RETURN( + aidl.hal.gain = VALUE_OR_RETURN( legacy2aidl_audio_gain_config_AudioGainConfig(legacy.gain, isInput)); } if (legacy.config_mask & AUDIO_PORT_CONFIG_FLAGS) { - aidl.flags = VALUE_OR_RETURN( + aidl.sys.flags = VALUE_OR_RETURN( legacy2aidl_audio_io_flags_AudioIoFlags(legacy.flags, legacy.role, legacy.type)); } RETURN_IF_ERROR(legacy2aidl_AudioPortExt(legacy.ext, legacy.type, legacy.role, - &aidl.ext, &aidl.extSys)); + &aidl.hal.ext, &aidl.sys.ext)); return aidl; } @@ -2603,7 +2611,7 @@ status_t legacy2aidl_audio_port_device_ext_AudioDevice( ConversionResult aidl2legacy_AudioPortMixExt_audio_port_mix_ext( - const media::AudioPortMixExt& aidl, const media::AudioPortMixExtSys& aidlSys) { + const AudioPortMixExt& aidl, const media::AudioPortMixExtSys& aidlSys) { audio_port_mix_ext legacy{}; legacy.hw_module = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_module_handle_t(aidlSys.hwModule)); legacy.handle = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_io_handle_t(aidl.handle)); @@ -2612,7 +2620,7 @@ aidl2legacy_AudioPortMixExt_audio_port_mix_ext( status_t legacy2aidl_audio_port_mix_ext_AudioPortMixExt(const audio_port_mix_ext& legacy, - media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { + AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt) { aidlMixExt->hwModule = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_module_handle_t_int32_t(legacy.hw_module)); aidl->handle = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_io_handle_t_int32_t(legacy.handle)); @@ -2635,7 +2643,7 @@ legacy2aidl_audio_port_session_ext_int32_t(const audio_port_session_ext& legacy) using audio_port_v7_ext = decltype(audio_port_v7::ext); ConversionResult aidl2legacy_AudioPortExt_audio_port_v7_ext( - const media::AudioPortExt& aidl, media::AudioPortType type, + const AudioPortExt& aidl, media::AudioPortType type, const media::AudioPortExtSys& aidlSys) { audio_port_v7_ext legacy; switch (type) { @@ -2667,7 +2675,7 @@ ConversionResult aidl2legacy_AudioPortExt_audio_port_v7_ext( status_t legacy2aidl_AudioPortExt( const audio_port_v7_ext& legacy, audio_port_type_t type, - media::AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { + AudioPortExt* aidl, media::AudioPortExtSys* aidlSys) { switch (type) { case AUDIO_PORT_TYPE_NONE: UNION_SET(*aidl, unspecified, false); @@ -2684,7 +2692,7 @@ status_t legacy2aidl_AudioPortExt( return OK; } case AUDIO_PORT_TYPE_MIX: { - media::AudioPortMixExt mix; + AudioPortMixExt mix; media::AudioPortMixExtSys mixSys; RETURN_STATUS_IF_ERROR( legacy2aidl_audio_port_mix_ext_AudioPortMixExt( @@ -2792,53 +2800,59 @@ legacy2aidl_audio_gain_AudioGain(const audio_gain& legacy, bool isInput) { ConversionResult aidl2legacy_AudioPort_audio_port_v7(const media::AudioPort& aidl) { audio_port_v7 legacy; - legacy.id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.id)); - legacy.role = VALUE_OR_RETURN(aidl2legacy_AudioPortRole_audio_port_role_t(aidl.role)); - legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioPortType_audio_port_type_t(aidl.type)); - RETURN_IF_ERROR(aidl2legacy_string(aidl.name, legacy.name, sizeof(legacy.name))); + legacy.id = VALUE_OR_RETURN(aidl2legacy_int32_t_audio_port_handle_t(aidl.hal.id)); + legacy.role = VALUE_OR_RETURN(aidl2legacy_AudioPortRole_audio_port_role_t(aidl.sys.role)); + legacy.type = VALUE_OR_RETURN(aidl2legacy_AudioPortType_audio_port_type_t(aidl.sys.type)); + RETURN_IF_ERROR(aidl2legacy_string(aidl.hal.name, legacy.name, sizeof(legacy.name))); - if (aidl.profiles.size() > std::size(legacy.audio_profiles)) { + if (aidl.hal.profiles.size() > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); } - const bool isInput = VALUE_OR_RETURN(direction(aidl.role, aidl.type)) == Direction::INPUT; - RETURN_IF_ERROR(convertRange(aidl.profiles.begin(), aidl.profiles.end(), legacy.audio_profiles, - [isInput](const AudioProfile& p) { - return aidl2legacy_AudioProfile_audio_profile(p, isInput); - })); - legacy.num_audio_profiles = aidl.profiles.size(); + const bool isInput = + VALUE_OR_RETURN(direction(aidl.sys.role, aidl.sys.type)) == Direction::INPUT; + RETURN_IF_ERROR(convertRange( + aidl.hal.profiles.begin(), aidl.hal.profiles.end(), legacy.audio_profiles, + [isInput](const AudioProfile& p) { + return aidl2legacy_AudioProfile_audio_profile(p, isInput); + })); + legacy.num_audio_profiles = aidl.hal.profiles.size(); - if (aidl.extraAudioDescriptors.size() > std::size(legacy.extra_audio_descriptors)) { + if (aidl.hal.extraAudioDescriptors.size() > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); } RETURN_IF_ERROR( - convertRange(aidl.extraAudioDescriptors.begin(), aidl.extraAudioDescriptors.end(), - legacy.extra_audio_descriptors, - aidl2legacy_ExtraAudioDescriptor_audio_extra_audio_descriptor)); - legacy.num_extra_audio_descriptors = aidl.extraAudioDescriptors.size(); + convertRange( + aidl.hal.extraAudioDescriptors.begin(), aidl.hal.extraAudioDescriptors.end(), + legacy.extra_audio_descriptors, + aidl2legacy_ExtraAudioDescriptor_audio_extra_audio_descriptor)); + legacy.num_extra_audio_descriptors = aidl.hal.extraAudioDescriptors.size(); - if (aidl.gains.size() > std::size(legacy.gains)) { + if (aidl.hal.gains.size() > std::size(legacy.gains)) { return unexpected(BAD_VALUE); } - RETURN_IF_ERROR(convertRange(aidl.gains.begin(), aidl.gains.end(), legacy.gains, + RETURN_IF_ERROR(convertRange(aidl.hal.gains.begin(), aidl.hal.gains.end(), legacy.gains, [isInput](const AudioGain& g) { return aidl2legacy_AudioGain_audio_gain(g, isInput); })); - legacy.num_gains = aidl.gains.size(); + legacy.num_gains = aidl.hal.gains.size(); + media::AudioPortConfig aidlPortConfig; + aidlPortConfig.hal = aidl.hal.activeConfig; + aidlPortConfig.sys = aidl.sys.activeConfig; legacy.active_config = VALUE_OR_RETURN( - aidl2legacy_AudioPortConfig_audio_port_config(aidl.activeConfig)); + aidl2legacy_AudioPortConfig_audio_port_config(aidlPortConfig)); legacy.ext = VALUE_OR_RETURN( - aidl2legacy_AudioPortExt_audio_port_v7_ext(aidl.ext, aidl.type, aidl.extSys)); + aidl2legacy_AudioPortExt_audio_port_v7_ext(aidl.hal.ext, aidl.sys.type, aidl.sys.ext)); return legacy; } ConversionResult legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { media::AudioPort aidl; - aidl.id = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.id)); - aidl.role = VALUE_OR_RETURN(legacy2aidl_audio_port_role_t_AudioPortRole(legacy.role)); - aidl.type = VALUE_OR_RETURN(legacy2aidl_audio_port_type_t_AudioPortType(legacy.type)); - aidl.name = VALUE_OR_RETURN(legacy2aidl_string(legacy.name, sizeof(legacy.name))); + aidl.hal.id = VALUE_OR_RETURN(legacy2aidl_audio_port_handle_t_int32_t(legacy.id)); + aidl.sys.role = VALUE_OR_RETURN(legacy2aidl_audio_port_role_t_AudioPortRole(legacy.role)); + aidl.sys.type = VALUE_OR_RETURN(legacy2aidl_audio_port_type_t_AudioPortType(legacy.type)); + aidl.hal.name = VALUE_OR_RETURN(legacy2aidl_string(legacy.name, sizeof(legacy.name))); if (legacy.num_audio_profiles > std::size(legacy.audio_profiles)) { return unexpected(BAD_VALUE); @@ -2846,7 +2860,7 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { const bool isInput = VALUE_OR_RETURN(direction(legacy.role, legacy.type)) == Direction::INPUT; RETURN_IF_ERROR( convertRange(legacy.audio_profiles, legacy.audio_profiles + legacy.num_audio_profiles, - std::back_inserter(aidl.profiles), + std::back_inserter(aidl.hal.profiles), [isInput](const audio_profile& p) { return legacy2aidl_audio_profile_AudioProfile(p, isInput); })); @@ -2854,11 +2868,11 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { if (legacy.num_extra_audio_descriptors > std::size(legacy.extra_audio_descriptors)) { return unexpected(BAD_VALUE); } - aidl.profilesSys.resize(legacy.num_audio_profiles); + aidl.sys.profiles.resize(legacy.num_audio_profiles); RETURN_IF_ERROR( convertRange(legacy.extra_audio_descriptors, legacy.extra_audio_descriptors + legacy.num_extra_audio_descriptors, - std::back_inserter(aidl.extraAudioDescriptors), + std::back_inserter(aidl.hal.extraAudioDescriptors), legacy2aidl_audio_extra_audio_descriptor_ExtraAudioDescriptor)); if (legacy.num_gains > std::size(legacy.gains)) { @@ -2866,16 +2880,18 @@ legacy2aidl_audio_port_v7_AudioPort(const audio_port_v7& legacy) { } RETURN_IF_ERROR( convertRange(legacy.gains, legacy.gains + legacy.num_gains, - std::back_inserter(aidl.gains), + std::back_inserter(aidl.hal.gains), [isInput](const audio_gain& g) { return legacy2aidl_audio_gain_AudioGain(g, isInput); })); - aidl.gainsSys.resize(legacy.num_gains); + aidl.sys.gains.resize(legacy.num_gains); - aidl.activeConfig = VALUE_OR_RETURN( + media::AudioPortConfig aidlPortConfig = VALUE_OR_RETURN( legacy2aidl_audio_port_config_AudioPortConfig(legacy.active_config)); + aidl.hal.activeConfig = aidlPortConfig.hal; + aidl.sys.activeConfig = aidlPortConfig.sys; RETURN_IF_ERROR( - legacy2aidl_AudioPortExt(legacy.ext, legacy.type, &aidl.ext, &aidl.extSys)); + legacy2aidl_AudioPortExt(legacy.ext, legacy.type, &aidl.hal.ext, &aidl.sys.ext)); return aidl; } @@ -3066,30 +3082,30 @@ legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(const audio_playback_rate_t& } ConversionResult -aidl2legacy_AudioStandard_audio_standard_t(media::AudioStandard aidl) { +aidl2legacy_AudioStandard_audio_standard_t(AudioStandard aidl) { switch (aidl) { - case media::AudioStandard::NONE: + case AudioStandard::NONE: return AUDIO_STANDARD_NONE; - case media::AudioStandard::EDID: + case AudioStandard::EDID: return AUDIO_STANDARD_EDID; } return unexpected(BAD_VALUE); } -ConversionResult +ConversionResult legacy2aidl_audio_standard_t_AudioStandard(audio_standard_t legacy) { switch (legacy) { case AUDIO_STANDARD_NONE: - return media::AudioStandard::NONE; + return AudioStandard::NONE; case AUDIO_STANDARD_EDID: - return media::AudioStandard::EDID; + return AudioStandard::EDID; } return unexpected(BAD_VALUE); } ConversionResult aidl2legacy_ExtraAudioDescriptor_audio_extra_audio_descriptor( - const media::ExtraAudioDescriptor& aidl) { + const ExtraAudioDescriptor& aidl) { audio_extra_audio_descriptor legacy; legacy.standard = VALUE_OR_RETURN(aidl2legacy_AudioStandard_audio_standard_t(aidl.standard)); if (aidl.audioDescriptor.size() > EXTRA_AUDIO_DESCRIPTOR_SIZE) { @@ -3104,10 +3120,10 @@ aidl2legacy_ExtraAudioDescriptor_audio_extra_audio_descriptor( return legacy; } -ConversionResult +ConversionResult legacy2aidl_audio_extra_audio_descriptor_ExtraAudioDescriptor( const audio_extra_audio_descriptor& legacy) { - media::ExtraAudioDescriptor aidl; + ExtraAudioDescriptor aidl; aidl.standard = VALUE_OR_RETURN(legacy2aidl_audio_standard_t_AudioStandard(legacy.standard)); if (legacy.descriptor_length > EXTRA_AUDIO_DESCRIPTOR_SIZE) { return unexpected(BAD_VALUE); diff --git a/media/libaudioclient/Android.bp b/media/libaudioclient/Android.bp index 3c8796e73b..f6446bbeca 100644 --- a/media/libaudioclient/Android.bp +++ b/media/libaudioclient/Android.bp @@ -323,23 +323,19 @@ aidl_interface { "aidl/android/media/AudioPatch.aidl", "aidl/android/media/AudioPlaybackRate.aidl", "aidl/android/media/AudioPort.aidl", + "aidl/android/media/AudioPortSys.aidl", "aidl/android/media/AudioPortConfig.aidl", + "aidl/android/media/AudioPortConfigSys.aidl", "aidl/android/media/AudioPortDeviceExtSys.aidl", - "aidl/android/media/AudioPortExt.aidl", "aidl/android/media/AudioPortExtSys.aidl", - "aidl/android/media/AudioPortMixExt.aidl", "aidl/android/media/AudioPortMixExtSys.aidl", - "aidl/android/media/AudioPortMixExtUseCase.aidl", "aidl/android/media/AudioPortRole.aidl", "aidl/android/media/AudioPortType.aidl", "aidl/android/media/AudioProfileSys.aidl", - "aidl/android/media/AudioStandard.aidl", "aidl/android/media/AudioTimestampInternal.aidl", "aidl/android/media/AudioUniqueIdUse.aidl", "aidl/android/media/AudioVibratorInfo.aidl", "aidl/android/media/EffectDescriptor.aidl", - "aidl/android/media/ExtraAudioDescriptor.aidl", - "aidl/android/media/Int.aidl", "aidl/android/media/TrackSecondaryOutputInfo.aidl", ], imports: [ diff --git a/media/libaudioclient/AudioEffect.cpp b/media/libaudioclient/AudioEffect.cpp index 3a979456c1..62f863ddae 100644 --- a/media/libaudioclient/AudioEffect.cpp +++ b/media/libaudioclient/AudioEffect.cpp @@ -567,7 +567,7 @@ status_t AudioEffect::queryDefaultPreProcessing(audio_session_t audioSession, int32_t audioSessionAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_session_t_int32_t(audioSession)); - media::Int countAidl; + media::audio::common::Int countAidl; countAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*count)); std::vector retAidl; RETURN_STATUS_IF_ERROR(statusTFromBinderStatus( diff --git a/media/libaudioclient/AudioSystem.cpp b/media/libaudioclient/AudioSystem.cpp index d9b428588a..edad6d1745 100644 --- a/media/libaudioclient/AudioSystem.cpp +++ b/media/libaudioclient/AudioSystem.cpp @@ -58,6 +58,7 @@ using media::audio::common::AudioOffloadInfo; using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; +using media::audio::common::Int; // client singleton for AudioFlinger binder interface Mutex AudioSystem::gLock; @@ -1493,7 +1494,7 @@ status_t AudioSystem::listAudioPorts(audio_port_role_t role, legacy2aidl_audio_port_role_t_AudioPortRole(role)); media::AudioPortType typeAidl = VALUE_OR_RETURN_STATUS( legacy2aidl_audio_port_type_t_AudioPortType(type)); - media::Int numPortsAidl; + Int numPortsAidl; numPortsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*num_ports)); std::vector portsAidl; int32_t generationAidl; @@ -1560,7 +1561,7 @@ status_t AudioSystem::listAudioPatches(unsigned int* num_patches, if (aps == 0) return PERMISSION_DENIED; - media::Int numPatchesAidl; + Int numPatchesAidl; numPatchesAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*num_patches)); std::vector patchesAidl; int32_t generationAidl; @@ -1873,7 +1874,7 @@ status_t AudioSystem::getSurroundFormats(unsigned int* numSurroundFormats, const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::Int numSurroundFormatsAidl; + Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); std::vector surroundFormatsAidl; @@ -1900,7 +1901,7 @@ status_t AudioSystem::getReportedSurroundFormats(unsigned int* numSurroundFormat const sp& aps = AudioSystem::get_audio_policy_service(); if (aps == 0) return PERMISSION_DENIED; - media::Int numSurroundFormatsAidl; + Int numSurroundFormatsAidl; numSurroundFormatsAidl.value = VALUE_OR_RETURN_STATUS(convertIntegral(*numSurroundFormats)); std::vector surroundFormatsAidl; diff --git a/media/libaudioclient/aidl/android/media/AudioPort.aidl b/media/libaudioclient/aidl/android/media/AudioPort.aidl index 76e55b9c40..ff177c0ac1 100644 --- a/media/libaudioclient/aidl/android/media/AudioPort.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPort.aidl @@ -16,43 +16,13 @@ package android.media; -import android.media.AudioGainSys; -import android.media.AudioPortConfig; -import android.media.AudioPortExt; -import android.media.AudioPortExtSys; -import android.media.AudioPortRole; -import android.media.AudioPortType; -import android.media.AudioProfileSys; -import android.media.ExtraAudioDescriptor; -import android.media.audio.common.AudioGain; -import android.media.audio.common.AudioProfile; +import android.media.AudioPortSys; +import android.media.audio.common.AudioPort; /** * {@hide} */ parcelable AudioPort { - /** Port unique ID. Interpreted as audio_port_handle_t. */ - int id; - /** Sink or source. */ - AudioPortRole role; - /** Device, mix ... */ - AudioPortType type; - @utf8InCpp String name; - /** AudioProfiles supported by this port (format, Rates, Channels). */ - AudioProfile[] profiles; - /** System-only parameters for each AudioProfile. */ - AudioProfileSys[] profilesSys; - /** - * ExtraAudioDescriptors supported by this port. The format is not unrecognized to the - * platform. The audio capability is described by a hardware descriptor. - */ - ExtraAudioDescriptor[] extraAudioDescriptors; - /** Gain controllers. */ - AudioGain[] gains; - /** System-only parameters for each AudioGain. */ - AudioGainSys[] gainsSys; - /** Current audio port configuration. */ - AudioPortConfig activeConfig; - AudioPortExt ext; - AudioPortExtSys extSys; + AudioPort hal; + AudioPortSys sys; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl index ffeb905587..3a4ca31e36 100644 --- a/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfig.aidl @@ -16,39 +16,13 @@ package android.media; -import android.media.AudioIoFlags; -import android.media.AudioPortExt; -import android.media.AudioPortExtSys; -import android.media.AudioPortRole; -import android.media.AudioPortType; -import android.media.Int; -import android.media.audio.common.AudioChannelLayout; -import android.media.audio.common.AudioFormatDescription; -import android.media.audio.common.AudioGainConfig; +import android.media.AudioPortConfigSys; +import android.media.audio.common.AudioPortConfig; /** * {@hide} */ parcelable AudioPortConfig { - /** - * Port unique ID. - * Interpreted as audio_port_handle_t. - */ - int id; - /** Sink or source. */ - AudioPortRole role; - /** Device, mix ... */ - AudioPortType type; - /** Sampling rate in Hz. Can be left unspecified. */ - @nullable Int sampleRate; - /** Channel mask. Can be left unspecified. */ - @nullable AudioChannelLayout channelMask; - /** Format. Can be left unspecified. */ - @nullable AudioFormatDescription format; - /** Gain to apply. Can be left unspecified. */ - @nullable AudioGainConfig gain; - /** Framework only: HW_AV_SYNC, DIRECT, ... Can be left unspecified. */ - @nullable AudioIoFlags flags; - AudioPortExt ext; - AudioPortExtSys extSys; + AudioPortConfig hal; + AudioPortConfigSys sys; } diff --git a/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl b/media/libaudioclient/aidl/android/media/AudioPortConfigSys.aidl similarity index 62% rename from media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl rename to media/libaudioclient/aidl/android/media/AudioPortConfigSys.aidl index 0ea0e4fd92..6a615cd975 100644 --- a/media/libaudioclient/aidl/android/media/ExtraAudioDescriptor.aidl +++ b/media/libaudioclient/aidl/android/media/AudioPortConfigSys.aidl @@ -16,17 +16,20 @@ package android.media; -import android.media.AudioStandard; -import android.media.audio.common.AudioEncapsulationType; +import android.media.AudioIoFlags; +import android.media.AudioPortExtSys; +import android.media.AudioPortRole; +import android.media.AudioPortType; /** - * The audio descriptor that descibes playback/capture capabilities according to - * a particular standard. - * * {@hide} */ -parcelable ExtraAudioDescriptor { - AudioStandard standard; - byte[] audioDescriptor; - AudioEncapsulationType encapsulationType; +parcelable AudioPortConfigSys { + /** Sink or source. */ + AudioPortRole role; + /** Device, mix ... */ + AudioPortType type; + /** Flags: HW_AV_SYNC, DIRECT, ... Can be left unspecified. */ + @nullable AudioIoFlags flags; + AudioPortExtSys ext; } diff --git a/media/libaudioclient/aidl/android/media/AudioPortExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortExt.aidl deleted file mode 100644 index 27693b2886..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortExt.aidl +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioPortMixExt; -import android.media.audio.common.AudioDevice; - -/** - * {@hide} - */ -union AudioPortExt { - /** - * This represents an empty union. Value is ignored. - * TODO(ytai): replace with the canonical representation for an empty union, as soon as it is - * established. - */ - boolean unspecified; - /** Audio device specification. */ - AudioDevice device; - /** Mix specific info. */ - AudioPortMixExt mix; - /** Audio session identifier. */ - int session; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl deleted file mode 100644 index d222d0a18e..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortMixExt.aidl +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.AudioPortMixExtUseCase; - -/** - * {@hide} - */ -parcelable AudioPortMixExt { - /** - * I/O handle of the input/output stream. Interpreted as audio_io_handle_t. - */ - int handle; - AudioPortMixExtUseCase usecase; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl b/media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl deleted file mode 100644 index 77f2fbb673..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioPortMixExtUseCase.aidl +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -import android.media.audio.common.AudioSource; -import android.media.audio.common.AudioStreamType; - -/** - * {@hide} - */ -union AudioPortMixExtUseCase { - /** - * This to be set if the containing config has the AudioPortRole::NONE role. - * This represents an empty value (value is ignored). - * TODO(ytai): replace with the canonical representation for an empty union, as soon as it is - * established. - */ - boolean unspecified; - /** This to be set if the containing config has the AudioPortRole::SOURCE role. */ - AudioStreamType stream; - /** This to be set if the containing config has the AudioPortRole::SINK role. */ - AudioSource source; -} diff --git a/media/libaudioclient/aidl/android/media/AudioPortSys.aidl b/media/libaudioclient/aidl/android/media/AudioPortSys.aidl new file mode 100644 index 0000000000..27c0fe58ae --- /dev/null +++ b/media/libaudioclient/aidl/android/media/AudioPortSys.aidl @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +import android.media.AudioGainSys; +import android.media.AudioPortConfigSys; +import android.media.AudioPortExtSys; +import android.media.AudioPortRole; +import android.media.AudioPortType; +import android.media.AudioProfileSys; + +/** + * {@hide} + */ +parcelable AudioPortSys { + /** Sink or source. */ + AudioPortRole role; + /** Device, mix ... */ + AudioPortType type; + /** System-only parameters for each AudioProfile from 'port.profiles'. */ + AudioProfileSys[] profiles; + /** System-only parameters for each AudioGain from 'port.gains'. */ + AudioGainSys[] gains; + /** System-only parameters for 'port.activeConfig'. */ + AudioPortConfigSys activeConfig; + /** System-only extra parameters for 'port.ext'. */ + AudioPortExtSys ext; +} diff --git a/media/libaudioclient/aidl/android/media/AudioStandard.aidl b/media/libaudioclient/aidl/android/media/AudioStandard.aidl deleted file mode 100644 index e131d0d0df..0000000000 --- a/media/libaudioclient/aidl/android/media/AudioStandard.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.media; - -/** - * The audio standard that describe audio playback/capture capabilites. - * - * {@hide} - */ -@Backing(type="int") -enum AudioStandard { - NONE = 0, - EDID = 1, -} diff --git a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl index 282bce1b0c..c59655dd5f 100644 --- a/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl +++ b/media/libaudioclient/aidl/android/media/IAudioPolicyService.aidl @@ -40,7 +40,6 @@ import android.media.GetSpatializerResponse; import android.media.IAudioPolicyServiceClient; import android.media.ICaptureStateListener; import android.media.INativeSpatializerCallback; -import android.media.Int; import android.media.SoundTriggerSession; import android.media.audio.common.AudioConfig; import android.media.audio.common.AudioConfigBase; @@ -53,6 +52,7 @@ import android.media.audio.common.AudioSource; import android.media.audio.common.AudioStreamType; import android.media.audio.common.AudioUsage; import android.media.audio.common.AudioUuid; +import android.media.audio.common.Int; /** * IAudioPolicyService interface (see AudioPolicyInterface for method descriptions). diff --git a/media/libaudioclient/aidl/android/media/Int.aidl b/media/libaudioclient/aidl/android/media/Int.aidl deleted file mode 100644 index 24f4d62a11..0000000000 --- a/media/libaudioclient/aidl/android/media/Int.aidl +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.media; - -/** - * This is a simple wrapper around an 'int', putting it in a parcelable, so it can be used as an - * inout parameter, be made @nullable, etc. - * - * {@hide} - */ -parcelable Int { - int value; -} diff --git a/media/libaudioclient/include/media/AidlConversion.h b/media/libaudioclient/include/media/AidlConversion.h index 30fd309497..52ea91b4e8 100644 --- a/media/libaudioclient/include/media/AidlConversion.h +++ b/media/libaudioclient/include/media/AidlConversion.h @@ -33,11 +33,9 @@ #include #include #include -#include #include #include #include -#include #include #include #include @@ -53,10 +51,14 @@ #include #include #include +#include +#include #include #include +#include #include #include +#include #include #include @@ -219,11 +221,11 @@ ConversionResult aidl2legacy_int32_t_audio_session_t(int32_t ai ConversionResult legacy2aidl_audio_session_t_int32_t(audio_session_t legacy); ConversionResult aidl2legacy_AudioPortMixExt( - const media::AudioPortMixExt& aidl, media::AudioPortRole role, + const media::audio::common::AudioPortMixExt& aidl, media::AudioPortRole role, const media::AudioPortMixExtSys& aidlMixExt); status_t legacy2aidl_AudioPortMixExt( const audio_port_config_mix_ext& legacy, audio_port_role_t role, - media::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt); + media::audio::common::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt); ConversionResult aidl2legacy_int32_t_audio_port_config_session_ext(int32_t aidl); @@ -352,11 +354,11 @@ status_t legacy2aidl_audio_port_device_ext_AudioDevice( ConversionResult aidl2legacy_AudioPortMixExt_audio_port_mix_ext( - const media::AudioPortMixExt& aidl, + const media::audio::common::AudioPortMixExt& aidl, const media::AudioPortMixExtSys& aidlMixExt); status_t legacy2aidl_audio_port_mix_ext_AudioPortMixExt( const audio_port_mix_ext& legacy, - media::AudioPortMixExt* aidl, + media::audio::common::AudioPortMixExt* aidl, media::AudioPortMixExtSys* aidlMixExt); ConversionResult @@ -416,14 +418,14 @@ ConversionResult legacy2aidl_audio_playback_rate_t_AudioPlaybackRate(const audio_playback_rate_t& legacy); ConversionResult -aidl2legacy_AudioStandard_audio_standard_t(media::AudioStandard aidl); -ConversionResult +aidl2legacy_AudioStandard_audio_standard_t(media::audio::common::AudioStandard aidl); +ConversionResult legacy2aidl_audio_standard_t_AudioStandard(audio_standard_t legacy); ConversionResult aidl2legacy_ExtraAudioDescriptor_audio_extra_audio_descriptor( - const media::ExtraAudioDescriptor& aidl); -ConversionResult + const media::audio::common::ExtraAudioDescriptor& aidl); +ConversionResult legacy2aidl_audio_extra_audio_descriptor_ExtraAudioDescriptor( const audio_extra_audio_descriptor& legacy); diff --git a/media/libaudiofoundation/AudioPort.cpp b/media/libaudiofoundation/AudioPort.cpp index 329ff9a76e..099aff4bab 100644 --- a/media/libaudiofoundation/AudioPort.cpp +++ b/media/libaudiofoundation/AudioPort.cpp @@ -18,7 +18,6 @@ #include #include -#include #include #include #include @@ -207,17 +206,19 @@ status_t AudioPort::writeToParcel(Parcel *parcel) const } status_t AudioPort::writeToParcelable(media::AudioPort* parcelable) const { - parcelable->name = mName; - parcelable->type = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_type_t_AudioPortType(mType)); - parcelable->role = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); + parcelable->hal.name = mName; + parcelable->sys.type = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_port_type_t_AudioPortType(mType)); + parcelable->sys.role = VALUE_OR_RETURN_STATUS( + legacy2aidl_audio_port_role_t_AudioPortRole(mRole)); auto aidlProfiles = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioProfileVector(mProfiles, useInputChannelMask())); - parcelable->profiles = aidlProfiles.first; - parcelable->profilesSys = aidlProfiles.second; - parcelable->extraAudioDescriptors = mExtraAudioDescriptors; + parcelable->hal.profiles = aidlProfiles.first; + parcelable->sys.profiles = aidlProfiles.second; + parcelable->hal.extraAudioDescriptors = mExtraAudioDescriptors; auto aidlGains = VALUE_OR_RETURN_STATUS(legacy2aidl_AudioGains(mGains)); - parcelable->gains = aidlGains.first; - parcelable->gainsSys = aidlGains.second; + parcelable->hal.gains = aidlGains.first; + parcelable->sys.gains = aidlGains.second; return OK; } @@ -228,16 +229,18 @@ status_t AudioPort::readFromParcel(const Parcel *parcel) { } status_t AudioPort::readFromParcelable(const media::AudioPort& parcelable) { - mName = parcelable.name; - mType = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortType_audio_port_type_t(parcelable.type)); - mRole = VALUE_OR_RETURN_STATUS(aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.role)); + mName = parcelable.hal.name; + mType = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioPortType_audio_port_type_t(parcelable.sys.type)); + mRole = VALUE_OR_RETURN_STATUS( + aidl2legacy_AudioPortRole_audio_port_role_t(parcelable.sys.role)); mProfiles = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioProfileVector( - std::make_pair(parcelable.profiles, parcelable.profilesSys), + std::make_pair(parcelable.hal.profiles, parcelable.sys.profiles), useInputChannelMask())); - mExtraAudioDescriptors = parcelable.extraAudioDescriptors; + mExtraAudioDescriptors = parcelable.hal.extraAudioDescriptors; mGains = VALUE_OR_RETURN_STATUS( - aidl2legacy_AudioGains(std::make_pair(parcelable.gains, parcelable.gainsSys))); + aidl2legacy_AudioGains(std::make_pair(parcelable.hal.gains, parcelable.sys.gains))); return OK; } @@ -340,8 +343,8 @@ bool AudioPortConfig::equals(const sp &other) const } status_t AudioPortConfig::writeToParcelable( - media::AudioPortConfig* parcelable, bool isInput) const { - media::Int aidl_sampleRate; + media::audio::common::AudioPortConfig* parcelable, bool isInput) const { + media::audio::common::Int aidl_sampleRate; aidl_sampleRate.value = VALUE_OR_RETURN_STATUS(convertIntegral(mSamplingRate)); parcelable->sampleRate = aidl_sampleRate; parcelable->format = VALUE_OR_RETURN_STATUS( @@ -356,7 +359,7 @@ status_t AudioPortConfig::writeToParcelable( } status_t AudioPortConfig::readFromParcelable( - const media::AudioPortConfig& parcelable, bool isInput) { + const media::audio::common::AudioPortConfig& parcelable, bool isInput) { if (parcelable.sampleRate.has_value()) { mSamplingRate = VALUE_OR_RETURN_STATUS( convertIntegral(parcelable.sampleRate.value().value)); diff --git a/media/libaudiofoundation/DeviceDescriptorBase.cpp b/media/libaudiofoundation/DeviceDescriptorBase.cpp index 2e9b0053ac..cf829b5662 100644 --- a/media/libaudiofoundation/DeviceDescriptorBase.cpp +++ b/media/libaudiofoundation/DeviceDescriptorBase.cpp @@ -166,18 +166,18 @@ status_t DeviceDescriptorBase::writeToParcel(Parcel *parcel) const status_t DeviceDescriptorBase::writeToParcelable(media::AudioPort* parcelable) const { AudioPort::writeToParcelable(parcelable); - AudioPortConfig::writeToParcelable(&parcelable->activeConfig, useInputChannelMask()); - parcelable->id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); + AudioPortConfig::writeToParcelable(&parcelable->hal.activeConfig, useInputChannelMask()); + parcelable->hal.id = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_handle_t_int32_t(mId)); media::audio::common::AudioDevice device = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioDeviceTypeAddress(mDeviceTypeAddr)); - UNION_SET(parcelable->ext, device, device); + UNION_SET(parcelable->hal.ext, device, device); media::AudioPortDeviceExtSys deviceSys; deviceSys.encapsulationModes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMode_mask(mEncapsulationModes)); deviceSys.encapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( legacy2aidl_AudioEncapsulationMetadataType_mask(mEncapsulationMetadataTypes)); - UNION_SET(parcelable->extSys, device, deviceSys); + UNION_SET(parcelable->sys.ext, device, deviceSys); return OK; } @@ -188,21 +188,22 @@ status_t DeviceDescriptorBase::readFromParcel(const Parcel *parcel) { } status_t DeviceDescriptorBase::readFromParcelable(const media::AudioPort& parcelable) { - if (parcelable.type != media::AudioPortType::DEVICE) { + if (parcelable.sys.type != media::AudioPortType::DEVICE) { return BAD_VALUE; } status_t status = AudioPort::readFromParcelable(parcelable) - ?: AudioPortConfig::readFromParcelable(parcelable.activeConfig, useInputChannelMask()); + ?: AudioPortConfig::readFromParcelable( + parcelable.hal.activeConfig, useInputChannelMask()); if (status != OK) { return status; } media::audio::common::AudioDevice device = VALUE_OR_RETURN_STATUS( - UNION_GET(parcelable.ext, device)); + UNION_GET(parcelable.hal.ext, device)); mDeviceTypeAddr = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioDeviceTypeAddress(device)); media::AudioPortDeviceExtSys deviceSys = VALUE_OR_RETURN_STATUS( - UNION_GET(parcelable.extSys, device)); + UNION_GET(parcelable.sys.ext, device)); mEncapsulationModes = VALUE_OR_RETURN_STATUS( aidl2legacy_AudioEncapsulationMode_mask(deviceSys.encapsulationModes)); mEncapsulationMetadataTypes = VALUE_OR_RETURN_STATUS( diff --git a/media/libaudiofoundation/include/media/AudioPort.h b/media/libaudiofoundation/include/media/AudioPort.h index 6e1d032097..aa9b5f6b6a 100644 --- a/media/libaudiofoundation/include/media/AudioPort.h +++ b/media/libaudiofoundation/include/media/AudioPort.h @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include #include @@ -69,10 +69,10 @@ public: AudioProfileVector &getAudioProfiles() { return mProfiles; } void setExtraAudioDescriptors( - const std::vector extraAudioDescriptors) { + const std::vector extraAudioDescriptors) { mExtraAudioDescriptors = extraAudioDescriptors; } - std::vector &getExtraAudioDescriptors() { + std::vector &getExtraAudioDescriptors() { return mExtraAudioDescriptors; } @@ -114,7 +114,7 @@ protected: // Audio capabilities that are defined by hardware descriptors when the format is unrecognized // by the platform, e.g. short audio descriptor in EDID for HDMI. - std::vector mExtraAudioDescriptors; + std::vector mExtraAudioDescriptors; private: template ::value || std::is_same::value, int> = 0> @@ -152,8 +152,10 @@ public: bool equals(const sp& other) const; - status_t writeToParcelable(media::AudioPortConfig* parcelable, bool isInput) const; - status_t readFromParcelable(const media::AudioPortConfig& parcelable, bool isInput); + status_t writeToParcelable( + media::audio::common::AudioPortConfig* parcelable, bool isInput) const; + status_t readFromParcelable( + const media::audio::common::AudioPortConfig& parcelable, bool isInput); protected: unsigned int mSamplingRate = 0u; diff --git a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp index 3a7ddd7280..0315a5984b 100644 --- a/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp +++ b/media/libaudiofoundation/tests/audiofoundation_parcelable_test.cpp @@ -130,11 +130,11 @@ TEST(AudioFoundationParcelableTest, ParcelingAudioPortConfig) { Parcel data; sp audioPortConfig = new AudioPortConfigTestStub(); audioPortConfig->applyAudioPortConfig(&TEST_AUDIO_PORT_CONFIG); - media::AudioPortConfig parcelable{}; + media::audio::common::AudioPortConfig parcelable{}; ASSERT_EQ(NO_ERROR, audioPortConfig->writeToParcelable(&parcelable, false /*isInput*/)); ASSERT_EQ(NO_ERROR, data.writeParcelable(parcelable)); data.setDataPosition(0); - media::AudioPortConfig parcelableFromParcel{}; + media::audio::common::AudioPortConfig parcelableFromParcel{}; ASSERT_EQ(NO_ERROR, data.readParcelable(&parcelableFromParcel)); sp audioPortConfigFromParcel = new AudioPortConfigTestStub(); ASSERT_EQ(NO_ERROR, audioPortConfigFromParcel->readFromParcelable( diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp index d01037d98d..db9be47be3 100644 --- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp +++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp @@ -59,6 +59,7 @@ using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; using media::audio::common::AudioUuid; +using media::audio::common::Int; const std::vector& SYSTEM_USAGES = { AUDIO_USAGE_CALL_ASSISTANT, @@ -1299,7 +1300,7 @@ status_t AudioPolicyService::getAudioPolicyEffects(sp& audio Status AudioPolicyService::queryDefaultPreProcessing( int32_t audioSessionAidl, - media::Int* countAidl, + Int* countAidl, std::vector* _aidl_return) { audio_session_t audioSession = VALUE_OR_RETURN_BINDER_STATUS( aidl2legacy_int32_t_audio_session_t(audioSessionAidl)); @@ -1480,7 +1481,7 @@ Status AudioPolicyService::isDirectOutputSupported( Status AudioPolicyService::listAudioPorts(media::AudioPortRole roleAidl, - media::AudioPortType typeAidl, media::Int* count, + media::AudioPortType typeAidl, Int* count, std::vector* portsAidl, int32_t* _aidl_return) { audio_port_role_t role = VALUE_OR_RETURN_BINDER_STATUS( @@ -1568,7 +1569,7 @@ Status AudioPolicyService::releaseAudioPatch(int32_t handleAidl) IPCThreadState::self()->getCallingUid())); } -Status AudioPolicyService::listAudioPatches(media::Int* count, +Status AudioPolicyService::listAudioPatches(Int* count, std::vector* patchesAidl, int32_t* _aidl_return) { unsigned int num_patches = VALUE_OR_RETURN_BINDER_STATUS( @@ -1853,7 +1854,7 @@ Status AudioPolicyService::getStreamVolumeDB( return Status::ok(); } -Status AudioPolicyService::getSurroundFormats(media::Int* count, +Status AudioPolicyService::getSurroundFormats(Int* count, std::vector* formats, std::vector* formatsEnabled) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( @@ -1887,7 +1888,7 @@ Status AudioPolicyService::getSurroundFormats(media::Int* count, } Status AudioPolicyService::getReportedSurroundFormats( - media::Int* count, std::vector* formats) { + Int* count, std::vector* formats) { unsigned int numSurroundFormats = VALUE_OR_RETURN_BINDER_STATUS( convertIntegral(count->value)); if (numSurroundFormats > MAX_ITEMS_PER_LIST) { diff --git a/services/audiopolicy/service/AudioPolicyService.h b/services/audiopolicy/service/AudioPolicyService.h index 92e1bb9696..03241a28f1 100644 --- a/services/audiopolicy/service/AudioPolicyService.h +++ b/services/audiopolicy/service/AudioPolicyService.h @@ -59,6 +59,7 @@ using media::audio::common::AudioSource; using media::audio::common::AudioStreamType; using media::audio::common::AudioUsage; using media::audio::common::AudioUuid; +using media::audio::common::Int; // ---------------------------------------------------------------------------- @@ -152,7 +153,7 @@ public: bool* _aidl_return) override; binder::Status isSourceActive(AudioSource source, bool* _aidl_return) override; binder::Status queryDefaultPreProcessing( - int32_t audioSession, media::Int* count, + int32_t audioSession, Int* count, std::vector* _aidl_return) override; binder::Status addSourceDefaultEffect(const AudioUuid& type, const std::string& opPackageName, @@ -174,14 +175,14 @@ public: const media::AudioAttributesInternal& attributes, bool* _aidl_return) override; binder::Status listAudioPorts(media::AudioPortRole role, media::AudioPortType type, - media::Int* count, std::vector* ports, + Int* count, std::vector* ports, int32_t* _aidl_return) override; binder::Status getAudioPort(const media::AudioPort& port, media::AudioPort* _aidl_return) override; binder::Status createAudioPatch(const media::AudioPatch& patch, int32_t handle, int32_t* _aidl_return) override; binder::Status releaseAudioPatch(int32_t handle) override; - binder::Status listAudioPatches(media::Int* count, std::vector* patches, + binder::Status listAudioPatches(Int* count, std::vector* patches, int32_t* _aidl_return) override; binder::Status setAudioPortConfig(const media::AudioPortConfig& config) override; binder::Status registerClient(const sp& client) override; @@ -208,11 +209,11 @@ public: binder::Status getStreamVolumeDB(AudioStreamType stream, int32_t index, const AudioDeviceDescription& device, float* _aidl_return) override; - binder::Status getSurroundFormats(media::Int* count, + binder::Status getSurroundFormats(Int* count, std::vector* formats, std::vector* formatsEnabled) override; binder::Status getReportedSurroundFormats( - media::Int* count, std::vector* formats) override; + Int* count, std::vector* formats) override; binder::Status getHwOffloadEncodingFormatsSupportedForA2DP( std::vector* _aidl_return) override; binder::Status setSurroundFormatEnabled(const AudioFormatDescription& audioFormat, -- GitLab From 18885d3567aac61637b2fd0a336b2d5af612539e Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Fri, 1 Oct 2021 13:03:09 -0700 Subject: [PATCH 158/694] Enhance the APM unit tests for surround format support Parametrize AudioPolicyManagerTestForHdmi and run it both for AC3 and E-AC3 formats. Bug: 201089251 Test: atest audiopolicy_tests Change-Id: Ifaf45163b467eb3ffa47f01393c458e6dcc5ae4d --- .../tests/audiopolicymanager_tests.cpp | 66 ++++++++++++------- 1 file changed, 41 insertions(+), 25 deletions(-) diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp index a16ab7d2b1..4bf3c9ede9 100644 --- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp +++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp @@ -803,7 +803,8 @@ TEST_F(AudioPolicyManagerTestDynamicPolicy, UnregisterPolicyMixes) { } class AudioPolicyManagerTestForHdmi - : public AudioPolicyManagerTestWithConfigurationFile { + : public AudioPolicyManagerTestWithConfigurationFile, + public testing::WithParamInterface { protected: void SetUp() override; std::string getConfigFile() override { return sTvConfig; } @@ -825,6 +826,7 @@ const std::string AudioPolicyManagerTestForHdmi::sTvConfig = void AudioPolicyManagerTestForHdmi::SetUp() { AudioPolicyManagerTest::SetUp(); + // Note that 'AC3' isn't added as it is handled automatically by APM. mClient->addSupportedFormat(AUDIO_FORMAT_E_AC3); mManager->setDeviceConnectionState( AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_AVAILABLE, @@ -914,76 +916,90 @@ std::unordered_set return formats; } -TEST_F(AudioPolicyManagerTestForHdmi, GetSurroundFormatsReturnsSupportedFormats) { +TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsReturnsSupportedFormats) { mManager->setForceUse( AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS); auto surroundFormats = getSurroundFormatsHelper(); - ASSERT_EQ(1, surroundFormats.count(AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(1, surroundFormats.count(GetParam())); } -TEST_F(AudioPolicyManagerTestForHdmi, +TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsReturnsManipulatedFormats) { mManager->setForceUse( AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL); status_t ret = - mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, false /*enabled*/); + mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/); ASSERT_EQ(NO_ERROR, ret); auto surroundFormats = getSurroundFormatsHelper(); - ASSERT_EQ(1, surroundFormats.count(AUDIO_FORMAT_E_AC3)); - ASSERT_FALSE(surroundFormats[AUDIO_FORMAT_E_AC3]); + ASSERT_EQ(1, surroundFormats.count(GetParam())); + ASSERT_FALSE(surroundFormats[GetParam()]); - ret = mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, true /*enabled*/); + ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/); ASSERT_EQ(NO_ERROR, ret); surroundFormats = getSurroundFormatsHelper(); - ASSERT_EQ(1, surroundFormats.count(AUDIO_FORMAT_E_AC3)); - ASSERT_TRUE(surroundFormats[AUDIO_FORMAT_E_AC3]); + ASSERT_EQ(1, surroundFormats.count(GetParam())); + ASSERT_TRUE(surroundFormats[GetParam()]); - ret = mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, false /*enabled*/); + ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/); ASSERT_EQ(NO_ERROR, ret); surroundFormats = getSurroundFormatsHelper(); - ASSERT_EQ(1, surroundFormats.count(AUDIO_FORMAT_E_AC3)); - ASSERT_FALSE(surroundFormats[AUDIO_FORMAT_E_AC3]); + ASSERT_EQ(1, surroundFormats.count(GetParam())); + ASSERT_FALSE(surroundFormats[GetParam()]); } -TEST_F(AudioPolicyManagerTestForHdmi, +TEST_P(AudioPolicyManagerTestForHdmi, ListAudioPortsReturnManipulatedHdmiFormats) { mManager->setForceUse( AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL); - ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, false /*enabled*/)); + ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/)); auto formats = getFormatsFromPorts(); - ASSERT_EQ(0, formats.count(AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(0, formats.count(GetParam())); - ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, true /*enabled*/)); + ASSERT_EQ(NO_ERROR, mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/)); formats = getFormatsFromPorts(); - ASSERT_EQ(1, formats.count(AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(1, formats.count(GetParam())); } -TEST_F(AudioPolicyManagerTestForHdmi, +TEST_P(AudioPolicyManagerTestForHdmi, GetReportedSurroundFormatsReturnsHdmiReportedFormats) { mManager->setForceUse( AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS); auto surroundFormats = getReportedSurroundFormatsHelper(); - ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam())); } -TEST_F(AudioPolicyManagerTestForHdmi, +TEST_P(AudioPolicyManagerTestForHdmi, GetReportedSurroundFormatsReturnsNonManipulatedHdmiReportedFormats) { mManager->setForceUse( AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL); - status_t ret = mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, false /*enabled*/); + status_t ret = mManager->setSurroundFormatEnabled(GetParam(), false /*enabled*/); ASSERT_EQ(NO_ERROR, ret); auto surroundFormats = getReportedSurroundFormatsHelper(); - ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam())); - ret = mManager->setSurroundFormatEnabled(AUDIO_FORMAT_E_AC3, true /*enabled*/); + ret = mManager->setSurroundFormatEnabled(GetParam(), true /*enabled*/); ASSERT_EQ(NO_ERROR, ret); surroundFormats = getReportedSurroundFormatsHelper(); - ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), AUDIO_FORMAT_E_AC3)); + ASSERT_EQ(1, std::count(surroundFormats.begin(), surroundFormats.end(), GetParam())); +} + +TEST_P(AudioPolicyManagerTestForHdmi, GetSurroundFormatsIgnoresSupportedFormats) { + mManager->setForceUse( + AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND, AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER); + auto surroundFormats = getSurroundFormatsHelper(); + ASSERT_EQ(1, surroundFormats.count(GetParam())); + ASSERT_FALSE(surroundFormats[GetParam()]); } +INSTANTIATE_TEST_SUITE_P(SurroundFormatSupport, AudioPolicyManagerTestForHdmi, + testing::Values(AUDIO_FORMAT_AC3, AUDIO_FORMAT_E_AC3), + [](const ::testing::TestParamInfo& info) { + return audio_format_to_string(info.param); + }); + class AudioPolicyManagerTestDPNoRemoteSubmixModule : public AudioPolicyManagerTestDynamicPolicy { protected: std::string getConfigFile() override { return sPrimaryOnlyConfig; } -- GitLab From 43a17a6138169dc80ec955d0eb9149435f2fda45 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Fri, 1 Oct 2021 14:53:08 -0700 Subject: [PATCH 159/694] media reliability folks doing mainline machinery Common list for all media/mainline machinery. Intended for assembling, publishing, and driving tests of media's mainline modules. Bug: 201770269 Test: n Change-Id: Ie3cf7ca7ee46a1c3b783047a1385d9ffa57ebc09 --- media/janitors/reliability_mainline_OWNERS | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 media/janitors/reliability_mainline_OWNERS diff --git a/media/janitors/reliability_mainline_OWNERS b/media/janitors/reliability_mainline_OWNERS new file mode 100644 index 0000000000..e4c4fc2e20 --- /dev/null +++ b/media/janitors/reliability_mainline_OWNERS @@ -0,0 +1,5 @@ +# Bug component: 1051309 +# go/android-media-relaibility + +essick@google.com +nchalko@google.com -- GitLab From 676764f235ff5b0fe8c4cd6e6dcc9855d740e0f4 Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Wed, 29 Sep 2021 23:04:08 +0000 Subject: [PATCH 160/694] Fix AAudio waiting for stop SIGABRT WaitForStateChange is a function that notifies the user if the state moves from a specific state. When the state moves to closed, however, a SIGABRT is thrown because waitForStateChange is in a deleted pointer. android::sp has a property where casting an instance to a sp increments the usage count by 1. Thus, by adding casting the AAudioStream to a sp, the AAudioStream is no longer deleted when the stream closes. With this change, the SIGABRT is no longer thrown. Bug: 63089499 Test: Ran new wait_for_state_change_closed with and without change. Verified that the test fails before the cl and the test now passes after the change. Change-Id: Id865ef3f55f3cf006fd94d7b376d1b87ad999ca5 --- media/libaaudio/src/core/AAudioAudio.cpp | 3 +- media/libaaudio/tests/test_various.cpp | 54 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/media/libaaudio/src/core/AAudioAudio.cpp b/media/libaaudio/src/core/AAudioAudio.cpp index 02e7f5f6a8..b9c4440898 100644 --- a/media/libaaudio/src/core/AAudioAudio.cpp +++ b/media/libaaudio/src/core/AAudioAudio.cpp @@ -340,7 +340,8 @@ AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream* stream, { AudioStream *audioStream = convertAAudioStreamToAudioStream(stream); - return audioStream->waitForStateChange(inputState, nextState, timeoutNanoseconds); + android::sp spAudioStream(audioStream); + return spAudioStream->waitForStateChange(inputState, nextState, timeoutNanoseconds); } // ============================================================ diff --git a/media/libaaudio/tests/test_various.cpp b/media/libaaudio/tests/test_various.cpp index cbf863fec7..b68fc7bd09 100644 --- a/media/libaaudio/tests/test_various.cpp +++ b/media/libaaudio/tests/test_various.cpp @@ -25,6 +25,7 @@ #include #include +#include // Callback function that does nothing. aaudio_data_callback_result_t NoopDataCallbackProc( @@ -51,6 +52,7 @@ aaudio_data_callback_result_t NoopDataCallbackProc( } constexpr int64_t NANOS_PER_MILLISECOND = 1000 * 1000; +constexpr int64_t MICROS_PER_MILLISECOND = 1000; void checkReleaseThenClose(aaudio_performance_mode_t perfMode, aaudio_sharing_mode_t sharingMode, @@ -762,6 +764,58 @@ TEST(test_various, aaudio_callback_once_lowlat) { checkCallbackOnce(AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); } +void waitForStateChangeToClosingorClosed(AAudioStream **stream, std::atomic* isReady) +{ + *isReady = true; + aaudio_stream_state_t state = AAUDIO_STREAM_STATE_UNKNOWN; + EXPECT_EQ(AAUDIO_OK, AAudioStream_waitForStateChange(*stream, + AAUDIO_STREAM_STATE_OPEN, &state, + 10000 * NANOS_PER_MILLISECOND)); + if ((state != AAUDIO_STREAM_STATE_CLOSING) && (state != AAUDIO_STREAM_STATE_CLOSED)){ + FAIL() << "ERROR - State not closing or closed. Current state: " << + AAudio_convertStreamStateToText(state); + } +} + +void testWaitForStateChangeClose(aaudio_performance_mode_t perfMode) { + AAudioStreamBuilder *aaudioBuilder = nullptr; + AAudioStream *aaudioStream = nullptr; + + ASSERT_EQ(AAUDIO_OK, AAudio_createStreamBuilder(&aaudioBuilder)); + AAudioStreamBuilder_setPerformanceMode(aaudioBuilder, perfMode); + ASSERT_EQ(AAUDIO_OK, AAudioStreamBuilder_openStream(aaudioBuilder, &aaudioStream)); + + // Verify Open State + aaudio_stream_state_t state = AAUDIO_STREAM_STATE_UNKNOWN; + EXPECT_EQ(AAUDIO_OK, AAudioStream_waitForStateChange(aaudioStream, + AAUDIO_STREAM_STATE_UNKNOWN, &state, + 1000 * NANOS_PER_MILLISECOND)); + EXPECT_EQ(AAUDIO_STREAM_STATE_OPEN, state); + + std::atomic isWaitThreadReady{false}; + + // Spawn a new thread to wait for the state change + std::thread waitThread (waitForStateChangeToClosingorClosed, &aaudioStream, + &isWaitThreadReady); + + // Wait for worker thread to be ready + while (!isWaitThreadReady) { + usleep(MICROS_PER_MILLISECOND); + } + // Sleep an additional millisecond to make sure waitForAudioThread is called + usleep(MICROS_PER_MILLISECOND); + EXPECT_EQ(AAUDIO_OK, AAudioStream_close(aaudioStream)); + waitThread.join(); +} + +TEST(test_various, wait_for_state_change_close_none) { + testWaitForStateChangeClose(AAUDIO_PERFORMANCE_MODE_NONE); +} + +TEST(test_various, wait_for_state_change_close_lowlat) { + testWaitForStateChangeClose(AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); +} + // ************************************************************ struct WakeUpCallbackData { void wakeOther() { -- GitLab From 0eb2f4aaf304aa91c271dad6fad0ed27770ff1b9 Mon Sep 17 00:00:00 2001 From: Eric Laurent Date: Tue, 5 Oct 2021 13:57:18 +0200 Subject: [PATCH 161/694] AudioPolicyInterface: add note on nullptr checks Add note in AudioPolicyInterface.h specifying that nullptr checks on input arguments are not needed in the implementation. Also fix line lengths. Bug: 136491767 Test: make Change-Id: I214f5e7461758862055571bfbff575c91398f2e9 --- services/audiopolicy/AudioPolicyInterface.h | 93 +++++++++++++-------- 1 file changed, 59 insertions(+), 34 deletions(-) diff --git a/services/audiopolicy/AudioPolicyInterface.h b/services/audiopolicy/AudioPolicyInterface.h index 8613b2ec91..add0684e64 100644 --- a/services/audiopolicy/AudioPolicyInterface.h +++ b/services/audiopolicy/AudioPolicyInterface.h @@ -32,30 +32,42 @@ using content::AttributionSourceState; // ---------------------------------------------------------------------------- -// The AudioPolicyInterface and AudioPolicyClientInterface classes define the communication interfaces -// between the platform specific audio policy manager and Android generic audio policy manager. -// The platform specific audio policy manager must implement methods of the AudioPolicyInterface class. +// The AudioPolicyInterface and AudioPolicyClientInterface classes define the communication +// interfaces between the platform specific audio policy manager and Android generic audio policy +// manager. +// The platform specific audio policy manager must implement methods of the AudioPolicyInterface +// class. // This implementation makes use of the AudioPolicyClientInterface to control the activity and // configuration of audio input and output streams. // // The platform specific audio policy manager is in charge of the audio routing and volume control // policies for a given platform. // The main roles of this module are: -// - keep track of current system state (removable device connections, phone state, user requests...). -// System state changes and user actions are notified to audio policy manager with methods of the AudioPolicyInterface. +// - keep track of current system state (removable device connections, phone state, +// user requests...). +// System state changes and user actions are notified to audio policy manager with methods of the +// AudioPolicyInterface. // - process getOutput() queries received when AudioTrack objects are created: Those queries -// return a handler on an output that has been selected, configured and opened by the audio policy manager and that -// must be used by the AudioTrack when registering to the AudioFlinger with the createTrack() method. -// When the AudioTrack object is released, a putOutput() query is received and the audio policy manager can decide -// to close or reconfigure the output depending on other streams using this output and current system state. -// - similarly process getInput() and putInput() queries received from AudioRecord objects and configure audio inputs. -// - process volume control requests: the stream volume is converted from an index value (received from UI) to a float value -// applicable to each output as a function of platform specific settings and current output route (destination device). It -// also make sure that streams are not muted if not allowed (e.g. camera shutter sound in some countries). +// return a handler on an output that has been selected, configured and opened by the audio +// policy manager and that must be used by the AudioTrack when registering to the AudioFlinger +// with the createTrack() method. +// When the AudioTrack object is released, a putOutput() query is received and the audio policy +// manager can decide to close or reconfigure the output depending on other streams using this +// output and current system state. +// - similarly process getInput() and putInput() queries received from AudioRecord objects and +// configure audio inputs. +// - process volume control requests: the stream volume is converted from an index value +// (received from UI) to a float value applicable to each output as a function of platform +// specificsettings and current output route (destination device). It also make sure that streams +// are not muted if not allowed (e.g. camera shutter sound in some countries). // -// The platform specific audio policy manager is provided as a shared library by platform vendors (as for libaudio.so) -// and is linked with libaudioflinger.so - +// The platform specific audio policy manager is provided as a shared library by platform vendors +// (as for libaudio.so) and is linked with libaudioflinger.so +// +// NOTE: by convention, the implementation of the AudioPolicyInterface in AudioPolicyManager does +// not have to perform any nullptr check on input arguments: The caller of this API is +// AudioPolicyService running in the same process and in charge of validating arguments received +// from incoming binder calls before calling AudioPolicyManager. // Audio Policy Manager Interface class AudioPolicyInterface @@ -100,7 +112,7 @@ public: audio_format_t encodedFormat) = 0; // retrieve a device connection status virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, - const char *device_address) = 0; + const char *device_address) = 0; // indicate a change in device configuration virtual status_t handleDeviceConfigChange(audio_devices_t device, const char *device_address, @@ -134,9 +146,11 @@ public: audio_port_handle_t *portId, std::vector *secondaryOutputs, output_type_t *outputType) = 0; - // indicates to the audio policy manager that the output starts being used by corresponding stream. + // indicates to the audio policy manager that the output starts being used by corresponding + // stream. virtual status_t startOutput(audio_port_handle_t portId) = 0; - // indicates to the audio policy manager that the output stops being used by corresponding stream. + // indicates to the audio policy manager that the output stops being used by corresponding + // stream. virtual status_t stopOutput(audio_port_handle_t portId) = 0; // releases the output, return true if the output descriptor is reopened. virtual bool releaseOutput(audio_port_handle_t portId) = 0; @@ -398,10 +412,13 @@ public: // Audio output Control functions // - // opens an audio output with the requested parameters. The parameter values can indicate to use the default values - // in case the audio policy manager has no specific requirements for the output being opened. - // When the function returns, the parameter values reflect the actual values used by the audio hardware output stream. - // The audio policy manager can check if the proposed parameters are suitable or not and act accordingly. + // opens an audio output with the requested parameters. The parameter values can indicate to + // use the default values in case the audio policy manager has no specific requirements for the + // output being opened. + // When the function returns, the parameter values reflect the actual values used by the audio + // hardware output stream. + // The audio policy manager can check if the proposed parameters are suitable or not and act + // accordingly. virtual status_t openOutput(audio_module_handle_t module, audio_io_handle_t *output, audio_config_t *halConfig, @@ -409,13 +426,15 @@ public: const sp& device, uint32_t *latencyMs, audio_output_flags_t flags) = 0; - // creates a special output that is duplicated to the two outputs passed as arguments. The duplication is performed by - // a special mixer thread in the AudioFlinger. - virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, audio_io_handle_t output2) = 0; + // creates a special output that is duplicated to the two outputs passed as arguments. + // The duplication is performed by a special mixer thread in the AudioFlinger. + virtual audio_io_handle_t openDuplicateOutput(audio_io_handle_t output1, + audio_io_handle_t output2) = 0; // closes the output stream virtual status_t closeOutput(audio_io_handle_t output) = 0; - // suspends the output. When an output is suspended, the corresponding audio hardware output stream is placed in - // standby and the AudioTracks attached to the mixer thread are still processed but the output mix is discarded. + // suspends the output. When an output is suspended, the corresponding audio hardware output + // stream is placed in standby and the AudioTracks attached to the mixer thread are still + // processed but the output mix is discarded. virtual status_t suspendOutput(audio_io_handle_t output) = 0; // restores a suspended output. virtual status_t restoreOutput(audio_io_handle_t output) = 0; @@ -438,16 +457,21 @@ public: // misc control functions // - // set a stream volume for a particular output. For the same user setting, a given stream type can have different volumes + // set a stream volume for a particular output. For the same user setting, a given stream type + // can have different volumes // for each output (destination device) it is attached to. - virtual status_t setStreamVolume(audio_stream_type_t stream, float volume, audio_io_handle_t output, int delayMs = 0) = 0; + virtual status_t setStreamVolume(audio_stream_type_t stream, float volume, + audio_io_handle_t output, int delayMs = 0) = 0; // invalidate a stream type, causing a reroute to an unspecified new output virtual status_t invalidateStream(audio_stream_type_t stream) = 0; - // function enabling to send proprietary informations directly from audio policy manager to audio hardware interface. - virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs, int delayMs = 0) = 0; - // function enabling to receive proprietary informations directly from audio hardware interface to audio policy manager. + // function enabling to send proprietary informations directly from audio policy manager to + // audio hardware interface. + virtual void setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs, + int delayMs = 0) = 0; + // function enabling to receive proprietary informations directly from audio hardware interface + // to audio policy manager. virtual String8 getParameters(audio_io_handle_t ioHandle, const String8& keys) = 0; // set down link audio volume. @@ -510,7 +534,8 @@ public: // These are the signatures of createAudioPolicyManager/destroyAudioPolicyManager // methods respectively, expected by AudioPolicyService, needs to be exposed by // libaudiopolicymanagercustom. - using CreateAudioPolicyManagerInstance = AudioPolicyInterface* (*)(AudioPolicyClientInterface*); + using CreateAudioPolicyManagerInstance = + AudioPolicyInterface* (*)(AudioPolicyClientInterface*); using DestroyAudioPolicyManagerInstance = void (*)(AudioPolicyInterface*); } // namespace android -- GitLab From d4c21aa434f8f789e897024693311b61c7b1fd4b Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 5 Oct 2021 15:10:16 -0700 Subject: [PATCH 162/694] Fix some issues with audiopolicy_tests 1. Update AudioPolicyManagerTestClientForHdmi to allow adding multiple supported formats. 2. Add missing assertions for helper functions to complete with no failures. 3. Set the name of the loaded config file so it can be seen in the APM config dump printed to syslog. Bug: 201089251 Test: atest audiopolicy_tests Change-Id: I02dac749b7927ee6f048156d0f8aa16af09a50ea --- .../AudioPolicyManagerTestClientForHdmi.h | 21 ++++++++++++------- .../tests/audiopolicymanager_tests.cpp | 13 ++++++------ 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/services/audiopolicy/tests/AudioPolicyManagerTestClientForHdmi.h b/services/audiopolicy/tests/AudioPolicyManagerTestClientForHdmi.h index a5ad9b1769..7343b9b653 100644 --- a/services/audiopolicy/tests/AudioPolicyManagerTestClientForHdmi.h +++ b/services/audiopolicy/tests/AudioPolicyManagerTestClientForHdmi.h @@ -28,19 +28,26 @@ namespace android { class AudioPolicyManagerTestClientForHdmi : public AudioPolicyManagerTestClient { public: String8 getParameters(audio_io_handle_t /* ioHandle */, const String8& /* keys*/ ) override { - return mAudioParameters.toString(); - } - - void addSupportedFormat(audio_format_t format) override { + AudioParameter mAudioParameters; + std::string formats; + for (const auto& f : mSupportedFormats) { + if (!formats.empty()) formats += AUDIO_PARAMETER_VALUE_LIST_SEPARATOR; + formats += audio_format_to_string(f); + } mAudioParameters.add( String8(AudioParameter::keyStreamSupportedFormats), - String8(audio_format_to_string(format))); + String8(formats.c_str())); mAudioParameters.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), 48000); mAudioParameters.add(String8(AudioParameter::keyStreamSupportedChannels), String8("")); + return mAudioParameters.toString(); + } + + void addSupportedFormat(audio_format_t format) override { + mSupportedFormats.insert(format); } private: - AudioParameter mAudioParameters; + std::set mSupportedFormats; }; -} // namespace android \ No newline at end of file +} // namespace android diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp index 4bf3c9ede9..6a6d75a600 100644 --- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp +++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp @@ -151,7 +151,7 @@ class AudioPolicyManagerTest : public testing::Test { void AudioPolicyManagerTest::SetUp() { mClient.reset(getClient()); mManager.reset(new AudioPolicyTestManager(mClient.get())); - SetUpManagerConfig(); // Subclasses may want to customize the config. + ASSERT_NO_FATAL_FAILURE(SetUpManagerConfig()); // Subclasses may want to customize the config. ASSERT_EQ(NO_ERROR, mManager->initialize()); ASSERT_EQ(NO_ERROR, mManager->initCheck()); } @@ -401,7 +401,7 @@ INSTANTIATE_TEST_CASE_P( void AudioPolicyManagerTestMsd::SetUpManagerConfig() { // TODO: Consider using Serializer to load part of the config from a string. - AudioPolicyManagerTest::SetUpManagerConfig(); + ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUpManagerConfig()); AudioPolicyConfig& config = mManager->getConfig(); mMsdOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_BUS); sp pcmOutputProfile = new AudioProfile( @@ -660,6 +660,7 @@ const std::string AudioPolicyManagerTestWithConfigurationFile::sDefaultConfig = void AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig() { status_t status = deserializeAudioPolicyFile(getConfigFile().c_str(), &mManager->getConfig()); ASSERT_EQ(NO_ERROR, status); + mManager->getConfig().setSource(getConfigFile()); } TEST_F(AudioPolicyManagerTestWithConfigurationFile, InitSuccess) { @@ -825,7 +826,7 @@ const std::string AudioPolicyManagerTestForHdmi::sTvConfig = "test_settop_box_surround_configuration.xml"; void AudioPolicyManagerTestForHdmi::SetUp() { - AudioPolicyManagerTest::SetUp(); + ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUp()); // Note that 'AC3' isn't added as it is handled automatically by APM. mClient->addSupportedFormat(AUDIO_FORMAT_E_AC3); mManager->setDeviceConnectionState( @@ -1051,7 +1052,7 @@ protected: }; void AudioPolicyManagerTestDPPlaybackReRouting::SetUp() { - AudioPolicyManagerTestDynamicPolicy::SetUp(); + ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp()); mTracker.reset(new RecordingActivityTracker()); @@ -1237,7 +1238,7 @@ protected: }; void AudioPolicyManagerTestDPMixRecordInjection::SetUp() { - AudioPolicyManagerTestDynamicPolicy::SetUp(); + ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestDynamicPolicy::SetUp()); mTracker.reset(new RecordingActivityTracker()); @@ -1535,7 +1536,7 @@ protected: }; void AudioPolicyManagerDynamicHwModulesTest::SetUpManagerConfig() { - AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig(); + ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTestWithConfigurationFile::SetUpManagerConfig()); // Only allow successful opening of "primary" hw module during APM initialization. mClient->swapAllowedModuleNames({"primary"}); } -- GitLab From 83caee075fffbb76d8323426c9d47ff9114b66a5 Mon Sep 17 00:00:00 2001 From: Mikhail Naganov Date: Tue, 5 Oct 2021 15:52:01 -0700 Subject: [PATCH 163/694] Remove automatic addition of AC3, IEC61937 to HDMI outputs Historically, the automatic addition of AC3 and IEC61937 formats to the list of supported formats for HDMI output ports was a workaround for the problem occuring in certain TV setups that don't report supported formats properly. It was found out that this workaround creates confusion in setups which report supported formats properly. This is why automatic addition is being removed now. It's still possible to restore the historic behavior if required: - on vendor side, by adding 'encodedFormats="AUDIO_FORMAT_AC3 AUDIO_FORMAT_IEC61937"' to the HDMI output device port in the APM config file; - on user side, by going to "Surround Sound" settings and enabling "Dolby Digital" manually. Bug: 201089251 Test: atest audiopolicy_tests Test: manual test on an Android TV dongle Change-Id: I54d9a2c2f203db9fb462ef6d1206ce17043ab997 --- .../common/managerdefinitions/src/DeviceDescriptor.cpp | 9 --------- services/audiopolicy/tests/audiopolicymanager_tests.cpp | 5 +++-- .../tests/resources/test_audio_policy_configuration.xml | 3 ++- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp index 1722032f83..c9c8ede39f 100644 --- a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp +++ b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp @@ -58,15 +58,6 @@ DeviceDescriptor::DeviceDescriptor(const AudioDeviceTypeAddr &deviceTypeAddr, mDeclaredAddress(DeviceDescriptorBase::address()) { mCurrentEncodedFormat = AUDIO_FORMAT_DEFAULT; - /* If framework runs against a pre 5.0 Audio HAL, encoded formats are absent from the config. - * FIXME: APM should know the version of the HAL and don't add the formats for V5.0. - * For now, the workaround to remove AC3 and IEC61937 support on HDMI is to declare - * something like 'encodedFormats="AUDIO_FORMAT_PCM_16_BIT"' on the HDMI devicePort. - */ - if (mDeviceTypeAddr.mType == AUDIO_DEVICE_OUT_HDMI && mEncodedFormats.empty()) { - mEncodedFormats.push_back(AUDIO_FORMAT_AC3); - mEncodedFormats.push_back(AUDIO_FORMAT_IEC61937); - } } void DeviceDescriptor::attach(const sp& module) diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp index 6a6d75a600..9c1adc6ae2 100644 --- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp +++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp @@ -827,7 +827,7 @@ const std::string AudioPolicyManagerTestForHdmi::sTvConfig = void AudioPolicyManagerTestForHdmi::SetUp() { ASSERT_NO_FATAL_FAILURE(AudioPolicyManagerTest::SetUp()); - // Note that 'AC3' isn't added as it is handled automatically by APM. + mClient->addSupportedFormat(AUDIO_FORMAT_AC3); mClient->addSupportedFormat(AUDIO_FORMAT_E_AC3); mManager->setDeviceConnectionState( AUDIO_DEVICE_OUT_HDMI, AUDIO_POLICY_DEVICE_STATE_AVAILABLE, @@ -1392,7 +1392,8 @@ TEST_P(AudioPolicyManagerTestDeviceConnection, SetDeviceConnectionState) { if (type == AUDIO_DEVICE_OUT_HDMI) { // Set device connection state failed due to no device descriptor found // For HDMI case, it is easier to simulate device descriptor not found error - // by using a undeclared encoded format. + // by using an encoded format which isn't listed in the 'encodedFormats' + // attribute for this devicePort. ASSERT_EQ(INVALID_OPERATION, mManager->setDeviceConnectionState( type, AUDIO_POLICY_DEVICE_STATE_AVAILABLE, address.c_str(), name.c_str(), AUDIO_FORMAT_MAT_2_1)); diff --git a/services/audiopolicy/tests/resources/test_audio_policy_configuration.xml b/services/audiopolicy/tests/resources/test_audio_policy_configuration.xml index 87f0ab9a46..41ed70ca2e 100644 --- a/services/audiopolicy/tests/resources/test_audio_policy_configuration.xml +++ b/services/audiopolicy/tests/resources/test_audio_policy_configuration.xml @@ -50,7 +50,8 @@ - + -- GitLab From 19249bd3cd3709f6fcd761f54b4a5d2dce7f3ac8 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Mon, 4 Oct 2021 19:10:03 -0700 Subject: [PATCH 164/694] Replace raw include paths with header_libs Replace the use of raw include paths involving media extractors with header_libs and export_include_dirs. Bug: 201944263 Test: build Change-Id: If1d43fbdcc756af0c1943739ec83d482af46095e --- media/extractors/Android.bp | 4 -- media/extractors/aac/Android.bp | 4 ++ .../aac/{ => include}/AACExtractor.h | 0 media/extractors/amr/Android.bp | 4 ++ .../amr/{ => include}/AMRExtractor.h | 0 media/extractors/flac/Android.bp | 4 +- .../flac/{ => include}/FLACExtractor.h | 0 media/extractors/fuzzers/Android.bp | 44 ------------------- media/extractors/midi/Android.bp | 4 ++ .../midi/{ => include}/MidiExtractor.h | 0 media/extractors/mkv/Android.bp | 6 +-- .../mkv/{ => include}/MatroskaExtractor.h | 0 media/extractors/mp3/Android.bp | 4 ++ .../mp3/{ => include}/MP3Extractor.h | 0 .../extractors/mp3/{ => include}/MP3Seeker.h | 0 .../extractors/mp3/{ => include}/VBRISeeker.h | 0 .../extractors/mp3/{ => include}/XINGSeeker.h | 0 media/extractors/mp4/Android.bp | 13 ++++++ .../extractors/mp4/{ => include}/AC4Parser.h | 0 .../extractors/mp4/{ => include}/ItemTable.h | 0 .../mp4/{ => include}/MPEG4Extractor.h | 0 .../mp4/{ => include}/SampleIterator.h | 0 .../mp4/{ => include}/SampleTable.h | 0 media/extractors/mpeg2/Android.bp | 4 ++ .../mpeg2/{ => include}/MPEG2PSExtractor.h | 0 .../mpeg2/{ => include}/MPEG2TSExtractor.h | 0 media/extractors/ogg/Android.bp | 4 +- .../ogg/{ => include}/OggExtractor.h | 0 media/extractors/tests/Android.bp | 5 --- media/extractors/tests/ExtractorUnitTest.cpp | 24 +++++----- media/extractors/wav/Android.bp | 4 +- .../wav/{ => include}/WAVExtractor.h | 0 media/libstagefright/mpeg2ts/test/Android.bp | 5 --- .../mpeg2ts/test/Mpeg2tsUnitTest.cpp | 4 +- 34 files changed, 55 insertions(+), 82 deletions(-) rename media/extractors/aac/{ => include}/AACExtractor.h (100%) rename media/extractors/amr/{ => include}/AMRExtractor.h (100%) rename media/extractors/flac/{ => include}/FLACExtractor.h (100%) rename media/extractors/midi/{ => include}/MidiExtractor.h (100%) rename media/extractors/mkv/{ => include}/MatroskaExtractor.h (100%) rename media/extractors/mp3/{ => include}/MP3Extractor.h (100%) rename media/extractors/mp3/{ => include}/MP3Seeker.h (100%) rename media/extractors/mp3/{ => include}/VBRISeeker.h (100%) rename media/extractors/mp3/{ => include}/XINGSeeker.h (100%) rename media/extractors/mp4/{ => include}/AC4Parser.h (100%) rename media/extractors/mp4/{ => include}/ItemTable.h (100%) rename media/extractors/mp4/{ => include}/MPEG4Extractor.h (100%) rename media/extractors/mp4/{ => include}/SampleIterator.h (100%) rename media/extractors/mp4/{ => include}/SampleTable.h (100%) rename media/extractors/mpeg2/{ => include}/MPEG2PSExtractor.h (100%) rename media/extractors/mpeg2/{ => include}/MPEG2TSExtractor.h (100%) rename media/extractors/ogg/{ => include}/OggExtractor.h (100%) rename media/extractors/wav/{ => include}/WAVExtractor.h (100%) diff --git a/media/extractors/Android.bp b/media/extractors/Android.bp index 7513cb15bf..66585daecd 100644 --- a/media/extractors/Android.bp +++ b/media/extractors/Android.bp @@ -24,10 +24,6 @@ package { cc_defaults { name: "extractor-defaults", - include_dirs: [ - "frameworks/av/media/libstagefright/include", - ], - shared_libs: [ "liblog", ], diff --git a/media/extractors/aac/Android.bp b/media/extractors/aac/Android.bp index 7bf3a1397d..a926422656 100644 --- a/media/extractors/aac/Android.bp +++ b/media/extractors/aac/Android.bp @@ -21,6 +21,10 @@ cc_library { srcs: ["AACExtractor.cpp"], + export_include_dirs: [ + "include", + ], + static_libs: [ "libstagefright_foundation", "libstagefright_metadatautils", diff --git a/media/extractors/aac/AACExtractor.h b/media/extractors/aac/include/AACExtractor.h similarity index 100% rename from media/extractors/aac/AACExtractor.h rename to media/extractors/aac/include/AACExtractor.h diff --git a/media/extractors/amr/Android.bp b/media/extractors/amr/Android.bp index 712360d10f..121b7a3bca 100644 --- a/media/extractors/amr/Android.bp +++ b/media/extractors/amr/Android.bp @@ -21,6 +21,10 @@ cc_library { srcs: ["AMRExtractor.cpp"], + export_include_dirs: [ + "include", + ], + static_libs: [ "libstagefright_foundation", ], diff --git a/media/extractors/amr/AMRExtractor.h b/media/extractors/amr/include/AMRExtractor.h similarity index 100% rename from media/extractors/amr/AMRExtractor.h rename to media/extractors/amr/include/AMRExtractor.h diff --git a/media/extractors/flac/Android.bp b/media/extractors/flac/Android.bp index 9a2a76bb48..fd51622397 100644 --- a/media/extractors/flac/Android.bp +++ b/media/extractors/flac/Android.bp @@ -23,8 +23,8 @@ cc_library { srcs: ["FLACExtractor.cpp"], - include_dirs: [ - "external/flac/include", + export_include_dirs: [ + "include", ], shared_libs: [ diff --git a/media/extractors/flac/FLACExtractor.h b/media/extractors/flac/include/FLACExtractor.h similarity index 100% rename from media/extractors/flac/FLACExtractor.h rename to media/extractors/flac/include/FLACExtractor.h diff --git a/media/extractors/fuzzers/Android.bp b/media/extractors/fuzzers/Android.bp index 0e54b58d4a..490e195bcf 100644 --- a/media/extractors/fuzzers/Android.bp +++ b/media/extractors/fuzzers/Android.bp @@ -80,11 +80,6 @@ cc_defaults { defaults: ["extractor-fuzzer-defaults"], host_supported: true, - include_dirs: [ - "frameworks/av/media/extractors/mpeg2", - "frameworks/av/media/libstagefright", - ], - static_libs: [ "libstagefright_foundation_without_imemory", "libstagefright_mpeg2support", @@ -124,14 +119,6 @@ cc_fuzz { "mp4_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/mp4", - ], - - header_libs: [ - "libaudioclient_headers", - ], - static_libs: [ "libstagefright_id3", "libstagefright_esds", @@ -150,10 +137,6 @@ cc_fuzz { "wav_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/wav", - ], - static_libs: [ "libfifo", "libwavextractor", @@ -173,10 +156,6 @@ cc_fuzz { "amr_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/amr", - ], - static_libs: [ "libamrextractor", ], @@ -193,10 +172,6 @@ cc_fuzz { "mkv_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/mkv", - ], - static_libs: [ "libwebm", "libstagefright_flacdec", @@ -217,9 +192,6 @@ cc_fuzz { "ogg_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/ogg", - ], static_libs: [ "libstagefright_metadatautils", @@ -265,10 +237,6 @@ cc_fuzz { "mp3_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/mp3", - ], - static_libs: [ "libfifo", "libmp3extractor", @@ -285,10 +253,6 @@ cc_fuzz { "aac_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/aac", - ], - static_libs: [ "libaacextractor", "libstagefright_metadatautils", @@ -304,10 +268,6 @@ cc_fuzz { "flac_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/flac", - ], - static_libs: [ "libstagefright_metadatautils", "libFLAC", @@ -329,10 +289,6 @@ cc_fuzz { "midi_extractor_fuzzer.cpp", ], - include_dirs: [ - "frameworks/av/media/extractors/midi", - ], - static_libs: [ "libsonivox", "libmedia_midiiowrapper", diff --git a/media/extractors/midi/Android.bp b/media/extractors/midi/Android.bp index 08a6fa04e2..feabf9e0fc 100644 --- a/media/extractors/midi/Android.bp +++ b/media/extractors/midi/Android.bp @@ -23,6 +23,10 @@ cc_library { srcs: ["MidiExtractor.cpp"], + export_include_dirs: [ + "include", + ], + header_libs: [ "libmedia_datasource_headers", ], diff --git a/media/extractors/midi/MidiExtractor.h b/media/extractors/midi/include/MidiExtractor.h similarity index 100% rename from media/extractors/midi/MidiExtractor.h rename to media/extractors/midi/include/MidiExtractor.h diff --git a/media/extractors/mkv/Android.bp b/media/extractors/mkv/Android.bp index 54c5b271eb..98ce3050f9 100644 --- a/media/extractors/mkv/Android.bp +++ b/media/extractors/mkv/Android.bp @@ -21,10 +21,8 @@ cc_library { srcs: ["MatroskaExtractor.cpp"], - include_dirs: [ - "external/flac/include", - "external/libvpx/libwebm", - "frameworks/av/media/libstagefright/flac/dec", + export_include_dirs: [ + "include", ], shared_libs: [ diff --git a/media/extractors/mkv/MatroskaExtractor.h b/media/extractors/mkv/include/MatroskaExtractor.h similarity index 100% rename from media/extractors/mkv/MatroskaExtractor.h rename to media/extractors/mkv/include/MatroskaExtractor.h diff --git a/media/extractors/mp3/Android.bp b/media/extractors/mp3/Android.bp index 75b9b7b368..396a13a3e7 100644 --- a/media/extractors/mp3/Android.bp +++ b/media/extractors/mp3/Android.bp @@ -16,6 +16,10 @@ cc_library { "XINGSeeker.cpp", ], + export_include_dirs: [ + "include", + ], + static_libs: [ "libutils", "libstagefright_id3", diff --git a/media/extractors/mp3/MP3Extractor.h b/media/extractors/mp3/include/MP3Extractor.h similarity index 100% rename from media/extractors/mp3/MP3Extractor.h rename to media/extractors/mp3/include/MP3Extractor.h diff --git a/media/extractors/mp3/MP3Seeker.h b/media/extractors/mp3/include/MP3Seeker.h similarity index 100% rename from media/extractors/mp3/MP3Seeker.h rename to media/extractors/mp3/include/MP3Seeker.h diff --git a/media/extractors/mp3/VBRISeeker.h b/media/extractors/mp3/include/VBRISeeker.h similarity index 100% rename from media/extractors/mp3/VBRISeeker.h rename to media/extractors/mp3/include/VBRISeeker.h diff --git a/media/extractors/mp3/XINGSeeker.h b/media/extractors/mp3/include/XINGSeeker.h similarity index 100% rename from media/extractors/mp3/XINGSeeker.h rename to media/extractors/mp3/include/XINGSeeker.h diff --git a/media/extractors/mp4/Android.bp b/media/extractors/mp4/Android.bp index 7fa6bfd423..540d75ddd5 100644 --- a/media/extractors/mp4/Android.bp +++ b/media/extractors/mp4/Android.bp @@ -15,6 +15,15 @@ license { ], } +cc_library_headers { + name: "libmp4extractor_headers", + host_supported: true, + + export_include_dirs: [ + "include", + ], +} + cc_library { name: "libmp4extractor", defaults: ["extractor-defaults"], @@ -27,6 +36,10 @@ cc_library { "SampleTable.cpp", ], + export_include_dirs: [ + "include", + ], + static_libs: [ "libstagefright_esds", "libstagefright_foundation", diff --git a/media/extractors/mp4/AC4Parser.h b/media/extractors/mp4/include/AC4Parser.h similarity index 100% rename from media/extractors/mp4/AC4Parser.h rename to media/extractors/mp4/include/AC4Parser.h diff --git a/media/extractors/mp4/ItemTable.h b/media/extractors/mp4/include/ItemTable.h similarity index 100% rename from media/extractors/mp4/ItemTable.h rename to media/extractors/mp4/include/ItemTable.h diff --git a/media/extractors/mp4/MPEG4Extractor.h b/media/extractors/mp4/include/MPEG4Extractor.h similarity index 100% rename from media/extractors/mp4/MPEG4Extractor.h rename to media/extractors/mp4/include/MPEG4Extractor.h diff --git a/media/extractors/mp4/SampleIterator.h b/media/extractors/mp4/include/SampleIterator.h similarity index 100% rename from media/extractors/mp4/SampleIterator.h rename to media/extractors/mp4/include/SampleIterator.h diff --git a/media/extractors/mp4/SampleTable.h b/media/extractors/mp4/include/SampleTable.h similarity index 100% rename from media/extractors/mp4/SampleTable.h rename to media/extractors/mp4/include/SampleTable.h diff --git a/media/extractors/mpeg2/Android.bp b/media/extractors/mpeg2/Android.bp index 7e6247bc86..8faecaebe5 100644 --- a/media/extractors/mpeg2/Android.bp +++ b/media/extractors/mpeg2/Android.bp @@ -38,6 +38,10 @@ cc_library { "MPEG2TSExtractor.cpp", ], + export_include_dirs: [ + "include", + ], + shared_libs: [ "libbase", "libcgrouprc#29", diff --git a/media/extractors/mpeg2/MPEG2PSExtractor.h b/media/extractors/mpeg2/include/MPEG2PSExtractor.h similarity index 100% rename from media/extractors/mpeg2/MPEG2PSExtractor.h rename to media/extractors/mpeg2/include/MPEG2PSExtractor.h diff --git a/media/extractors/mpeg2/MPEG2TSExtractor.h b/media/extractors/mpeg2/include/MPEG2TSExtractor.h similarity index 100% rename from media/extractors/mpeg2/MPEG2TSExtractor.h rename to media/extractors/mpeg2/include/MPEG2TSExtractor.h diff --git a/media/extractors/ogg/Android.bp b/media/extractors/ogg/Android.bp index d7540c4b17..dc3c25c4f1 100644 --- a/media/extractors/ogg/Android.bp +++ b/media/extractors/ogg/Android.bp @@ -22,8 +22,8 @@ cc_library { srcs: ["OggExtractor.cpp"], - include_dirs: [ - "external/tremolo", + export_include_dirs: [ + "include", ], header_libs: [ diff --git a/media/extractors/ogg/OggExtractor.h b/media/extractors/ogg/include/OggExtractor.h similarity index 100% rename from media/extractors/ogg/OggExtractor.h rename to media/extractors/ogg/include/OggExtractor.h diff --git a/media/extractors/tests/Android.bp b/media/extractors/tests/Android.bp index 23c74f74d4..3c3bbdc0e9 100644 --- a/media/extractors/tests/Android.bp +++ b/media/extractors/tests/Android.bp @@ -79,11 +79,6 @@ cc_test { "libbase", ], - include_dirs: [ - "frameworks/av/media/extractors/", - "frameworks/av/media/libstagefright/", - ], - compile_multilib: "first", cflags: [ diff --git a/media/extractors/tests/ExtractorUnitTest.cpp b/media/extractors/tests/ExtractorUnitTest.cpp index 84ec1f2167..2bd9c6acbb 100644 --- a/media/extractors/tests/ExtractorUnitTest.cpp +++ b/media/extractors/tests/ExtractorUnitTest.cpp @@ -27,18 +27,18 @@ #include #include -#include "aac/AACExtractor.h" -#include "amr/AMRExtractor.h" -#include "flac/FLACExtractor.h" -#include "midi/MidiExtractor.h" -#include "mkv/MatroskaExtractor.h" -#include "mp3/MP3Extractor.h" -#include "mp4/MPEG4Extractor.h" -#include "mp4/SampleTable.h" -#include "mpeg2/MPEG2PSExtractor.h" -#include "mpeg2/MPEG2TSExtractor.h" -#include "ogg/OggExtractor.h" -#include "wav/WAVExtractor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "ExtractorUnitTestEnvironment.h" diff --git a/media/extractors/wav/Android.bp b/media/extractors/wav/Android.bp index cc5e1c7eea..b7e2af3526 100644 --- a/media/extractors/wav/Android.bp +++ b/media/extractors/wav/Android.bp @@ -22,8 +22,8 @@ cc_library { srcs: ["WAVExtractor.cpp"], - include_dirs: [ - "frameworks/av/media/libstagefright/include", + export_include_dirs: [ + "include", ], shared_libs: [ diff --git a/media/extractors/wav/WAVExtractor.h b/media/extractors/wav/include/WAVExtractor.h similarity index 100% rename from media/extractors/wav/WAVExtractor.h rename to media/extractors/wav/include/WAVExtractor.h diff --git a/media/libstagefright/mpeg2ts/test/Android.bp b/media/libstagefright/mpeg2ts/test/Android.bp index 464b039657..34a8d3e20e 100644 --- a/media/libstagefright/mpeg2ts/test/Android.bp +++ b/media/libstagefright/mpeg2ts/test/Android.bp @@ -57,11 +57,6 @@ cc_test{ "libstagefright_mpeg2support", ], - include_dirs: [ - "frameworks/av/media/extractors/", - "frameworks/av/media/libstagefright/", - ], - header_libs: [ "libmedia_headers", "libaudioclient_headers", diff --git a/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp index 79c233b638..7f25d78a5b 100644 --- a/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp +++ b/media/libstagefright/mpeg2ts/test/Mpeg2tsUnitTest.cpp @@ -27,8 +27,8 @@ #include #include -#include "mpeg2ts/ATSParser.h" -#include "mpeg2ts/AnotherPacketSource.h" +#include +#include #include "Mpeg2tsUnitTestEnvironment.h" -- GitLab From a00dbcaa5967d2fe0283dcf34fe8aca3aad23dcb Mon Sep 17 00:00:00 2001 From: Robert Wu Date: Wed, 6 Oct 2021 18:27:21 +0000 Subject: [PATCH 165/694] Change docs to include aaudio/Aaudio.h Currently, the docs incorrectly include AAudio.h See https://developer.android.com/ndk/reference/group/audio This needs to be changed to aaudio/AAudio.h Bug: 120860319 Test: not sure how to verify docs Change-Id: I3365721a42b6f44613ca21a4e9e76af64777f0e4 --- media/libaaudio/include/aaudio/AAudio.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h index fc86001356..ed3b9863be 100644 --- a/media/libaaudio/include/aaudio/AAudio.h +++ b/media/libaaudio/include/aaudio/AAudio.h @@ -20,7 +20,7 @@ */ /** - * @file AAudio.h + * @file aaudio/AAudio.h */ /** -- GitLab From 41da5034cc3dc9ecc5752ed992a1057e42f7a809 Mon Sep 17 00:00:00 2001 From: Chethan Kumar R E Date: Fri, 28 May 2021 13:03:20 +0530 Subject: [PATCH 166/694] Added mediarecorder_fuzzer Test: ./mediarecorder_fuzzer Bug: 189053744 Change-Id: I0d5056d075cdb9fd9ad4f74e871c554c8dae5d9d --- media/libmediaplayerservice/fuzzer/Android.bp | 65 ++++ media/libmediaplayerservice/fuzzer/README.md | 26 ++ .../fuzzer/mediarecorder_fuzzer.cpp | 312 ++++++++++++++++++ 3 files changed, 403 insertions(+) create mode 100644 media/libmediaplayerservice/fuzzer/Android.bp create mode 100644 media/libmediaplayerservice/fuzzer/README.md create mode 100644 media/libmediaplayerservice/fuzzer/mediarecorder_fuzzer.cpp diff --git a/media/libmediaplayerservice/fuzzer/Android.bp b/media/libmediaplayerservice/fuzzer/Android.bp new file mode 100644 index 0000000000..fb1d494d89 --- /dev/null +++ b/media/libmediaplayerservice/fuzzer/Android.bp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +cc_defaults { + name: "libmediaplayerserviceFuzzer_defaults", + include_dirs: [ + "frameworks/av/media/libmediaplayerservice", + ], + static_libs: [ + "libmediaplayerservice", + "liblog", + ], + shared_libs: [ + "framework-permission-aidl-cpp", + "libbinder", + "libcutils", + "libmedia", + "libstagefright", + "libutils", + "libstagefright_foundation", + ], + fuzz_config: { + cc: [ + "android-media-fuzzing-reports@google.com", + ], + componentid: 155276, + }, +} + +cc_fuzz { + name: "mediarecorder_fuzzer", + srcs: [ + "mediarecorder_fuzzer.cpp", + ], + defaults: [ + "libmediaplayerserviceFuzzer_defaults", + ], + static_libs: [ + "libstagefright_rtsp", + "libbase", + ], + shared_libs: [ + "av-types-aidl-cpp", + "media_permission-aidl-cpp", + "libaudioclient_aidl_conversion", + "libandroid_net", + "libcamera_client", + "libgui", + "libmediametrics", + ], +} diff --git a/media/libmediaplayerservice/fuzzer/README.md b/media/libmediaplayerservice/fuzzer/README.md new file mode 100644 index 0000000000..9100f1296c --- /dev/null +++ b/media/libmediaplayerservice/fuzzer/README.md @@ -0,0 +1,26 @@ +# Fuzzer for libmediaplayerservice +## Table of contents ++ [StagefrightMediaRecorder](#StagefrightMediaRecorder) + +# Fuzzer for StagefrightMediaRecorder + +StagefrightMediaRecorder supports the following parameters: +1. Output Formats (parameter name: `setOutputFormat`) +2. Audio Encoders (parameter name: `setAudioEncoder`) +3. Video Encoders (parameter name: `setVideoEncoder`) +4. Audio Sources (parameter name: `setAudioSource`) +5. Video Sources (parameter name: `setVideoSource`) +6. Microphone Direction (parameter name: `setMicrophoneDirection`) + +You can find the possible values in the fuzzer's source code. + +#### Steps to run +1. Build the fuzzer +``` + $ mm -j$(nproc) mediarecorder_fuzzer +``` +2. Run on device +``` + $ adb sync data + $ adb shell /data/fuzz/arm64/mediarecorder_fuzzer/mediarecorder_fuzzer +``` diff --git a/media/libmediaplayerservice/fuzzer/mediarecorder_fuzzer.cpp b/media/libmediaplayerservice/fuzzer/mediarecorder_fuzzer.cpp new file mode 100644 index 0000000000..b0040fed70 --- /dev/null +++ b/media/libmediaplayerservice/fuzzer/mediarecorder_fuzzer.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "fuzzer/FuzzedDataProvider.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace android; +using namespace android::hardware; + +constexpr video_source kSupportedVideoSources[] = {VIDEO_SOURCE_DEFAULT, VIDEO_SOURCE_CAMERA, + VIDEO_SOURCE_SURFACE}; + +constexpr audio_source_t kSupportedAudioSources[] = { + AUDIO_SOURCE_DEFAULT, AUDIO_SOURCE_MIC, + AUDIO_SOURCE_VOICE_UPLINK, AUDIO_SOURCE_VOICE_DOWNLINK, + AUDIO_SOURCE_VOICE_CALL, AUDIO_SOURCE_CAMCORDER, + AUDIO_SOURCE_VOICE_RECOGNITION, AUDIO_SOURCE_VOICE_COMMUNICATION, + AUDIO_SOURCE_REMOTE_SUBMIX, AUDIO_SOURCE_UNPROCESSED, + AUDIO_SOURCE_VOICE_PERFORMANCE, AUDIO_SOURCE_ECHO_REFERENCE, + AUDIO_SOURCE_FM_TUNER, AUDIO_SOURCE_HOTWORD}; + +constexpr audio_microphone_direction_t kSupportedMicrophoneDirections[] = { + MIC_DIRECTION_UNSPECIFIED, MIC_DIRECTION_FRONT, MIC_DIRECTION_BACK, MIC_DIRECTION_EXTERNAL}; + +struct RecordingConfig { + output_format outputFormat; + audio_encoder audioEncoder; + video_encoder videoEncoder; +}; + +const struct RecordingConfig kRecordingConfigList[] = { + {OUTPUT_FORMAT_AMR_NB, AUDIO_ENCODER_AMR_NB, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_AMR_WB, AUDIO_ENCODER_AMR_WB, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_AAC_ADTS, AUDIO_ENCODER_AAC, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_AAC_ADTS, AUDIO_ENCODER_HE_AAC, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_AAC_ADTS, AUDIO_ENCODER_AAC_ELD, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_OGG, AUDIO_ENCODER_OPUS, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_RTP_AVP, AUDIO_ENCODER_DEFAULT, VIDEO_ENCODER_DEFAULT}, + {OUTPUT_FORMAT_MPEG2TS, AUDIO_ENCODER_AAC, VIDEO_ENCODER_H264}, + {OUTPUT_FORMAT_WEBM, AUDIO_ENCODER_VORBIS, VIDEO_ENCODER_VP8}, + {OUTPUT_FORMAT_THREE_GPP, AUDIO_ENCODER_DEFAULT, VIDEO_ENCODER_MPEG_4_SP}, + {OUTPUT_FORMAT_MPEG_4, AUDIO_ENCODER_AAC, VIDEO_ENCODER_H264}, + {OUTPUT_FORMAT_MPEG_4, AUDIO_ENCODER_DEFAULT, VIDEO_ENCODER_MPEG_4_SP}, + {OUTPUT_FORMAT_MPEG_4, AUDIO_ENCODER_DEFAULT, VIDEO_ENCODER_HEVC}}; + +const string kParametersList[] = {"max-duration", + "max-filesize", + "interleave-duration-us", + "param-movie-time-scale", + "param-geotag-longitude", + "param-geotag-latitude", + "param-track-time-status", + "audio-param-sampling-rate", + "audio-param-encoding-bitrate", + "audio-param-number-of-channels", + "audio-param-time-scale", + "video-param-rotation-angle-degrees", + "video-param-encoding-bitrate", + "video-param-bitrate-mode", + "video-param-i-frames-interval", + "video-param-encoder-profile", + "video-param-encoder-level", + "video-param-camera-id", + "video-param-time-scale", + "param-use-64bit-offset", + "time-lapse-enable", + "time-lapse-fps", + "rtp-param-local-ip", + "rtp-param-local-port", + "rtp-param-remote-port", + "rtp-param-self-id", + "rtp-param-opponent-id", + "rtp-param-payload-type", + "rtp-param-ext-cvo-extmap", + "rtp-param-ext-cvo-degrees", + "video-param-request-i-frame", + "rtp-param-set-socket-dscp", + "rtp-param-set-socket-network"}; + +constexpr int32_t kMaxSleepTimeInMs = 100; +constexpr int32_t kMinSleepTimeInMs = 0; +constexpr int32_t kMinVideoSize = 2; +constexpr int32_t kMaxVideoSize = 8192; +constexpr int32_t kNumRecordMin = 1; +constexpr int32_t kNumRecordMax = 10; + +class TestAudioDeviceCallback : public AudioSystem::AudioDeviceCallback { + public: + virtual ~TestAudioDeviceCallback() = default; + + void onAudioDeviceUpdate(audio_io_handle_t /*audioIo*/, + audio_port_handle_t /*deviceId*/) override{}; +}; + +class TestCamera : public ICamera { + public: + virtual ~TestCamera() = default; + + binder::Status disconnect() override { return binder::Status::ok(); }; + status_t connect(const sp & /*client*/) override { return 0; }; + status_t lock() override { return 0; }; + status_t unlock() override { return 0; }; + status_t setPreviewTarget(const sp & /*bufferProducer*/) override { + return 0; + }; + void setPreviewCallbackFlag(int /*flag*/) override{}; + status_t setPreviewCallbackTarget( + const sp & /*callbackProducer*/) override { + return 0; + }; + status_t startPreview() override { return 0; }; + void stopPreview() override{}; + bool previewEnabled() override { return true; }; + status_t startRecording() override { return 0; }; + void stopRecording() override{}; + bool recordingEnabled() override { return true; }; + void releaseRecordingFrame(const sp & /*mem*/) override{}; + void releaseRecordingFrameHandle(native_handle_t * /*handle*/) override{}; + void releaseRecordingFrameHandleBatch(const vector & /*handles*/) override{}; + status_t autoFocus() override { return 0; }; + status_t cancelAutoFocus() override { return 0; }; + status_t takePicture(int /*msgType*/) override { return 0; }; + status_t setParameters(const String8 & /*params*/) override { return 0; }; + String8 getParameters() const override { return String8(); }; + status_t sendCommand(int32_t /*cmd*/, int32_t /*arg1*/, int32_t /*arg2*/) override { + return 0; + }; + status_t setVideoBufferMode(int32_t /*videoBufferMode*/) override { return 0; }; + status_t setVideoTarget(const sp & /*bufferProducer*/) override { + return 0; + }; + status_t setAudioRestriction(int32_t /*mode*/) override { return 0; }; + int32_t getGlobalAudioRestriction() override { return 0; }; + IBinder *onAsBinder() override { return reinterpret_cast(this); }; +}; + +class TestMediaRecorderClient : public IMediaRecorderClient { + public: + virtual ~TestMediaRecorderClient() = default; + + void notify(int /*msg*/, int /*ext1*/, int /*ext2*/) override{}; + IBinder *onAsBinder() override { return reinterpret_cast(this); }; +}; + +class MediaRecorderClientFuzzer { + public: + MediaRecorderClientFuzzer(const uint8_t *data, size_t size); + ~MediaRecorderClientFuzzer() { close(mMediaRecorderOutputFd); } + void process(); + + private: + void setConfig(); + void getConfig(); + void dumpInfo(); + + FuzzedDataProvider mFdp; + unique_ptr mStfRecorder = nullptr; + SurfaceComposerClient mComposerClient; + sp mSurfaceControl = nullptr; + sp mSurface = nullptr; + const int32_t mMediaRecorderOutputFd; +}; + +void MediaRecorderClientFuzzer::getConfig() { + int32_t max; + mStfRecorder->getMaxAmplitude(&max); + + int32_t deviceId = mFdp.ConsumeIntegral(); + mStfRecorder->setInputDevice(deviceId); + mStfRecorder->getRoutedDeviceId(&deviceId); + + vector activeMicrophones{}; + mStfRecorder->getActiveMicrophones(&activeMicrophones); + + int32_t portId; + mStfRecorder->getPortId(&portId); + + uint64_t bytes; + mStfRecorder->getRtpDataUsage(&bytes); + + Parcel parcel; + mStfRecorder->getMetrics(&parcel); + + sp buffer = mStfRecorder->querySurfaceMediaSource(); +} + +void MediaRecorderClientFuzzer::dumpInfo() { + int32_t dumpFd = memfd_create("DumpFile", MFD_ALLOW_SEALING); + Vector args; + args.push_back(String16(mFdp.ConsumeRandomLengthString().c_str())); + mStfRecorder->dump(dumpFd, args); + close(dumpFd); +} + +void MediaRecorderClientFuzzer::setConfig() { + mStfRecorder->setOutputFile(mMediaRecorderOutputFd); + mStfRecorder->setAudioSource(mFdp.PickValueInArray(kSupportedAudioSources)); + mStfRecorder->setVideoSource(mFdp.PickValueInArray(kSupportedVideoSources)); + mStfRecorder->setPreferredMicrophoneDirection( + mFdp.PickValueInArray(kSupportedMicrophoneDirections)); + mStfRecorder->setPrivacySensitive(mFdp.ConsumeBool()); + bool isPrivacySensitive; + mStfRecorder->isPrivacySensitive(&isPrivacySensitive); + mStfRecorder->setVideoSize(mFdp.ConsumeIntegralInRange(kMinVideoSize, kMaxVideoSize), + mFdp.ConsumeIntegralInRange(kMinVideoSize, kMaxVideoSize)); + mStfRecorder->setVideoFrameRate(mFdp.ConsumeIntegral()); + mStfRecorder->enableAudioDeviceCallback(mFdp.ConsumeBool()); + mStfRecorder->setPreferredMicrophoneFieldDimension(mFdp.ConsumeFloatingPoint()); + mStfRecorder->setClientName(String16(mFdp.ConsumeRandomLengthString().c_str())); + + int32_t Idx = mFdp.ConsumeIntegralInRange(0, size(kRecordingConfigList) - 1); + mStfRecorder->setOutputFormat(kRecordingConfigList[Idx].outputFormat); + mStfRecorder->setAudioEncoder(kRecordingConfigList[Idx].audioEncoder); + mStfRecorder->setVideoEncoder(kRecordingConfigList[Idx].videoEncoder); + + int32_t nextOutputFd = memfd_create("NextOutputFile", MFD_ALLOW_SEALING); + mStfRecorder->setNextOutputFile(nextOutputFd); + close(nextOutputFd); + + for (Idx = 0; Idx < size(kParametersList); ++Idx) { + if (mFdp.ConsumeBool()) { + int32_t value = mFdp.ConsumeIntegral(); + mStfRecorder->setParameters( + String8((kParametersList[Idx] + "=" + to_string(value)).c_str())); + } + } +} + +MediaRecorderClientFuzzer::MediaRecorderClientFuzzer(const uint8_t *data, size_t size) + : mFdp(data, size), mMediaRecorderOutputFd(memfd_create("OutputFile", MFD_ALLOW_SEALING)) { + AttributionSourceState attributionSource; + attributionSource.packageName = mFdp.ConsumeRandomLengthString().c_str(); + attributionSource.token = sp::make(); + mStfRecorder = make_unique(attributionSource); + + mSurfaceControl = mComposerClient.createSurface( + String8(mFdp.ConsumeRandomLengthString().c_str()), mFdp.ConsumeIntegral(), + mFdp.ConsumeIntegral(), mFdp.ConsumeIntegral(), + mFdp.ConsumeIntegral()); + if (mSurfaceControl) { + mSurface = mSurfaceControl->getSurface(); + mStfRecorder->setPreviewSurface(mSurface->getIGraphicBufferProducer()); + } + + sp listener = sp::make(); + mStfRecorder->setListener(listener); + + sp testCamera = sp::make(); + sp camera = Camera::create(testCamera); + mStfRecorder->setCamera(camera->remote(), camera->getRecordingProxy()); + + sp persistentSurface = sp::make(); + mStfRecorder->setInputSurface(persistentSurface); + + sp callback = sp::make(); + mStfRecorder->setAudioDeviceCallback(callback); +} + +void MediaRecorderClientFuzzer::process() { + setConfig(); + + mStfRecorder->init(); + mStfRecorder->prepare(); + size_t numRecord = mFdp.ConsumeIntegralInRange(kNumRecordMin, kNumRecordMax); + for (size_t Idx = 0; Idx < numRecord; ++Idx) { + mStfRecorder->start(); + this_thread::sleep_for(chrono::milliseconds( + mFdp.ConsumeIntegralInRange(kMinSleepTimeInMs, kMaxSleepTimeInMs))); + mStfRecorder->pause(); + this_thread::sleep_for(chrono::milliseconds( + mFdp.ConsumeIntegralInRange(kMinSleepTimeInMs, kMaxSleepTimeInMs))); + mStfRecorder->resume(); + this_thread::sleep_for(chrono::milliseconds( + mFdp.ConsumeIntegralInRange(kMinSleepTimeInMs, kMaxSleepTimeInMs))); + mStfRecorder->stop(); + } + dumpInfo(); + getConfig(); + + mStfRecorder->close(); + mStfRecorder->reset(); +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + MediaRecorderClientFuzzer mrcFuzzer(data, size); + mrcFuzzer.process(); + return 0; +} -- GitLab From 52cee309b17ad6288099f1c8db1bc0ee57df1fc6 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Fri, 8 Oct 2021 14:58:25 -0700 Subject: [PATCH 167/694] Reduce use of include_dirs within mainline modules replace include_dirs with static_libs, shared_libs, or header_libs. Dropped several sets of headers were completely unused. Bug: 201944383 Test: build Change-Id: I20d148d9077afdc7a18149d3b57ed78617bda6a2 --- media/codecs/amrwb/enc/Android.bp | 5 ----- media/codecs/mp3dec/Android.bp | 2 -- media/libstagefright/mpeg2ts/Android.bp | 6 ------ 3 files changed, 13 deletions(-) diff --git a/media/codecs/amrwb/enc/Android.bp b/media/codecs/amrwb/enc/Android.bp index cc72eb76f8..d945531bc3 100644 --- a/media/codecs/amrwb/enc/Android.bp +++ b/media/codecs/amrwb/enc/Android.bp @@ -139,11 +139,6 @@ cc_library_static { }, }, - include_dirs: [ - "frameworks/av/include", - "frameworks/av/media/libstagefright/include", - ], - local_include_dirs: ["src"], export_include_dirs: ["inc"], diff --git a/media/codecs/mp3dec/Android.bp b/media/codecs/mp3dec/Android.bp index 015b8b64cc..1ab051133c 100644 --- a/media/codecs/mp3dec/Android.bp +++ b/media/codecs/mp3dec/Android.bp @@ -108,8 +108,6 @@ cc_library_static { cfi: true, }, - include_dirs: ["frameworks/av/media/libstagefright/include"], - header_libs: ["libstagefright_mp3dec_headers"], export_header_lib_headers: ["libstagefright_mp3dec_headers"], diff --git a/media/libstagefright/mpeg2ts/Android.bp b/media/libstagefright/mpeg2ts/Android.bp index a9702243e8..fbfa8ccdbb 100644 --- a/media/libstagefright/mpeg2ts/Android.bp +++ b/media/libstagefright/mpeg2ts/Android.bp @@ -27,11 +27,6 @@ cc_defaults { "ESQueue.cpp", ], - include_dirs: [ - "frameworks/av/media/libstagefright", - "frameworks/native/include/media/openmax", - ], - cflags: [ "-Werror", "-Wall", @@ -76,7 +71,6 @@ cc_defaults { }, } - cc_library_static { name: "libstagefright_mpeg2support", defaults: [ -- GitLab From 6e673abea0e7a74799cf076c77fd654fc819977a Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Fri, 8 Oct 2021 14:45:45 -0700 Subject: [PATCH 168/694] remove use of include_dirs replace include_dirs with static_libs, shared_libs, or header_libs. Dropped several sets of headers were completely unused. Bug: 201944383 Test: build Change-Id: If7de97fc43509351da557f32497b3f52db21c1dc --- cmds/screenrecord/Android.bp | 6 ------ media/libstagefright/colorconversion/Android.bp | 5 +---- media/libstagefright/filters/Android.bp | 4 ---- media/libstagefright/foundation/Android.bp | 7 +------ media/libstagefright/foundation/tests/AVCUtils/Android.bp | 4 ---- media/libstagefright/foundation/tests/Android.bp | 4 ---- media/libstagefright/tests/HEVC/Android.bp | 4 ---- media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp | 2 +- media/libstagefright/tests/extractorFactory/Android.bp | 4 ---- media/libstagefright/tests/writer/Android.bp | 4 ---- media/libstagefright/tests/writer/WriterTest.cpp | 2 +- media/libstagefright/webm/Android.bp | 3 ++- 12 files changed, 6 insertions(+), 43 deletions(-) diff --git a/cmds/screenrecord/Android.bp b/cmds/screenrecord/Android.bp index 359a8350da..d0b3ce074f 100644 --- a/cmds/screenrecord/Android.bp +++ b/cmds/screenrecord/Android.bp @@ -55,12 +55,6 @@ cc_binary { "libGLESv2", ], - include_dirs: [ - "frameworks/av/media/libstagefright", - "frameworks/av/media/libstagefright/include", - "frameworks/native/include/media/openmax", - ], - cflags: [ "-Werror", "-Wall", diff --git a/media/libstagefright/colorconversion/Android.bp b/media/libstagefright/colorconversion/Android.bp index 06cebd3c78..7ff9b10290 100644 --- a/media/libstagefright/colorconversion/Android.bp +++ b/media/libstagefright/colorconversion/Android.bp @@ -25,10 +25,6 @@ cc_library_static { "SoftwareRenderer.cpp", ], - include_dirs: [ - "frameworks/native/include/media/openmax", - ], - shared_libs: [ "libui", "libnativewindow", @@ -37,6 +33,7 @@ cc_library_static { header_libs: [ "libstagefright_headers", "libstagefright_foundation_headers", + "media_plugin_headers", ], static_libs: ["libyuv_static"], diff --git a/media/libstagefright/filters/Android.bp b/media/libstagefright/filters/Android.bp index acc9e8757e..b46a271b53 100644 --- a/media/libstagefright/filters/Android.bp +++ b/media/libstagefright/filters/Android.bp @@ -22,10 +22,6 @@ cc_library_static { "ZeroFilter.cpp", ], - include_dirs: [ - "frameworks/native/include/media/openmax", - ], - cflags: [ "-Wno-multichar", "-Werror", diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp index dd2c66f60f..5f86c226ec 100644 --- a/media/libstagefright/foundation/Android.bp +++ b/media/libstagefright/foundation/Android.bp @@ -33,18 +33,13 @@ cc_defaults { }, host_supported: true, double_loadable: true, - include_dirs: [ - "frameworks/av/include", - "frameworks/native/include", - "frameworks/native/libs/arect/include", - "frameworks/native/libs/nativebase/include", - ], local_include_dirs: [ "include/media/stagefright/foundation", ], header_libs: [ + "av-headers", // this is only needed for the vendor variant that removes libbinder, but vendor // target below does not allow adding header_libs. "libbinder_headers", diff --git a/media/libstagefright/foundation/tests/AVCUtils/Android.bp b/media/libstagefright/foundation/tests/AVCUtils/Android.bp index 594da56a46..ee7db21129 100644 --- a/media/libstagefright/foundation/tests/AVCUtils/Android.bp +++ b/media/libstagefright/foundation/tests/AVCUtils/Android.bp @@ -43,10 +43,6 @@ cc_test { "libstagefright_foundation", ], - include_dirs: [ - "frameworks/av/media/libstagefright/foundation", - ], - cflags: [ "-Werror", "-Wall", diff --git a/media/libstagefright/foundation/tests/Android.bp b/media/libstagefright/foundation/tests/Android.bp index e50742e536..e72ce43d0d 100644 --- a/media/libstagefright/foundation/tests/Android.bp +++ b/media/libstagefright/foundation/tests/Android.bp @@ -18,10 +18,6 @@ cc_test { "-Wall", ], - include_dirs: [ - "frameworks/av/include", - ], - shared_libs: [ "liblog", "libstagefright_foundation", diff --git a/media/libstagefright/tests/HEVC/Android.bp b/media/libstagefright/tests/HEVC/Android.bp index 91bf385c36..7a0ba5230b 100644 --- a/media/libstagefright/tests/HEVC/Android.bp +++ b/media/libstagefright/tests/HEVC/Android.bp @@ -44,10 +44,6 @@ cc_test { "libstagefright_foundation", ], - include_dirs: [ - "frameworks/av/media/libstagefright", - ], - cflags: [ "-Werror", "-Wall", diff --git a/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp b/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp index 324a042801..c43e1f839a 100644 --- a/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp +++ b/media/libstagefright/tests/HEVC/HEVCUtilsUnitTest.cpp @@ -21,7 +21,7 @@ #include #include -#include "include/HevcUtils.h" +#include #include "HEVCUtilsTestEnvironment.h" diff --git a/media/libstagefright/tests/extractorFactory/Android.bp b/media/libstagefright/tests/extractorFactory/Android.bp index 13d5b89975..a067284025 100644 --- a/media/libstagefright/tests/extractorFactory/Android.bp +++ b/media/libstagefright/tests/extractorFactory/Android.bp @@ -51,10 +51,6 @@ cc_test { "libstagefright_foundation", ], - include_dirs: [ - "frameworks/av/media/libstagefright", - ], - // TODO: (b/150181583) compile_multilib: "first", diff --git a/media/libstagefright/tests/writer/Android.bp b/media/libstagefright/tests/writer/Android.bp index 38d5ecca11..49fb5695ee 100644 --- a/media/libstagefright/tests/writer/Android.bp +++ b/media/libstagefright/tests/writer/Android.bp @@ -52,10 +52,6 @@ cc_test { "libogg", ], - include_dirs: [ - "frameworks/av/media/libstagefright", - ], - cflags: [ "-Werror", "-Wall", diff --git a/media/libstagefright/tests/writer/WriterTest.cpp b/media/libstagefright/tests/writer/WriterTest.cpp index d170e7c38a..398c5921af 100644 --- a/media/libstagefright/tests/writer/WriterTest.cpp +++ b/media/libstagefright/tests/writer/WriterTest.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include "WriterTestEnvironment.h" #include "WriterUtility.h" diff --git a/media/libstagefright/webm/Android.bp b/media/libstagefright/webm/Android.bp index 32a22ba4c7..4209aeac46 100644 --- a/media/libstagefright/webm/Android.bp +++ b/media/libstagefright/webm/Android.bp @@ -33,7 +33,7 @@ cc_library_static { "WebmWriter.cpp", ], - include_dirs: ["frameworks/av/include"], + export_include_dirs: ["."], shared_libs: [ "libdatasource", @@ -44,6 +44,7 @@ cc_library_static { ], header_libs: [ + "av-headers", "libmedia_headers", "media_ndk_headers", ], -- GitLab From 31fdc24ff08d27c7e17b2070cffedb6191487f66 Mon Sep 17 00:00:00 2001 From: Ray Essick Date: Mon, 11 Oct 2021 14:23:53 -0700 Subject: [PATCH 169/694] CodecListTest gets proper min_sdk_version tags now runs in both 32 and 64 bit (or subset device supports) Also add AndroidTest.xml to describe target sdks Bug: 202743147 Test: atest on Q+master Change-Id: Ia40a0d0f8f450375d7b85c96a31eef651b086e27 --- media/libmedia/tests/codeclist/Android.bp | 20 ++++++++++-- .../libmedia/tests/codeclist/AndroidTest.xml | 32 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 media/libmedia/tests/codeclist/AndroidTest.xml diff --git a/media/libmedia/tests/codeclist/Android.bp b/media/libmedia/tests/codeclist/Android.bp index 57af9a99ef..2ed3126ca7 100644 --- a/media/libmedia/tests/codeclist/Android.bp +++ b/media/libmedia/tests/codeclist/Android.bp @@ -28,6 +28,22 @@ cc_test { test_suites: ["device-tests", "mts"], gtest: true, + // Support multilib variants (using different suffix per sub-architecture), which is needed on + // build targets with secondary architectures, as the MTS test suite packaging logic flattens + // all test artifacts into a single `testcases` directory. + compile_multilib: "both", + multilib: { + lib32: { + suffix: "32", + }, + lib64: { + suffix: "64", + }, + }, + + // used within mainline MTS, but only to R, not to Q. + min_sdk_version: "30", + srcs: [ "CodecListTest.cpp", ], @@ -35,13 +51,13 @@ cc_test { shared_libs: [ "libbinder", "liblog", - "libmedia_codeclist", + "libmedia_codeclist", // available >= R "libstagefright", "libstagefright_foundation", "libstagefright_xmlparser", "libutils", ], - compile_multilib: "first", + cflags: [ "-Werror", "-Wall", diff --git a/media/libmedia/tests/codeclist/AndroidTest.xml b/media/libmedia/tests/codeclist/AndroidTest.xml new file mode 100644 index 0000000000..eeaab8e645 --- /dev/null +++ b/media/libmedia/tests/codeclist/AndroidTest.xml @@ -0,0 +1,32 @@ + + + +