connect mediametrics service to statsd

take the collected media.metrics (as they arrive) and push a copy over
to statsd, the statistics logging subsystem.
gather data, wrap in protobufs apppropriately, and submit it to statsd.

Bug: 118782504
Test: statsd's test_drive app
Change-Id: Ieb82c43633851075e9eaf65d2a95c8cba87441ea
diff --git a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
index 06e68a9..07a5a43 100644
--- a/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
+++ b/services/audiopolicy/service/AudioPolicyInterfaceImpl.cpp
@@ -511,6 +511,7 @@
     }
 
     // including successes gets very verbose
+    // but once we cut over to westworld, log them all.
     if (status != NO_ERROR) {
 
         static constexpr char kAudioPolicy[] = "audiopolicy";
@@ -571,6 +572,9 @@
             delete item;
             item = NULL;
         }
+    }
+
+    if (status != NO_ERROR) {
         client->active = false;
         client->startTimeNs = 0;
         updateUidStates_l();
diff --git a/services/mediaanalytics/Android.bp b/services/mediaanalytics/Android.bp
index c93c120..72f4b52 100644
--- a/services/mediaanalytics/Android.bp
+++ b/services/mediaanalytics/Android.bp
@@ -7,8 +7,22 @@
     srcs: [
         "main_mediametrics.cpp",
         "MediaAnalyticsService.cpp",
+        "iface_statsd.cpp",
+        "statsd_audiopolicy.cpp",
+        "statsd_audiorecord.cpp",
+        "statsd_audiothread.cpp",
+        "statsd_audiotrack.cpp",
+        "statsd_codec.cpp",
+        "statsd_drm.cpp",
+        "statsd_extractor.cpp",
+        "statsd_nuplayer.cpp",
+        "statsd_recorder.cpp",
     ],
 
+    proto: {
+        type: "lite",
+    },
+
     shared_libs: [
         "libcutils",
         "liblog",
@@ -21,10 +35,15 @@
         "libmediautils",
         "libmediametrics",
         "libstagefright_foundation",
+        "libstatslog",
         "libutils",
+        "libprotobuf-cpp-lite",
     ],
 
-    static_libs: ["libregistermsext"],
+    static_libs: [
+        "libplatformprotos",
+        "libregistermsext",
+    ],
 
     include_dirs: [
         "frameworks/av/media/libstagefright/include",
diff --git a/services/mediaanalytics/MediaAnalyticsService.cpp b/services/mediaanalytics/MediaAnalyticsService.cpp
index 06baac9..3626ad1 100644
--- a/services/mediaanalytics/MediaAnalyticsService.cpp
+++ b/services/mediaanalytics/MediaAnalyticsService.cpp
@@ -210,21 +210,24 @@
 
     // XXX: if we have a sessionid in the new record, look to make
     // sure it doesn't appear in the finalized list.
-    // XXX: this is for security / DOS prevention.
-    // may also require that we persist the unique sessionIDs
-    // across boots [instead of within a single boot]
 
     if (item->count() == 0) {
-        // drop empty records
+        ALOGV("dropping empty record...");
         delete item;
         item = NULL;
         return MediaAnalyticsItem::SessionIDInvalid;
     }
 
     // save the new record
+    //
+    // send a copy to statsd
+    dump2Statsd(item);
+
+    // and keep our copy for dumpsys
     MediaAnalyticsItem::SessionID_t id = item->getSessionID();
     saveItem(item);
     mItemsFinalized++;
+
     return id;
 }
 
diff --git a/services/mediaanalytics/MediaAnalyticsService.h b/services/mediaanalytics/MediaAnalyticsService.h
index 632c692..6c9cbaa 100644
--- a/services/mediaanalytics/MediaAnalyticsService.h
+++ b/services/mediaanalytics/MediaAnalyticsService.h
@@ -112,6 +112,9 @@
 
 };
 
+// hook to send things off to the statsd subsystem
+extern bool dump2Statsd(MediaAnalyticsItem *item);
+
 // ----------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/services/mediaanalytics/iface_statsd.cpp b/services/mediaanalytics/iface_statsd.cpp
