perfetto: select Java event encoding per trace session

Let each trace config choose LEGACY or ENCODED. Keep LEGACY as the
default for absent, UNSPECIFIED and unknown values. Store the choice in
session TLS and expose the modes requested for each category, so Java
can choose which representations to build.

Define ENCODED event, category and argument names as inline strings.
Explicit addFieldWithInterning() calls keep their sequence-local IDs.
The setting does not change ordinary C or C++ events.
diff --git a/include/perfetto/public/abi/track_event_abi.h b/include/perfetto/public/abi/track_event_abi.h
index 2a35057..33495fd 100644
--- a/include/perfetto/public/abi/track_event_abi.h
+++ b/include/perfetto/public/abi/track_event_abi.h
@@ -74,6 +74,18 @@
 PERFETTO_SDK_EXPORT PERFETTO_ATOMIC(bool) *
     PerfettoTeCategoryImplGetEnabled(struct PerfettoTeCategoryImpl*);
 
+// Experimental Java binding encoder modes. These are a bitmask, not the
+// TrackEventConfig enum values. Ordinary C/C++ emitters ignore this selection.
+#define PERFETTO_TE_JAVA_ENCODING_LEGACY 1u
+#define PERFETTO_TE_JAVA_ENCODING_ENCODED 2u
+
+// Returns the Java representations currently requested for this category, or
+// zero if disabled. This is an advisory snapshot: sessions may start or stop
+// before emission. The builder retains these bits; a later session is eligible
+// only if its requested representation was built. NULL returns zero.
+PERFETTO_SDK_EXPORT uint32_t
+PerfettoTeHlGetJavaEncodingModes(struct PerfettoTeCategoryImpl* cat);
+
 // Called when a data source instance is created (if `created` is true) or
 // destroyed (if `created` is false) with a registered category enabled.
 // `global_state_changed` is true if this was the first instance created with
diff --git a/include/perfetto/public/protos/config/track_event/track_event_config.pzc.h b/include/perfetto/public/protos/config/track_event/track_event_config.pzc.h
index 3d1ede0..07d4627 100644
--- a/include/perfetto/public/protos/config/track_event/track_event_config.pzc.h
+++ b/include/perfetto/public/protos/config/track_event/track_event_config.pzc.h
@@ -25,6 +25,15 @@
 
 #include "perfetto/public/pb_macros.h"
 
+PERFETTO_PB_ENUM_IN_MSG(perfetto_protos_TrackEventConfig, JavaEventEncoding){
+    PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_TrackEventConfig,
+                                  JAVA_EVENT_ENCODING_UNSPECIFIED) = 0,
+    PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_TrackEventConfig,
+                                  JAVA_EVENT_ENCODING_LEGACY) = 1,
+    PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_TrackEventConfig,
+                                  JAVA_EVENT_ENCODING_ENCODED) = 2,
+};
+
 PERFETTO_PB_MSG(perfetto_protos_TrackEventConfig);
 PERFETTO_PB_FIELD(perfetto_protos_TrackEventConfig,
                   STRING,
@@ -76,5 +85,10 @@
                   bool,
                   filter_dynamic_event_names,
                   9);
+PERFETTO_PB_FIELD(perfetto_protos_TrackEventConfig,
+                  VARINT,
+                  enum perfetto_protos_TrackEventConfig_JavaEventEncoding,
+                  experimental_java_event_encoding,
+                  11);
 
 #endif  // INCLUDE_PERFETTO_PUBLIC_PROTOS_CONFIG_TRACK_EVENT_TRACK_EVENT_CONFIG_PZC_H_
diff --git a/protos/perfetto/config/track_event/track_event_config.proto b/protos/perfetto/config/track_event/track_event_config.proto
index b85acd2..ffb0f45 100644
--- a/protos/perfetto/config/track_event/track_event_config.proto
+++ b/protos/perfetto/config/track_event/track_event_config.proto
@@ -103,4 +103,20 @@
   // When true, event_names wrapped in perfetto::DynamicString will be filtered
   // out.
   optional bool filter_dynamic_event_names = 9;
+
+  // Selects the Java SDK encoder for this recording. This is independent of
+  // the trace writer's v1/v2 selection and does not affect C or C++ events.
+  // Experimental: remove this switch after the Java encoder migration.
+  enum JavaEventEncoding {
+    JAVA_EVENT_ENCODING_UNSPECIFIED = 0;
+    JAVA_EVENT_ENCODING_LEGACY = 1;
+    JAVA_EVENT_ENCODING_ENCODED = 2;
+  }
+  // Absent or UNSPECIFIED selects LEGACY. Unknown values also select LEGACY.
+  // ENCODED writes event, category and debug-argument names inline. Explicit
+  // addFieldWithInterning() calls still use sequence-local interned IDs.
+  // Concurrent recordings may request different modes; Java then builds both
+  // representations. A builder keeps the modes selected when it was created.
+  // Recordings started later receive it only if their mode was selected.
+  optional JavaEventEncoding experimental_java_event_encoding = 11;
 }
