Apply input event profile to mitigate input latency of input threads

Bug: 347122505
Flag: com.android.input.flags.enable_input_policy_profile
Test: check the priority and latency of input thread in Perffeto
Change-Id: I428b9e718eace0bc39f1965d98475eebe9d3aaa5
diff --git a/libs/input/input_flags.aconfig b/libs/input/input_flags.aconfig
index f1c4aed..3753990 100644
--- a/libs/input/input_flags.aconfig
+++ b/libs/input/input_flags.aconfig
@@ -192,3 +192,12 @@
   description: "Prevents touchpad gesture changing window focus."
   bug: "364460018"
 }
+
+flag {
+  name: "enable_input_policy_profile"
+  namespace: "input"
+  description: "Apply input policy profile for input threads."
+  bug: "347122505"
+  is_fixed_read_only: true
+}
+
diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp
index cb220ab..ca92ab5 100644
--- a/services/inputflinger/Android.bp
+++ b/services/inputflinger/Android.bp
@@ -217,6 +217,7 @@
         "libcutils",
         "libinput",
         "liblog",
+        "libprocessgroup",
         "libstatslog",
         "libutils",
     ],
diff --git a/services/inputflinger/InputThread.cpp b/services/inputflinger/InputThread.cpp
index e74f258..449eb45 100644
--- a/services/inputflinger/InputThread.cpp
+++ b/services/inputflinger/InputThread.cpp
@@ -16,8 +16,14 @@
 
 #include "InputThread.h"
 
+#include <android-base/logging.h>
+#include <com_android_input_flags.h>
+#include <processgroup/processgroup.h>
+
 namespace android {
 
+namespace input_flags = com::android::input::flags;
+
 namespace {
 
 // Implementation of Thread from libutils.
@@ -43,6 +49,11 @@
       : mName(name), mThreadWake(wake) {
     mThread = sp<InputThreadImpl>::make(loop);
     mThread->run(mName.c_str(), ANDROID_PRIORITY_URGENT_DISPLAY);
+    if (input_flags::enable_input_policy_profile()) {
+        if (!applyInputEventProfile()) {
+            LOG(ERROR) << "Couldn't apply input policy profile for " << name;
+        }
+    }
 }
 
 InputThread::~InputThread() {
@@ -63,4 +74,14 @@
 #endif
 }
 
+bool InputThread::applyInputEventProfile() {
+#if defined(__ANDROID__)
+    return SetTaskProfiles(mThread->getTid(), {"InputPolicy"});
+#else
+    // Since thread information is not available and there's no benefit of
+    // applying the task profile on host, return directly.
+    return true;
+#endif
+}
+
 } // namespace android
\ No newline at end of file
diff --git a/services/inputflinger/include/InputThread.h b/services/inputflinger/include/InputThread.h
index 5e75027..fcd913d 100644
--- a/services/inputflinger/include/InputThread.h
+++ b/services/inputflinger/include/InputThread.h
@@ -38,6 +38,7 @@
     std::string mName;
     std::function<void()> mThreadWake;
     sp<Thread> mThread;
+    bool applyInputEventProfile();
 };
 
 } // namespace android