new file mode 100644
index 0000000..6845f06
--- /dev/null
+++ b/services/mediaanalytics/iface_statsd.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2019 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 "iface_statsd"
+#include <utils/Log.h>
+
+#include <stdint.h>
+#include <inttypes.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <dirent.h>
+#include <pthread.h>
+#include <unistd.h>
+
+#include <string.h>
+#include <pwd.h>
+
+#include "MediaAnalyticsService.h"
+#include "iface_statsd.h"
+
+#include <statslog.h>
+
+namespace android {
+
+// set of routines that crack a MediaAnalyticsItem
+// and send it off to statsd with the appropriate hooks
+//
+// each MediaAnalyticsItem type (extractor, codec, nuplayer, etc)
+// has its own routine to handle this.
+//
+
+bool enabled_statsd = true;
+
+struct statsd_hooks {
+    const char *key;
+    bool (*handler)(MediaAnalyticsItem *);
+};
+
+// keep this sorted, so we can do binary searches
+struct statsd_hooks  statsd_handlers[] =
+{
+    { "audiopolicy", statsd_audiopolicy },
+    { "audiorecord", statsd_audiorecord },
+    { "audiothread", statsd_audiothread },
+    { "audiotrack", statsd_audiotrack },
+    { "codec", statsd_codec},
+    { "drm.vendor.Google.WidevineCDM", statsd_widevineCDM },
+    { "extractor", statsd_extractor },
+    { "mediadrm", statsd_mediadrm },
+    { "nuplayer", statsd_nuplayer },
+    { "nuplayer2", statsd_nuplayer },
+    { "recorder", statsd_recorder },
+};
+
+
+// give me a record, i'll look at the type and upload appropriately
+bool dump2Statsd(MediaAnalyticsItem *item) {
+    if (item == NULL) return false;
+
+    // get the key
+    std::string key = item->getKey();
+
+    if (!enabled_statsd) {
+        ALOGV("statsd logging disabled for record key=%s", key.c_str());
+        return false;
+    }
+
+    int i;
+    for(i = 0;i < sizeof(statsd_handlers) / sizeof(statsd_handlers[0]) ; i++) {
+        if (key == statsd_handlers[i].key) {
+            return (*statsd_handlers[i].handler)(item);
+        }
+    }
+    return false;
+}
+
+} // namespace android
diff --git a/services/mediaanalytics/iface_statsd.h b/services/mediaanalytics/iface_statsd.h
new file mode 100644
index 0000000..f85d303
--- /dev/null
+++ b/services/mediaanalytics/iface_statsd.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+namespace android {
+
+extern bool enabled_statsd;
+
+// component specific dumpers
+extern bool statsd_audiopolicy(MediaAnalyticsItem *);
+extern bool statsd_audiorecord(MediaAnalyticsItem *);
+extern bool statsd_audiothread(MediaAnalyticsItem *);
+extern bool statsd_audiotrack(MediaAnalyticsItem *);
+extern bool statsd_codec(MediaAnalyticsItem *);
+extern bool statsd_extractor(MediaAnalyticsItem *);
+extern bool statsd_nuplayer(MediaAnalyticsItem *);
+extern bool statsd_recorder(MediaAnalyticsItem *);
+
+extern bool statsd_mediadrm(MediaAnalyticsItem *);
+extern bool statsd_widevineCDM(MediaAnalyticsItem *);
+
+} // namespace android
diff --git a/services/mediaanalytics/statsd_audiopolicy.cpp b/services/mediaanalytics/statsd_audiopolicy.cpp
new file mode 100644
index 0000000..06c4dde
--- /dev/null
+++ b/services/mediaanalytics/statsd_audiopolicy.cpp
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2019 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 "statsd_audiopolicy"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_audiopolicy(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::AudioPolicyData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+    //int32 char kAudioPolicyStatus[] = "android.media.audiopolicy.status";
+    int32_t status = -1;
+    if (item->getInt32("android.media.audiopolicy.status", &status)) {
+        metrics_proto.set_status(status);
+    }
+    //string char kAudioPolicyRqstSrc[] = "android.media.audiopolicy.rqst.src";
+    char *rqst_src = NULL;
+    if (item->getCString("android.media.audiopolicy.rqst.src", &rqst_src)) {
+        metrics_proto.set_request_source(rqst_src);
+    }
+    //string char kAudioPolicyRqstPkg[] = "android.media.audiopolicy.rqst.pkg";
+    char *rqst_pkg = NULL;
+    if (item->getCString("android.media.audiopolicy.rqst.pkg", &rqst_pkg)) {
+        metrics_proto.set_request_package(rqst_pkg);
+    }
+    //int32 char kAudioPolicyRqstSession[] = "android.media.audiopolicy.rqst.session";
+    int32_t rqst_session = -1;
+    if (item->getInt32("android.media.audiopolicy.rqst.session", &rqst_session)) {
+        metrics_proto.set_request_session(rqst_session);
+    }
+    //string char kAudioPolicyRqstDevice[] = "android.media.audiopolicy.rqst.device";
+    char *rqst_device = NULL;
+    if (item->getCString("android.media.audiopolicy.rqst.device", &rqst_device)) {
+        metrics_proto.set_request_device(rqst_device);
+    }
+
+    //string char kAudioPolicyActiveSrc[] = "android.media.audiopolicy.active.src";
+    char *active_src = NULL;
+    if (item->getCString("android.media.audiopolicy.active.src", &active_src)) {
+        metrics_proto.set_active_source(active_src);
+    }
+    //string char kAudioPolicyActivePkg[] = "android.media.audiopolicy.active.pkg";
+    char *active_pkg = NULL;
+    if (item->getCString("android.media.audiopolicy.active.pkg", &active_pkg)) {
+        metrics_proto.set_active_package(active_pkg);
+    }
+    //int32 char kAudioPolicyActiveSession[] = "android.media.audiopolicy.active.session";
+    int32_t active_session = -1;
+    if (item->getInt32("android.media.audiopolicy.active.session", &active_session)) {
+        metrics_proto.set_active_session(active_session);
+    }
+    //string char kAudioPolicyActiveDevice[] = "android.media.audiopolicy.active.device";
+    char *active_device = NULL;
+    if (item->getCString("android.media.audiopolicy.active.device", &active_device)) {
+        metrics_proto.set_active_device(active_device);
+    }
+
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize audipolicy metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_AUDIOPOLICY_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(rqst_src);
+    free(rqst_pkg);
+    free(rqst_device);
+    free(active_src);
+    free(active_pkg);
+    free(active_device);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_audiorecord.cpp b/services/mediaanalytics/statsd_audiorecord.cpp
new file mode 100644
index 0000000..c9edb27
--- /dev/null
+++ b/services/mediaanalytics/statsd_audiorecord.cpp
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2019 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 "statsd_audiorecord"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_audiorecord(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::AudioRecordData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+    char *encoding = NULL;
+    if (item->getCString("android.media.audiorecord.encoding", &encoding)) {
+        metrics_proto.set_encoding(encoding);
+    }
+
+    char *source = NULL;
+    if (item->getCString("android.media.audiorecord.source", &source)) {
+        metrics_proto.set_source(source);
+    }
+
+    int32_t latency = -1;
+    if (item->getInt32("android.media.audiorecord.latency", &latency)) {
+        metrics_proto.set_latency(latency);
+    }
+
+    int32_t samplerate = -1;
+    if (item->getInt32("android.media.audiorecord.samplerate", &samplerate)) {
+        metrics_proto.set_samplerate(samplerate);
+    }
+
+    int32_t channels = -1;
+    if (item->getInt32("android.media.audiorecord.channels", &channels)) {
+        metrics_proto.set_channels(channels);
+    }
+
+    int64_t createdMs = -1;
+    if (item->getInt64("android.media.audiorecord.createdMs", &createdMs)) {
+        metrics_proto.set_created_millis(createdMs);
+    }
+
+    int64_t durationMs = -1;
+    if (item->getInt64("android.media.audiorecord.durationMs", &durationMs)) {
+        metrics_proto.set_duration_millis(durationMs);
+    }
+
+    int32_t count = -1;
+    if (item->getInt32("android.media.audiorecord.n", &count)) {
+        metrics_proto.set_count(count);
+    }
+
+    int32_t errcode = -1;
+    if (item->getInt32("android.media.audiorecord.errcode", &errcode)) {
+        metrics_proto.set_error_code(errcode);
+    } else if (item->getInt32("android.media.audiorecord.lastError.code", &errcode)) {
+        metrics_proto.set_error_code(errcode);
+    }
+
+    char *errfunc = NULL;
+    if (item->getCString("android.media.audiorecord.errfunc", &errfunc)) {
+        metrics_proto.set_error_function(errfunc);
+    } else if (item->getCString("android.media.audiorecord.lastError.at", &errfunc)) {
+        metrics_proto.set_error_function(errfunc);
+    }
+
+    // portId (int32)
+    int32_t port_id = -1;
+    if (item->getInt32("android.media.audiorecord.portId", &port_id)) {
+        metrics_proto.set_port_id(count);
+    }
+    // frameCount (int32)
+    int32_t frameCount = -1;
+    if (item->getInt32("android.media.audiorecord.frameCount", &frameCount)) {
+        metrics_proto.set_frame_count(frameCount);
+    }
+    // attributes (string)
+    char *attributes = NULL;
+    if (item->getCString("android.media.audiorecord.attributes", &attributes)) {
+        metrics_proto.set_attributes(attributes);
+    }
+    // channelMask (int64)
+    int64_t channelMask = -1;
+    if (item->getInt64("android.media.audiorecord.channelMask", &channelMask)) {
+        metrics_proto.set_channel_mask(channelMask);
+    }
+    // startcount (int64)
+    int64_t startcount = -1;
+    if (item->getInt64("android.media.audiorecord.startcount", &startcount)) {
+        metrics_proto.set_start_count(startcount);
+    }
+
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize audiorecord metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_AUDIORECORD_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(encoding);
+    free(source);
+    free(errfunc);
+    free(attributes);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_audiothread.cpp b/services/mediaanalytics/statsd_audiothread.cpp
new file mode 100644
index 0000000..8232424
--- /dev/null
+++ b/services/mediaanalytics/statsd_audiothread.cpp
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2019 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 "statsd_audiothread"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_audiothread(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::AudioThreadData metrics_proto;
+
+#define	MM_PREFIX "android.media.audiothread."
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+    char *mytype = NULL;
+    if (item->getCString(MM_PREFIX "type", &mytype)) {
+        metrics_proto.set_type(mytype);
+    }
+    int32_t framecount = -1;
+    if (item->getInt32(MM_PREFIX "framecount", &framecount)) {
+        metrics_proto.set_framecount(framecount);
+    }
+    int32_t samplerate = -1;
+    if (item->getInt32(MM_PREFIX "samplerate", &samplerate)) {
+        metrics_proto.set_samplerate(samplerate);
+    }
+    char *workhist = NULL;
+    if (item->getCString(MM_PREFIX "workMs.hist", &workhist)) {
+        metrics_proto.set_work_millis_hist(workhist);
+    }
+    char *latencyhist = NULL;
+    if (item->getCString(MM_PREFIX "latencyMs.hist", &latencyhist)) {
+        metrics_proto.set_latency_millis_hist(latencyhist);
+    }
+    char *warmuphist = NULL;
+    if (item->getCString(MM_PREFIX "warmupMs.hist", &warmuphist)) {
+        metrics_proto.set_warmup_millis_hist(warmuphist);
+    }
+    int64_t underruns = -1;
+    if (item->getInt64(MM_PREFIX "underruns", &underruns)) {
+        metrics_proto.set_underruns(underruns);
+    }
+    int64_t overruns = -1;
+    if (item->getInt64(MM_PREFIX "overruns", &overruns)) {
+        metrics_proto.set_overruns(overruns);
+    }
+    int64_t activeMs = -1;
+    if (item->getInt64(MM_PREFIX "activeMs", &activeMs)) {
+        metrics_proto.set_active_millis(activeMs);
+    }
+    int64_t durationMs = -1;
+    if (item->getInt64(MM_PREFIX "durationMs", &durationMs)) {
+        metrics_proto.set_duration_millis(durationMs);
+    }
+
+    // item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
+    int32_t id = -1;
+    if (item->getInt32(MM_PREFIX "id", &id)) {
+        metrics_proto.set_id(id);
+    }
+    // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
+    int32_t port_id = -1;
+    if (item->getInt32(MM_PREFIX "portId", &id)) {
+        metrics_proto.set_port_id(port_id);
+    }
+    // item->setCString(MM_PREFIX "type", threadTypeToString(mType));
+    char *type = NULL;
+    if (item->getCString(MM_PREFIX "type", &type)) {
+        metrics_proto.set_type(type);
+    }
+    // item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
+    int32_t sample_rate = -1;
+    if (item->getInt32(MM_PREFIX "sampleRate", &sample_rate)) {
+        metrics_proto.set_sample_rate(sample_rate);
+    }
+    // item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
+    int32_t channel_mask = -1;
+    if (item->getInt32(MM_PREFIX "channelMask", &channel_mask)) {
+        metrics_proto.set_channel_mask(channel_mask);
+    }
+    // item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
+    char *encoding = NULL;
+    if (item->getCString(MM_PREFIX "encoding", &encoding)) {
+        metrics_proto.set_encoding(encoding);
+    }
+    // item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
+    int32_t frame_count = -1;
+    if (item->getInt32(MM_PREFIX "frameCount", &frame_count)) {
+        metrics_proto.set_frame_count(frame_count);
+    }
+    // item->setCString(MM_PREFIX "outDevice", toString(mOutDevice).c_str());
+    char *outDevice = NULL;
+    if (item->getCString(MM_PREFIX "outDevice", &outDevice)) {
+        metrics_proto.set_output_device(outDevice);
+    }
+    // item->setCString(MM_PREFIX "inDevice", toString(mInDevice).c_str());
+    char *inDevice = NULL;
+    if (item->getCString(MM_PREFIX "inDevice", &inDevice)) {
+        metrics_proto.set_input_device(inDevice);
+    }
+    // item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
+    double iojitters_ms_mean = -1;
+    if (item->getDouble(MM_PREFIX "ioJitterMs.mean", &iojitters_ms_mean)) {
+        metrics_proto.set_io_jitter_mean_millis(iojitters_ms_mean);
+    }
+    // item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
+    double iojitters_ms_std = -1;
+    if (item->getDouble(MM_PREFIX "ioJitterMs.std", &iojitters_ms_std)) {
+        metrics_proto.set_io_jitter_stddev_millis(iojitters_ms_std);
+    }
+    // item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
+    double process_time_ms_mean = -1;
+    if (item->getDouble(MM_PREFIX "processTimeMs.mean", &process_time_ms_mean)) {
+        metrics_proto.set_process_time_mean_millis(process_time_ms_mean);
+    }
+    // item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
+    double process_time_ms_std = -1;
+    if (item->getDouble(MM_PREFIX "processTimeMs.std", &process_time_ms_std)) {
+        metrics_proto.set_process_time_stddev_millis(process_time_ms_std);
+    }
+    // item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
+    double timestamp_jitter_ms_mean = -1;
+    if (item->getDouble(MM_PREFIX "timestampJitterMs.mean", &timestamp_jitter_ms_mean)) {
+        metrics_proto.set_timestamp_jitter_mean_millis(timestamp_jitter_ms_mean);
+    }
+    // item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
+    double timestamp_jitter_ms_stddev = -1;
+    if (item->getDouble(MM_PREFIX "timestampJitterMs.std", &timestamp_jitter_ms_stddev)) {
+        metrics_proto.set_timestamp_jitter_stddev_millis(timestamp_jitter_ms_stddev);
+    }
+    // item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
+    double latency_ms_mean = -1;
+    if (item->getDouble(MM_PREFIX "latencyMs.mean", &latency_ms_mean)) {
+        metrics_proto.set_latency_mean_millis(latency_ms_mean);
+    }
+    // item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
+    double latency_ms_stddev = -1;
+    if (item->getDouble(MM_PREFIX "latencyMs.std", &latency_ms_stddev)) {
+        metrics_proto.set_latency_stddev_millis(latency_ms_stddev);
+    }
+
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize audiothread metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_AUDIOTHREAD_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(mytype);
+    free(workhist);
+    free(latencyhist);
+    free(warmuphist);
+    free(type);
+    free(encoding);
+    free(inDevice);
+    free(outDevice);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_audiotrack.cpp b/services/mediaanalytics/statsd_audiotrack.cpp
new file mode 100644
index 0000000..f250ced
--- /dev/null
+++ b/services/mediaanalytics/statsd_audiotrack.cpp
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2019 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 "statsd_audiotrack"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_audiotrack(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::AudioTrackData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+
+    // static constexpr char kAudioTrackStreamType[] = "android.media.audiotrack.streamtype";
+    // optional string streamType;
+    char *streamtype = NULL;
+    if (item->getCString("android.media.audiotrack.streamtype", &streamtype)) {
+        metrics_proto.set_stream_type(streamtype);
+    }
+
+    // static constexpr char kAudioTrackContentType[] = "android.media.audiotrack.type";
+    // optional string contentType;
+    char *contenttype = NULL;
+    if (item->getCString("android.media.audiotrack.type", &contenttype)) {
+        metrics_proto.set_content_type(contenttype);
+    }
+
+    // static constexpr char kAudioTrackUsage[] = "android.media.audiotrack.usage";
+    // optional string trackUsage;
+    char *trackusage = NULL;
+    if (item->getCString("android.media.audiotrack.usage", &trackusage)) {
+        metrics_proto.set_track_usage(trackusage);
+    }
+
+    // static constexpr char kAudioTrackSampleRate[] = "android.media.audiotrack.samplerate";
+    // optional int32 samplerate;
+    int32_t samplerate = -1;
+    if (item->getInt32("android.media.audiotrack.samplerate", &samplerate)) {
+        metrics_proto.set_sample_rate(samplerate);
+    }
+
+    // static constexpr char kAudioTrackChannelMask[] = "android.media.audiotrack.channelmask";
+    // optional int64 channelMask;
+    int64_t channelMask = -1;
+    if (item->getInt64("android.media.audiotrack.channelmask", &channelMask)) {
+        metrics_proto.set_channel_mask(channelMask);
+    }
+
+    // NB: These are not yet exposed as public Java API constants.
+    // static constexpr char kAudioTrackUnderrunFrames[] = "android.media.audiotrack.underrunframes";
+    // optional int32 underrunframes;
+    int32_t underrunframes = -1;
+    if (item->getInt32("android.media.audiotrack.underrunframes", &underrunframes)) {
+        metrics_proto.set_underrun_frames(underrunframes);
+    }
+
+    // static constexpr char kAudioTrackStartupGlitch[] = "android.media.audiotrack.glitch.startup";
+    // optional int32 startupglitch;
+    int32_t startupglitch = -1;
+    if (item->getInt32("android.media.audiotrack.glitch.startup", &startupglitch)) {
+        metrics_proto.set_startup_glitch(startupglitch);
+    }
+
+    // portId (int32)
+    int32_t port_id = -1;
+    if (item->getInt32("android.media.audiotrack.portId", &port_id)) {
+        metrics_proto.set_port_id(port_id);
+    }
+    // encoding (string)
+    char *encoding = NULL;
+    if (item->getCString("android.media.audiotrack.encoding", &encoding)) {
+        metrics_proto.set_encoding(encoding);
+    }
+    // frameCount (int32)
+    int32_t frame_count = -1;
+    if (item->getInt32("android.media.audiotrack.frameCount", &frame_count)) {
+        metrics_proto.set_frame_count(frame_count);
+    }
+    // attributes (string)
+    char *attributes = NULL;
+    if (item->getCString("android.media.audiotrack.attributes", &attributes)) {
+        metrics_proto.set_attributes(attributes);
+    }
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize audiotrack metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_AUDIOTRACK_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(streamtype);
+    free(contenttype);
+    free(trackusage);
+    free(encoding);
+    free(attributes);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_codec.cpp b/services/mediaanalytics/statsd_codec.cpp
new file mode 100644
index 0000000..dc8e4ef
--- /dev/null
+++ b/services/mediaanalytics/statsd_codec.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2019 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 "statsd_codec"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_codec(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::CodecData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+    // android.media.mediacodec.codec   string
+    char *codec = NULL;
+    if (item->getCString("android.media.mediacodec.codec", &codec)) {
+        metrics_proto.set_codec(codec);
+    }
+    // android.media.mediacodec.mime    string
+    char *mime = NULL;
+    if (item->getCString("android.media.mediacodec.mime", &mime)) {
+        metrics_proto.set_mime(mime);
+    }
+    // android.media.mediacodec.mode    string
+    char *mode = NULL;
+    if ( item->getCString("android.media.mediacodec.mode", &mode)) {
+        metrics_proto.set_mode(mode);
+    }
+    // android.media.mediacodec.encoder int32
+    int32_t encoder = -1;
+    if ( item->getInt32("android.media.mediacodec.encoder", &encoder)) {
+        metrics_proto.set_encoder(encoder);
+    }
+    // android.media.mediacodec.secure  int32
+    int32_t secure = -1;
+    if ( item->getInt32("android.media.mediacodec.secure", &secure)) {
+        metrics_proto.set_secure(secure);
+    }
+    // android.media.mediacodec.width   int32
+    int32_t width = -1;
+    if ( item->getInt32("android.media.mediacodec.width", &width)) {
+        metrics_proto.set_width(width);
+    }
+    // android.media.mediacodec.height  int32
+    int32_t height = -1;
+    if ( item->getInt32("android.media.mediacodec.height", &height)) {
+        metrics_proto.set_height(height);
+    }
+    // android.media.mediacodec.rotation-degrees        int32
+    int32_t rotation = -1;
+    if ( item->getInt32("android.media.mediacodec.rotation-degrees", &rotation)) {
+        metrics_proto.set_rotation(rotation);
+    }
+    // android.media.mediacodec.crypto  int32 (although missing if not needed
+    int32_t crypto = -1;
+    if ( item->getInt32("android.media.mediacodec.crypto", &crypto)) {
+        metrics_proto.set_crypto(crypto);
+    }
+    // android.media.mediacodec.profile int32
+    int32_t profile = -1;
+    if ( item->getInt32("android.media.mediacodec.profile", &profile)) {
+        metrics_proto.set_profile(profile);
+    }
+    // android.media.mediacodec.level   int32
+    int32_t level = -1;
+    if ( item->getInt32("android.media.mediacodec.level", &level)) {
+        metrics_proto.set_level(level);
+    }
+    // android.media.mediacodec.maxwidth        int32
+    int32_t maxwidth = -1;
+    if ( item->getInt32("android.media.mediacodec.maxwidth", &maxwidth)) {
+        metrics_proto.set_max_width(maxwidth);
+    }
+    // android.media.mediacodec.maxheight       int32
+    int32_t maxheight = -1;
+    if ( item->getInt32("android.media.mediacodec.maxheight", &maxheight)) {
+        metrics_proto.set_max_height(maxheight);
+    }
+    // android.media.mediacodec.errcode         int32
+    int32_t errcode = -1;
+    if ( item->getInt32("android.media.mediacodec.errcode", &errcode)) {
+        metrics_proto.set_error_code(errcode);
+    }
+    // android.media.mediacodec.errstate        string
+    char *errstate = NULL;
+    if ( item->getCString("android.media.mediacodec.errstate", &errstate)) {
+        metrics_proto.set_error_state(errstate);
+    }
+    // android.media.mediacodec.latency.max  int64
+    int64_t latency_max = -1;
+    if ( item->getInt64("android.media.mediacodec.latency.max", &latency_max)) {
+        metrics_proto.set_latency_max(latency_max);
+    }
+    // android.media.mediacodec.latency.min  int64
+    int64_t latency_min = -1;
+    if ( item->getInt64("android.media.mediacodec.latency.min", &latency_min)) {
+        metrics_proto.set_latency_min(latency_min);
+    }
+    // android.media.mediacodec.latency.avg  int64
+    int64_t latency_avg = -1;
+    if ( item->getInt64("android.media.mediacodec.latency.avg", &latency_avg)) {
+        metrics_proto.set_latency_avg(latency_avg);
+    }
+    // android.media.mediacodec.latency.n    int64
+    int64_t latency_count = -1;
+    if ( item->getInt64("android.media.mediacodec.latency.n", &latency_count)) {
+        metrics_proto.set_latency_count(latency_count);
+    }
+    // android.media.mediacodec.latency.unknown    int64
+    int64_t latency_unknown = -1;
+    if ( item->getInt64("android.media.mediacodec.latency.unknown", &latency_unknown)) {
+        metrics_proto.set_latency_unknown(latency_unknown);
+    }
+    // android.media.mediacodec.latency.hist    NOT EMITTED
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize codec metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_CODEC_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(codec);
+    free(mime);
+    free(mode);
+    free(errstate);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_drm.cpp b/services/mediaanalytics/statsd_drm.cpp
new file mode 100644
index 0000000..902483a
--- /dev/null
+++ b/services/mediaanalytics/statsd_drm.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2019 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 "statsd_drm"
+#include <utils/Log.h>
+
+#include <stdint.h>
+#include <inttypes.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <dirent.h>
+#include <pthread.h>
+#include <unistd.h>
+
+#include <string.h>
+#include <pwd.h>
+
+#include "MediaAnalyticsService.h"
+#include "iface_statsd.h"
+
+#include <statslog.h>
+
+namespace android {
+
+// mediadrm
+bool statsd_mediadrm(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+    char *vendor = NULL;
+    (void) item->getCString("vendor", &vendor);
+    char *description = NULL;
+    (void) item->getCString("description", &description);
+    char *serialized_metrics = NULL;
+    (void) item->getCString("serialized_metrics", &serialized_metrics);
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized(serialized_metrics ? serialized_metrics : NULL,
+                                                serialized_metrics ? strlen(serialized_metrics)
+                                                                   : 0);
+        android::util::stats_write(android::util::MEDIAMETRICS_MEDIADRM_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   vendor, description,
+                                   bf_serialized);
+    } else {
+        ALOGV("NOT sending: mediadrm private data (len=%zu)",
+              serialized_metrics ? strlen(serialized_metrics) : 0);
+    }
+
+    free(vendor);
+    free(description);
+    free(serialized_metrics);
+    return true;
+}
+
+// widevineCDM
+bool statsd_widevineCDM(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+    char *serialized_metrics = NULL;
+    (void) item->getCString("serialized_metrics", &serialized_metrics);
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized(serialized_metrics ? serialized_metrics : NULL,
+                                                serialized_metrics ? strlen(serialized_metrics)
+                                                                   : 0);
+        android::util::stats_write(android::util::MEDIAMETRICS_DRM_WIDEVINE_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+    } else {
+        ALOGV("NOT sending: widevine private data (len=%zu)",
+              serialized_metrics ? strlen(serialized_metrics) : 0);
+    }
+
+    free(serialized_metrics);
+    return true;
+}
+
+} // namespace android
diff --git a/services/mediaanalytics/statsd_extractor.cpp b/services/mediaanalytics/statsd_extractor.cpp
new file mode 100644
index 0000000..395c912
--- /dev/null
+++ b/services/mediaanalytics/statsd_extractor.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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 "statsd_extractor"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_extractor(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::ExtractorData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+
+    // android.media.mediaextractor.fmt         string
+    char *fmt = NULL;
+    if (item->getCString("android.media.mediaextractor.fmt", &fmt)) {
+        metrics_proto.set_format(fmt);
+    }
+    // android.media.mediaextractor.mime        string
+    char *mime = NULL;
+    if (item->getCString("android.media.mediaextractor.mime", &mime)) {
+        metrics_proto.set_mime(mime);
+    }
+    // android.media.mediaextractor.ntrk        int32
+    int32_t ntrk = -1;
+    if (item->getInt32("android.media.mediaextractor.ntrk", &ntrk)) {
+        metrics_proto.set_tracks(ntrk);
+    }
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize extractor metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_EXTRACTOR_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(fmt);
+    free(mime);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_nuplayer.cpp b/services/mediaanalytics/statsd_nuplayer.cpp
new file mode 100644
index 0000000..5ec118a
--- /dev/null
+++ b/services/mediaanalytics/statsd_nuplayer.cpp
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2019 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 "statsd_nuplayer"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+/*
+ *  handles nuplayer AND nuplayer2
+ *  checks for the union of what the two players generate
+ */
+bool statsd_nuplayer(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::NuPlayerData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+
+    // differentiate between nuplayer and nuplayer2
+    metrics_proto.set_whichplayer(item->getKey().c_str());
+
+    char *video_mime = NULL;
+    if (item->getCString("android.media.mediaplayer.video.mime", &video_mime)) {
+        metrics_proto.set_video_mime(video_mime);
+    }
+    char *video_codec = NULL;
+    if (item->getCString("android.media.mediaplayer.video.codec", &video_codec)) {
+        metrics_proto.set_video_codec(video_codec);
+    }
+
+    int32_t width = -1;
+    if (item->getInt32("android.media.mediaplayer.width", &width)) {
+        metrics_proto.set_width(width);
+    }
+    int32_t height = -1;
+    if (item->getInt32("android.media.mediaplayer.height", &height)) {
+        metrics_proto.set_height(height);
+    }
+
+    int64_t frames = -1;
+    if (item->getInt64("android.media.mediaplayer.frames", &frames)) {
+        metrics_proto.set_frames(frames);
+    }
+    int64_t frames_dropped = -1;
+    if (item->getInt64("android.media.mediaplayer.dropped", &frames_dropped)) {
+        metrics_proto.set_frames_dropped(frames_dropped);
+    }
+    int64_t frames_dropped_startup = -1;
+    if (item->getInt64("android.media.mediaplayer.startupdropped", &frames_dropped_startup)) {
+        metrics_proto.set_frames_dropped_startup(frames_dropped_startup);
+    }
+    double fps = -1.0;
+    if (item->getDouble("android.media.mediaplayer.fps", &fps)) {
+        metrics_proto.set_framerate(fps);
+    }
+
+    char *audio_mime = NULL;
+    if (item->getCString("android.media.mediaplayer.audio.mime", &audio_mime)) {
+        metrics_proto.set_audio_mime(audio_mime);
+    }
+    char *audio_codec = NULL;
+    if (item->getCString("android.media.mediaplayer.audio.codec", &audio_codec)) {
+        metrics_proto.set_audio_codec(audio_codec);
+    }
+
+    int64_t duration_ms = -1;
+    if (item->getInt64("android.media.mediaplayer.durationMs", &duration_ms)) {
+        metrics_proto.set_duration_millis(duration_ms);
+    }
+    int64_t playing_ms = -1;
+    if (item->getInt64("android.media.mediaplayer.playingMs", &playing_ms)) {
+        metrics_proto.set_playing_millis(playing_ms);
+    }
+
+    int32_t err = -1;
+    if (item->getInt32("android.media.mediaplayer.err", &err)) {
+        metrics_proto.set_error(err);
+    }
+    int32_t error_code = -1;
+    if (item->getInt32("android.media.mediaplayer.errcode", &error_code)) {
+        metrics_proto.set_error_code(error_code);
+    }
+    char *error_state = NULL;
+    if (item->getCString("android.media.mediaplayer.errstate", &error_state)) {
+        metrics_proto.set_error_state(error_state);
+    }
+
+    char *data_source_type = NULL;
+    if (item->getCString("android.media.mediaplayer.dataSource", &data_source_type)) {
+        metrics_proto.set_data_source_type(data_source_type);
+    }
+
+    int64_t rebufferingMs = -1;
+    if (item->getInt64("android.media.mediaplayer.rebufferingMs", &rebufferingMs)) {
+        metrics_proto.set_rebuffering_millis(rebufferingMs);
+    }
+    int32_t rebuffers = -1;
+    if (item->getInt32("android.media.mediaplayer.rebuffers", &rebuffers)) {
+        metrics_proto.set_rebuffers(rebuffers);
+    }
+    int32_t rebufferExit = -1;
+    if (item->getInt32("android.media.mediaplayer.rebufferExit", &rebufferExit)) {
+        metrics_proto.set_rebuffer_at_exit(rebufferExit);
+    }
+
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize nuplayer metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_NUPLAYER_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(video_mime);
+    free(video_codec);
+    free(audio_mime);
+    free(audio_codec);
+    free(error_state);
+    free(data_source_type);
+
+    return true;
+}
+
+};
diff --git a/services/mediaanalytics/statsd_recorder.cpp b/services/mediaanalytics/statsd_recorder.cpp
new file mode 100644
index 0000000..4d981b4
--- /dev/null
+++ b/services/mediaanalytics/statsd_recorder.cpp
@@ -0,0 +1,193 @@
+/*
+ * Copyright (C) 2019 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 "statsd_recorder"
+#include <utils/Log.h>
+
+#include <dirent.h>
+#include <inttypes.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <stdint.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <statslog.h>
+
+#include "MediaAnalyticsService.h"
+#include "frameworks/base/core/proto/android/stats/mediametrics/mediametrics.pb.h"
+#include "iface_statsd.h"
+
+namespace android {
+
+bool statsd_recorder(MediaAnalyticsItem *item)
+{
+    if (item == NULL) return false;
+
+    // these go into the statsd wrapper
+    nsecs_t timestamp = item->getTimestamp();
+    std::string pkgName = item->getPkgName();
+    int64_t pkgVersionCode = item->getPkgVersionCode();
+    int64_t mediaApexVersion = 0;
+
+
+    // the rest into our own proto
+    //
+    ::android::stats::mediametrics::RecorderData metrics_proto;
+
+    // flesh out the protobuf we'll hand off with our data
+    //
+
+    // string kRecorderAudioMime = "android.media.mediarecorder.audio.mime";
+    char *audio_mime = NULL;
+    if (item->getCString("android.media.mediarecorder.audio.mime", &audio_mime)) {
+        metrics_proto.set_audio_mime(audio_mime);
+    }
+    // string kRecorderVideoMime = "android.media.mediarecorder.video.mime";
+    char *video_mime = NULL;
+    if (item->getCString("android.media.mediarecorder.video.mime", &video_mime)) {
+        metrics_proto.set_video_mime(video_mime);
+    }
+    // int32 kRecorderVideoProfile = "android.media.mediarecorder.video-encoder-profile";
+    int32_t videoProfile = -1;
+    if (item->getInt32("android.media.mediarecorder.video-encoder-profile", &videoProfile)) {
+        metrics_proto.set_video_profile(videoProfile);
+    }
+    // int32 kRecorderVideoLevel = "android.media.mediarecorder.video-encoder-level";
+    int32_t videoLevel = -1;
+    if (item->getInt32("android.media.mediarecorder.video-encoder-level", &videoLevel)) {
+        metrics_proto.set_video_level(videoLevel);
+    }
+    // int32 kRecorderWidth = "android.media.mediarecorder.width";
+    int32_t width = -1;
+    if (item->getInt32("android.media.mediarecorder.width", &width)) {
+        metrics_proto.set_width(width);
+    }
+    // int32 kRecorderHeight = "android.media.mediarecorder.height";
+    int32_t height = -1;
+    if (item->getInt32("android.media.mediarecorder.height", &height)) {
+        metrics_proto.set_height(height);
+    }
+    // int32 kRecorderRotation = "android.media.mediarecorder.rotation";
+    int32_t rotation = -1;                      // default to 0?
+    if (item->getInt32("android.media.mediarecorder.rotation", &rotation)) {
+        metrics_proto.set_rotation(rotation);
+    }
+    // int32 kRecorderFrameRate = "android.media.mediarecorder.frame-rate";
+    int32_t framerate = -1;
+    if (item->getInt32("android.media.mediarecorder.frame-rate", &framerate)) {
+        metrics_proto.set_framerate(framerate);
+    }
+
+    // int32 kRecorderCaptureFps = "android.media.mediarecorder.capture-fps";
+    int32_t captureFps = -1;
+    if (item->getInt32("android.media.mediarecorder.capture-fps", &captureFps)) {
+        metrics_proto.set_capture_fps(captureFps);
+    }
+    // double kRecorderCaptureFpsEnable = "android.media.mediarecorder.capture-fpsenable";
+    double captureFpsEnable = -1;
+    if (item->getDouble("android.media.mediarecorder.capture-fpsenable", &captureFpsEnable)) {
+        metrics_proto.set_capture_fps_enable(captureFpsEnable);
+    }
+
+    // int64 kRecorderDurationMs = "android.media.mediarecorder.durationMs";
+    int64_t durationMs = -1;
+    if (item->getInt64("android.media.mediarecorder.durationMs", &durationMs)) {
+        metrics_proto.set_duration_millis(durationMs);
+    }
+    // int64 kRecorderPaused = "android.media.mediarecorder.pausedMs";
+    int64_t pausedMs = -1;
+    if (item->getInt64("android.media.mediarecorder.pausedMs", &pausedMs)) {
+        metrics_proto.set_paused_millis(pausedMs);
+    }
+    // int32 kRecorderNumPauses = "android.media.mediarecorder.NPauses";
+    int32_t pausedCount = -1;
+    if (item->getInt32("android.media.mediarecorder.NPauses", &pausedCount)) {
+        metrics_proto.set_paused_count(pausedCount);
+    }
+
+    // int32 kRecorderAudioBitrate = "android.media.mediarecorder.audio-bitrate";
+    int32_t audioBitrate = -1;
+    if (item->getInt32("android.media.mediarecorder.audio-bitrate", &audioBitrate)) {
+        metrics_proto.set_audio_bitrate(audioBitrate);
+    }
+    // int32 kRecorderAudioChannels = "android.media.mediarecorder.audio-channels";
+    int32_t audioChannels = -1;
+    if (item->getInt32("android.media.mediarecorder.audio-channels", &audioChannels)) {
+        metrics_proto.set_audio_channels(audioChannels);
+    }
+    // int32 kRecorderAudioSampleRate = "android.media.mediarecorder.audio-samplerate";
+    int32_t audioSampleRate = -1;
+    if (item->getInt32("android.media.mediarecorder.audio-samplerate", &audioSampleRate)) {
+        metrics_proto.set_audio_samplerate(audioSampleRate);
+    }
+
+    // int32 kRecorderMovieTimescale = "android.media.mediarecorder.movie-timescale";
+    int32_t movieTimescale = -1;
+    if (item->getInt32("android.media.mediarecorder.movie-timescale", &movieTimescale)) {
+        metrics_proto.set_movie_timescale(movieTimescale);
+    }
+    // int32 kRecorderAudioTimescale = "android.media.mediarecorder.audio-timescale";
+    int32_t audioTimescale = -1;
+    if (item->getInt32("android.media.mediarecorder.audio-timescale", &audioTimescale)) {
+        metrics_proto.set_audio_timescale(audioTimescale);
+    }
+    // int32 kRecorderVideoTimescale = "android.media.mediarecorder.video-timescale";
+    int32_t videoTimescale = -1;
+    if (item->getInt32("android.media.mediarecorder.video-timescale", &videoTimescale)) {
+        metrics_proto.set_video_timescale(videoTimescale);
+    }
+
+    // int32 kRecorderVideoBitrate = "android.media.mediarecorder.video-bitrate";
+    int32_t videoBitRate = -1;
+    if (item->getInt32("android.media.mediarecorder.video-bitrate", &videoBitRate)) {
+        metrics_proto.set_video_bitrate(videoBitRate);
+    }
+    // int32 kRecorderVideoIframeInterval = "android.media.mediarecorder.video-iframe-interval";
+    int32_t iFrameInterval = -1;
+    if (item->getInt32("android.media.mediarecorder.video-iframe-interval", &iFrameInterval)) {
+        metrics_proto.set_iframe_interval(iFrameInterval);
+    }
+
+    std::string serialized;
+    if (!metrics_proto.SerializeToString(&serialized)) {
+        ALOGE("Failed to serialize recorder metrics");
+        return false;
+    }
+
+    if (enabled_statsd) {
+        android::util::BytesField bf_serialized( serialized.c_str(), serialized.size());
+        (void)android::util::stats_write(android::util::MEDIAMETRICS_RECORDER_REPORTED,
+                                   timestamp, pkgName.c_str(), pkgVersionCode,
+                                   mediaApexVersion,
+                                   bf_serialized);
+
+    } else {
+        ALOGV("NOT sending: private data (len=%zu)", strlen(serialized.c_str()));
+    }
+
+    // must free the strings that we were given
+    free(audio_mime);
+    free(video_mime);
+
+    return true;
+}
+
+};