Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ The camera starts only when you tap **Start camera** in the app. The notificatio

## Compatibility

This first APK uses Termux's public GitHub development signing key and `com.termux` shared UID. It installs alongside **GitHub-signed Termux only**. It cannot install alongside F-Droid or Play Store Termux; do not uninstall your existing Termux or its data just to try this build. Android 12+ and ARM64 are required.
The published build uses Termux's public GitHub development signing key and `com.termux` shared UID, so it installs alongside **GitHub-signed Termux only**. This local branch removes the shared UID and uses an authenticated FD handoff. A Pixel 6a (Android 17) with F-Droid Termux captured live frames, but this branch is not yet a release. The cross-UID handoff requires Android 14+; Android 12–13 remain unsupported until an authenticated alternative is implemented. Do not uninstall Termux or its data to try either build.

The public key does not establish trust in an APK: verify the source and artifact before installing. The expected APK signing certificate SHA-256 is `b6da01480eefd5fbf2cd3771b8d1021ec791304bdd6c4bf41d3faabad48ee5e1`.

## Build and use

Every APK and native library in CI is compiled from the source pinned in this repository. The [build workflow](.github/workflows/build.yml) fetches Termux's public key at a pinned commit, verifies its SHA-256, runs fauxdev's tests, builds the APK and Termux-native library, verifies the APK certificate, and uploads both artifacts. No locally compiled library is checked in or repackaged.

Install the CI APK on a device with GitHub-signed Termux. In Termux, extract the matching `camera2termux-termux-arm64.tar.gz`, then install its two files:
For the published build, install the CI APK on a device with GitHub-signed Termux. This local branch can be built and tested with F-Droid Termux, but has no published artifact. In Termux, extract the matching `camera2termux-termux-arm64.tar.gz`, then install its two files:

```sh
tar -xzf camera2termux-termux-arm64.tar.gz
install -m 755 libfauxdev-termux.so "$PREFIX/lib/libfauxdev-termux.so"
install -m 755 camera2termux-run "$PREFIX/bin/camera2termux-run"
```

Open Camera2Termux, grant camera permission, and tap **Start camera**. Then use `camera2termux-run COMMAND ...` for a native Termux program that opens `/dev/video0` through V4L2. The launcher sets `FAUXDEV_VIDEO_SOCKET` and `LD_PRELOAD`; it does not enable the camera in arbitrary processes. Stop the service when finished.
Open Camera2Termux, grant camera permission, and tap **Start camera**. Then use `camera2termux-run COMMAND ...` for a native Termux program that opens `/dev/video0` through V4L2. The published launcher uses the app-private socket path; this branch instead hands an already-connected FD to the command and preloads the native shim. It does not enable the camera in arbitrary processes. Stop the service when finished.

PRoot/glibc programs need their own fauxdev build and setup; this ARM64 Bionic library is for native Termux programs. Device-side Termux capture and F-Droid compatibility are not yet validated.
PRoot/glibc programs need their own fauxdev build and setup; this ARM64 Bionic library is for native Termux programs. The local F-Droid/Pixel result does not establish compatibility across devices or Termux variants.
11 changes: 9 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:sharedUserId="com.termux">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
<queries>
<package android:name="com.termux" />
</queries>
<application android:label="Camera2Termux" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:usesCleartextTraffic="false">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
Expand All @@ -13,5 +15,10 @@
</intent-filter>
</activity>
<service android:name=".CameraService" android:exported="false" android:foregroundServiceType="camera" />
<receiver android:name=".CameraFdReceiver" android:exported="true">
<intent-filter>
<action android:name="org.randomcoder.camera2termux.REQUEST_FD" />
</intent-filter>
</receiver>
</application>
</manifest>
1 change: 1 addition & 0 deletions app/src/main/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.22)
project(camera2termux C)
set(CMAKE_C_STANDARD 11)
add_library(fauxdev-camera SHARED
camera_socket.c
../../../../fauxdev/android/camera_broker.c
../../../../fauxdev/android/yuv_rgb.c
../../../../fauxdev/src/transport.c)
Expand Down
30 changes: 30 additions & 0 deletions app/src/main/cpp/camera_socket.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <errno.h>
#include <jni.h>
#include <stddef.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