diff --git a/src/android_sdk/java/main/dev/perfetto/sdk/PerfettoTrace.java b/src/android_sdk/java/main/dev/perfetto/sdk/PerfettoTrace.java
index 30b0d91..e1af677 100644
--- a/src/android_sdk/java/main/dev/perfetto/sdk/PerfettoTrace.java
+++ b/src/android_sdk/java/main/dev/perfetto/sdk/PerfettoTrace.java
@@ -109,6 +109,9 @@
     @CriticalNative
     private static native boolean native_is_enabled(long ptr);
 
+    @CriticalNative
+    private static native int native_get_encoding_modes(long ptr);
+
     /** Create the native category object and register it. */
     public synchronized Category register() {
       if (mPtr == 0) {
@@ -144,6 +147,12 @@
       return mPtr != 0 && native_is_enabled(mPtr);
     }
 
+    // Freeze this snapshot in the builder; native emission checks each session.
+    int getEncodingModes() {
+      long ptr = mPtr;
+      return ptr == 0 ? 0 : native_get_encoding_modes(ptr);
+    }
+
     /** Whether the category is registered or not. */
     public boolean isRegistered() {
       return mIsRegistered;
diff --git a/src/android_sdk/jni/dev_perfetto_sdk_PerfettoTrace.cc b/src/android_sdk/jni/dev_perfetto_sdk_PerfettoTrace.cc
index f3e5f67..dce2650 100644
--- a/src/android_sdk/jni/dev_perfetto_sdk_PerfettoTrace.cc
+++ b/src/android_sdk/jni/dev_perfetto_sdk_PerfettoTrace.cc
@@ -96,6 +96,13 @@
   return category->is_category_enabled();
 }
 
+static jint dev_perfetto_sdk_PerfettoTraceCategory_get_encoding_modes(
+    PERFETTO_JNI_HOST_PARAMS_COMMA jlong ptr) {
+  auto* category = toPointer<sdk_for_jni::Category>(ptr);
+  return static_cast<jint>(
+      PerfettoTeHlGetJavaEncodingModes(category->get()->impl));
+}
+
 static jlong dev_perfetto_sdk_PerfettoTrace_start_session(
     JNIEnv* env,
     jclass /* obj */,
@@ -147,6 +154,8 @@
      (void*)dev_perfetto_sdk_PerfettoTraceCategory_unregister},
     {"native_is_enabled", "(J)Z",
      (void*)dev_perfetto_sdk_PerfettoTraceCategory_is_enabled},
+    {"native_get_encoding_modes", "(J)I",
+     (void*)dev_perfetto_sdk_PerfettoTraceCategory_get_encoding_modes},
 };
 
 static const JNINativeMethod gTraceMethods[] = {
diff --git a/src/shared_lib/test/api_integrationtest.cc b/src/shared_lib/test/api_integrationtest.cc
index 35747f6..8565794 100644
--- a/src/shared_lib/test/api_integrationtest.cc
+++ b/src/shared_lib/test/api_integrationtest.cc
@@ -1906,6 +1906,51 @@
   EXPECT_FALSE(std::atomic_load(cat3.enabled));
 }
 
