1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.media;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.os.Bundle;
22 
23 import java.nio.ByteBuffer;
24 import java.nio.ByteOrder;
25 import java.nio.charset.Charset;
26 import java.nio.charset.StandardCharsets;
27 import java.util.Objects;
28 
29 /**
30  * MediaMetrics is the Java interface to the MediaMetrics service.
31  *
32  * This is used to collect media statistics by the framework.
33  * It is not intended for direct application use.
34  *
35  * @hide
36  */
37 public class MediaMetrics {
38     public static final String TAG = "MediaMetrics";
39 
40     public static final String SEPARATOR = ".";
41 
42     /**
43      * A list of established MediaMetrics names that can be used for Items.
44      */
45     public static class Name {
46         public static final String AUDIO = "audio";
47         public static final String AUDIO_BLUETOOTH = AUDIO + SEPARATOR + "bluetooth";
48         public static final String AUDIO_DEVICE = AUDIO + SEPARATOR + "device";
49         public static final String AUDIO_FOCUS = AUDIO + SEPARATOR + "focus";
50         public static final String AUDIO_FORCE_USE = AUDIO + SEPARATOR + "forceUse";
51         public static final String AUDIO_MIC = AUDIO + SEPARATOR + "mic";
52         public static final String AUDIO_SERVICE = AUDIO + SEPARATOR + "service";
53         public static final String AUDIO_VOLUME = AUDIO + SEPARATOR + "volume";
54         public static final String AUDIO_VOLUME_EVENT = AUDIO_VOLUME + SEPARATOR + "event";
55         public static final String AUDIO_MODE = AUDIO + SEPARATOR + "mode";
56         public static final String METRICS_MANAGER = "metrics" + SEPARATOR + "manager";
57     }
58 
59     /**
60      * A list of established string values.
61      */
62     public static class Value {
63         public static final String CONNECT = "connect";
64         public static final String CONNECTED = "connected";
65         public static final String DISCONNECT = "disconnect";
66         public static final String DISCONNECTED = "disconnected";
67         public static final String DOWN = "down";
68         public static final String MUTE = "mute";
69         public static final String NO = "no";
70         public static final String OFF = "off";
71         public static final String ON = "on";
72         public static final String UNMUTE = "unmute";
73         public static final String UP = "up";
74         public static final String YES = "yes";
75     }
76 
77     /**
78      * A list of standard property keys for consistent use and type.
79      */
80     public static class Property {
81         // A use for Bluetooth or USB device addresses
82         public static final Key<String> ADDRESS = createKey("address", String.class);
83         // A string representing the Audio Attributes
84         public static final Key<String> ATTRIBUTES = createKey("attributes", String.class);
85 
86         // The calling package responsible for the state change
87         public static final Key<String> CALLING_PACKAGE =
88                 createKey("callingPackage", String.class);
89 
90         // The client name
91         public static final Key<String> CLIENT_NAME = createKey("clientName", String.class);
92 
93         // The device type
94         public static final Key<Integer> DELAY_MS = createKey("delayMs", Integer.class);
95 
96         // The device type
97         public static final Key<String> DEVICE = createKey("device", String.class);
98 
99         // For volume changes, up or down
100         public static final Key<String> DIRECTION = createKey("direction", String.class);
101 
102         // A reason for early return or error
103         public static final Key<String> EARLY_RETURN =
104                 createKey("earlyReturn", String.class);
105         // ENCODING_ ... string to match AudioFormat encoding
106         public static final Key<String> ENCODING = createKey("encoding", String.class);
107 
108         public static final Key<String> EVENT = createKey("event#", String.class);
109 
110         // event generated is external (yes, no)
111         public static final Key<String> EXTERNAL = createKey("external", String.class);
112 
113         public static final Key<Integer> FLAGS = createKey("flags", Integer.class);
114         public static final Key<String> FOCUS_CHANGE_HINT =
115                 createKey("focusChangeHint", String.class);
116         public static final Key<String> FORCE_USE_DUE_TO =
117                 createKey("forceUseDueTo", String.class);
118         public static final Key<String> FORCE_USE_MODE =
119                 createKey("forceUseMode", String.class);
120         public static final Key<Double> GAIN_DB =
121                 createKey("gainDb", Double.class);
122         public static final Key<String> GROUP =
123                 createKey("group", String.class);
124 
125         public static final Key<Integer> INDEX = createKey("index", Integer.class); // volume
126         public static final Key<String> LOG_SESSION_ID = createKey("logSessionId", String.class);
127         public static final Key<Integer> MAX_INDEX = createKey("maxIndex", Integer.class); // vol
128         public static final Key<Integer> MIN_INDEX = createKey("minIndex", Integer.class); // vol
129         public static final Key<String> MODE =
130                 createKey("mode", String.class); // audio_mode
131         public static final Key<String> MUTE =
132                 createKey("mute", String.class); // microphone, on or off.
133 
134         // Bluetooth or Usb device name
135         public static final Key<String> NAME =
136                 createKey("name", String.class);
137 
138         // Number of observers
139         public static final Key<Integer> OBSERVERS =
140                 createKey("observers", Integer.class);
141 
142         public static final Key<String> REQUEST =
143                 createKey("request", String.class);
144 
145         // For audio mode
146         public static final Key<String> REQUESTED_MODE =
147                 createKey("requestedMode", String.class); // audio_mode
148 
149         // For Bluetooth
150         public static final Key<String> SCO_AUDIO_MODE =
151                 createKey("scoAudioMode", String.class);
152         public static final Key<Integer> SDK = createKey("sdk", Integer.class);
153         public static final Key<String> STATE = createKey("state", String.class);
154         public static final Key<Integer> STATUS = createKey("status", Integer.class);
155         public static final Key<String> STREAM_TYPE = createKey("streamType", String.class);
156     }
157 
158     /**
159      * The TYPE constants below should match those in native MediaMetricsItem.h
160      */
161     private static final int TYPE_NONE = 0;
162     private static final int TYPE_INT32 = 1;     // Java integer
163     private static final int TYPE_INT64 = 2;     // Java long
164     private static final int TYPE_DOUBLE = 3;    // Java double
165     private static final int TYPE_CSTRING = 4;   // Java string
166     private static final int TYPE_RATE = 5;      // Two longs, ignored in Java
167 
168     // The charset used for encoding Strings to bytes.
169     private static final Charset MEDIAMETRICS_CHARSET = StandardCharsets.UTF_8;
170 
171     /**
172      * Key interface.
173      *
174      * The presence of this {@code Key} interface on an object allows
175      * it to be used to set metrics.
176      *
177      * @param <T> type of value associated with {@code Key}.
178      */
179     public interface Key<T> {
180         /**
181          * Returns the internal name of the key.
182          */
183         @NonNull
getName()184         String getName();
185 
186         /**
187          * Returns the class type of the associated value.
188          */
189         @NonNull
getValueClass()190         Class<T> getValueClass();
191     }
192 
193     /**
194      * Returns a Key object with the correct interface for MediaMetrics.
195      *
196      * @param name The name of the key.
197      * @param type The class type of the value represented by the key.
198      * @param <T> The type of value.
199      * @return a new key interface.
200      */
201     @NonNull
createKey(@onNull String name, @NonNull Class<T> type)202     public static <T> Key<T> createKey(@NonNull String name, @NonNull Class<T> type) {
203         // Implementation specific.
204         return new Key<T>() {
205             private final String mName = name;
206             private final Class<T> mType = type;
207 
208             @Override
209             @NonNull
210             public String getName() {
211                 return mName;
212             }
213 
214             @Override
215             @NonNull
216             public Class<T> getValueClass() {
217                 return mType;
218             }
219 
220             /**
221              * Return true if the name and the type of two objects are the same.
222              */
223             @Override
224             public boolean equals(Object obj) {
225                 if (obj == this) {
226                     return true;
227                 }
228                 if (!(obj instanceof Key)) {
229                     return false;
230                 }
231                 Key<?> other = (Key<?>) obj;
232                 return mName.equals(other.getName()) && mType.equals(other.getValueClass());
233             }
234 
235             @Override
236             public int hashCode() {
237                 return Objects.hash(mName, mType);
238             }
239         };
240     }
241 
242     /**
243      * Item records properties and delivers to the MediaMetrics service
244      *
245      */
246     public static class Item {
247 
248         /*
249          * MediaMetrics Item
250          *
251          * Creates a Byte String and sends to the MediaMetrics service.
252          * The Byte String serves as a compact form for logging data
253          * with low overhead for storage.
254          *
255          * The Byte String format is as follows:
256          *
257          * For Java
258          *  int64 corresponds to long
259          *  int32, uint32 corresponds to int
260          *  uint16 corresponds to char
261          *  uint8, int8 corresponds to byte
262          *
263          * For items transmitted from Java, uint8 and uint32 values are limited
264          * to INT8_MAX and INT32_MAX.  This constrains the size of large items
265          * to 2GB, which is consistent with ByteBuffer max size. A native item
266          * can conceivably have size of 4GB.
267          *
268          * Physical layout of integers and doubles within the MediaMetrics byte string
269          * is in Native / host order, which is usually little endian.
270          *
271          * Note that primitive data (ints, doubles) within a Byte String has
272          * no extra padding or alignment requirements, like ByteBuffer.
273          *
274          * -- begin of item
275          * -- begin of header
276          * (uint32) item size: including the item size field
277          * (uint32) header size, including the item size and header size fields.
278          * (uint16) version: exactly 0
279          * (uint16) key size, that is key strlen + 1 for zero termination.
280          * (int8)+ key, a string which is 0 terminated (UTF-8).
281          * (int32) pid
282          * (int32) uid
283          * (int64) timestamp
284          * -- end of header
285          * -- begin body
286          * (uint32) number of properties
287          * -- repeat for number of properties
288          *     (uint16) property size, including property size field itself
289          *     (uint8) type of property
290          *     (int8)+ key string, including 0 termination
291          *      based on type of property (given above), one of:
292          *       (int32)
293          *       (int64)
294          *       (double)
295          *       (int8)+ for TYPE_CSTRING, including 0 termination
296          *       (int64, int64) for rate
297          * -- end body
298          * -- end of item
299          *
300          * To record a MediaMetrics event, one creates a new item with an id,
301          * then use a series of puts to add properties
302          * and then a record() to send to the MediaMetrics service.
303          *
304          * The properties may not be unique, and putting a later property with
305          * the same name as an earlier property will overwrite the value and type
306          * of the prior property.
307          *
308          * The timestamp can only be recorded by a system service (and is ignored otherwise;
309          * the MediaMetrics service will fill in the timestamp as needed).
310          *
311          * The units of time are in SystemClock.elapsedRealtimeNanos().
312          *
313          * A clear() may be called to reset the properties to empty, the time to 0, but keep
314          * the other entries the same. This may be called after record().
315          * Additional properties may be added after calling record().  Changing the same property
316          * repeatedly is discouraged as - for this particular implementation - extra data
317          * is stored per change.
318          *
319          * new MediaMetrics.Item(mSomeId)
320          *     .putString("event", "javaCreate")
321          *     .putInt("value", intValue)
322          *     .record();
323          */
324 
325         /**
326          * Creates an Item with server added uid, time.
327          *
328          * This is the typical way to record a MediaMetrics item.
329          *
330          * @param key the Metrics ID associated with the item.
331          */
Item(String key)332         public Item(String key) {
333             this(key, -1 /* pid */, -1 /* uid */, 0 /* SystemClock.elapsedRealtimeNanos() */,
334                     2048 /* capacity */);
335         }
336 
337         /**
338          * Creates an Item specifying pid, uid, time, and initial Item capacity.
339          *
340          * This might be used by a service to specify a different PID or UID for a client.
341          *
342          * @param key the Metrics ID associated with the item.
343          *        An app may only set properties on an item which has already been
344          *        logged previously by a service.
345          * @param pid the process ID corresponding to the item.
346          *        A value of -1 (or a record() from an app instead of a service) causes
347          *        the MediaMetrics service to fill this in.
348          * @param uid the user ID corresponding to the item.
349          *        A value of -1 (or a record() from an app instead of a service) causes
350          *        the MediaMetrics service to fill this in.
351          * @param timeNs the time when the item occurred (may be in the past).
352          *        A value of 0 (or a record() from an app instead of a service) causes
353          *        the MediaMetrics service to fill it in.
354          *        Should be obtained from SystemClock.elapsedRealtimeNanos().
355          * @param capacity the anticipated size to use for the buffer.
356          *        If the capacity is too small, the buffer will be resized to accommodate.
357          *        This is amortized to copy data no more than twice.
358          */
Item(String key, int pid, int uid, long timeNs, int capacity)359         public Item(String key, int pid, int uid, long timeNs, int capacity) {
360             final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
361             final int keyLength = keyBytes.length;
362             if (keyLength > Character.MAX_VALUE - 1) {
363                 throw new IllegalArgumentException("Key length too large");
364             }
365 
366             // Version 0 - compute the header offsets here.
367             mHeaderSize = 4 + 4 + 2 + 2 + keyLength + 1 + 4 + 4 + 8; // see format above.
368             mPidOffset = mHeaderSize - 16;
369             mUidOffset = mHeaderSize - 12;
370             mTimeNsOffset = mHeaderSize - 8;
371             mPropertyCountOffset = mHeaderSize;
372             mPropertyStartOffset = mHeaderSize + 4;
373 
374             mKey = key;
375             mBuffer = ByteBuffer.allocateDirect(
376                     Math.max(capacity, mHeaderSize + MINIMUM_PAYLOAD_SIZE));
377 
378             // Version 0 - fill the ByteBuffer with the header (some details updated later).
379             mBuffer.order(ByteOrder.nativeOrder())
380                 .putInt((int) 0)                      // total size in bytes (filled in later)
381                 .putInt((int) mHeaderSize)            // size of header
382                 .putChar((char) FORMAT_VERSION)       // version
383                 .putChar((char) (keyLength + 1))      // length, with zero termination
384                 .put(keyBytes).put((byte) 0)
385                 .putInt(pid)
386                 .putInt(uid)
387                 .putLong(timeNs);
388             if (mHeaderSize != mBuffer.position()) {
389                 throw new IllegalStateException("Mismatched sizing");
390             }
391             mBuffer.putInt(0);     // number of properties (to be later filled in by record()).
392         }
393 
394         /**
395          * Sets a metrics typed key
396          * @param key
397          * @param value
398          * @param <T>
399          * @return
400          */
401         @NonNull
set(@onNull Key<T> key, @Nullable T value)402         public <T> Item set(@NonNull Key<T> key, @Nullable T value) {
403             if (value instanceof Integer) {
404                 putInt(key.getName(), (int) value);
405             } else if (value instanceof Long) {
406                 putLong(key.getName(), (long) value);
407             } else if (value instanceof Double) {
408                 putDouble(key.getName(), (double) value);
409             } else if (value instanceof String) {
410                 putString(key.getName(), (String) value);
411             }
412             // if value is null, etc. no error is raised.
413             return this;
414         }
415 
416         /**
417          * Sets the property with key to an integer (32 bit) value.
418          *
419          * @param key
420          * @param value
421          * @return itself
422          */
putInt(String key, int value)423         public Item putInt(String key, int value) {
424             final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
425             final char propSize = (char) reserveProperty(keyBytes, 4 /* payloadSize */);
426             final int estimatedFinalPosition = mBuffer.position() + propSize;
427             mBuffer.putChar(propSize)
428                 .put((byte) TYPE_INT32)
429                 .put(keyBytes).put((byte) 0) // key, zero terminated
430                 .putInt(value);
431             ++mPropertyCount;
432             if (mBuffer.position() != estimatedFinalPosition) {
433                 throw new IllegalStateException("Final position " + mBuffer.position()
434                         + " != estimatedFinalPosition " + estimatedFinalPosition);
435             }
436             return this;
437         }
438 
439         /**
440          * Sets the property with key to a long (64 bit) value.
441          *
442          * @param key
443          * @param value
444          * @return itself
445          */
putLong(String key, long value)446         public Item putLong(String key, long value) {
447             final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
448             final char propSize = (char) reserveProperty(keyBytes, 8 /* payloadSize */);
449             final int estimatedFinalPosition = mBuffer.position() + propSize;
450             mBuffer.putChar(propSize)
451                 .put((byte) TYPE_INT64)
452                 .put(keyBytes).put((byte) 0) // key, zero terminated
453                 .putLong(value);
454             ++mPropertyCount;
455             if (mBuffer.position() != estimatedFinalPosition) {
456                 throw new IllegalStateException("Final position " + mBuffer.position()
457                     + " != estimatedFinalPosition " + estimatedFinalPosition);
458             }
459             return this;
460         }
461 
462         /**
463          * Sets the property with key to a double value.
464          *
465          * @param key
466          * @param value
467          * @return itself
468          */
putDouble(String key, double value)469         public Item putDouble(String key, double value) {
470             final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
471             final char propSize = (char) reserveProperty(keyBytes, 8 /* payloadSize */);
472             final int estimatedFinalPosition = mBuffer.position() + propSize;
473             mBuffer.putChar(propSize)
474                 .put((byte) TYPE_DOUBLE)
475                 .put(keyBytes).put((byte) 0) // key, zero terminated
476                 .putDouble(value);
477             ++mPropertyCount;
478             if (mBuffer.position() != estimatedFinalPosition) {
479                 throw new IllegalStateException("Final position " + mBuffer.position()
480                     + " != estimatedFinalPosition " + estimatedFinalPosition);
481             }
482             return this;
483         }
484 
485         /**
486          * Sets the property with key to a String value.
487          *
488          * @param key
489          * @param value
490          * @return itself
491          */
putString(String key, String value)492         public Item putString(String key, String value) {
493             final byte[] keyBytes = key.getBytes(MEDIAMETRICS_CHARSET);
494             final byte[] valueBytes = value.getBytes(MEDIAMETRICS_CHARSET);
495             final char propSize = (char) reserveProperty(keyBytes, valueBytes.length + 1);
496             final int estimatedFinalPosition = mBuffer.position() + propSize;
497             mBuffer.putChar(propSize)
498                 .put((byte) TYPE_CSTRING)
499                 .put(keyBytes).put((byte) 0) // key, zero terminated
500                 .put(valueBytes).put((byte) 0); // value, zero term.
501             ++mPropertyCount;
502             if (mBuffer.position() != estimatedFinalPosition) {
503                 throw new IllegalStateException("Final position " + mBuffer.position()
504                     + " != estimatedFinalPosition " + estimatedFinalPosition);
505             }
506             return this;
507         }
508 
509         /**
510          * Sets the pid to the provided value.
511          *
512          * @param pid which can be -1 if the service is to fill it in from the calling info.
513          * @return itself
514          */
setPid(int pid)515         public Item setPid(int pid) {
516             mBuffer.putInt(mPidOffset, pid); // pid location in byte string.
517             return this;
518         }
519 
520         /**
521          * Sets the uid to the provided value.
522          *
523          * The UID represents the client associated with the property. This must be the UID
524          * of the application if it comes from the application client.
525          *
526          * Trusted services are allowed to set the uid for a client-related item.
527          *
528          * @param uid which can be -1 if the service is to fill it in from calling info.
529          * @return itself
530          */
setUid(int uid)531         public Item setUid(int uid) {
532             mBuffer.putInt(mUidOffset, uid); // uid location in byte string.
533             return this;
534         }
535 
536         /**
537          * Sets the timestamp to the provided value.
538          *
539          * The time is referenced by the Boottime obtained by SystemClock.elapsedRealtimeNanos().
540          * This should be associated with the occurrence of the event.  It is recommended that
541          * the event be registered immediately when it occurs, and no later than 500ms
542          * (and certainly not in the future).
543          *
544          * @param timeNs which can be 0 if the service is to fill it in at the time of call.
545          * @return itself
546          */
setTimestamp(long timeNs)547         public Item setTimestamp(long timeNs) {
548             mBuffer.putLong(mTimeNsOffset, timeNs); // time location in byte string.
549             return this;
550         }
551 
552         /**
553          * Clears the properties and resets the time to 0.
554          *
555          * No other values are changed.
556          *
557          * @return itself
558          */
clear()559         public Item clear() {
560             mBuffer.position(mPropertyStartOffset);
561             mBuffer.limit(mBuffer.capacity());
562             mBuffer.putLong(mTimeNsOffset, 0); // reset time.
563             mPropertyCount = 0;
564             return this;
565         }
566 
567         /**
568          * Sends the item to the MediaMetrics service.
569          *
570          * The item properties are unchanged, hence record() may be called more than once
571          * to send the same item twice. Also, record() may be called without any properties.
572          *
573          * @return true if successful.
574          */
record()575         public boolean record() {
576             updateHeader();
577             return native_submit_bytebuffer(mBuffer, mBuffer.limit()) >= 0;
578         }
579 
580         /**
581          * Converts the Item to a Bundle.
582          *
583          * This is primarily used as a test API for CTS.
584          *
585          * @return a Bundle with the keys set according to data in the Item's buffer.
586          */
toBundle()587         public Bundle toBundle() {
588             updateHeader();
589 
590             final ByteBuffer buffer = mBuffer.duplicate();
591             buffer.order(ByteOrder.nativeOrder()) // restore order property
592                 .flip();                          // convert from write buffer to read buffer
593 
594             return toBundle(buffer);
595         }
596 
597         // The following constants are used for tests to extract
598         // the content of the Bundle for CTS testing.
599         public static final String BUNDLE_TOTAL_SIZE = "_totalSize";
600         public static final String BUNDLE_HEADER_SIZE = "_headerSize";
601         public static final String BUNDLE_VERSION = "_version";
602         public static final String BUNDLE_KEY_SIZE = "_keySize";
603         public static final String BUNDLE_KEY = "_key";
604         public static final String BUNDLE_PID = "_pid";
605         public static final String BUNDLE_UID = "_uid";
606         public static final String BUNDLE_TIMESTAMP = "_timestamp";
607         public static final String BUNDLE_PROPERTY_COUNT = "_propertyCount";
608 
609         /**
610          * Converts a buffer contents to a bundle
611          *
612          * This is primarily used as a test API for CTS.
613          *
614          * @param buffer contains the byte data serialized according to the byte string version.
615          * @return a Bundle with the keys set according to data in the buffer.
616          */
toBundle(ByteBuffer buffer)617         public static Bundle toBundle(ByteBuffer buffer) {
618             final Bundle bundle = new Bundle();
619 
620             final int totalSize = buffer.getInt();
621             final int headerSize = buffer.getInt();
622             final char version = buffer.getChar();
623             final char keySize = buffer.getChar(); // includes zero termination, i.e. keyLength + 1
624 
625             if (totalSize < 0 || headerSize < 0) {
626                 throw new IllegalArgumentException("Item size cannot be > " + Integer.MAX_VALUE);
627             }
628             final String key;
629             if (keySize > 0) {
630                 key = getStringFromBuffer(buffer, keySize);
631             } else {
632                 throw new IllegalArgumentException("Illegal null key");
633             }
634 
635             final int pid = buffer.getInt();
636             final int uid = buffer.getInt();
637             final long timestamp = buffer.getLong();
638 
639             // Verify header size (depending on version).
640             final int headerRead = buffer.position();
641             if (version == 0) {
642                 if (headerRead != headerSize) {
643                     throw new IllegalArgumentException(
644                             "Item key:" + key
645                             + " headerRead:" + headerRead + " != headerSize:" + headerSize);
646                 }
647             } else {
648                 // future versions should only increase header size
649                 // by adding to the end.
650                 if (headerRead > headerSize) {
651                     throw new IllegalArgumentException(
652                             "Item key:" + key
653                             + " headerRead:" + headerRead + " > headerSize:" + headerSize);
654                 } else if (headerRead < headerSize) {
655                     buffer.position(headerSize);
656                 }
657             }
658 
659             // Body always starts with properties.
660             final int propertyCount = buffer.getInt();
661             if (propertyCount < 0) {
662                 throw new IllegalArgumentException(
663                         "Cannot have more than " + Integer.MAX_VALUE + " properties");
664             }
665             bundle.putInt(BUNDLE_TOTAL_SIZE, totalSize);
666             bundle.putInt(BUNDLE_HEADER_SIZE, headerSize);
667             bundle.putChar(BUNDLE_VERSION, version);
668             bundle.putChar(BUNDLE_KEY_SIZE, keySize);
669             bundle.putString(BUNDLE_KEY, key);
670             bundle.putInt(BUNDLE_PID, pid);
671             bundle.putInt(BUNDLE_UID, uid);
672             bundle.putLong(BUNDLE_TIMESTAMP, timestamp);
673             bundle.putInt(BUNDLE_PROPERTY_COUNT, propertyCount);
674 
675             for (int i = 0; i < propertyCount; ++i) {
676                 final int initialBufferPosition = buffer.position();
677                 final char propSize = buffer.getChar();
678                 final byte type = buffer.get();
679 
680                 // Log.d(TAG, "(" + i + ") propSize:" + ((int)propSize) + " type:" + type);
681                 final String propKey = getStringFromBuffer(buffer);
682                 switch (type) {
683                     case TYPE_INT32:
684                         bundle.putInt(propKey, buffer.getInt());
685                         break;
686                     case TYPE_INT64:
687                         bundle.putLong(propKey, buffer.getLong());
688                         break;
689                     case TYPE_DOUBLE:
690                         bundle.putDouble(propKey, buffer.getDouble());
691                         break;
692                     case TYPE_CSTRING:
693                         bundle.putString(propKey, getStringFromBuffer(buffer));
694                         break;
695                     case TYPE_NONE:
696                         break; // ignore on Java side
697                     case TYPE_RATE:
698                         buffer.getLong();  // consume the first int64_t of rate
699                         buffer.getLong();  // consume the second int64_t of rate
700                         break; // ignore on Java side
701                     default:
702                         // These are unsupported types for version 0
703                         // We ignore them if the version is greater than 0.
704                         if (version == 0) {
705                             throw new IllegalArgumentException(
706                                     "Property " + propKey + " has unsupported type " + type);
707                         }
708                         buffer.position(initialBufferPosition + propSize); // advance and skip
709                         break;
710                 }
711                 final int deltaPosition = buffer.position() - initialBufferPosition;
712                 if (deltaPosition != propSize) {
713                     throw new IllegalArgumentException("propSize:" + propSize
714                         + " != deltaPosition:" + deltaPosition);
715                 }
716             }
717 
718             final int finalPosition = buffer.position();
719             if (finalPosition != totalSize) {
720                 throw new IllegalArgumentException("totalSize:" + totalSize
721                     + " != finalPosition:" + finalPosition);
722             }
723             return bundle;
724         }
725 
726         // Version 0 byte offsets for the header.
727         private static final int FORMAT_VERSION = 0;
728         private static final int TOTAL_SIZE_OFFSET = 0;
729         private static final int HEADER_SIZE_OFFSET = 4;
730         private static final int MINIMUM_PAYLOAD_SIZE = 4;
731         private final int mPidOffset;            // computed in constructor
732         private final int mUidOffset;            // computed in constructor
733         private final int mTimeNsOffset;         // computed in constructor
734         private final int mPropertyCountOffset;  // computed in constructor
735         private final int mPropertyStartOffset;  // computed in constructor
736         private final int mHeaderSize;           // computed in constructor
737 
738         private final String mKey;
739 
740         private ByteBuffer mBuffer;     // may be reallocated if capacity is insufficient.
741         private int mPropertyCount = 0; // overflow not checked (mBuffer would overflow first).
742 
reserveProperty(byte[] keyBytes, int payloadSize)743         private int reserveProperty(byte[] keyBytes, int payloadSize) {
744             final int keyLength = keyBytes.length;
745             if (keyLength > Character.MAX_VALUE) {
746                 throw new IllegalStateException("property key too long "
747                         + new String(keyBytes, MEDIAMETRICS_CHARSET));
748             }
749             if (payloadSize > Character.MAX_VALUE) {
750                 throw new IllegalStateException("payload too large " + payloadSize);
751             }
752 
753             // See the byte string property format above.
754             final int size = 2      /* length */
755                     + 1             /* type */
756                     + keyLength + 1 /* key length with zero termination */
757                     + payloadSize;  /* payload size */
758 
759             if (size > Character.MAX_VALUE) {
760                 throw new IllegalStateException("Item property "
761                         + new String(keyBytes, MEDIAMETRICS_CHARSET) + " is too large to send");
762             }
763 
764             if (mBuffer.remaining() < size) {
765                 int newCapacity = mBuffer.position() + size;
766                 if (newCapacity > Integer.MAX_VALUE >> 1) {
767                     throw new IllegalStateException(
768                         "Item memory requirements too large: " + newCapacity);
769                 }
770                 newCapacity <<= 1;
771                 ByteBuffer buffer = ByteBuffer.allocateDirect(newCapacity);
772                 buffer.order(ByteOrder.nativeOrder());
773 
774                 // Copy data from old buffer to new buffer.
775                 mBuffer.flip();
776                 buffer.put(mBuffer);
777 
778                 // set buffer to new buffer
779                 mBuffer = buffer;
780             }
781             return size;
782         }
783 
784         // Used for test
getStringFromBuffer(ByteBuffer buffer)785         private static String getStringFromBuffer(ByteBuffer buffer) {
786             return getStringFromBuffer(buffer, Integer.MAX_VALUE);
787         }
788 
789         // Used for test
getStringFromBuffer(ByteBuffer buffer, int size)790         private static String getStringFromBuffer(ByteBuffer buffer, int size) {
791             int i = buffer.position();
792             int limit = buffer.limit();
793             if (size < Integer.MAX_VALUE - i && i + size < limit) {
794                 limit = i + size;
795             }
796             for (; i < limit; ++i) {
797                 if (buffer.get(i) == 0) {
798                     final int newPosition = i + 1;
799                     if (size != Integer.MAX_VALUE && newPosition - buffer.position() != size) {
800                         throw new IllegalArgumentException("chars consumed at " + i + ": "
801                             + (newPosition - buffer.position()) + " != size: " + size);
802                     }
803                     final String found;
804                     if (buffer.hasArray()) {
805                         found = new String(
806                             buffer.array(), buffer.position() + buffer.arrayOffset(),
807                             i - buffer.position(), MEDIAMETRICS_CHARSET);
808                         buffer.position(newPosition);
809                     } else {
810                         final byte[] array = new byte[i - buffer.position()];
811                         buffer.get(array);
812                         found = new String(array, MEDIAMETRICS_CHARSET);
813                         buffer.get(); // remove 0.
814                     }
815                     return found;
816                 }
817             }
818             throw new IllegalArgumentException(
819                     "No zero termination found in string position: "
820                     + buffer.position() + " end: " + i);
821         }
822 
823         /**
824          * May be called multiple times - just makes the header consistent with the current
825          * properties written.
826          */
updateHeader()827         private void updateHeader() {
828             // Buffer sized properly in constructor.
829             mBuffer.putInt(TOTAL_SIZE_OFFSET, mBuffer.position())      // set total length
830                 .putInt(mPropertyCountOffset, (char) mPropertyCount); // set number of properties
831         }
832     }
833 
native_submit_bytebuffer(@onNull ByteBuffer buffer, int length)834     private static native int native_submit_bytebuffer(@NonNull ByteBuffer buffer, int length);
835 }
836