JNIEXPORT jint JNICALL
Java_org_randomcoder_udroid_camera_CameraBrokerBridge_connect(JNIEnv *env, jclass type, jstring path) {
(void)type;
if (!path) return -EINVAL;
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
if (!name) return -ENOMEM;
struct sockaddr_un address = {.sun_family = AF_UNIX};
int fd = -ENAMETOOLONG;
size_t length = strlen(name);
if (length < sizeof(address.sun_path)) {
memcpy(address.sun_path, name, length + 1);
fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (fd >= 0 && connect(fd, (const struct sockaddr *)&address,
offsetof(struct sockaddr_un, sun_path) + length + 1) < 0) {
int error = errno;
close(fd);
fd = -error;
}
}
(*env)->ReleaseStringUTFChars(env, path, name);
return fd;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ final class CameraBrokerBridge {
static native boolean prepare();
static native int run(String socketPath);
static native void stop();
static native int connect(String socketPath);
static native String inventory();
private CameraBrokerBridge() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.randomcoder.udroid.camera;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.util.Log;
import java.io.File;

/** Hands the running broker's socket to a Termux-side Binder callback. */
public final class CameraFdReceiver extends BroadcastReceiver {
static final String ACTION = "org.randomcoder.camera2termux.REQUEST_FD";
static final int TRANSACTION_FD = IBinder.FIRST_CALL_TRANSACTION;

@Override public void onReceive(Context context, Intent intent) {
// shortcut: sender UID is available only on API 34+, keep older Android closed until authenticated transport exists.
if (!ACTION.equals(intent.getAction()) || Build.VERSION.SDK_INT < 34) return;
int uid = getSentFromUid();
Log.i("Camera2Termux", "Camera FD request from UID " + uid);
int termuxUid;
try {
termuxUid = context.getPackageManager().getPackageUid("com.termux", 0);
} catch (PackageManager.NameNotFoundException error) {
return;
}
boolean debugShell = uid == Process.SHELL_UID &&
(context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
if (uid != termuxUid && !debugShell) {
Log.w("Camera2Termux", "Rejected camera FD request from UID " + uid);
return;
}
IBinder callback = intent.getExtras() == null ? null : intent.getExtras().getBinder("callback");
if (callback == null) return;
File path = new File(context.getFilesDir(), "camera.sock");
int socketFd = CameraBrokerBridge.connect(path.getAbsolutePath());
if (socketFd < 0) {
Log.e("Camera2Termux", "Camera broker connect failed: errno " + -socketFd);
return;
}
try (ParcelFileDescriptor fd = ParcelFileDescriptor.adoptFd(socketFd)) {
Parcel data = Parcel.obtain();
try {
fd.writeToParcel(data, 0);
if (!callback.transact(TRANSACTION_FD, data, null, IBinder.FLAG_ONEWAY))
Log.e("Camera2Termux", "Camera FD callback rejected the transaction");
} finally {
data.recycle();
}
} catch (Exception error) {
Log.e("Camera2Termux", "Camera FD handoff failed", error);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public final class CameraService extends Service {
Notification notification = new Notification.Builder(this, CHANNEL)
.setSmallIcon(android.R.drawable.ic_menu_camera)
.setContentTitle("Camera available to Termux")
.setContentText("Camera2Termux is streaming only while this service runs")
.setContentText("Camera available while service runs; capture starts when a client streams")
.setOngoing(true)
.addAction(new Notification.Action.Builder(null, "Stop", stopAction).build())
.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package org.randomcoder.udroid.camera;

import android.content.Context;
import android.content.ComponentName;
import android.content.Intent;
import android.app.BroadcastOptions;
import android.content.pm.ApplicationInfo;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.system.Os;
import android.system.OsConstants;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/** Receives an authorized broker FD, then replaces this app_process helper with a Termux command. */
public final class CameraTermuxLauncher {
public static void main(String[] args) throws Exception {
if (args.length == 0) throw new IllegalArgumentException("Usage: camera2termux-run COMMAND [ARG...]");
Looper.prepareMainLooper();
// app_process has no app Context; use Termux's UID and package identity for the broadcast.
Class<?> threadClass = Class.forName("android.app.ActivityThread");
Object thread = threadClass.getMethod("systemMain").invoke(null);
Context system = (Context) threadClass.getMethod("getSystemContext").invoke(thread);
String caller = Process.myUid() == Process.SHELL_UID ? "com.android.shell" : "com.termux";
ApplicationInfo info = system.getPackageManager().getApplicationInfo(caller, 0);
Object loaded = threadClass.getMethod("getPackageInfoNoCheck", ApplicationInfo.class).invoke(thread, info);
Method create = Class.forName("android.app.ContextImpl").getDeclaredMethod(
"createAppContext", threadClass, Class.forName("android.app.LoadedApk"));
create.setAccessible(true);
Context context = (Context) create.invoke(null, thread, loaded);
CountDownLatch received = new CountDownLatch(1);
AtomicReference<ParcelFileDescriptor> brokerFd = new AtomicReference<>();
AtomicReference<Exception> failure = new AtomicReference<>();
IBinder callback = new Binder() {
@Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
if (code != CameraFdReceiver.TRANSACTION_FD) return false;
ParcelFileDescriptor fd = null;
try {
fd = ParcelFileDescriptor.CREATOR.createFromParcel(data);
if (!OsConstants.S_ISSOCK(Os.fstat(fd.getFileDescriptor()).st_mode))
throw new IllegalStateException("Received descriptor is not a socket");
brokerFd.set(fd);
fd = null;
} catch (Exception error) {
failure.set(error);
} finally {
if (fd != null) try { fd.close(); } catch (Exception ignored) { }
}
received.countDown();
return true;
}
};
Bundle extras = new Bundle();
extras.putBinder("callback", callback);
Intent request = new Intent(CameraFdReceiver.ACTION)
.setComponent(new ComponentName("org.randomcoder.camera2termux",
"org.randomcoder.udroid.camera.CameraFdReceiver"))
.putExtras(extras);
context.sendBroadcast(request, null, BroadcastOptions.makeBasic()
.setShareIdentityEnabled(true).toBundle());
if (!received.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("No camera FD received");
if (failure.get() != null) throw failure.get();
try (ParcelFileDescriptor fd = brokerFd.get()) {
if (fd == null) throw new IllegalStateException("Camera FD callback returned nothing");
String prefix = System.getenv("PREFIX");
if (prefix == null || prefix.isEmpty()) prefix = "/data/data/com.termux/files/usr";
String library = prefix + "/lib/libfauxdev-termux.so";
if (!new File(library).isFile())
throw new IllegalStateException("Missing Termux camera library: " + library);
String command = resolveCommand(args[0], System.getenv("PATH"));
int flags = Os.fcntlInt(fd.getFileDescriptor(), OsConstants.F_GETFD, 0);
Os.fcntlInt(fd.getFileDescriptor(), OsConstants.F_SETFD, flags & ~OsConstants.FD_CLOEXEC);
ArrayList<String> environment = new ArrayList<>();
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
if (!entry.getKey().equals("LD_PRELOAD") && !entry.getKey().equals("FAUXDEV_VIDEO_FD") &&
!entry.getKey().equals("FAUXDEV_VIDEO_SOCKET"))
environment.add(entry.getKey() + "=" + entry.getValue());
}
String preload = System.getenv("LD_PRELOAD");
environment.add("LD_PRELOAD=" + library + (preload == null ? "" : ":" + preload));
environment.add("FAUXDEV_VIDEO_FD=" + fd.getFd());
Os.execve(command, args, environment.toArray(new String[0]));
}
}

private static String resolveCommand(String name, String path) {
if (name.contains("/")) return new File(name).getAbsolutePath();
if (path != null) for (String directory : path.split(":")) {
File candidate = new File(directory, name);
if (candidate.isFile() && candidate.canExecute()) return candidate.getAbsolutePath();
}
throw new IllegalArgumentException("Command not found: " + name);
}
}
35 changes: 33 additions & 2 deletions app/src/main/java/org/randomcoder/udroid/camera/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public final class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1;
private static final int INVENTORY_REQUEST = 2;
private TextView status;

@Override public void onCreate(Bundle state) {
Expand All @@ -20,8 +24,7 @@ public final class MainActivity extends Activity {
int padding = (int) (24 * getResources().getDisplayMetrics().density);
layout.setPadding(padding, padding, padding, padding);
TextView help = new TextView(this);
help.setText("Camera2Termux\n\nStart the camera here, then run a native Termux program with camera2termux-run.\n\nSocket: "
+ new java.io.File(getFilesDir(), "camera.sock").getAbsolutePath());
help.setText("Camera2Termux\n\nStart the camera here, then use camera2termux-run in native Termux. Camera sharing is experimental; stop the service when finished.");
layout.addView(help);
status = new TextView(this);
status.setText("Camera is off");
Expand All @@ -41,6 +44,14 @@ public final class MainActivity extends Activity {
status.setText("Camera stopped");
});
layout.addView(stop);
Button inventory = new Button(this);
inventory.setText("Camera inventory");
inventory.setOnClickListener(v -> {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
showInventory();
else requestPermissions(new String[]{Manifest.permission.CAMERA}, INVENTORY_REQUEST);
});
layout.addView(inventory);
setContentView(layout);
}

Expand All @@ -49,9 +60,29 @@ public final class MainActivity extends Activity {
if (requestCode == CAMERA_REQUEST) {
if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) startCamera();
else status.setText("Camera permission denied");
} else if (requestCode == INVENTORY_REQUEST) {
if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) showInventory();
else status.setText("Camera permission denied");
}
}

private void showInventory() {
String report = CameraBrokerBridge.inventory();
TextView text = new TextView(this);
text.setText(report);
text.setTextIsSelectable(true);
text.setTypeface(Typeface.MONOSPACE);
int padding = (int) (16 * getResources().getDisplayMetrics().density);
text.setPadding(padding, padding, padding, padding);
ScrollView scroll = new ScrollView(this);
scroll.addView(text);
new AlertDialog.Builder(this)
.setTitle("Camera inventory")
.setView(scroll)
.setPositiveButton("Close", null)
.show();
}

private void startCamera() {
try {
startForegroundService(new Intent(this, CameraService.class).setAction(CameraService.START));
Expand Down
11 changes: 5 additions & 6 deletions scripts/camera2termux-run
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ if [ "$#" -eq 0 ]; then
echo 'Usage: camera2termux-run COMMAND [ARG...]' >&2
exit 2
fi
lib="/data/data/com.termux/files/usr/lib/libfauxdev-termux.so"
if [ ! -r "$lib" ]; then
echo "Camera2Termux library missing: $lib" >&2
apk=$(/system/bin/pm path org.randomcoder.camera2termux | sed -n '1s/^package://p')
if [ -z "$apk" ]; then
echo 'Camera2Termux app is not installed' >&2
exit 1
fi
export FAUXDEV_VIDEO_SOCKET=/data/data/org.randomcoder.camera2termux/files/camera.sock
export LD_PRELOAD="$lib${LD_PRELOAD:+:$LD_PRELOAD}"
exec "$@"
CLASSPATH="$apk" exec /system/bin/app_process / \
org.randomcoder.udroid.camera.CameraTermuxLauncher "$@"
Loading
Loading