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