+TEST_F(SharedLibTrackEventTest, JavaEncodingModesFollowSessionConfig) {
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(nullptr), 0u);
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl), 0u);
+  auto legacy = TracingSession::Builder()
+                    .set_data_source_name("track_event")
+                    .add_enabled_category("cat1")
+                    .set_java_event_encoding(1)
+                    .Build();
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl),
+            PERFETTO_TE_JAVA_ENCODING_LEGACY);
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat2.impl), 0u);
+  auto encoded = TracingSession::Builder()
+                     .set_data_source_name("track_event")
+                     .add_enabled_category("cat1")
+                     .set_java_event_encoding(2)
+                     .Build();
+  EXPECT_EQ(
+      PerfettoTeHlGetJavaEncodingModes(cat1.impl),
+      PERFETTO_TE_JAVA_ENCODING_LEGACY | PERFETTO_TE_JAVA_ENCODING_ENCODED);
+  legacy.StopBlocking();
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl),
+            PERFETTO_TE_JAVA_ENCODING_ENCODED);
+  encoded.StopBlocking();
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl), 0u);
+}
+
+TEST_F(SharedLibTrackEventTest, JavaEncodingUnknownModeUsesLegacy) {
+  auto session = TracingSession::Builder()
+                     .set_data_source_name("track_event")
+                     .add_enabled_category("cat1")
+                     .set_java_event_encoding(12345)
+                     .Build();
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl),
+            PERFETTO_TE_JAVA_ENCODING_LEGACY);
+}
+
+TEST_F(SharedLibTrackEventTest, JavaEncodingDefaultUsesLegacy) {
+  auto session = TracingSession::Builder()
+                     .set_data_source_name("track_event")
+                     .add_enabled_category("cat1")
+                     .Build();
+  EXPECT_EQ(PerfettoTeHlGetJavaEncodingModes(cat1.impl),
+            PERFETTO_TE_JAVA_ENCODING_LEGACY);
+}
+
 TEST_F(SharedLibTrackEventTest, TrackEventCategoryCallback) {
   StrictMock<MockFunction<void(struct PerfettoTeCategoryImpl*,
                                PerfettoDsInstanceIndex, bool, bool)>>
diff --git a/src/shared_lib/test/utils.cc b/src/shared_lib/test/utils.cc
index 8e8e170..b9c450d 100644
--- a/src/shared_lib/test/utils.cc
+++ b/src/shared_lib/test/utils.cc
@@ -92,7 +92,7 @@
                                                             &protovm_cfg);
       }
       if (!enabled_categories_.empty() || !disabled_categories_.empty() ||
-          !enabled_tags_.empty()) {
+          !enabled_tags_.empty() || java_event_encoding_.has_value()) {
         perfetto_protos_TrackEventConfig te_cfg;
         perfetto_protos_DataSourceConfig_begin_track_event_config(&ds_cfg,
                                                                   &te_cfg);
@@ -108,6 +108,13 @@
           perfetto_protos_TrackEventConfig_set_enabled_tags(&te_cfg, tag.data(),
                                                             tag.size());
         }
+        if (java_event_encoding_.has_value()) {
+          // Keep unknown values representable for compatibility coverage.
+          PerfettoPbMsgAppendType0Field(
+              &te_cfg.msg,
+              perfetto_protos_TrackEventConfig_experimental_java_event_encoding_field_number,
+              *java_event_encoding_);
+        }
         perfetto_protos_DataSourceConfig_end_track_event_config(&ds_cfg,
                                                                 &te_cfg);
       }
diff --git a/src/shared_lib/test/utils.h b/src/shared_lib/test/utils.h
index cde1e47..35527ba 100644
--- a/src/shared_lib/test/utils.h
+++ b/src/shared_lib/test/utils.h
@@ -87,6 +87,10 @@
       enabled_tags_.push_back(std::move(tag));
       return *this;
     }
+    Builder& set_java_event_encoding(uint32_t encoding) {
+      java_event_encoding_ = encoding;
+      return *this;
+    }
     Builder& set_clear_period_ms(uint32_t clear_period_ms) {
       clear_period_ms_ = clear_period_ms;
       return *this;
@@ -111,6 +115,7 @@
     uint32_t clear_period_ms_ = 0;
     bool enable_protovm_config_ = false;
     std::optional<uint32_t> v2_probability_;
+    std::optional<uint32_t> java_event_encoding_;
   };
 
   static TracingSession Adopt(struct PerfettoTracingSessionImpl*);
diff --git a/src/shared_lib/track_event/ds.h b/src/shared_lib/track_event/ds.h
index 942fecb..2ad3ffd 100644
--- a/src/shared_lib/track_event/ds.h
+++ b/src/shared_lib/track_event/ds.h
@@ -94,6 +94,7 @@
     timestamp_unit_multiplier = 1;
     if (locked_ds.valid()) {
       const auto& config = locked_ds->GetConfig();
+      java_encoding_mode = GlobalState::JavaEncodingMode(config);
       disable_incremental_timestamps = config.disable_incremental_timestamps();
       if (config.has_timestamp_unit_multiplier() &&
           config.timestamp_unit_multiplier() != 0) {
@@ -110,6 +111,7 @@
       default_clock_id = PERFETTO_TE_TIMESTAMP_TYPE_INCREMENTAL;
     }
   }
+  uint32_t java_encoding_mode = PERFETTO_TE_JAVA_ENCODING_LEGACY;
   uint32_t default_clock_id;
   uint64_t timestamp_unit_multiplier;
 };
diff --git a/src/shared_lib/track_event/global_state.cc b/src/shared_lib/track_event/global_state.cc
index eb74f9e..ef5d8d6 100644
--- a/src/shared_lib/track_event/global_state.cc
+++ b/src/shared_lib/track_event/global_state.cc
@@ -42,9 +42,39 @@
   perfetto_te_any_categories_enabled = &perfetto_te_any_categories->flag;
 }
 
