Prevent audioflinger battery notes leak

Ensure battery notes from audioflinger are encapsulated in an RAII
object so noteStart is always properly matched.

Remove uid refcounting in audioserver, since it already exists in
the battery notifier utility class, and is error-prone. As a byproduct,
notes occur during track transitions rather than in the threadloop,
which happens to avoid problematic blocking.

Bump refcount mismatch logging to error.

Bug: 259449389
Test: Manual verification of battery stats notes w/ multiple refs
Change-Id: Ifc931a9ac46f37d662e42dd4696f0a62eec22c25
diff --git a/services/audioflinger/TrackBase.h b/services/audioflinger/TrackBase.h
index 254fb91..5adeb1f 100644
--- a/services/audioflinger/TrackBase.h
+++ b/services/audioflinger/TrackBase.h
@@ -270,6 +270,23 @@
     /** Set that a metadata has changed and needs to be notified to backend. Thread safe. */
     void setMetadataHasChanged() { mChangeNotified.clear(); }
 
+    /**
+     * Called when a track moves to active state to record its contribution to battery usage.
+     * Track state transitions should eventually be handled within the track class.
+     */
+    void beginBatteryAttribution() {
+        mBatteryStatsHolder.emplace(uid());
+    }
+
+    /**
+     * Called when a track moves out of the active state to record its contribution
+     * to battery usage.
+     */
+    void endBatteryAttribution() {
+        mBatteryStatsHolder.reset();
+    }
+
+
 protected:
     DISALLOW_COPY_AND_ASSIGN(TrackBase);
 
@@ -412,6 +429,8 @@
 
     // If the last track change was notified to the client with readAndClearHasChanged
     std::atomic_flag    mChangeNotified = ATOMIC_FLAG_INIT;
+    // RAII object for battery stats book-keeping
+    std::optional<mediautils::BatteryStatsAudioHandle> mBatteryStatsHolder;
 };
 
 // PatchProxyBufferProvider interface is implemented by PatchTrack and PatchRecord.