+uint32_t GlobalState::JavaEncodingMode(
+    const perfetto::protos::gen::TrackEventConfig& config) {
+  using Config = perfetto::protos::gen::TrackEventConfig;
+  return config.experimental_java_event_encoding() ==
+                 Config::JAVA_EVENT_ENCODING_ENCODED
+             ? PERFETTO_TE_JAVA_ENCODING_ENCODED
+             : PERFETTO_TE_JAVA_ENCODING_LEGACY;
+}
+
+uint32_t GlobalState::GetJavaEncodingModes(
+    const PerfettoTeCategoryImpl* cat) const {
+  if (!cat)
+    return 0;
+  const uint8_t active = cat->instances.load(std::memory_order_relaxed);
+  const uint8_t encoded =
+      java_encoded_instances_.load(std::memory_order_relaxed);
+  uint32_t modes = 0;
+  if (active & encoded)
+    modes |= PERFETTO_TE_JAVA_ENCODING_ENCODED;
+  if (active & ~encoded)
+    modes |= PERFETTO_TE_JAVA_ENCODING_LEGACY;
+  return modes;
+}
+
 void GlobalState::OnStart(const perfetto::protos::gen::TrackEventConfig& config,
                           uint32_t instance_id) PERFETTO_LOCKS_EXCLUDED(mu_) {
   std::lock_guard<std::mutex> lock(mu_);
+  const auto bit = static_cast<uint8_t>(1u << instance_id);
+  if (JavaEncodingMode(config) == PERFETTO_TE_JAVA_ENCODING_ENCODED)
+    java_encoded_instances_.fetch_or(bit, std::memory_order_relaxed);
+  else
+    java_encoded_instances_.fetch_and(static_cast<uint8_t>(~bit),
+                                      std::memory_order_relaxed);
   perfetto_te_any_categories->EnableInstance(instance_id);
   for (PerfettoTeCategoryImpl* cat : categories_) {
     if (IsRegisteredCategoryEnabled(*cat, config)) {
@@ -60,6 +90,8 @@
     cat->DisableInstance(instance_id);
   }
   perfetto_te_any_categories->DisableInstance(instance_id);
+  java_encoded_instances_.fetch_and(static_cast<uint8_t>(~(1u << instance_id)),
+                                    std::memory_order_relaxed);
   active_configs_.erase(instance_id);
 }
 
diff --git a/src/shared_lib/track_event/global_state.h b/src/shared_lib/track_event/global_state.h
index fce42a0..ee76fa7 100644
--- a/src/shared_lib/track_event/global_state.h
+++ b/src/shared_lib/track_event/global_state.h
@@ -17,6 +17,7 @@
 #ifndef SRC_SHARED_LIB_TRACK_EVENT_GLOBAL_STATE_H_
 #define SRC_SHARED_LIB_TRACK_EVENT_GLOBAL_STATE_H_
 
+#include <atomic>
 #include <cstdint>
 #include <mutex>
 #include <unordered_map>
@@ -35,6 +36,11 @@
     return *instance;
   }
 
+  // The single default-policy boundary, shared by queries and session TLS.
+  static uint32_t JavaEncodingMode(
+      const perfetto::protos::gen::TrackEventConfig& config);
+  uint32_t GetJavaEncodingModes(const PerfettoTeCategoryImpl* cat) const;
+
   void OnStart(const perfetto::protos::gen::TrackEventConfig& config,
                uint32_t instance_id) PERFETTO_LOCKS_EXCLUDED(mu_);
   void OnStop(uint32_t instance_id) PERFETTO_LOCKS_EXCLUDED(mu_);
@@ -51,6 +57,9 @@
  private:
   GlobalState();
 
+  // Updated before publishing category activation and after disabling it.
+  // Queries are hints; emission checks the selected instance's immutable TLS.
+  std::atomic<uint8_t> java_encoded_instances_{0};
   mutable std::mutex mu_;
   std::vector<PerfettoTeCategoryImpl*> categories_ PERFETTO_GUARDED_BY(mu_);
   std::unordered_map<uint32_t, perfetto::protos::gen::TrackEventConfig>
diff --git a/src/shared_lib/track_event/track_event.cc b/src/shared_lib/track_event/track_event.cc
index b4177dd..5c465e0 100644
--- a/src/shared_lib/track_event/track_event.cc
+++ b/src/shared_lib/track_event/track_event.cc
@@ -89,3 +89,7 @@
   perfetto::shlib::GlobalState::Instance().UnregisterCategory(cat);
   delete cat;
 }
+
+uint32_t PerfettoTeHlGetJavaEncodingModes(struct PerfettoTeCategoryImpl* cat) {
+  return perfetto::shlib::GlobalState::Instance().GetJavaEncodingModes(cat);
+}