Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
chdkbridge.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file chdkbridge.c
20 * @brief Standalone USB PTP client for CHDK JPEG capture and normalized zoom.
21 * @details One invocation owns one USB interface and PTP session. Standard PTP
22 * framing carries CHDK vendor commands; small Lua scripts execute on the camera,
23 * not on the host. USB access uses Linux usbfs directly (usbfs.h); no USB
24 * library is loaded. This standalone C client implements camera control
25 * directly over USB PTP.
26 * @warning A failed transaction is not retried: capture or lens movement may
27 * already have occurred. Fake-USB tests are not physical-camera validation.
28 */
29#define _POSIX_C_SOURCE 200809L
30#define _DEFAULT_SOURCE
31#include <dlfcn.h>
32#include <errno.h>
33#include <math.h>
34#include <fcntl.h>
35#include <limits.h>
36#include <poll.h>
37#include <signal.h>
38#include <stdbool.h>
39#include <stdint.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <sys/stat.h>
44#include <sys/wait.h>
45#include <time.h>
46#include <unistd.h>
47#include "usbfs.h"
48#include "version.h"
49
50/** @brief USB operations used by the application; tests substitute fakes. */
51static struct {
52 int (*devices_open)(struct usbfs_devices *);
53 int (*devices_next)(struct usbfs_devices *, struct usbfs_device *);
54 void (*devices_close)(struct usbfs_devices *);
55 int (*active_config)(const struct usbfs_device *, uint8_t *, size_t, const uint8_t **, size_t *);
56 int (*open)(const struct usbfs_device *, struct usbfs_handle *);
57 void (*close)(struct usbfs_handle *);
58 int (*claim_interface)(struct usbfs_handle *, int);
59 int (*release_interface)(struct usbfs_handle *, int);
60 int (*set_alternate)(struct usbfs_handle *, int, int);
61 int (*bulk_transfer)(struct usbfs_handle *, unsigned char, unsigned char *, int, int *, unsigned);
62 int (*control_transfer)(struct usbfs_handle *, uint8_t, uint8_t, uint16_t, uint16_t,
63 unsigned char *, uint16_t, unsigned);
64 int (*clear_halt)(struct usbfs_handle *, unsigned char);
65} usb = {
69};
70
71/** @brief Wire constants and resource limits, not an exhaustive PTP API. */
72enum {
75 PTP_OK = 0x2001, PTP_CHDK = 0x9999,
87 /* 0x100 rejects an existing script; 0x200/0x400 flush old message queues. */
93 MAX_DOWNLOAD = 256 * 1024 * 1024
94};
95
96/**
97 * @brief Single-session USB transport with bounded input staging.
98 * @details Unread bytes occupy buffered[offset..available). They may belong to
99 * the next container: USB transfer boundaries need not match PTP containers.
100 * The caller owns the handle and maintains one overall operation deadline.
101 */
102struct transport {
103 struct usbfs_handle *handle; /**< Borrowed handle for the claimed interface. */
104 uint8_t input_endpoint, output_endpoint; /**< Discovered bulk endpoint addresses. */
105 unsigned output_packet_size; /**< Bulk-OUT wMaxPacketSize; zero disables ZLP termination. */
106 uint32_t transaction_id; /**< Next command ID; OpenSession starts with zero. */
107 uint8_t buffered[TRANSFER_SIZE]; /**< Fixed 64 KiB receive buffer, never image-sized. */
108 size_t offset, available; /**< Consumed offset and valid-byte count in buffered. */
109 uint64_t deadline_ms; /**< Absolute CLOCK_MONOTONIC deadline in milliseconds. */
113};
114
115/** @brief Validated successful PTP response and optional data-phase length. */
116struct response {
117 uint32_t parameters[5]; /**< Decoded little-endian response parameters. */
118 size_t count, data_size; /**< Parameter count and bytes in the received data phase. */
119};
120
126
127static bool download_direct_chunk(struct transport *transport, FILE *file,
128 struct direct_download *download);
129
130/** @brief Signal-safe cancellation flag checked before blocking USB calls. */
131static volatile sig_atomic_t interrupted;
132
133/** @brief Request cancellation without allocation, I/O, or USB calls in a signal handler. */
134static void interrupt_handler(int signal_number)
135{
136 (void)signal_number;
137 interrupted = 1;
138}
139
140/** @brief Read a wall-clock-independent time base; return zero if the clock fails. */
141static uint64_t monotonic_ms(void)
142{
143 struct timespec now;
144 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) return 0;
145 return (uint64_t)now.tv_sec * 1000 + (uint64_t)now.tv_nsec / 1000000;
146}
147
148/**
149 * @brief Compute the next USB call's timeout within the operation deadline.
150 * @param transport Active session and its absolute deadline.
151 * @return 1..10000 ms, or zero for cancellation, expiry, or clock failure.
152 * @note A zero result means "do not call"; USB calls always receive a nonzero
153 * timeout. Calls default to a 1 s cap; --usb-timeout
154 * permits 50..10000 ms without extending the overall operation deadline.
155 */
156static unsigned remaining_ms(const struct transport *transport)
157{
158 uint64_t now = monotonic_ms();
159 if ((interrupted && !transport->closing_session) || !now || now >= transport->deadline_ms) return 0;
160 uint64_t remaining = transport->deadline_ms - now;
161 unsigned limit = transport->usb_timeout_ms ? transport->usb_timeout_ms : 1000;
162 return remaining > limit ? limit : (unsigned)remaining;
163}
164
165/** @brief Select a recovery hint for a USB transport failure.
166 * @param error usbfs wrapper status.
167 * @return Borrowed static diagnostic.
168 * @details Distinguish device loss, access and ownership from timeouts that
169 * may leave a completed shot on the camera. Do not prescribe blind replay. */
170static const char *usb_failure_hint(int error)
171{
172 switch (error) {
173 case USBFS_ERROR_NO_DEVICE: return "camera disconnected; check camera power, data cable and hub; rediscover with --list";
174 case USBFS_ERROR_ACCESS: return "grant the USHER service user read/write access to the camera USB device (plugdev); do not run the service as root";
175 case USBFS_ERROR_BUSY: return "selected desktop camera mount could not be released or another PTP client still owns the camera; no USB reset is attempted";
176 case USBFS_ERROR_TIMEOUT: return "check camera power, USB cable/hub, SD-card readiness and active scripts; a shot may already exist on SD";
177 case USBFS_ERROR_IO: return "check USB power and cable/hub integrity; other cameras are not reset";
178 default: return "inspect the USB error and camera state; failed commands are not replayed";
179 }
180}
181
182/** @brief Decode a 16-bit little-endian value without alignment assumptions.
183 * @param bytes At least two readable bytes. */
184static uint16_t decode16(const uint8_t *bytes)
185{
186 return (uint16_t)((uint16_t)bytes[0] | (uint16_t)bytes[1] << 8);
187}
188
189/** @brief Decode a 32-bit little-endian value without native-endian casts.
190 * @param bytes At least four readable bytes. */
191static uint32_t decode32(const uint8_t *bytes)
192{
193 return (uint32_t)bytes[0] | (uint32_t)bytes[1] << 8 |
194 (uint32_t)bytes[2] << 16 | (uint32_t)bytes[3] << 24;
195}
196
197/** @brief Encode a wire value into two writable bytes.
198 * @param bytes Destination of at least two bytes.
199 * @param value Host-order value to encode little-endian. */
200static void encode16(uint8_t *bytes, uint16_t value)
201{
202 bytes[0] = (uint8_t)value;
203 bytes[1] = (uint8_t)(value >> 8);
204}
205
206/** @brief Encode a wire value into four writable bytes.
207 * @param bytes Destination of at least four bytes.
208 * @param value Host-order value to encode little-endian. */
209static void encode32(uint8_t *bytes, uint32_t value)
210{
211 for (size_t index = 0; index < 4; ++index)
212 bytes[index] = (uint8_t)(value >> (index * 8));
213}
214
215/**
216 * @brief Submit one complete, small outbound PTP container.
217 * @param transport Claimed USB transport.
218 * @param bytes Encoded container; the URB API requires a non-const buffer.
219 * @param length Number of bytes to transmit, representable by an int.
220 * @return True only when the complete container was transferred.
221 * @warning Partial writes abort rather than resend a possibly executed command.
222 */
223static bool send_packet(struct transport *transport, uint8_t *bytes, size_t length)
224{
225 int transferred = 0;
226 unsigned timeout = remaining_ms(transport);
227 if (!timeout || length > INT_MAX) return false;
228 int result = usb.bulk_transfer(transport->handle, transport->output_endpoint,
229 bytes, (int)length, &transferred, timeout);
230 if (result != 0 || transferred != (int)length) {
231 fprintf(stderr, "USB send failed: %s (%d/%zu bytes); %s\n",
232 usbfs_error_name(result), transferred, length, usb_failure_hint(result));
233 return false;
234 }
235 return true;
236}
237
238/**
239 * @brief Refill empty bounded USB storage without replaying a command.
240 * @param transport Input stream whose previous bytes have been consumed.
241 * @return False on cancellation, exhausted deadline, repeated empty reads, or a USB error.
242 * @details Read-ahead is retained for subsequent headers or payloads. Failed
243 * calls may already have consumed part of the stream; do not retry parsing.
244 */
246{
247 unsigned empty_reads = 0;
248 for (;;) {
249 unsigned timeout = remaining_ms(transport);
250 int transferred = 0;
251 if (!timeout) return false;
252 int result = usb.bulk_transfer(transport->handle, transport->input_endpoint,
254 &transferred, timeout);
255 if (transferred < 0 || transferred > TRANSFER_SIZE) return false;
256 /* A ZLP can terminate a data phase at a packet-size boundary. Retrying a
257 * read is safe; the corresponding command is never retransmitted. */
258 if (!transferred && (result == 0 || result == USBFS_ERROR_INTERRUPTED)) {
259 if (++empty_reads <= 3) continue;
260 fprintf(stderr, "USB receive made no progress after repeated empty/interrupted reads\n");
261 return false;
262 }
263 if (!transferred || (result != 0 && result != USBFS_ERROR_TIMEOUT &&
265 fprintf(stderr, "USB receive failed: %s; %s\n", usbfs_error_name(result), usb_failure_hint(result));
266 return false;
267 }
268 /* usbfs may return useful bytes with timeout/interruption. Preserve them
269 * instead of shifting the stream by discarding a partially read header. */
270 transport->offset = 0;
271 transport->available = (size_t)transferred;
272 return true;
273 }
274}
275
276/** @brief Read an exact bounded payload across arbitrary USB transfer splits.
277 * @param transport Input stream, including retained read-ahead.
278 * @param destination Writable region of at least length bytes.
279 * @param length Exact number of bytes required by the parser.
280 * @return True only when the requested bytes have been copied. */
281static bool receive_bytes(struct transport *transport, uint8_t *destination, size_t length)
282{
283 while (length) {
284 if (!remaining_ms(transport)) return false;
285 if (transport->offset == transport->available && !refill_buffer(transport)) return false;
286 size_t amount = transport->available - transport->offset;
287 if (amount > length) amount = length;
288 for (size_t index = 0; index < amount; ++index)
289 destination[index] = transport->buffered[transport->offset + index];
290 transport->offset += amount;
291 destination += amount;
292 length -= amount;
293 }
294 return true;
295}
296
297/** @brief Describe standard PTP response failures without triggering recovery actions. */
298static const char *ptp_response_name(uint16_t code)
299{
300 switch (code) {
301 case 0x2002: return "general camera error";
302 case 0x2003: return "session not open";
303 case 0x2005: return "operation not supported";
304 case 0x200f: return "access denied";
305 case 0x2019: return "camera busy; stop competing clients or wait for the current action";
306 case 0x201d: return "invalid parameter";
307 case 0x201e: return "session already open; another client may own the camera";
308 default: return "unrecognized PTP response";
309 }
310}
311
312/**
313 * @brief Perform command, optional data, and response phases for one PTP operation.
314 * @param transport Single-session transport; transaction_id advances once.
315 * @param operation Standard PTP or vendor operation code.
316 * @param parameters Host-order command parameters, or NULL for zero parameters.
317 * @param parameter_count Number of command parameters, at most five.
318 * @param outgoing Optional host-to-camera data; NULL means no outgoing data phase.
319 * @param outgoing_size Payload size, limited to SCRIPT_CAPACITY bytes.
320 * @param incoming Optional destination for a small camera-to-host payload.
321 * @param capacity Writable size of incoming; ignored when file is supplied.
322 * @param file Optional stream for image data; takes precedence over incoming.
323 * @param response Successful response parameters and data size; reset on entry.
324 * @return True only after a matching PTP_OK response and any required data phase.
325 * @details A data phase is bounded before it is consumed. Response bodies contain
326 * at most five 32-bit parameters. This minimal client does not recover the USB
327 * stream after malformed input or retry non-idempotent operations.
328 */
329static bool transaction(struct transport *transport, uint16_t operation,
330 const uint32_t *parameters, size_t parameter_count,
331 const uint8_t *outgoing, size_t outgoing_size,
332 uint8_t *incoming, size_t capacity, FILE *file,
333 struct response *response)
334{
335 uint8_t command[32] = {0}, header[12], payload[SCRIPT_CAPACITY + 12];
336 if (parameter_count > 5 || outgoing_size > sizeof(payload) - 12) return false;
337 *response = (struct response){0};
338 uint32_t transaction_id = transport->transaction_id++;
339 encode32(command, (uint32_t)(12 + parameter_count * 4));
340 encode16(command + 4, PTP_COMMAND);
341 encode16(command + 6, operation);
342 encode32(command + 8, transaction_id);
343 for (size_t index = 0; index < parameter_count; ++index)
344 encode32(command + 12 + index * 4, parameters[index]);
345 if (!send_packet(transport, command, 12 + parameter_count * 4)) return false;
346 if (outgoing) {
347 encode32(payload, (uint32_t)(12 + outgoing_size));
348 encode16(payload + 4, PTP_DATA);
349 encode16(payload + 6, operation);
350 encode32(payload + 8, transaction_id);
351 for (size_t index = 0; index < outgoing_size; ++index)
352 payload[12 + index] = outgoing[index];
353 if (!send_packet(transport, payload, 12 + outgoing_size)) return false;
354 /* A container ending exactly on a packet boundary needs a ZLP, as chdkptp sends. */
355 if (transport->output_packet_size && (12 + outgoing_size) % transport->output_packet_size == 0 &&
356 !send_packet(transport, payload, 0)) return false;
357 }
358 /* Parse framing independently of USB packet boundaries. A transaction may
359 * carry one incoming data container followed by its response container. */
360 bool received_data = false;
361 for (;;) {
362 if (!receive_bytes(transport, header, sizeof(header))) return false;
363 uint32_t length = decode32(header);
364 uint16_t type = decode16(header + 4), code = decode16(header + 6);
365 if (length < 12 || decode32(header + 8) != transaction_id) {
366 fprintf(stderr, "Invalid PTP container or transaction ID\n");
367 return false;
368 }
369 size_t body_size = length - 12;
370 if (type == PTP_DATA) {
371 size_t maximum = file ? (transport->max_download ? transport->max_download : MAX_DOWNLOAD) : capacity;
372 if (received_data || code != operation || (!incoming && !file) ||
373 body_size > maximum) {
374 fprintf(stderr, "Rejected unexpected or oversized PTP data (%zu bytes)\n", body_size);
375 return false;
376 }
377 received_data = true;
378 response->data_size = body_size;
379 /* Stream images directly from receive storage; small replies use bounded scratch storage. */
380 size_t position = 0;
381 while (position < body_size) {
382 if (!remaining_ms(transport)) return false;
383 size_t amount = body_size - position;
384 if (file) {
385 if (transport->offset == transport->available && !refill_buffer(transport)) return false;
387 if (amount > available) amount = available;
388 if (fwrite(transport->buffered + transport->offset, 1, amount, file) != amount) return false;
389 transport->offset += amount;
390 } else {
391 if (amount > sizeof(payload)) amount = sizeof(payload);
392 if (!receive_bytes(transport, payload, amount)) return false;
393 for (size_t index = 0; index < amount; ++index)
394 incoming[position + index] = payload[index];
395 }
396 position += amount;
397 }
398 continue;
399 }
400 if (type != PTP_RESPONSE || body_size > 20 || body_size % 4) return false;
401 if (!receive_bytes(transport, payload, body_size)) return false;
402 if (code != PTP_OK) {
403 fprintf(stderr, "PTP operation 0x%04x failed: response 0x%04x (%s)\n",
404 operation, code, ptp_response_name(code));
405 return false;
406 }
407 if ((incoming || file) && !received_data) return false;
408 response->count = body_size / 4;
409 for (size_t index = 0; index < response->count; ++index)
410 response->parameters[index] = decode32(payload + index * 4);
411 return true;
412 }
413}
414
415/**
416 * @brief Place a CHDK subcommand and argument in vendor operation 0x9999.
417 * @details Payloads and response validation are delegated to transaction().
418 */
419static bool chdk_call(struct transport *transport, uint32_t command, uint32_t argument,
420 const uint8_t *outgoing, size_t size, uint8_t *incoming,
421 size_t capacity, FILE *file, struct response *response)
422{
423 uint32_t parameters[2] = {command, argument};
424 return transaction(transport, PTP_CHDK, parameters, 2, outgoing, size,
425 incoming, capacity, file, response);
426}
427
428/** @brief Best-effort close of an owned session, even after cancellation, within one second. */
430{
433 if (transport->handle) transport->handle->cancel = NULL;
434 struct response response;
435 if (!transaction(transport, PTP_CLOSE_SESSION, NULL, 0, NULL, 0, NULL, 0, NULL, &response))
436 fprintf(stderr, "Owned PTP session close was not confirmed; no reset or takeover attempted\n");
437 transport->closing_session = false;
438}
439
440enum {
444};
445
446/**
447 * @brief Clear a session or stale data left by an interrupted earlier run.
448 * @param transport Claimed interface whose OpenSession just failed.
449 * @param interface_number Claimed still-image interface.
450 * @return True when the device is present and OpenSession may be retried once.
451 * @details Uses the still-image class requests and endpoint halt clearing, as
452 * chdkptp does; never resets the USB port. Stale input is drained with a bound.
453 */
454static bool recover_ptp(struct transport *transport, int interface_number)
455{
456 if (interface_number < 0 || interface_number > 255 || !remaining_ms(transport)) return false;
457 fprintf(stderr, "Recovering camera PTP state left by an earlier run (class reset, no USB port reset)\n");
458 unsigned char status[4] = {0};
459 const uint16_t index = (uint16_t)interface_number;
460 unsigned timeout = remaining_ms(transport);
461 if (!timeout) return false;
462 if (timeout > RECOVERY_CONTROL_MS) timeout = RECOVERY_CONTROL_MS;
464 0, index, status, sizeof(status), timeout);
465 if (result == USBFS_ERROR_NO_DEVICE) return false;
466 (void)usb.clear_halt(transport->handle, transport->input_endpoint);
467 (void)usb.clear_halt(transport->handle, transport->output_endpoint);
468 timeout = remaining_ms(transport);
469 if (!timeout) return false;
470 if (timeout > RECOVERY_CONTROL_MS) timeout = RECOVERY_CONTROL_MS;
472 0, index, NULL, 0, timeout);
473 if (result == USBFS_ERROR_NO_DEVICE) return false;
474 if (result < 0) fprintf(stderr, "PTP device reset request failed: %s\n", usbfs_error_name(result));
476 for (unsigned reads = 0; reads < RECOVERY_DRAIN_READS; ++reads) {
477 timeout = remaining_ms(transport);
478 if (!timeout) return false;
479 if (timeout > RECOVERY_DRAIN_MS) timeout = RECOVERY_DRAIN_MS;
480 int transferred = 0;
482 TRANSFER_SIZE, &transferred, timeout);
483 if (result == USBFS_ERROR_NO_DEVICE) return false;
484 if (transferred <= 0 || (result != 0 && result != USBFS_ERROR_TIMEOUT)) break;
485 }
486 timeout = remaining_ms(transport);
487 if (!timeout) return false;
488 if (timeout > RECOVERY_CONTROL_MS) timeout = RECOVERY_CONTROL_MS;
490 0, index, status, sizeof(status), timeout);
493 return transport->handle->fd >= 0;
494}
495
496/**
497 * @brief Report CHDK protocol and script capabilities without executing a script.
498 * @param transport Open session on one selected camera.
499 * @return True when version, scripting support, and status queries succeed.
500 * @note Does not enter record mode, drain messages, move the lens, or touch files.
501 */
502static bool camera_info(struct transport *transport)
503{
504 struct response response;
505 if (!chdk_call(transport, CHDK_VERSION, 0, NULL, 0, NULL, 0, NULL, &response) ||
506 response.count < 2) return false;
507 printf("CHDK PTP protocol: %u.%u\n", response.parameters[0], response.parameters[1]);
508 if (!chdk_call(transport, CHDK_SUPPORT, 0, NULL, 0, NULL, 0, NULL, &response) ||
509 response.count < 1) return false;
510 printf("Camera-side Lua: %s\n", response.parameters[0] & 1 ? "supported" : "not supported");
511 if (!chdk_call(transport, CHDK_STATUS, 0, NULL, 0, NULL, 0, NULL, &response) ||
512 response.count < 1) return false;
513 printf("Script running: %s; messages waiting: %s\n",
514 response.parameters[0] & 1 ? "yes" : "no", response.parameters[0] & 2 ? "yes" : "no");
515 return true;
516}
517
518/** @brief Translate a CHDK script status for diagnostics.
519 * @param error Camera-reported script error code.
520 * @return Borrowed static description, including an unknown-code fallback. */
521static const char *script_error_name(uint32_t error)
522{
523 switch (error) {
524 case CHDK_ERROR_NONE: return "unspecified script error";
525 case CHDK_ERROR_COMPILE: return "compilation error";
526 case CHDK_ERROR_RUNTIME: return "runtime error";
527 case CHDK_ERROR_RUNNING: return "another script is running; it was not interrupted";
528 default: return "unknown script error";
529 }
530}
531
532/** @brief Validate known message types and payload lengths, including empty-message zero padding. */
533static bool valid_script_message(const struct response *response, const uint8_t *message)
534{
535 if (response->count < 4) return false;
536 size_t length = response->parameters[3];
537 if (length) {
538 if (length != response->data_size) return false;
539 } else {
540 if (!response->data_size) return false;
541 for (size_t index = 0; index < response->data_size; ++index)
542 if (message[index]) return false;
543 }
544 uint32_t subtype = response->parameters[1];
545 switch (response->parameters[0]) {
547 return subtype == 0 && length == 0;
549 return subtype <= CHDK_ERROR_RUNTIME;
552 switch (subtype) {
553 case CHDK_UNSUPPORTED:
554 case CHDK_STRING:
555 case CHDK_TABLE: return true;
556 case CHDK_NIL: return length == 0;
557 case CHDK_BOOLEAN:
558 case CHDK_INTEGER: return length == sizeof(uint32_t);
559 default: return false;
560 }
561 default: return false;
562 }
563}
564
565/** @brief Sleep to a monotonic poll target without extending it on EINTR or exceeding the deadline. */
566static bool wait_script_poll(const struct transport *transport, unsigned interval_ms)
567{
568 uint64_t wake_ms = monotonic_ms() + interval_ms;
569 for (;;) {
570 unsigned remaining = remaining_ms(transport);
571 uint64_t now = monotonic_ms();
572 if (!remaining || !now || now >= transport->deadline_ms) return false;
573 if (now >= wake_ms) return true;
574 uint64_t delay_ms = wake_ms - now;
575 if (delay_ms > remaining) delay_ms = remaining;
576 struct timespec delay = {.tv_sec = (time_t)(delay_ms / 1000),
577 .tv_nsec = (long)(delay_ms % 1000) * 1000000};
578 if (nanosleep(&delay, NULL) != 0 && errno != EINTR) {
579 fprintf(stderr, "Camera script polling sleep failed: %s\n", strerror(errno));
580 return false;
581 }
582 }
583}
584
585/** @brief Wait within the deadline until no camera script is running; never interrupts one. */
587{
588 fprintf(stderr, "Waiting for a camera script left by an earlier run to finish\n");
589 unsigned poll_ms = SCRIPT_POLL_MIN_MS;
590 struct response response;
591 for (;;) {
592 if (!chdk_call(transport, CHDK_STATUS, 0, NULL, 0, NULL, 0, NULL, &response) ||
593 response.count < 1) return false;
594 if (!(response.parameters[0] & 1)) return true;
595 if (!wait_script_poll(transport, poll_ms)) return false;
596 poll_ms = poll_ms * 2 > SCRIPT_POLL_MAX_MS ? SCRIPT_POLL_MAX_MS : poll_ms * 2;
597 }
598}
599
600static const char record_mode_script[] =
601 "if not get_mode() then set_record(true) end\n"
602 "local started=get_tick_count()\n"
603 "while not get_mode() and bitand(get_tick_count()-started,2147483647)<5000 do sleep(100) end\n"
604 "if not get_mode() then error('cannot enter record mode') end\n";
605#define SCRIPT_BODY_CAPACITY (SCRIPT_CAPACITY - sizeof(record_mode_script))
606
607/**
608 * @brief Run camera-side Lua and wait for its correlated string return value.
609 * @param transport Open CHDK PTP session and overall operation deadline.
610 * @param body Independently authored script body.
611 * @param result Destination for one nonempty, NUL-terminated return string.
612 * @param result_capacity Total writable capacity, including the terminator.
613 * @param direct_file Optional JPEG stream serviced while the script runs.
614 * @param enter_record Prepend record-mode setup for existing capture/configuration operations.
615 * @return True when this script has returned a string and is no longer running.
616 * @details Requires CHDK protocol 2.6+ within major version 2. Existing scripts
617 * are not killed. Messages belonging to another script ID are ignored, camera
618 * errors fail the operation, and an oversized or embedded-NUL result is rejected.
619 * @warning Host cancellation/timeout does not stop a script already on the camera.
620 */
621static bool run_script_operation(struct transport *transport, const char *body,
622 char *result, size_t result_capacity, FILE *direct_file,
623 bool enter_record)
624{
625 char script[SCRIPT_CAPACITY];
626 int script_length = snprintf(script, sizeof(script), "%s%s", enter_record ? record_mode_script : "", body);
627 if (!result_capacity || script_length < 0 || (size_t)script_length + 1 > sizeof(script))
628 return false;
629 result[0] = '\0';
630 struct response response;
631 if (!chdk_call(transport, CHDK_VERSION, 0, NULL, 0, NULL, 0, NULL, &response) ||
632 response.count < 2 || response.parameters[0] != 2 || response.parameters[1] < 6) {
633 fprintf(stderr, "CHDK PTP protocol 2.6 or later (major 2) is required\n");
634 return false;
635 }
636 if (!chdk_call(transport, CHDK_SUPPORT, 0, NULL, 0, NULL, 0, NULL, &response) ||
637 response.count < 1 || !(response.parameters[0] & 1)) {
638 fprintf(stderr, "Camera does not report CHDK Lua support; no script was started\n");
639 return false;
640 }
642 (const uint8_t *)script, (size_t)script_length + 1, NULL, 0, NULL, &response)) {
643 fprintf(stderr, "Camera script startup transaction failed; execution state is unknown, not retried\n");
644 return false;
645 }
646 /* A bounded script left by an interrupted earlier run is never killed; wait once for it. */
649 (const uint8_t *)script, (size_t)script_length + 1, NULL, 0, NULL, &response)) {
650 fprintf(stderr, "Camera script startup transaction failed; execution state is unknown, not retried\n");
651 return false;
652 }
653 if (response.count < 2) {
654 fprintf(stderr, "Malformed camera script startup response; execution state is unknown\n");
655 return false;
656 }
658 fprintf(stderr, "Camera rejected script: %s (0x%08x)\n",
660 return false;
661 }
662 uint32_t script_id = response.parameters[0];
663 bool have_result = false;
664 struct direct_download download = {0};
665 unsigned poll_ms = SCRIPT_POLL_MIN_MS;
666 while (remaining_ms(transport)) {
667 if (!chdk_call(transport, CHDK_STATUS, 0, NULL, 0, NULL, 0, NULL, &response) ||
668 response.count < 1) return false;
669 uint32_t status = response.parameters[0];
670 /* Drain messages even after RUN clears; a script's final return may still
671 * be queued. Accept it only if the script ID matches ExecuteScript's ID. */
672 if (status & 2) {
673 uint8_t message[4096];
674 if (!chdk_call(transport, CHDK_MESSAGE, 0, NULL, 0, message,
675 sizeof(message), NULL, &response)) return false;
676 if (!valid_script_message(&response, message)) {
677 fprintf(stderr, "Malformed camera script message: %zu parameters, %zu payload bytes\n",
679 return false;
680 }
682 if (response.parameters[2] != script_id) continue;
683 size_t length = response.parameters[3];
685 fprintf(stderr, "Camera script %u %s (0x%08x): %.*s\n", script_id,
687 (int)length, (char *)message);
688 return false;
689 }
691 if (response.parameters[1] != CHDK_STRING || have_result ||
692 !length || length >= result_capacity) {
693 fprintf(stderr, "Invalid camera script return; expected one nonempty bounded string\n");
694 return false;
695 }
696 for (size_t index = 0; index < length; ++index) {
697 if (!message[index]) {
698 result[0] = '\0';
699 fprintf(stderr, "Invalid embedded NUL in camera script return\n");
700 return false;
701 }
702 result[index] = (char)message[index];
703 }
704 result[length] = '\0';
705 have_result = true;
706 }
707 if (direct_file && response.parameters[0] == CHDK_MESSAGE_USER) {
708 static const char ready[] = "Direct ready";
709 if (download.armed || response.parameters[1] != CHDK_STRING ||
710 length != sizeof(ready) - 1 || memcmp(message, ready, sizeof(ready) - 1)) {
711 fprintf(stderr, "Unexpected direct capture script message\n");
712 return false;
713 }
714 download.armed = true;
715 }
716 poll_ms = SCRIPT_POLL_MIN_MS;
717 continue;
718 }
719 }
720 if (direct_file && download.armed && !download.complete) {
721 if (!chdk_call(transport, CHDK_CAPTURE_READY, 0, NULL, 0, NULL, 0, NULL, &response) ||
722 response.count != 2) return false;
723 uint32_t ready = response.parameters[0];
724 if (ready != 0 && ready != CHDK_CAPTURE_JPEG) {
725 fprintf(stderr, "Direct JPEG capture unavailable or cancelled (0x%08x)\n", ready);
726 return false;
727 }
728 if (ready == CHDK_CAPTURE_JPEG) {
729 if (!response.parameters[1] ||
730 (download.image_number && download.image_number != response.parameters[1])) {
731 fprintf(stderr, "Direct JPEG image identity changed during transfer\n");
732 return false;
733 }
734 download.image_number = response.parameters[1];
735 if (!download_direct_chunk(transport, direct_file, &download)) return false;
736 if (download.complete) {
737 static const uint8_t done[] = "Direct done";
738 if (!chdk_call(transport, CHDK_WRITE_MESSAGE, script_id, done, sizeof(done) - 1,
739 NULL, 0, NULL, &response) || response.count != 1 || response.parameters[0] != 0)
740 return false;
741 }
742 poll_ms = SCRIPT_POLL_MIN_MS;
743 continue;
744 }
745 }
746 if (!(status & 1)) {
747 if (!have_result || (direct_file && !download.complete)) {
748 fprintf(stderr, "Camera script ended without its expected return value\n");
749 return false;
750 }
751 break;
752 }
753 if (!wait_script_poll(transport, poll_ms)) return false;
754 if (poll_ms < SCRIPT_POLL_MAX_MS) {
755 poll_ms *= 2;
756 if (poll_ms > SCRIPT_POLL_MAX_MS) poll_ms = SCRIPT_POLL_MAX_MS;
757 }
758 }
759 if (!have_result || !remaining_ms(transport)) return false;
760 if (direct_file) {
761 char expected[64];
762 int length = snprintf(expected, sizeof(expected), "Direct JPEG %u", download.image_number);
763 if (!download.complete || length < 0 || (size_t)length >= sizeof(expected) || strcmp(result, expected)) {
764 fprintf(stderr, "Direct JPEG and script image identities do not match\n");
765 return false;
766 }
767 fprintf(stderr, "Direct JPEG image=%u bytes=%zu transferred=%zu; no SD JPEG retained\n",
768 download.image_number, download.extent, download.received);
769 }
770 return true;
771}
772
773/** @brief Execute a capture-path script without direct-download output.
774 * @param transport Active PTP session and deadline.
775 * @param body Camera-side Lua source.
776 * @param[out] result Caller buffer for the validated script result.
777 * @param result_capacity Buffer size including the terminator.
778 * @return True after the script operation succeeds.
779 * @details Reuse the common script runner with the capture-path policy so
780 * ordinary SD capture and direct transfer share result validation. */
781static bool run_script(struct transport *transport, const char *body,
782 char *result, size_t result_capacity)
783{
784 return run_script_operation(transport, body, result, result_capacity, NULL, true);
785}
786
787static const char retract_lens_script[] =
788 "if type(get_mode)~='function' or type(get_shooting)~='function' or "
789 "type(get_tick_count)~='function' or type(sleep)~='function' then error('missing playback API') end\n"
790 "if get_shooting() then error('camera is shooting; lens retract rejected') end\n"
791 "local record=get_mode()\n"
792 "if type(record)~='boolean' then error('invalid camera mode') end\n"
793 "if record then\n"
794 " if type(switch_mode_usb)=='function' then switch_mode_usb(0)\n"
795 " elseif type(set_record)=='function' then set_record(false)\n"
796 " else error('missing playback transition API') end\n"
797 " local started=get_tick_count()\n"
798 " while get_mode() and bitand(get_tick_count()-started,2147483647)<5000 do sleep(50) end\n"
799 " if get_mode()~=false then error('cannot enter playback mode') end\n"
800 "end\n"
801 "return 'Playback confirmed; physical lens retraction not verified'\n";
802
803/** @brief Ask the camera to enter playback and confirm the resulting mode.
804 * @param transport Active PTP session.
805 * @return True if playback was confirmed.
806 * @warning Success does not establish physical lens position. */
807static bool retract_lens(struct transport *transport)
808{
809 char result[256];
810 if (!run_script_operation(transport, retract_lens_script, result, sizeof(result), NULL, false) ||
811 strcmp(result, "Playback confirmed; physical lens retraction not verified")) return false;
812 printf("%s\n", result);
813 return true;
814}
815
816/* Read-only: reports CHDK "Disable LCD off" policy (config 1221; 3 holds main
817 * power through LockMainPower) with battery voltage and temperatures when the
818 * firmware exposes them. No record mode, shooting or configuration change. */
819static const char power_status_script[] =
820 "if type(get_config_value)~='function' then error('missing power status API') end\n"
821 "local policy=get_config_value(1221)\n"
822 "if type(policy)~='number' or policy<0 or policy>3 or policy%1~=0 then error('power policy unavailable') end\n"
823 "local report='idle_shutdown_policy='..tostring(policy)..'; keep_awake='..(policy==3 and '1' or '0')\n"
824 "if type(get_vbatt)=='function' then\n"
825 " local millivolts=get_vbatt()\n"
826 " if type(millivolts)=='number' then report=report..'; battery_mv='..tostring(millivolts) end\n"
827 "end\n"
828 "if type(get_temperature)=='function' then\n"
829 " local names={'optics','sensor','battery'}\n"
830 " for which=0,2 do\n"
831 " local celsius=get_temperature(which)\n"
832 " if type(celsius)=='number' and celsius>-100 then report=report..'; '..names[which+1]..'_c='..tostring(celsius) end\n"
833 " end\n"
834 "end\n"
835 "for _,entry in ipairs{{'zoom_step',get_zoom},{'focus_mm',get_focus}} do\n"
836 " if type(entry[2])=='function' then\n"
837 " local ok,value=pcall(entry[2])\n"
838 " if ok and type(value)=='number' then report=report..'; '..entry[1]..'='..tostring(value) end\n"
839 " end\n"
840 "end\n"
841 "if type(require)=='function' and type(get_prop)=='function' then\n"
842 " local ok,props=pcall(require,'propcase')\n"
843 " if ok and type(props)=='table' then\n"
844 " for _,entry in ipairs{{'focus_mode',props.FOCUS_MODE},{'af_lock',props.AF_LOCK},{'canon_mode',props.SHOOTING_MODE},{'iso_mode',props.ISO_MODE}} do\n"
845 " if type(entry[2])=='number' then\n"
846 " local valid,value=pcall(get_prop,entry[2])\n"
847 " if valid and type(value)=='number' then report=report..'; '..entry[1]..'='..tostring(value) end\n"
848 " end\n"
849 " end\n"
850 " end\n"
851 "end\n"
852 "if type(get_mode)=='function' and type(bitand)=='function' then\n"
853 " local valid,_,_,mode=pcall(get_mode)\n"
854 " if valid and type(mode)=='number' then report=report..'; mode='..tostring(bitand(mode,255)) end\n"
855 "end\n"
856 "for _,entry in ipairs{{'overrides_off',2003},{'tv_ovr',1110},{'iso_ovr',1130},{'iso_ovr_koef',1131},{'sd_ovr_koef',1141},{'autoiso',1160}} do\n"
857 " local valid,value=pcall(get_config_value,entry[2])\n"
858 " if valid and type(value)=='number' then report=report..'; '..entry[1]..'='..tostring(value) end\n"
859 "end\n"
860 "return report\n";
861
862/** @brief Print the camera's idle power-off policy and available telemetry.
863 * @param transport Active PTP session.
864 * @return True only for a valid reply indicating the Always keep-awake policy.
865 * @details The query is read-only. Report the observed setting even if it
866 * does not satisfy the operational policy. */
867static bool power_status(struct transport *transport)
868{
869 static const char prefix[] = "idle_shutdown_policy=";
870 char result[512];
871 if (!run_script_operation(transport, power_status_script, result, sizeof(result), NULL, false) ||
872 strncmp(result, prefix, sizeof(prefix) - 1)) return false;
873 printf("%s\n", result);
874 if (!strstr(result, "; keep_awake=1")) {
875 fprintf(stderr, "Camera idle power-off prevention is not Always; run --configure --keep-awake 1\n");
876 return false;
877 }
878 return true;
879}
880
881/**
882 * @brief Validate a bounded printable camera pathname with no traversal components.
883 * @param path Absolute camera path beginning with A/; no script interpolation occurs.
884 * @return True for a nonempty file path shorter than 512 bytes.
885 */
886static bool valid_camera_path(const char *path)
887{
888 if (!path || path[0] != 'A' || path[1] != '/') return false;
889 size_t length = strlen(path);
890 if (length < 4 || length >= 512) return false;
891 const char *component = path + 2;
892 for (const char *position = component;; ++position) {
893 unsigned char character = (unsigned char)*position;
894 if (character && (character < 32 || character > 126 || character == '\\')) return false;
895 if (character == '/' || !character) {
896 size_t component_length = (size_t)(position - component);
897 if (!component_length || (component_length == 1 && component[0] == '.') ||
898 (component_length == 2 && component[0] == '.' && component[1] == '.')) return false;
899 if (!character) return true;
900 component = position + 1;
901 }
902 }
903}
904
905/**
906 * @brief Stream an existing SD-card file without executing a camera script.
907 * @param transport Open session on a selected camera.
908 * @param remote_path Valid A/ pathname; original is never deleted.
909 * @param file Writable caller-owned temporary file.
910 * @return True after bounded file transfer and a successful PTP response.
911 * @note main() still requires JPEG markers before publishing a download.
912 */
913static bool download_file(struct transport *transport, const char *remote_path, FILE *file)
914{
915 struct response response;
916 if (!valid_camera_path(remote_path)) {
917 fprintf(stderr, "Invalid camera file path; use a printable A/ path without . or .. components\n");
918 return false;
919 }
920 fprintf(stderr, "Downloading %s\n", remote_path);
921 if (!chdk_call(transport, CHDK_TEMP_DATA, 0, (const uint8_t *)remote_path,
922 strlen(remote_path), NULL, 0, NULL, &response)) return false;
923 return chdk_call(transport, CHDK_DOWNLOAD, 0, NULL, 0, NULL, 0, file, &response);
924}
925
926static const char romlog_script[] =
927 "if type(call_event_proc)~='function' then error('native event procedures unavailable') end\n"
928 "if type(os)~='table' or type(os.stat)~='function' or type(os.remove)~='function' then error('log filesystem API unavailable') end\n"
929 "if type(get_config_value)~='function' or get_config_value(1999)~=1 then error('Enable Lua native calls in CHDK menu, or use Save ROM crash log') end\n"
930 "if call_event_proc('SystemEventInit')==-1 and call_event_proc('System.Create')==-1 then error('log export initialization failed') end\n"
931 "for _,path in ipairs{'A/ROMLOG.LOG','A/RomLogErr.txt'} do\n"
932 " if os.stat(path) and not os.remove(path) then error('cannot replace old log '..path) end\n"
933 "end\n"
934 "if call_event_proc('GetLogToFile','A/ROMLOG.LOG',1)~=0 then error('GetLogToFile failed') end\n"
935 "if os.stat('A/RomLogErr.txt') then error('camera reported RomLogErr.txt') end\n"
936 "local info=os.stat('A/ROMLOG.LOG')\n"
937 "if type(info)~='table' or type(info.size)~='number' or info.size<1 or info.size>65536 then error('missing or oversized ROM log') end\n"
938 "return 'A/ROMLOG.LOG'\n";
939
940/** @brief Export and download the camera's bounded ROM crash log.
941 * @param transport Active PTP session.
942 * @param file Caller-owned writable output stream.
943 * @return True after a successful export and download.
944 * @details Require the expected fixed camera pathname before reading it
945 * instead of treating arbitrary script output as a destination selector. */
946static bool download_romlog(struct transport *transport, FILE *file)
947{
948 char path[64];
949 return run_script_operation(transport, romlog_script, path, sizeof(path), NULL, false) &&
950 !strcmp(path, "A/ROMLOG.LOG") && download_file(transport, path, file);
951}
952
953/** @brief Receive one direct JPEG chunk into the private output stream.
954 * @param transport Active PTP session with the global download limit.
955 * @param[in,out] file Seekable temporary stream open for reading and writing.
956 * @param[in,out] download Transfer cursor, file extent and completion state.
957 * @return True for an accepted chunk; discard the temporary image after failure.
958 * @details Stage at the end until the reply supplies the actual offset.
959 * Permit backpatching existing bytes but reject gaps, and bound total
960 * transferred bytes separately from the resulting extent. */
961static bool download_direct_chunk(struct transport *transport, FILE *file,
962 struct direct_download *download)
963{
965 if (download->complete || download->received >= maximum ||
966 fseeko(file, (off_t)download->extent, SEEK_SET) != 0) return false;
967 struct response response;
968 size_t saved_limit = transport->max_download;
969 transport->max_download = maximum - download->received;
971 NULL, 0, NULL, 0, file, &response);
972 transport->max_download = saved_limit;
973 if (!transferred) return false;
974 if (response.count != 3 || !response.data_size ||
976 fprintf(stderr, "Invalid direct JPEG chunk length or completion response\n");
977 return false;
978 }
979 size_t position = response.parameters[2] == UINT32_MAX ? download->cursor : response.parameters[2];
980 if (position > download->extent || response.data_size > maximum - position) {
981 fprintf(stderr, "Rejected direct JPEG seek gap or oversized image\n");
982 return false;
983 }
984 size_t next_cursor = position + response.data_size;
985 size_t next_extent = next_cursor > download->extent ? next_cursor : download->extent;
986 if (position != download->extent) {
987 uint8_t block[TRANSFER_SIZE];
988 size_t moved = 0;
989 while (moved < response.data_size) {
990 if (!remaining_ms(transport)) return false;
991 size_t amount = response.data_size - moved;
992 if (amount > sizeof(block)) amount = sizeof(block);
993 if (fseeko(file, (off_t)(download->extent + moved), SEEK_SET) != 0 ||
994 fread(block, 1, amount, file) != amount ||
995 fseeko(file, (off_t)(position + moved), SEEK_SET) != 0 ||
996 fwrite(block, 1, amount, file) != amount) return false;
997 moved += amount;
998 }
999 if (fflush(file) != 0 || ftruncate(fileno(file), (off_t)next_extent) != 0) return false;
1000 }
1001 if (fseeko(file, (off_t)next_cursor, SEEK_SET) != 0) return false;
1002 download->cursor = next_cursor;
1003 download->extent = next_extent;
1004 download->received += response.data_size;
1005 download->complete = response.parameters[1] == 0;
1006 return true;
1007}
1008
1009/**
1010 * @brief Shoot to the camera SD card and stream the resulting JPEG to a local file.
1011 * @param transport Open session on one selected Canon camera.
1012 * @param file Caller-owned writable temporary stream, positioned at its start.
1013 * @return True when the download data phase and final response both succeed.
1014 * @details TempData carries the remote pathname before DownloadFile. File flush,
1015 * JPEG-marker checks, publication, and cleanup belong to main(). The SD original
1016 * is retained; conventional IMG_####.JPG naming and JPEG-capable settings are assumed.
1017 */
1019 const char *option;
1020 const char *property;
1021 unsigned maximum;
1022};
1023
1024static const struct camera_setting camera_settings[] = {
1025 {"--iso-mode", "ISO_MODE", 32767},
1026 {"--flash", "FLASH_MODE", 2},
1027 {"--resolution", "RESOLUTION", 8},
1028 {"--quality", "QUALITY", 2},
1029 {"--date-stamp", "DATE_STAMP", 3},
1030 {"--af-assist", "AF_ASSIST_BEAM", 1},
1031 {"--raw", NULL, 1}
1032};
1033#define CAMERA_SETTING_COUNT (sizeof(camera_settings) / sizeof(camera_settings[0]))
1034
1036
1043
1046
1054
1063
1064/** @brief Check whether an explicit exposure override is present.
1065 * @param exposure Requested exposure policy.
1066 * @return True if at least one override was supplied.
1067 * @details Presence, not the numeric value, determines whether a control was requested. */
1068static bool exposure_requested(const struct exposure_policy *exposure)
1069{
1070 for (size_t index = 0; index < EXPOSURE_COUNT; ++index)
1071 if (exposure->present[index]) return true;
1072 return false;
1073}
1074
1075/** @brief Check whether a capture needs camera configuration before shooting.
1076 * @param settings Parsed optional settings.
1077 * @return True if a focus, exposure, power or camera setting was requested.
1078 * @details Skip the configuration script when the user requested no changes. */
1079static bool settings_requested(const struct capture_settings *settings)
1080{
1081 if (settings->keep_awake_present || settings->focus.mode != FOCUS_UNCHANGED ||
1082 exposure_requested(&settings->exposure)) return true;
1083 for (size_t index = 0; index < CAMERA_SETTING_COUNT; ++index)
1084 if (settings->present[index]) return true;
1085 return false;
1086}
1087
1088/** @brief Build the focus setup and readback portion of a CHDK script.
1089 * @param focus Requested mode, distance and verification bounds.
1090 * @param[out] body Script buffer; discard on failure.
1091 * @param capacity Available bytes including the terminator.
1092 * @param exposure_cleanup Include the exposure-abort hook in focus failure handling.
1093 * @return True if the policy is supported locally and the script fits.
1094 * @details Validate mode combinations before formatting. The camera script
1095 * checks model capabilities and bounds waits for mode and distance readback. */
1096static bool focus_script(const struct focus_policy *focus, char *body, size_t capacity, bool exposure_cleanup)
1097{
1098 if (focus->mode == FOCUS_UNCHANGED) { if (capacity) body[0] = '\0'; return capacity != 0; }
1099 if (focus->mode > FOCUS_AUTO || !focus->timeout_ms || focus->timeout_ms > 60000 ||
1100 (focus->distance_present && focus->distance_mm != -1 && focus->distance_mm < 1) ||
1101 (focus->mode == FOCUS_AF && focus->distance_present) ||
1102 ((focus->mode == FOCUS_AUTO || focus->mode == FOCUS_MANUAL) && !focus->distance_present)) return false;
1103 char distance[24] = "nil";
1104 if (focus->distance_present && snprintf(distance, sizeof(distance), "%d", focus->distance_mm) < 0) return false;
1105 int length = snprintf(body, capacity,
1106 "local props=require('propcase')\n"
1107 "local mode=%u local distance=%s local timeout=%u local tolerance=%u\n"
1108 "for _,name in ipairs{'set_mf','set_aflock','get_focus','get_focus_ok','get_shooting','press','release'} do\n"
1109 " if type(_G[name])~='function' then error('missing focus API: '..name) end\n"
1110 "end\n"
1111 "if type(props.AF_LOCK)~='number' or type(props.FOCUS_MODE)~='number' then error('missing focus properties') end\n"
1112 "local _,video=get_mode() if video then error('still-photo mode required') end\n"
1113 "if distance then\n"
1114 " if type(get_sd_over_modes)~='function' or type(set_focus)~='function' then error('missing distance API') end\n"
1115 " local modes=get_sd_over_modes()\n"
1116 " if type(modes)~='number' or modes<0 or modes%%1~=0 then error('invalid capabilities') end\n"
1117 " local function supported(flag) return modes%%(flag*2)>=flag end\n"
1118 " if mode==4 then\n"
1119 " if supported(4) then mode=3 elseif supported(2) then mode=2 else error('no MF/AFL distance support') end\n"
1120 " elseif not supported(mode==3 and 4 or 2) then error('distance mode unsupported') end\n"
1121 "end\n"
1122 "if mode==1 or (mode==2 and not distance and get_prop(props.AF_LOCK)~=1) then\n"
1123 " for _,name in ipairs{'CONTINUOUS_AF','SERVO_AF'} do\n"
1124 " if props[name] and get_prop(props[name])~=0 then error('disable '..name) end\n"
1125 " end\n"
1126 "end\n"
1127 "local held=false\n"
1128 "local started=0\n"
1129 "local function focus_release() if held then release('shoot_half') held=false end end\n"
1130 "local function fail(message) focus_release() %serror('focus: '..message) end\n"
1131 "local function wait(check,message)\n"
1132 " while true do\n"
1133 " local elapsed=bitand(get_tick_count()-started,2147483647)\n"
1134 " if elapsed>=timeout then fail(message..'; actual='..tostring(get_focus())) end\n"
1135 " if check()==true then return end sleep(20)\n"
1136 " end\n"
1137 "end\n"
1138 "local function selected()\n"
1139 " return get_prop(props.AF_LOCK)==(mode==2 and 1 or 0) and get_prop(props.FOCUS_MODE)==(mode==3 and 1 or 0)\n"
1140 "end\n"
1141 "local function halfpress()\n"
1142 " if not held then held=true press('shoot_half') end\n"
1143 " wait(get_shooting,'half-press timeout')\n"
1144 "end\n"
1145 "local function focus_prepare()\n"
1146 " started=get_tick_count()\n"
1147 " if mode~=2 and get_prop(props.AF_LOCK)==1 then set_aflock(false) end\n"
1148 " if mode~=3 and get_prop(props.FOCUS_MODE)==1 then set_mf(false) end\n"
1149 " wait(function() return (mode==2 or get_prop(props.AF_LOCK)==0) and (mode==3 or get_prop(props.FOCUS_MODE)==0) end,'unlock rejected')\n"
1150 " if mode==3 and not selected() then set_mf(true) end\n"
1151 " if mode==2 and not selected() then\n"
1152 " if not distance then halfpress() wait(get_focus_ok,'AF timeout') end\n"
1153 " set_aflock(true)\n"
1154 " end\n"
1155 " wait(selected,'mode rejected')\n"
1156 " if distance and set_focus(distance)~=true then fail('override rejected') end\n"
1157 " halfpress()\n"
1158 " if mode==1 then wait(get_focus_ok,'AF timeout') end\n"
1159 " wait(function()\n"
1160 " local actual=get_focus() if type(actual)~='number' then return false end\n"
1161 " if distance==-1 then return actual==-1 end\n"
1162 " if distance then return actual>0 and actual-distance>=-tolerance and actual-distance<=tolerance end\n"
1163 " return actual==-1 or actual>0\n"
1164 " end,'distance timeout')\n"
1165 "end\n",
1166 (unsigned)focus->mode, distance, focus->timeout_ms, focus->tolerance_mm,
1167 exposure_cleanup ? "if exposure_abort then exposure_abort() end " : "");
1168 return length >= 0 && (size_t)length < capacity;
1169}
1170
1171/** @brief Assemble bounded Lua for applying the requested camera settings.
1172 * @param settings Parsed settings and focus/exposure policies.
1173 * @param[out] body Script buffer; discard on failure.
1174 * @param capacity Available bytes including the terminator.
1175 * @return True when the script fits and local policy checks pass.
1176 * @details Share the setup and cleanup fragments between configuration and
1177 * capture so both paths apply the same camera-side checks. */
1178static bool settings_script(const struct capture_settings *settings, char *body, size_t capacity)
1179{
1180 if (!focus_script(&settings->focus, body, capacity, exposure_requested(&settings->exposure))) return false;
1181 size_t used = strlen(body);
1182 if (exposure_requested(&settings->exposure)) {
1183 const struct exposure_policy *exposure = &settings->exposure;
1184 int length = snprintf(body + used, capacity - used,
1185 "local overrides={}\n"
1186 "local exp_timeout=%u local exp_held=false\n"
1187 "for _,name in ipairs{'get_shooting','press','release'} do\n"
1188 " if type(_G[name])~='function' then error('missing exposure API: '..name) end\n"
1189 "end\n"
1190 "%s",
1191 exposure->timeout_ms ? exposure->timeout_ms : 5000,
1192 settings->focus.mode == FOCUS_UNCHANGED ?
1193 "local _,video=get_mode() if video then error('still-photo mode required') end\n" : "");
1194 if (length < 0 || (size_t)length >= capacity - used) return false;
1195 used += (size_t)length;
1196 static const char *const names[EXPOSURE_COUNT][4] = {
1197 {"TV96", "set_tv96_direct", "get_tv96", "set_tv96_direct"}, {"SV96", "set_sv96", "get_sv96", "set_sv96"},
1198 {"AV96", "set_av96_direct", "get_av96", "set_av96_direct"}, {"ND", "set_nd_filter", "get_nd_current_ev96", "set_nd_filter"}
1199 };
1200 for (size_t index = 0; index < EXPOSURE_COUNT; ++index) {
1201 if (!exposure->present[index]) continue;
1202 const char *setter = names[index][1];
1203 char argument[32], expected[64];
1204 int argument_length = snprintf(argument, sizeof(argument), "%d", exposure->values[index]);
1205 int expected_length = snprintf(expected, sizeof(expected), "%d", exposure->values[index]);
1206 if (argument_length < 0 || (size_t)argument_length >= sizeof(argument) ||
1207 expected_length < 0 || (size_t)expected_length >= sizeof(expected)) return false;
1208 if (index == EXPOSURE_TV && exposure->shutter_numerator) {
1209 length = snprintf(body + used, capacity - used,
1210 "if type(seconds_to_tv96)~='function' then error('missing shutter conversion API') end\n"
1211 "local target_tv=seconds_to_tv96(%u,%u)\n",
1212 exposure->shutter_numerator, exposure->shutter_denominator);
1213 if (length < 0 || (size_t)length >= capacity - used) return false;
1214 used += (size_t)length;
1215 snprintf(argument, sizeof(argument), "target_tv");
1216 snprintf(expected, sizeof(expected), "target_tv");
1217 } else if (index == EXPOSURE_SV && exposure->iso_kind != EXPOSURE_ISO_SV96) {
1218 length = snprintf(body + used, capacity - used,
1219 "if type(iso_to_sv96)~='function' %s then error('missing ISO conversion API') end\n"
1220 "local real_iso=%s(%d)\n"
1221 "if type(real_iso)~='number' or real_iso%%1~=0 or real_iso<=0 or real_iso>32767 then error('invalid real ISO conversion') end\n",
1222 exposure->iso_kind == EXPOSURE_ISO_MARKET ? "or type(iso_market_to_real)~='function'" : "",
1223 exposure->iso_kind == EXPOSURE_ISO_MARKET ? "iso_market_to_real" : "", exposure->values[index]);
1224 if (length < 0 || (size_t)length >= capacity - used) return false;
1225 used += (size_t)length;
1226 snprintf(argument, sizeof(argument), "real_iso");
1227 snprintf(expected, sizeof(expected), "iso_to_sv96(real_iso)");
1228 setter = "set_iso_real";
1229 } else if (index == EXPOSURE_AV) {
1230 length = snprintf(body + used, capacity - used,
1231 "if type(get_nd_present)~='function' or type(get_min_av96)~='function' or type(get_max_av96)~='function' then error('iris/range unavailable') end\n"
1232 "local iris_type=get_nd_present() if iris_type~=0 and iris_type~=2 then error('no verified iris capability') end\n");
1233 if (length < 0 || (size_t)length >= capacity - used) return false;
1234 used += (size_t)length;
1235 if (exposure->aperture_milli) {
1236 length = snprintf(body + used, capacity - used,
1237 "if type(aperture_to_av96)~='function' then error('missing aperture conversion API') end\n"
1238 "local target_av=aperture_to_av96(%u)\n", exposure->aperture_milli);
1239 if (length < 0 || (size_t)length >= capacity - used) return false;
1240 used += (size_t)length;
1241 snprintf(argument, sizeof(argument), "target_av");
1242 snprintf(expected, sizeof(expected), "target_av");
1243 setter = "set_av96";
1244 }
1245 } else if (index == EXPOSURE_ND) {
1246 length = snprintf(body + used, capacity - used,
1247 "if type(get_nd_present)~='function' or type(get_nd_value_ev96)~='function' then error('ND filter unavailable') end\n"
1248 "local nd_type=get_nd_present() if nd_type~=1 and nd_type~=2 then error('ND filter unavailable') end\n"
1249 "local nd_value=get_nd_value_ev96() if type(nd_value)~='number' or nd_value<=0 then error('unknown ND attenuation') end\n");
1250 if (length < 0 || (size_t)length >= capacity - used) return false;
1251 used += (size_t)length;
1252 snprintf(expected, sizeof(expected), "%s", exposure->values[index] == 1 ? "nd_value" : "0");
1253 }
1254 length = snprintf(body + used, capacity - used,
1255 "overrides[#overrides+1]={'%s','%s','%s',%s,%s,%u,'%s',%d,%d,%d}\n",
1256 names[index][0],
1257 setter, names[index][2], argument, expected, index == EXPOSURE_ND ? 0 : exposure->tolerance96,
1258 names[index][3], index == EXPOSURE_TV ? 32767 : 0,
1259 index == EXPOSURE_TV ? -576 : index == EXPOSURE_ND ? 0 : 1,
1260 index == EXPOSURE_TV ? 1920 : index == EXPOSURE_AV ? 1152 : 1536);
1261 if (length < 0 || (size_t)length >= capacity - used) return false;
1262 used += (size_t)length;
1263 }
1264 length = snprintf(body + used, capacity - used,
1265 "for _,entry in ipairs(overrides) do\n"
1266 " for _,slot in ipairs{2,3,7} do entry[slot]=_G[entry[slot]] if type(entry[slot])~='function' then error('missing '..entry[1]..' API') end end\n"
1267 " if type(entry[4])~='number' or type(entry[5])~='number' or entry[4]%%1~=0 or entry[5]%%1~=0 then error('invalid exposure conversion: '..entry[1]) end\n"
1268 " if entry[5]<entry[9] or entry[5]>entry[10] then error('exposure bounds: '..entry[1]) end\n"
1269 "end\n"
1270 "local function exp_release() if exp_held then release('shoot_half') exp_held=false end end\n"
1271 "function restore() if get_shooting()==false then for _,entry in ipairs(overrides) do entry[7](entry[8]) end end end\n"
1272 "function exposure_abort()\n"
1273 " exp_release() %s local stopped=get_tick_count()\n"
1274 " while get_shooting()~=false do if bitand(get_tick_count()-stopped,2147483647)>=1000 then error('exposure cleanup: camera still shooting') end sleep(20) end restore()\n"
1275 "end\n"
1276 "local function exp_fail(message) exposure_abort() error('exposure: '..message) end\n"
1277 "local function exp_stage() for _,entry in ipairs(overrides) do entry[2](entry[4]) end end\n"
1278 "local function exp_prepare()\n"
1279 " local started=get_tick_count()\n"
1280 " if get_shooting()~=true then exp_held=true press('shoot_half') end\n"
1281 " while get_shooting()~=true do\n"
1282 " if bitand(get_tick_count()-started,2147483647)>=exp_timeout then exp_fail('half-press timeout') end sleep(20)\n"
1283 " end\n"
1284 " for _,entry in ipairs(overrides) do\n"
1285 " if entry[1]=='AV96' then\n"
1286 " local low,high=get_min_av96(),get_max_av96()\n"
1287 " if type(low)~='number' or type(high)~='number' or low<=0 or high<=low or entry[5]<low or entry[5]>high then exp_fail('aperture outside verified iris range') end\n"
1288 " end\n"
1289 " if entry[3]()~=entry[5] then entry[2](entry[4]) end\n"
1290 " end\n"
1291 " while true do\n"
1292 " if get_shooting()~=true then exp_fail('half-press lost before exposure') end\n"
1293 " local bad=nil\n"
1294 " for _,entry in ipairs(overrides) do\n"
1295 " local actual=entry[3]()\n"
1296 " if type(actual)~='number' or actual~=actual or actual-entry[5]>entry[6] or actual-entry[5]<-entry[6] then bad=entry break end\n"
1297 " end\n"
1298 " if bitand(get_tick_count()-started,2147483647)>=exp_timeout then exp_fail(bad and (bad[1]..' rejected; actual='..tostring(bad[3]())..'; expected='..bad[5]) or 'verification timeout') end\n"
1299 " if not bad then return end sleep(20)\n"
1300 " end\n"
1301 "end\n",
1302 settings->focus.mode == FOCUS_UNCHANGED ? "" : "focus_release()");
1303 if (length < 0 || (size_t)length >= capacity - used) return false;
1304 used += (size_t)length;
1305 }
1306 int length = snprintf(body + used, capacity - used,
1307 "local props=require('propcase')\n"
1308 "local requested={");
1309 if (length < 0 || (size_t)length >= capacity - used) return false;
1310 used += (size_t)length;
1311 for (size_t index = 0; index < CAMERA_SETTING_COUNT; ++index) {
1312 if (!settings->present[index] || !camera_settings[index].property) continue;
1313 length = snprintf(body + used, capacity - used, "{'%s',%u},",
1314 camera_settings[index].property, settings->values[index]);
1315 if (length < 0 || (size_t)length >= capacity - used) return false;
1316 used += (size_t)length;
1317 }
1318 length = snprintf(body + used, capacity - used,
1319 "}\n"
1320 "for _,entry in ipairs(requested) do\n"
1321 " if type(props[entry[1]])~='number' then error('unsupported property '..entry[1]) end\n"
1322 " if entry[1]=='QUALITY' then\n"
1323 " if type(set_prop_str)~='function' or type(get_prop_str)~='function' then error('missing JPEG quality property API') end\n"
1324 " entry[3]=string.char(entry[2],0,0,0)\n"
1325 " end\n"
1326 "end\n"
1327 "local capture_mode=0\n"
1328 "if type(get_mode)=='function' then local _,_,mode=get_mode() if type(mode)=='number' then capture_mode=bitand(mode,255) end end\n"
1329 "if capture_mode<2 or capture_mode>5 then\n"
1330 " for index=#requested,1,-1 do if requested[index][1]=='ISO_MODE' then table.remove(requested,index) end end\n"
1331 "end\n");
1332 if (length < 0 || (size_t)length >= capacity - used) return false;
1333 used += (size_t)length;
1334 if (settings->keep_awake_present) {
1335 if (settings->keep_awake > 1) return false;
1336 length = snprintf(body + used, capacity - used,
1337 "if type(get_config_value)~='function' or type(set_config_value)~='function' then error('missing keep-awake API') end\n"
1338 "local shutdown=get_config_value(1221)\n"
1339 "if type(shutdown)~='number' or shutdown<0 or shutdown>3 or shutdown%%1~=0 then error('keep-awake setting unavailable') end\n"
1340 "if shutdown~=%u then set_config_value(1221,%u) end\n"
1341 "if get_config_value(1221)~=%u then error('keep-awake setting rejected') end\n",
1342 settings->keep_awake * 3, settings->keep_awake * 3, settings->keep_awake * 3);
1343 if (length < 0 || (size_t)length >= capacity - used) return false;
1344 used += (size_t)length;
1345 }
1346 length = snprintf(body + used, capacity - used,
1347 "local function setting(entry) return entry[3] and get_prop_str(props[entry[1]],4) or get_prop(props[entry[1]]) end\n"
1348 "local changed=false\n"
1349 "for _,entry in ipairs(requested) do\n"
1350 " if setting(entry)~=(entry[3] or entry[2]) then\n"
1351 " if entry[3] then\n"
1352 " if set_prop_str(props[entry[1]],entry[3])~=true then error('property rejected QUALITY') end\n"
1353 " else set_prop(props[entry[1]],entry[2]) end\n"
1354 " changed=true\n"
1355 " end\n"
1356 "end\n"
1357 "if changed then sleep(100) end\n"
1358 "for _,entry in ipairs(requested) do\n"
1359 " if setting(entry)~=(entry[3] or entry[2]) then error('property rejected '..entry[1]) end\n"
1360 "end\n");
1361 if (length < 0 || (size_t)length >= capacity - used) return false;
1362 used += (size_t)length;
1363 if (settings->present[CAMERA_SETTING_COUNT - 1]) {
1364 length = snprintf(body + used, capacity - used,
1365 "if get_raw()~=(%u~=0) then set_raw(%u) end\nif get_raw()~=(%u~=0) then error('raw setting rejected') end\n",
1366 settings->values[CAMERA_SETTING_COUNT - 1], settings->values[CAMERA_SETTING_COUNT - 1], settings->values[CAMERA_SETTING_COUNT - 1]);
1367 if (length < 0 || (size_t)length >= capacity - used) return false;
1368 used += (size_t)length;
1369 }
1370 if (exposure_requested(&settings->exposure)) {
1371 length = snprintf(body + used, capacity - used, "exp_stage()\n");
1372 if (length < 0 || (size_t)length >= capacity - used) return false;
1373 used += (size_t)length;
1374 }
1375 if (settings->focus.mode != FOCUS_UNCHANGED) {
1376 length = snprintf(body + used, capacity - used, "focus_prepare()\n");
1377 if (length < 0 || (size_t)length >= capacity - used) return false;
1378 used += (size_t)length;
1379 }
1380 if (exposure_requested(&settings->exposure)) {
1381 length = snprintf(body + used, capacity - used, "exp_prepare()\n");
1382 if (length < 0 || (size_t)length >= capacity - used) return false;
1383 }
1384 return true;
1385}
1386
1387/** @brief Build a configuration-only script with an observed-state report.
1388 * @param settings Requested settings.
1389 * @param[out] body Destination script buffer.
1390 * @param capacity Available bytes including the terminator.
1391 * @return True if setup and the report fit.
1392 * @details Append readback and release temporary focus/exposure state
1393 * without taking a picture. */
1394static bool configure_script(const struct capture_settings *settings, char *body, size_t capacity)
1395{
1396 if (!settings_script(settings, body, capacity)) return false;
1397 size_t used = strlen(body);
1398 int length = snprintf(body + used, capacity - used, "local report='Configured'\n%s%s%s%sreturn report\n",
1399 settings->keep_awake_present ? "report=report..'; keep_awake='..(get_config_value(1221)==3 and 1 or 0)\n" : "",
1400 settings->focus.mode == FOCUS_UNCHANGED ? "" :
1401 "report=report..'; mode='..({'af','aflock','manual'})[mode]..'; distance_mm='..get_focus()\n",
1402 exposure_requested(&settings->exposure) ?
1403 "for _,entry in ipairs(overrides) do report=report..'; '..entry[1]..'='..entry[3]() end\nexposure_abort()\n" : "",
1404 settings->focus.mode == FOCUS_UNCHANGED ? "" : "focus_release()\n");
1405 return length >= 0 && (size_t)length < capacity - used;
1406}
1407
1408/** @brief Apply settings without capturing a picture.
1409 * @param transport Active PTP session.
1410 * @param settings Requested settings and optional readback checks.
1411 * @return True when a configuration report was accepted.
1412 * @details Require the expected report shape before displaying an apparent success. */
1413static bool configure_camera(struct transport *transport, const struct capture_settings *settings)
1414{
1415 char body[SCRIPT_BODY_CAPACITY], result[256];
1416 if (!configure_script(settings, body, sizeof(body)) ||
1417 !run_script(transport, body, result, sizeof(result)) ||
1418 (!settings->keep_awake_present && settings->focus.mode == FOCUS_UNCHANGED && !exposure_requested(&settings->exposure) ? strcmp(result, "Configured") :
1419 strncmp(result, "Configured; ", 12))) return false;
1420 puts(result);
1421 return true;
1422}
1423
1424/** @brief Build the ordinary SD-backed still-capture script.
1425 * @param settings Optional settings to apply before exposing.
1426 * @param[out] body Script buffer.
1427 * @param capacity Available bytes including the terminator.
1428 * @return True when the capture program fits.
1429 * @details Require the exposure counter to advance, then allow the new
1430 * JPEG to settle before the host attempts to download its path. */
1431static bool capture_script(const struct capture_settings *settings, char *body, size_t capacity)
1432{
1433 static const char capture_body[] =
1434 "if get_exp_count()==before then error('capture did not advance file counter') end\n"
1435 "local path=get_image_dir()..string.format('/IMG_%04d.JPG',get_exp_count())\n"
1436 "local stat=type(os)=='table' and type(os.stat)=='function' and os.stat or nil\n"
1437 "if not stat then sleep(1500) else\n"
1438 " local last,still,began=-1,0,get_tick_count()\n"
1439 " while still<3 and bitand(get_tick_count()-began,2147483647)<5000 do\n"
1440 " local info=stat(path) local size=type(info)=='table' and info.size or -1\n"
1441 " if size>0 and size==last then still=still+1 else still=0 end\n"
1442 " last=size sleep(100)\n"
1443 " end\n"
1444 "end\n"
1445 "return path\n";
1446 if (!capacity) return false;
1447 body[0] = '\0';
1448 if (settings_requested(settings) && !settings_script(settings, body, capacity)) return false;
1449 size_t used = strlen(body);
1450 int length = snprintf(body + used, capacity - used,
1451 "local before=get_exp_count()\nlocal shot_status=shoot(0)\n%s%sif shot_status~=0 then error('shoot failed; status='..tostring(shot_status)) end\n%s",
1452 exposure_requested(&settings->exposure) ? "exposure_abort()\n" : "",
1453 settings->focus.mode == FOCUS_UNCHANGED ? "" : "focus_release()\n", capture_body);
1454 return length >= 0 && (size_t)length < capacity - used;
1455}
1456
1457/** @brief Capture to the camera's SD card and download the resulting JPEG.
1458 * @param transport Active PTP session and deadline.
1459 * @param file Caller-owned temporary destination stream.
1460 * @param settings Optional settings for this shot.
1461 * @return True if the script and file download succeeded.
1462 * @warning A failed download does not imply the exposure failed. */
1463static bool capture(struct transport *transport, FILE *file, const struct capture_settings *settings)
1464{
1465 char body[SCRIPT_BODY_CAPACITY];
1466 if (!capture_script(settings, body, sizeof(body))) return false;
1467 char remote_path[512];
1468 if (!run_script(transport, body, remote_path, sizeof(remote_path))) return false;
1469 return download_file(transport, remote_path, file);
1470}
1471
1472/** @brief Build the direct JPEG handshake and its camera-side cleanup.
1473 * @param settings Optional settings for this shot.
1474 * @param timeout_ms Remaining operation budget supplied to the camera.
1475 * @param[out] body Script buffer.
1476 * @param capacity Available bytes including the terminator.
1477 * @return True when the complete script fits.
1478 * @details Require single-still support and an unused direct-capture slot.
1479 * Own cleanup only after enabling the slot; require the host's completion
1480 * reply before reporting the final image identity. */
1481static bool direct_capture_script(const struct capture_settings *settings, unsigned timeout_ms,
1482 char *body, size_t capacity)
1483{
1484 int length = snprintf(body, capacity,
1485 "for _,name in ipairs{'get_usb_capture_support','get_usb_capture_target','init_usb_capture','set_usb_capture_timeout','write_usb_msg','read_usb_msg','get_drive_mode'} do\n"
1486 " if type(_G[name])~='function' then error('missing direct capture API: '..name) end\nend\n"
1487 "local support=get_usb_capture_support()\n"
1488 "if type(support)~='number' or support%%2~=1 then error('direct JPEG unsupported; USB capture mask='..tostring(support)) end\n"
1489 "local _,video=get_mode() if video or get_drive_mode()~=0 then error('single still-photo mode required') end\n"
1490 "if get_usb_capture_target()~=0 then error('remote capture already enabled; not replaced') end\n");
1491 if (length < 0 || (size_t)length >= capacity) return false;
1492 size_t used = (size_t)length;
1493 if (settings_requested(settings)) {
1494 if (!settings_script(settings, body + used, capacity - used)) return false;
1495 used += strlen(body + used);
1496 }
1497 length = snprintf(body + used, capacity - used,
1498 "local owned=false local previous_restore=restore\n"
1499 "local function direct_release() if owned then init_usb_capture(0) set_usb_capture_timeout() owned=false end end\n"
1500 "function restore() direct_release() if previous_restore then previous_restore() end end\n"
1501 "if not init_usb_capture(1) then error('direct JPEG initialization failed') end owned=true\n"
1502 "set_usb_capture_timeout(%u)\n"
1503 "if not write_usb_msg('Direct ready') then direct_release() error('direct readiness message failed') end\n"
1504 "local before=get_exp_count() local started=get_tick_count()\nlocal shot_status=shoot(0)\n"
1505 "if shot_status~=0 then direct_release() error('shoot failed; status='..tostring(shot_status)) end\n"
1506 "local remaining=%u-bitand(get_tick_count()-started,2147483647)\n"
1507 "local done=remaining>0 and read_usb_msg(remaining)=='Direct done'\n"
1508 "local active=get_usb_capture_target()==1\ndirect_release()\n%s%s"
1509 "if not done or not active then error('direct capture incomplete; not retried') end\n"
1510 "if get_exp_count()==before then error('direct capture counter did not advance') end\n"
1511 "return 'Direct JPEG '..get_exp_count()\n",
1513 exposure_requested(&settings->exposure) ? "exposure_abort()\n" : "",
1514 settings->focus.mode == FOCUS_UNCHANGED ? "" : "focus_release()\n");
1515 return length >= 0 && (size_t)length < capacity - used;
1516}
1517
1518/** @brief Capture and stream a JPEG via CHDK's direct-download protocol.
1519 * @param transport Active session with an absolute operation deadline.
1520 * @param file Seekable temporary stream for JPEG chunks.
1521 * @param settings Optional capture settings.
1522 * @return True when script completion and transfer agree on the image.
1523 * @details Pass the remaining budget to the camera rather than extending
1524 * the original host deadline with a new per-shot timeout. */
1525static bool capture_direct(struct transport *transport, FILE *file, const struct capture_settings *settings)
1526{
1527 char body[SCRIPT_BODY_CAPACITY], result[64];
1528 uint64_t now_ms = monotonic_ms();
1529 if (!remaining_ms(transport) || !now_ms || now_ms >= transport->deadline_ms ||
1530 transport->deadline_ms - now_ms > UINT_MAX ||
1531 !direct_capture_script(settings, (unsigned)(transport->deadline_ms - now_ms), body, sizeof(body))) {
1532 fprintf(stderr, "Direct capture script exceeds storage or operation deadline\n");
1533 return false;
1534 }
1535 return run_script_operation(transport, body, result, sizeof(result), file, true);
1536}
1537
1538static bool parse_range(const char *text, unsigned minimum, unsigned maximum, unsigned *value);
1539
1540/**
1541 * @brief Set normalized optical zoom without taking or downloading a photo.
1542 * @param transport Open camera session.
1543 * @param level 0 selects the first zoom step; 255 selects the last.
1544 * @param observed Optional confirmed normalized lens-step position.
1545 * @return True after camera-side get_zoom() confirms the requested step.
1546 * @details The camera computes floor((level * (steps - 1) + 127) / 255), using
1547 * get_zoom_steps() as a count. This rounds to a lens step, not a focal length.
1548 * A lens with one step maps every valid level to zero. Digital zoom is not set.
1549 */
1550static bool set_zoom(struct transport *transport, unsigned level, uint8_t *observed)
1551{
1552 if (level > 255) return false;
1553 char body[1024], result[128];
1554 int length = snprintf(body, sizeof(body),
1555 "local level=%u\n"
1556 "local steps=get_zoom_steps()\n"
1557 "if steps<1 then error('camera reports no zoom steps') end\n"
1558 "local scaled=level*(steps-1)+127\n"
1559 "local target=(scaled-scaled%%255)/255\n"
1560 "set_zoom(target)\n"
1561 "local started=get_tick_count()\n"
1562 "while get_zoom()~=target and bitand(get_tick_count()-started,2147483647)<5000 do sleep(50) end\n"
1563 "if get_zoom()~=target then error('zoom did not reach target') end\n"
1564 "return string.format('%%d/%%d',get_zoom(),steps-1)\n", level);
1565 if (length < 0 || (size_t)length >= sizeof(body) ||
1566 !run_script(transport, body, result, sizeof(result))) return false;
1567 char *separator = strchr(result, '/');
1568 unsigned step, last;
1569 if (!separator) return false;
1570 *separator = '\0';
1571 if (!parse_range(result, 0, 65535, &step) || !parse_range(separator + 1, 0, 65535, &last)
1572 || step > last || step != (level * last + 127) / 255) return false;
1573 if (observed) *observed = last ? (uint8_t)((step * 255 + last / 2) / last) : 0;
1574 printf("Zoom %u: camera step %u/%u\n", level, step, last);
1575 return true;
1576}
1577
1578/**
1579 * @brief Validate one USB still-image interface without opening the device.
1580 * @param descriptor Candidate alternate-setting descriptor.
1581 * @param input Bulk-IN address, modified only on successful validation.
1582 * @param output Bulk-OUT address, modified only on successful validation.
1583 * @return True for PTP 6/1/1 with one valid bulk endpoint in each direction.
1584 * @details Zero/reserved endpoint addresses, missing packet sizes, duplicate
1585 * bulk directions, and unsupported endpoint types are rejected. One optional
1586 * interrupt-IN endpoint is allowed for events, although this client does not
1587 * consume events. Packet-size checks cover full/high/super-speed bulk limits.
1588 */
1590 uint8_t *input, uint8_t *output)
1591{
1592 if (!descriptor || !input || !output || descriptor->bInterfaceClass != 6 ||
1593 descriptor->bInterfaceSubClass != 1 || descriptor->bInterfaceProtocol != 1 ||
1594 descriptor->bNumEndpoints < 2 || descriptor->bNumEndpoints > 3) return false;
1595 uint8_t bulk_input = 0, bulk_output = 0;
1596 bool interrupt_input = false;
1597 for (uint8_t index = 0; index < descriptor->bNumEndpoints; ++index) {
1598 const struct usbfs_endpoint *endpoint = &descriptor->endpoint[index];
1599 uint8_t address = endpoint->bEndpointAddress;
1600 unsigned packet_size = endpoint->wMaxPacketSize & 0x7ffU;
1601 unsigned type = endpoint->bmAttributes & USBFS_TRANSFER_TYPE_MASK;
1602 if (!(address & 0x0fU) || (address & 0x70U) || !packet_size || packet_size > 1024)
1603 return false;
1604 for (uint8_t previous = 0; previous < index; ++previous)
1605 if (descriptor->endpoint[previous].bEndpointAddress == address) return false;
1606 if (type == USBFS_TRANSFER_TYPE_BULK) {
1607 if ((endpoint->wMaxPacketSize & 0xf800U) ||
1608 (packet_size != 8 && packet_size != 16 && packet_size != 32 &&
1609 packet_size != 64 && packet_size != 512 && packet_size != 1024)) return false;
1610 if (address & USBFS_ENDPOINT_IN) {
1611 if (bulk_input) return false;
1612 bulk_input = address;
1613 } else {
1614 if (bulk_output) return false;
1615 bulk_output = address;
1616 }
1617 } else if (type == USBFS_TRANSFER_TYPE_INTERRUPT &&
1618 (address & USBFS_ENDPOINT_IN) && !interrupt_input) {
1619 interrupt_input = true;
1620 } else return false;
1621 }
1622 if (!bulk_input || !bulk_output) return false;
1623 *input = bulk_input;
1624 *output = bulk_output;
1625 return true;
1626}
1627
1628/**
1629 * @brief Find a still-image PTP interface and its bulk endpoints.
1630 * @param device Enumerated USB device; ownership stays with the device list.
1631 * @param interface_number Output interface number, not its array index.
1632 * @param alternate Output alternate-setting number, not its array index.
1633 * @param input Output bulk-IN endpoint address on success.
1634 * @param output Output bulk-OUT endpoint address on success.
1635 * @param output_packet_size Output bulk-OUT maximum packet size in bytes.
1636 * @return True for a class/subclass/protocol 6/1/1 interface with both endpoints.
1637 * @note This examines descriptors, not CHDK support. CHDK is checked after opening
1638 * the selected device; listing never claims an interface or triggers capture.
1639 */
1640static bool find_interface(const struct usbfs_device *device, int *interface_number, int *alternate,
1641 uint8_t *input, uint8_t *output, unsigned *output_packet_size)
1642{
1643 uint8_t buffer[USBFS_DESCRIPTOR_CAPACITY];
1644 const uint8_t *config;
1645 size_t length, offset = 0;
1646 if (usb.active_config(device, buffer, sizeof(buffer), &config, &length) != 0) return false;
1648 while (usbfs_next_interface(config, length, &offset, &descriptor)) {
1649 if (valid_ptp_interface(&descriptor, input, output)) {
1650 *interface_number = descriptor.bInterfaceNumber;
1651 *alternate = descriptor.bAlternateSetting;
1652 *output_packet_size = 0;
1653 for (uint8_t index = 0; index < descriptor.bNumEndpoints; ++index)
1654 if (descriptor.endpoint[index].bEndpointAddress == *output)
1655 *output_packet_size = descriptor.endpoint[index].wMaxPacketSize & 0x7ffU;
1656 return true;
1657 }
1658 }
1659 return false;
1660}
1661
1662/** @brief Parse unsigned decimal CLI input with inclusive bounds.
1663 * @param text Nonempty digits; signs, whitespace, and trailing text are rejected.
1664 * @param minimum Lowest accepted number, inclusive.
1665 * @param maximum Highest accepted number, inclusive.
1666 * @param value Output destination, modified only on success.
1667 * @return True for a representable value in the specified range. */
1668static bool parse_range(const char *text, unsigned minimum, unsigned maximum, unsigned *value)
1669{
1670 char *end;
1671 errno = 0;
1672 unsigned long parsed = strtoul(text, &end, 10);
1673 if (errno || !*text || *text < '0' || *text > '9' || *end ||
1674 parsed < minimum || parsed > maximum) return false;
1675 *value = (unsigned)parsed;
1676 return true;
1677}
1678
1679/** @brief Parse a positive CLI number; zero is reserved for unspecified selection. */
1680static bool parse_number(const char *text, unsigned maximum, unsigned *value)
1681{
1682 return parse_range(text, 1, maximum, value);
1683}
1684
1685/** @brief Parse a bounded signed decimal command-line value.
1686 * @param text Null-terminated token, optionally prefixed by minus.
1687 * @param minimum Inclusive lower bound.
1688 * @param maximum Inclusive upper bound.
1689 * @param[out] value Result written on success.
1690 * @return True for a complete in-range token.
1691 * @details Check both syntax and range before narrowing the conversion. */
1692static bool parse_signed(const char *text, int minimum, int maximum, int *value)
1693{
1694 const char *digits = *text == '-' ? text + 1 : text;
1695 char *end;
1696 errno = 0;
1697 long parsed = strtol(text, &end, 10);
1698 if (*digits < '0' || *digits > '9' || errno || *end || parsed < minimum || parsed > maximum) return false;
1699 *value = (int)parsed;
1700 return true;
1701}
1702
1703/** @brief Parse a decimal setting and convert it to rounded integer units.
1704 * @param text Null-terminated numeric token beginning with a decimal digit.
1705 * @param scale Multiplier applied before checking bounds.
1706 * @param minimum Inclusive minimum in scaled units.
1707 * @param maximum Inclusive maximum in scaled units.
1708 * @param[out] value Rounded result written on success.
1709 * @return True when syntax and scaled range are accepted.
1710 * @details Reject hexadecimal and non-finite inputs rather than passing unusual
1711 * spellings through to camera-side option handling. */
1712static bool parse_scaled(const char *text, unsigned scale, unsigned minimum, unsigned maximum, unsigned *value)
1713{
1714 char *end;
1715 errno = 0;
1716 double parsed = strtod(text, &end) * scale;
1717 if (*text < '0' || *text > '9' || (text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) ||
1718 errno || *end || !(parsed >= minimum && parsed <= maximum)) return false;
1719 *value = (unsigned)(parsed + 0.5);
1720 return true;
1721}
1722
1723/** @brief Convert a decimal or rational shutter time to an exposure ratio.
1724 * @param text Exposure in seconds, as a decimal or numerator/denominator.
1725 * @param[in,out] exposure Policy receiving the checked ratio.
1726 * @return True for an exposure from one microsecond through 64 seconds.
1727 * @details Keep fractions exact and convert decimal seconds to microseconds;
1728 * validate rational bounds with widened integers before updating the policy. */
1729static bool parse_shutter(const char *text, struct exposure_policy *exposure)
1730{
1731 unsigned numerator, denominator;
1732 const char *slash = strchr(text, '/');
1733 if (slash) {
1734 char *end;
1735 errno = 0;
1736 unsigned long parsed = strtoul(text, &end, 10);
1737 if (*text < '0' || *text > '9' || errno || end != slash || parsed < 1 || parsed > 64000000 ||
1738 !parse_number(slash + 1, 1000000, &denominator) || parsed > (uint64_t)64 * denominator ||
1739 parsed * UINT64_C(1000000) < denominator) return false;
1740 numerator = (unsigned)parsed;
1741 } else {
1742 if (!parse_scaled(text, 1000000, 1, 64000000, &numerator)) return false;
1743 denominator = 1000000;
1744 }
1745 exposure->shutter_numerator = numerator;
1746 exposure->shutter_denominator = denominator;
1747 return true;
1748}
1749
1751 unsigned bus;
1752 uint8_t ports[7];
1753 size_t depth;
1754};
1755
1756/** @brief Parse a stable USB bus and port-chain selector.
1757 * @param text USB path in BUS-PORT[.PORT...] form.
1758 * @param[out] selection Parsed selector; discard on failure.
1759 * @return True when the complete nonempty chain fits.
1760 * @details Select the physical port independently of changing device addresses. */
1761static bool parse_usb_port(const char *text, struct usb_port_selection *selection)
1762{
1763 *selection = (struct usb_port_selection){0};
1764 char *end;
1765 errno = 0;
1766 unsigned long bus = strtoul(text, &end, 10);
1767 if (errno || *text < '0' || *text > '9' || bus < 1 || bus > 255 || *end != '-') return false;
1768 selection->bus = (unsigned)bus;
1769 text = end + 1;
1770 for (;;) {
1771 errno = 0;
1772 unsigned long port = strtoul(text, &end, 10);
1773 if (errno || *text < '0' || *text > '9' || port < 1 || port > 255 || selection->depth == sizeof(selection->ports)) return false;
1774 selection->ports[selection->depth++] = (uint8_t)port;
1775 if (!*end) return true;
1776 if (*end != '.') return false;
1777 text = end + 1;
1778 }
1779}
1780
1781/** @brief Compare a discovered device with the optional port selector.
1782 * @param selection Parsed selector; empty depth disables the filter.
1783 * @param bus Discovered bus number.
1784 * @param ports Discovered port chain with @p depth entries when valid.
1785 * @param depth Discovered chain length, or a negative unavailable value.
1786 * @return True for an exact match or an unconfigured selector.
1787 * @details Do not accept a prefix match: another device may be farther
1788 * downstream on the same hub. */
1789static bool usb_port_matches(const struct usb_port_selection *selection, unsigned bus,
1790 const uint8_t *ports, int depth)
1791{
1792 if (!selection->depth) return true;
1793 if (bus != selection->bus || depth < 0 || (size_t)depth != selection->depth) return false;
1794 for (size_t index = 0; index < selection->depth; ++index)
1795 if (ports[index] != selection->ports[index]) return false;
1796 return true;
1797}
1798
1800 void *(*monitor_get)(void);
1801 int (*context_iteration)(void *, int);
1802 void *(*volumes_get)(void *);
1803 void *(*list_nth)(void *, unsigned);
1804 char *(*identifier_get)(void *, const char *);
1805 void *(*mount_get)(void *);
1806 void *(*root_get)(void *);
1807 char *(*uri_get)(void *);
1808 void (*unref)(void *);
1809 void (*free)(void *);
1810 void (*list_free_full)(void *, void (*)(void *));
1811};
1812
1813/** @brief Find the unique desktop mount attached to the selected USB node.
1814 * @param api Loaded desktop volume-monitor functions.
1815 * @param device Exact USB device path to match.
1816 * @param[out] uri Buffer for a matching gphoto2 URI.
1817 * @param capacity Available bytes including the terminator.
1818 * @return True only for a unique matching mount within the scan bound.
1819 * @details Match the desktop volume by device identity before considering its
1820 * URI; never choose an unrelated camera by mount order. */
1821static bool desktop_camera_uri(const struct desktop_api *api, const char *device,
1822 char *uri, size_t capacity)
1823{
1824 if (!capacity) return false;
1825 uri[0] = '\0';
1826 void *monitor = api->monitor_get();
1827 if (!monitor) return false;
1828 void *volumes = api->volumes_get(monitor);
1829 bool valid = true;
1830 for (unsigned index = 0; index < DESKTOP_VOLUME_LIMIT; ++index) {
1831 void *volume = api->list_nth(volumes, index);
1832 if (!volume) break;
1833 char *identifier = api->identifier_get(volume, "unix-device");
1834 bool selected = identifier && !strcmp(identifier, device);
1835 api->free(identifier);
1836 if (!selected) continue;
1837 void *mount = api->mount_get(volume);
1838 if (!mount) continue;
1839 void *root = api->root_get(mount);
1840 char *location = root ? api->uri_get(root) : NULL;
1841 size_t length = location ? strnlen(location, capacity) : 0;
1842 if (!location || length < 10 || length >= capacity ||
1843 strncmp(location, "gphoto2://", 10) || uri[0]) valid = false;
1844 if (valid) {
1845 for (size_t byte = 0; byte <= length; ++byte) uri[byte] = location[byte];
1846 }
1847 api->free(location);
1848 if (root) api->unref(root);
1849 api->unref(mount);
1850 if (!valid) break;
1851 }
1852 if (api->list_nth(volumes, DESKTOP_VOLUME_LIMIT)) valid = false;
1853 api->list_free_full(volumes, api->unref);
1854 api->unref(monitor);
1855 if (!valid) uri[0] = '\0';
1856 return valid && uri[0];
1857}
1858
1859/** @brief Resolve one optional desktop camera mount and invoke its unmount.
1860 * @param bus Selected USB bus.
1861 * @param address Selected device address.
1862 * @return One on failure; successful exec replaces this helper process.
1863 * @details Load desktop dependencies only in the helper so headless
1864 * operation does not require the GIO runtime. */
1865static int unmount_desktop_camera(unsigned bus, unsigned address)
1866{
1867 void *library = dlopen("libgio-2.0.so.0", RTLD_NOW | RTLD_LOCAL);
1868 if (!library) {
1869 fprintf(stderr, "chdkbridge: optional desktop GIO runtime unavailable; release the selected camera mount manually\n");
1870 return 1;
1871 }
1872 struct desktop_api api = {0};
1873#define DESKTOP_SYMBOL(FIELD, NAME) \
1874 api.FIELD = (__typeof__(api.FIELD))dlsym(library, NAME); \
1875 if (!api.FIELD) { fprintf(stderr, "chdkbridge: missing desktop API %s\n", NAME); return 1; }
1876 DESKTOP_SYMBOL(monitor_get, "g_volume_monitor_get")
1877 DESKTOP_SYMBOL(context_iteration, "g_main_context_iteration")
1878 DESKTOP_SYMBOL(volumes_get, "g_volume_monitor_get_volumes")
1879 DESKTOP_SYMBOL(list_nth, "g_list_nth_data")
1880 DESKTOP_SYMBOL(identifier_get, "g_volume_get_identifier")
1881 DESKTOP_SYMBOL(mount_get, "g_volume_get_mount")
1882 DESKTOP_SYMBOL(root_get, "g_mount_get_root")
1883 DESKTOP_SYMBOL(uri_get, "g_file_get_uri")
1884 DESKTOP_SYMBOL(unref, "g_object_unref")
1885 DESKTOP_SYMBOL(free, "g_free")
1886 DESKTOP_SYMBOL(list_free_full, "g_list_free_full")
1887#undef DESKTOP_SYMBOL
1888 void *monitor = api.monitor_get();
1889 if (!monitor) return 1;
1890 for (unsigned iteration = 0; iteration < DESKTOP_DISCOVERY_POLLS; ++iteration) {
1891 for (unsigned event = 0; event < 64 && api.context_iteration(NULL, 0); ++event) {}
1892 if (poll(NULL, 0, DESKTOP_DISCOVERY_POLL_MS) < 0 && errno != EINTR) {
1893 api.unref(monitor);
1894 return 1;
1895 }
1896 }
1897 char device[32], uri[PATH_MAX];
1898 int length = snprintf(device, sizeof(device), "/dev/bus/usb/%03u/%03u", bus, address);
1899 bool found = length >= 0 && (size_t)length < sizeof(device) &&
1900 desktop_camera_uri(&api, device, uri, sizeof(uri));
1901 api.unref(monitor);
1902 if (!found) {
1903 fprintf(stderr, "chdkbridge: no unique mounted desktop camera for USB %u:%u\n", bus, address);
1904 return 1;
1905 }
1906 fprintf(stderr, "chdkbridge: releasing selected desktop camera mount %s\n", uri);
1907 execlp("gio", "gio", "mount", "--unmount", uri, (char *)NULL);
1908 fprintf(stderr, "chdkbridge: cannot run optional desktop gio tool: %s\n", strerror(errno));
1909 return 1;
1910}
1911
1912/** @brief Supervise a targeted desktop unmount helper.
1913 * @param transport Operation whose deadline bounds the helper.
1914 * @param bus Selected USB bus.
1915 * @param address Selected device address.
1916 * @return True if the helper exited successfully.
1917 * @details Run the helper in its own process group and terminate it on
1918 * expiry or cancellation. Success permits a claim attempt, not assumed ownership. */
1919static bool release_desktop_camera(struct transport *transport, unsigned bus, unsigned address)
1920{
1921 uint64_t started = monotonic_ms();
1922 if (!started || !remaining_ms(transport)) return false;
1923 uint64_t deadline = started + DESKTOP_RELEASE_MS;
1924 if (deadline > transport->deadline_ms) deadline = transport->deadline_ms;
1925 char bus_text[4], address_text[4];
1926 if (snprintf(bus_text, sizeof(bus_text), "%u", bus) < 0 ||
1927 snprintf(address_text, sizeof(address_text), "%u", address) < 0) return false;
1928 pid_t child = fork();
1929 if (child < 0) { perror("Starting desktop camera release"); return false; }
1930 if (child == 0) {
1931 if (setpgid(0, 0) != 0) _exit(127);
1932 signal(SIGINT, SIG_DFL);
1933 signal(SIGTERM, SIG_DFL);
1934 int input = open("/dev/null", O_RDONLY);
1935 if (input < 0 || dup2(input, STDIN_FILENO) < 0 ||
1936 dup2(STDERR_FILENO, STDOUT_FILENO) < 0) _exit(127);
1937 if (input != STDIN_FILENO) close(input);
1938 execl("/proc/self/exe", "chdkbridge", "--internal-unmount", bus_text, address_text, (char *)NULL);
1939 _exit(127);
1940 }
1941 (void)setpgid(child, child);
1942 int status = 0;
1943 while (true) {
1944 pid_t result = waitpid(child, &status, WNOHANG);
1945 if (result == child) return WIFEXITED(status) && WEXITSTATUS(status) == 0;
1946 if (result < 0 && errno != EINTR) return false;
1947 uint64_t now = monotonic_ms();
1948 if (interrupted || !now || now >= deadline) break;
1949 int delay = deadline - now < 10 ? (int)(deadline - now) : 10;
1950 if (poll(NULL, 0, delay) < 0 && errno != EINTR) break;
1951 }
1952 (void)kill(-child, SIGKILL);
1953 (void)kill(child, SIGKILL);
1954 while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}
1955 fprintf(stderr, "chdkbridge: selected desktop camera release cancelled or timed out\n");
1956 return false;
1957}
1958
1959/** @brief Claim an interface, optionally releasing its selected desktop mount.
1960 * @param transport Active device transport and deadline.
1961 * @param interface_number USB interface number to claim.
1962 * @param bus Selected USB bus.
1963 * @param address Selected device address.
1964 * @param release_mount Targeted desktop release callback.
1965 * @return USBFS_SUCCESS or a negative USBFS status.
1966 * @details Only a busy claim triggers desktop release. Use bounded polling
1967 * to allow that owner to close the descriptor; do not reset the USB device. */
1968static int claim_camera_interface(struct transport *transport, int interface_number,
1969 unsigned bus, unsigned address,
1970 bool (*release_mount)(struct transport *, unsigned, unsigned))
1971{
1973 int result = usb.claim_interface(transport->handle, interface_number);
1974 if (result != USBFS_ERROR_BUSY || !release_mount(transport, bus, address)) return result;
1975 uint64_t now = monotonic_ms();
1976 if (!now) return USBFS_ERROR_IO;
1977 uint64_t deadline = now + DESKTOP_RECLAIM_MS;
1978 if (deadline > transport->deadline_ms) deadline = transport->deadline_ms;
1979 while (remaining_ms(transport)) {
1980 result = usb.claim_interface(transport->handle, interface_number);
1981 if (result != USBFS_ERROR_BUSY) return result;
1982 now = monotonic_ms();
1983 if (!now) return USBFS_ERROR_IO;
1984 if (now >= deadline) return result;
1985 int delay = deadline - now < DESKTOP_RECLAIM_POLL_MS ? (int)(deadline - now) : DESKTOP_RECLAIM_POLL_MS;
1986 if (poll(NULL, 0, delay) < 0 && errno != EINTR) return USBFS_ERROR_IO;
1987 }
1989}
1990
1991/** @brief Print build identity and CLI usage without initializing USB.
1992 * @param program Program name from argv[0]. */
1993static void print_help(const char *program)
1994{
1996 printf("Usage: %s [options] OUTPUT.jpg\n"
1997 " %s [options] zoom LEVEL\n"
1998 " %s [options] --info\n"
1999 " %s [options] --retract-lens\n"
2000 " %s [options] --power-status\n"
2001 " %s [options] --download A/DCIM/.../IMAGE.JPG OUTPUT.jpg\n"
2002 " %s --list\n\n"
2003 "Options:\n"
2004 " --help, -h Show this help.\n"
2005 " --version, -V Show application version and build Git revision.\n"
2006 " --list List Canon USB PTP devices without claiming them.\n"
2007 " --info Query CHDK protocol, Lua support, and script status.\n"
2008 " --retract-lens Request playback/lens retraction without powering off or shooting.\n"
2009 " --power-status Read-only: report idle power-off prevention, battery and temperatures; fails unless prevention is Always.\n"
2010 " --romlog OUTPUT Export and download the Canon ROM crash log (max 64 KiB); no record mode, shoot, zoom or power-off.\n"
2011 " --check-runtime Check Linux USB device access without opening a camera.\n"
2012 " --download PATH Download an existing camera JPEG without shooting.\n"
2013 " --direct-download Capture JPEG directly over USB; no JPEG saved on SD.\n"
2014 " --bus N Select USB bus (requires --device).\n"
2015 " --device N Select USB device address (requires --bus).\n"
2016 " --port BUS-P[.P] Select physical USB port path from --list (survives device readdressing).\n"
2017 " --timeout SECONDS Operation timeout, 1..3600 (default: 60).\n\n"
2018 " --usb-timeout MS Individual USB-call timeout, 50..10000 (default: 1000).\n"
2019 " --max-download-mib N File-size limit, 1..256 MiB (default: 64); streaming RAM is fixed.\n\n"
2020 " --configure Apply settings without shooting (requires settings).\n"
2021 " --iso-mode N Canon ISO_MODE property, 0..32767; 0 is auto.\n"
2022 " --flash N 0 auto, 1 on, 2 off.\n"
2023 " --resolution N Camera resolution code, 0..8 (model-dependent).\n"
2024 " --quality N 0 superfine, 1 fine, 2 normal (model-dependent).\n"
2025 " --date-stamp N Camera date-stamp code, 0..3 (model-dependent).\n"
2026 " --af-assist N AF assist beam: 0 off, 1 on.\n"
2027 " --raw N CHDK raw saving: 0 off, 1 on.\n"
2028 " --keep-awake N CHDK idle-shutdown prevention: 0 Never, 1 Always; saved by default.\n\n"
2029 " --focus-mode MODE af: refocus; aflock: preserve/acquire lock; manual: fixed distance; auto: supported MF/AFL distance.\n"
2030 " --focus-distance MM|inf Distance in millimeters, 1..1000000, or infinity; requires manual/auto/aflock.\n"
2031 " --focus-timeout MS Total focus-wait budget, 50..60000 (default: 5000); less than --timeout.\n"
2032 " --focus-tolerance MM Distance readback tolerance, 0..100000 (default: 100); infinity requires -1 readback.\n\n"
2033 " --shutter SECONDS Shutter override: decimal seconds or fraction (e.g. 0.001 or 1/1000), 1 us..64 s.\n"
2034 " --tv96 N Direct shutter APEX96, -576..1920; alternative to --shutter.\n"
2035 " --iso-real N Real sensor ISO, 1..32767; model limits/readback apply.\n"
2036 " --iso-market N Camera-calibrated conversion of displayed ISO, 1..32767.\n"
2037 " --sv96 N Direct real-sensitivity APEX96, 1..1536; alternative ISO override.\n"
2038 " --aperture F F-number, 1..64; requires verified adjustable-iris range.\n"
2039 " --av96 N Direct aperture APEX96, 1..1152; alternative to --aperture.\n"
2040 " --nd in|out Explicit ND insertion/removal; requires ND capability and readback.\n"
2041 " --exposure-timeout MS Shared exposure-wait budget, 50..60000 (default: 5000).\n"
2042 " --exposure-tolerance N APEX96 tolerance, 0..32 (default: 4); ND readback is exact.\n\n"
2043 "Capture saves a JPEG to a new file; existing files are never overwritten.\n"
2044 "zoom/Zoom LEVEL accepts 0..255: 0 is minimum optical zoom, 255 maximum.\n"
2045 "Lens retraction timing is camera-dependent; set Canon Lens Retraction to 0 sec. for immediate retraction.\n"
2046 "--retract-lens confirms playback, not physical lens position; later capture/configuration enters record mode.\n"
2047 "Exactly one camera must match; --port cannot be combined with --bus/--device.\n",
2048 program, program, program, program, program, program, program);
2049}
2050
2051/** @brief Emit the control operation's fixed-size binary receipt.
2052 * @param descriptor Caller-provided descriptor, or zero to omit the receipt.
2053 * @param command Echoed command ID.
2054 * @param observed Observed camera value when applicable.
2055 * @param evidence Kind of confirmation supplied with the value.
2056 * @return True for a complete write or when no receipt was requested.
2057 * @details Keep this receipt separate from human-readable stdout so the
2058 * parent can distinguish camera evidence from process success. */
2059static bool publish_control_reply(unsigned descriptor, uint8_t command, uint8_t observed, uint8_t evidence)
2060{
2061 if (!descriptor) return true;
2062 const uint8_t reply[] = {0xc1, command, observed, evidence};
2063 ssize_t written;
2064 do { written = write((int)descriptor, reply, sizeof(reply)); } while (written < 0 && errno == EINTR);
2065 return written == (ssize_t)sizeof(reply);
2066}
2067
2068/**
2069 * @brief Select one camera, execute one operation, and release owned resources.
2070 * @param argc Argument count.
2071 * @param argv Program name and CLI arguments.
2072 * @return 0 for success, 1 for dependency/device/operation failure, 2 for invalid CLI.
2073 * @details Capture publishes a complete temporary file with link(), which fails
2074 * if the destination exists, including a file created after the initial check.
2075 * Zoom and info bypass local-file creation. Cleanup closes only a session opened
2076 * here and removes only a temporary file successfully created by this invocation.
2077 */
2078int main(int argc, char **argv)
2079{
2080 if (argc == 4 && !strcmp(argv[1], "--internal-unmount")) {
2081 unsigned helper_bus, helper_address;
2082 if (!parse_number(argv[2], 255, &helper_bus) || !parse_number(argv[3], 255, &helper_address)) return 2;
2083 return unmount_desktop_camera(helper_bus, helper_address);
2084 }
2085 unsigned bus = 0, address = 0, timeout_seconds = 60, zoom_level = 0;
2086 unsigned usb_timeout_ms = 1000, max_download_mib = 64;
2087 unsigned control_result_fd = 0;
2088 struct usb_port_selection port_selection = {0};
2089 struct capture_settings settings = {.focus = {.timeout_ms = 5000, .tolerance_mm = 100},
2090 .exposure = {.timeout_ms = 5000, .tolerance96 = 4}};
2091 const struct {
2092 const char *name;
2093 unsigned *value;
2094 unsigned minimum, maximum;
2095 } numeric_options[] = {
2096 {"--bus", &bus, 1, 255}, {"--device", &address, 1, 255},
2097 {"--timeout", &timeout_seconds, 1, 3600},
2098 {"--usb-timeout", &usb_timeout_ms, 50, 10000},
2099 {"--max-download-mib", &max_download_mib, 1, 256},
2100 {"--focus-timeout", &settings.focus.timeout_ms, 50, 60000},
2101 {"--focus-tolerance", &settings.focus.tolerance_mm, 0, 100000},
2102 {"--exposure-timeout", &settings.exposure.timeout_ms, 50, 60000},
2103 {"--exposure-tolerance", &settings.exposure.tolerance96, 0, 32}
2104 };
2105 const struct {
2106 const char *name;
2107 enum exposure_parameter parameter;
2108 int minimum, maximum;
2109 } apex_options[] = {
2110 {"--tv96", EXPOSURE_TV, -576, 1920}, {"--sv96", EXPOSURE_SV, 1, 1536},
2111 {"--av96", EXPOSURE_AV, 1, 1152}
2112 };
2113 bool numeric_seen[sizeof(numeric_options) / sizeof(numeric_options[0])] = {0};
2114 const char *output = NULL;
2115 const char *remote_download = NULL;
2116 bool list_only = false, zoom_requested = false, info_requested = false;
2117 bool configure_requested = false, retract_requested = false;
2118 bool runtime_requested = false, power_requested = false;
2119 bool direct_requested = false, romlog_requested = false;
2120 for (int index = 1; index < argc; ++index) {
2121 bool setting_option = false;
2122 for (size_t setting = 0; setting < CAMERA_SETTING_COUNT; ++setting) {
2123 if (strcmp(argv[index], camera_settings[setting].option)) continue;
2124 if (settings.present[setting] || ++index >= argc ||
2125 !parse_range(argv[index], 0, camera_settings[setting].maximum, &settings.values[setting])) {
2126 fprintf(stderr, "Invalid or duplicate value for %s\n", camera_settings[setting].option);
2127 return 2;
2128 }
2129 settings.present[setting] = true;
2130 setting_option = true;
2131 break;
2132 }
2133 if (setting_option) continue;
2134 for (size_t option = 0; option < sizeof(apex_options) / sizeof(apex_options[0]); ++option) {
2135 if (strcmp(argv[index], apex_options[option].name)) continue;
2136 enum exposure_parameter parameter = apex_options[option].parameter;
2137 if (settings.exposure.present[parameter] || ++index >= argc ||
2138 !parse_signed(argv[index], apex_options[option].minimum, apex_options[option].maximum, &settings.exposure.values[parameter])) {
2139 fprintf(stderr, "Invalid, duplicate or conflicting value for %s\n", apex_options[option].name);
2140 return 2;
2141 }
2142 settings.exposure.present[parameter] = true;
2143 setting_option = true;
2144 break;
2145 }
2146 if (setting_option) continue;
2147 for (size_t option = 0; option < sizeof(numeric_options) / sizeof(numeric_options[0]); ++option) {
2148 if (strcmp(argv[index], numeric_options[option].name)) continue;
2149 if (numeric_seen[option] || ++index >= argc || !(numeric_options[option].minimum == 1
2150 ? parse_number(argv[index], numeric_options[option].maximum, numeric_options[option].value)
2151 : parse_range(argv[index], numeric_options[option].minimum, numeric_options[option].maximum, numeric_options[option].value))) {
2152 fprintf(stderr, "Invalid or duplicate value for %s\n", numeric_options[option].name);
2153 return 2;
2154 }
2155 numeric_seen[option] = true;
2156 setting_option = true;
2157 break;
2158 }
2159 if (setting_option) continue;
2160 if (!strcmp(argv[index], "--help") || !strcmp(argv[index], "-h")) {
2161 print_help(argv[0]);
2162 return 0;
2163 } else if (!strcmp(argv[index], "--version") || !strcmp(argv[index], "-V")) {
2165 return 0;
2166 } else if (!strcmp(argv[index], "--list")) list_only = true;
2167 else if (!strcmp(argv[index], "--control-result-fd")) {
2168 if (control_result_fd || ++index >= argc || !parse_range(argv[index], 3, 31, &control_result_fd)
2169 || fcntl((int)control_result_fd, F_GETFD) < 0) return 2;
2170 if (fcntl((int)control_result_fd, F_SETFD, FD_CLOEXEC) < 0) return 2;
2171 }
2172 else if (!strcmp(argv[index], "--info")) info_requested = true;
2173 else if (!strcmp(argv[index], "--retract-lens")) {
2174 if (retract_requested) {
2175 fprintf(stderr, "Duplicate --retract-lens option\n");
2176 return 2;
2177 }
2178 retract_requested = true;
2179 }
2180 else if (!strcmp(argv[index], "--configure")) configure_requested = true;
2181 else if (!strcmp(argv[index], "--check-runtime")) runtime_requested = true;
2182 else if (!strcmp(argv[index], "--power-status")) power_requested = true;
2183 else if (!strcmp(argv[index], "--romlog")) {
2184 if (romlog_requested) return 2;
2185 romlog_requested = true;
2186 }
2187 else if (!strcmp(argv[index], "--keep-awake")) {
2188 if (settings.keep_awake_present || ++index >= argc ||
2189 !parse_range(argv[index], 0, 1, &settings.keep_awake)) {
2190 fprintf(stderr, "--keep-awake requires one value: 0 Never or 1 Always\n");
2191 return 2;
2192 }
2193 settings.keep_awake_present = true;
2194 }
2195 else if (!strcmp(argv[index], "--direct-download")) {
2196 if (direct_requested) {
2197 fprintf(stderr, "Duplicate --direct-download option\n");
2198 return 2;
2199 }
2200 direct_requested = true;
2201 }
2202 else if (!strcmp(argv[index], "--shutter")) {
2203 if (settings.exposure.present[EXPOSURE_TV] || ++index >= argc || !parse_shutter(argv[index], &settings.exposure)) {
2204 fprintf(stderr, "--shutter requires one decimal/fraction from 1 us to 64 seconds; do not combine with --tv96\n");
2205 return 2;
2206 }
2207 settings.exposure.present[EXPOSURE_TV] = true;
2208 } else if (!strcmp(argv[index], "--iso-real") || !strcmp(argv[index], "--iso-market")) {
2209 bool market = !strcmp(argv[index], "--iso-market");
2210 unsigned iso;
2211 if (settings.exposure.present[EXPOSURE_SV] || ++index >= argc || !parse_number(argv[index], 32767, &iso)) {
2212 fprintf(stderr, "Choose exactly one --iso-real, --iso-market or --sv96 override; ISO requires 1..32767\n");
2213 return 2;
2214 }
2216 settings.exposure.values[EXPOSURE_SV] = (int)iso;
2217 settings.exposure.present[EXPOSURE_SV] = true;
2218 } else if (!strcmp(argv[index], "--aperture")) {
2219 if (settings.exposure.present[EXPOSURE_AV] || ++index >= argc ||
2220 !parse_scaled(argv[index], 1000, 1000, 64000, &settings.exposure.aperture_milli)) {
2221 fprintf(stderr, "--aperture requires one f-number from 1 to 64; do not combine with --av96\n");
2222 return 2;
2223 }
2224 settings.exposure.present[EXPOSURE_AV] = true;
2225 } else if (!strcmp(argv[index], "--nd")) {
2226 if (settings.exposure.present[EXPOSURE_ND] || ++index >= argc ||
2227 (strcmp(argv[index], "in") && strcmp(argv[index], "out"))) {
2228 fprintf(stderr, "--nd requires one explicit in or out state\n");
2229 return 2;
2230 }
2231 settings.exposure.values[EXPOSURE_ND] = !strcmp(argv[index], "in") ? 1 : 2;
2232 settings.exposure.present[EXPOSURE_ND] = true;
2233 }
2234 else if (!strcmp(argv[index], "--focus-mode")) {
2235 const char *modes[] = {"af", "aflock", "manual", "auto"};
2236 if (settings.focus.mode != FOCUS_UNCHANGED || ++index >= argc) {
2237 fprintf(stderr, "--focus-mode requires one af, aflock, manual or auto policy\n");
2238 return 2;
2239 }
2240 for (unsigned mode = 0; mode < sizeof(modes) / sizeof(modes[0]); ++mode)
2241 if (!strcmp(argv[index], modes[mode])) settings.focus.mode = (enum focus_mode)(mode + 1);
2242 if (settings.focus.mode == FOCUS_UNCHANGED) {
2243 fprintf(stderr, "Unknown focus mode; use af, aflock, manual or auto\n");
2244 return 2;
2245 }
2246 } else if (!strcmp(argv[index], "--focus-distance")) {
2247 unsigned distance = 0;
2248 if (settings.focus.distance_present || ++index >= argc ||
2249 (strcmp(argv[index], "inf") && !parse_number(argv[index], 1000000, &distance))) {
2250 fprintf(stderr, "--focus-distance requires one distance: 1..1000000 mm or inf\n");
2251 return 2;
2252 }
2253 settings.focus.distance_present = true;
2254 settings.focus.distance_mm = distance ? (int)distance : -1;
2255 }
2256 else if (!strcmp(argv[index], "--download")) {
2257 if (remote_download || ++index >= argc || !valid_camera_path(argv[index])) {
2258 fprintf(stderr, "--download requires a valid A/ camera file path\n");
2259 return 2;
2260 }
2261 remote_download = argv[index];
2262 }
2263 else if (!strcmp(argv[index], "--port")) {
2264 if (port_selection.depth || ++index >= argc || !parse_usb_port(argv[index], &port_selection)) {
2265 fprintf(stderr, "--port requires one BUS-PORT[.PORT...] path from --list\n");
2266 return 2;
2267 }
2268 } else if ((!strcmp(argv[index], "zoom") || !strcmp(argv[index], "Zoom")) &&
2269 !output && !zoom_requested) {
2270 if (++index >= argc || !parse_range(argv[index], 0, 255, &zoom_level)) {
2271 fprintf(stderr, "Zoom requires an integer from 0 to 255\n");
2272 return 2;
2273 }
2274 zoom_requested = true;
2275 } else if (argv[index][0] == '-' || output || zoom_requested) {
2276 fprintf(stderr, "Unexpected argument: %s\n", argv[index]);
2277 return 2;
2278 } else output = argv[index];
2279 }
2280 unsigned action_count = (unsigned)list_only + (unsigned)zoom_requested +
2281 (unsigned)info_requested + (unsigned)configure_requested +
2282 (unsigned)runtime_requested + (unsigned)retract_requested +
2283 (unsigned)power_requested + (unsigned)(output != NULL);
2284 if ((settings.focus.mode == FOCUS_UNCHANGED &&
2285 (settings.focus.distance_present || numeric_seen[5] || numeric_seen[6])) ||
2286 (settings.focus.mode == FOCUS_AF && settings.focus.distance_present) ||
2287 ((settings.focus.mode == FOCUS_MANUAL || settings.focus.mode == FOCUS_AUTO) && !settings.focus.distance_present) ||
2288 (numeric_seen[6] && !settings.focus.distance_present) ||
2289 (settings.focus.mode != FOCUS_UNCHANGED && settings.focus.timeout_ms >= timeout_seconds * 1000)) {
2290 fprintf(stderr, "Focus requires an explicit compatible mode/distance and a focus timeout shorter than --timeout\n");
2291 return 2;
2292 }
2293 if ((!exposure_requested(&settings.exposure) && (numeric_seen[7] || numeric_seen[8])) ||
2294 (exposure_requested(&settings.exposure) && settings.exposure.timeout_ms >= timeout_seconds * 1000) ||
2295 (settings.exposure.present[EXPOSURE_SV] && settings.present[0] && settings.values[0] != 0)) {
2296 fprintf(stderr, "Exposure limits require overrides and a shorter wait than --timeout; real ISO overrides conflict with nonzero --iso-mode\n");
2297 return 2;
2298 }
2299 uint64_t requested_ms = settings.focus.mode == FOCUS_UNCHANGED ? 0 : settings.focus.timeout_ms;
2300 if (exposure_requested(&settings.exposure)) requested_ms += settings.exposure.timeout_ms + 1000U;
2301 if (settings.exposure.shutter_numerator)
2302 requested_ms += ((uint64_t)settings.exposure.shutter_numerator * 1000 +
2304 else if (settings.exposure.present[EXPOSURE_TV])
2305 requested_ms += (uint64_t)ceil(exp2(-(double)settings.exposure.values[EXPOSURE_TV] / 96.0) * 1000.0);
2306 if (requested_ms >= (uint64_t)timeout_seconds * 1000) {
2307 fprintf(stderr, "--timeout must exceed combined focus/exposure waits, exposure cleanup and the requested shutter duration; leave time for record mode and download\n");
2308 return 2;
2309 }
2310 if ((control_result_fd && !zoom_requested && !retract_requested) ||
2311 (bus == 0) != (address == 0) || (port_selection.depth && bus) || action_count != 1 || (remote_download && !output) ||
2312 (romlog_requested && (!output || remote_download || direct_requested || settings_requested(&settings))) ||
2313 (direct_requested && (!output || remote_download || list_only || info_requested || zoom_requested || configure_requested || runtime_requested || power_requested)) ||
2314 (configure_requested && !settings_requested(&settings)) ||
2315 (settings_requested(&settings) && (list_only || info_requested || zoom_requested || remote_download || runtime_requested || retract_requested || power_requested))) {
2316 fprintf(stderr, "Select one action; specify both --bus and --device OR --port. Use --help for usage\n");
2317 return 2;
2318 }
2319 if (runtime_requested) {
2320 if (usbfs_available()) return 0;
2321 fprintf(stderr, "chdkbridge: Linux USB device access unavailable (%s and %s)\n",
2323 return 1;
2324 }
2325 struct usbfs_devices devices = {0};
2326 struct usbfs_device selected = {0};
2327 struct usbfs_handle handle = {.fd = -1};
2328 bool opened = false;
2329 FILE *file = NULL;
2330 int result = 1, interface_number = -1, alternate = 0;
2331 bool claimed = false, session = false, temporary_created = false;
2332 char temporary[PATH_MAX] = {0};
2333 struct transport transport = {0};
2334 uint64_t started_ms = monotonic_ms();
2335 if (!started_ms) { fprintf(stderr, "Cannot read monotonic clock\n"); return 1; }
2336 transport.deadline_ms = started_ms + (uint64_t)timeout_seconds * 1000;
2338 transport.max_download = romlog_requested ? 65536U : (size_t)max_download_mib * 1024U * 1024U;
2339 struct sigaction cancellation = {.sa_handler = interrupt_handler};
2340 sigemptyset(&cancellation.sa_mask);
2341 sigaction(SIGINT, &cancellation, NULL);
2342 sigaction(SIGTERM, &cancellation, NULL);
2343 signal(SIGPIPE, SIG_IGN);
2344 int usb_result = usb.devices_open(&devices);
2345 if (usb_result != 0) {
2346 fprintf(stderr, "chdkbridge: USB device enumeration failed: %s\n", usbfs_error_name(usb_result));
2347 goto cleanup;
2348 }
2349 unsigned matches = 0;
2350 struct usbfs_device candidate;
2351 while ((usb_result = usb.devices_next(&devices, &candidate)) > 0) {
2352 if (!remaining_ms(&transport)) { fprintf(stderr, "USB discovery cancelled or operation deadline reached\n"); goto cleanup; }
2353 int candidate_interface, candidate_alternate;
2354 uint8_t input = 0, output_endpoint = 0;
2355 unsigned packet_size = 0;
2356 if (candidate.vendor != 0x04a9 ||
2357 (bus && (bus != candidate.bus || address != candidate.address)) ||
2358 !usb_port_matches(&port_selection, candidate.bus, candidate.ports, candidate.depth) ||
2359 !find_interface(&candidate, &candidate_interface, &candidate_alternate,
2360 &input, &output_endpoint, &packet_size)) continue;
2361 if (list_only) {
2362 printf("bus=%u device=%u Canon %04x:%04x", candidate.bus, candidate.address, candidate.vendor, candidate.product);
2363 if (candidate.depth > 0) {
2364 printf(" port=%u-", candidate.bus);
2365 for (int port = 0; port < candidate.depth; ++port) printf("%s%u", port ? "." : "", candidate.ports[port]);
2366 }
2367 putchar('\n');
2368 }
2369 selected = candidate;
2370 interface_number = candidate_interface;
2371 alternate = candidate_alternate;
2372 transport.input_endpoint = input;
2373 transport.output_endpoint = output_endpoint;
2374 transport.output_packet_size = packet_size;
2375 ++matches;
2376 }
2377 if (usb_result < 0) {
2378 fprintf(stderr, "chdkbridge: USB device enumeration failed: %s\n", usbfs_error_name(usb_result));
2379 goto cleanup;
2380 }
2381 if (list_only) {
2382 if (!matches) fprintf(stderr, "No matching Canon PTP camera on USB; check power, CHDK firmware, USB mode, data cable and selected port\n");
2383 result = 0; goto cleanup;
2384 }
2385 if (matches != 1) {
2386 if (!matches) fprintf(stderr, "No matching Canon PTP camera on USB; check power, CHDK firmware, USB mode, data cable and selected port; run --list\n");
2387 else fprintf(stderr, "Found %u matching Canon PTP cameras; use --list and select --port or --bus/--device\n", matches);
2388 goto cleanup;
2389 }
2390 /* Check output access before touching the camera. mkstemp reserves a private
2391 * same-directory file so publication cannot expose a partial download. */
2392 if (output) {
2393 struct stat existing;
2394 if (lstat(output, &existing) == 0 || errno != ENOENT) {
2395 fprintf(stderr, "Output already exists or cannot be accessed: %s\n", output);
2396 goto cleanup;
2397 }
2398 int length = snprintf(temporary, sizeof(temporary), "%s.part.XXXXXX", output);
2399 if (length < 0 || (size_t)length >= sizeof(temporary)) goto cleanup;
2400 int descriptor = mkstemp(temporary);
2401 if (descriptor < 0) { perror("Creating output"); temporary[0] = '\0'; goto cleanup; }
2402 temporary_created = true;
2403 if (fcntl(descriptor, F_SETFD, FD_CLOEXEC) < 0) { close(descriptor); goto cleanup; }
2404 file = fdopen(descriptor, "w+b");
2405 if (!file) { close(descriptor); goto cleanup; }
2406 }
2407 usb_result = usb.open(&selected, &handle);
2408 if (usb_result != 0) {
2409 fprintf(stderr, "Cannot open camera: %s; %s\n", usbfs_error_name(usb_result), usb_failure_hint(usb_result));
2410 goto cleanup;
2411 }
2412 opened = true;
2413 handle.cancel = &interrupted;
2414 transport.handle = &handle;
2415 usb_result = claim_camera_interface(&transport, interface_number,
2416 selected.bus, selected.address, release_desktop_camera);
2417 if (usb_result != 0) {
2418 fprintf(stderr, "Cannot claim camera: %s; %s\n", usbfs_error_name(usb_result), usb_failure_hint(usb_result));
2419 goto cleanup;
2420 }
2421 claimed = true;
2422 if (alternate && (usb_result = usb.set_alternate(&handle, interface_number, alternate)) != 0) {
2423 fprintf(stderr, "Cannot select camera interface setting: %s; %s\n", usbfs_error_name(usb_result), usb_failure_hint(usb_result));
2424 goto cleanup;
2425 }
2426 struct response response;
2427 /* OpenSession uses transaction zero; subsequent commands increment the ID.
2428 * The claimed interface excludes other host clients, so a session or data
2429 * left by an interrupted earlier run is ours; recover it once, as chdkptp does. */
2430 uint32_t session_id = 1;
2431 if (!transaction(&transport, PTP_OPEN_SESSION, &session_id, 1,
2432 NULL, 0, NULL, 0, NULL, &response) &&
2433 (!recover_ptp(&transport, interface_number) ||
2434 !transaction(&transport, PTP_OPEN_SESSION, &session_id, 1,
2435 NULL, 0, NULL, 0, NULL, &response))) goto cleanup;
2436 session = true;
2437 if (retract_requested) {
2438 if (retract_lens(&transport) && publish_control_reply(control_result_fd, 2, 0, 2)) result = 0;
2439 else fprintf(stderr, "Lens retract request failed or timed out; camera state may have changed, no automatic retry\n");
2440 goto cleanup;
2441 }
2442 if (power_requested) {
2443 if (power_status(&transport)) result = 0;
2444 else fprintf(stderr, "Power status query failed or prevention is not Always\n");
2445 goto cleanup;
2446 }
2447 if (info_requested) {
2448 if (camera_info(&transport)) result = 0;
2449 else fprintf(stderr, "Camera information query failed\n");
2450 goto cleanup;
2451 }
2452 if (zoom_requested) {
2453 uint8_t observed = 0;
2454 if (set_zoom(&transport, zoom_level, &observed)
2455 && publish_control_reply(control_result_fd, 1, observed, 1)) result = 0;
2456 else fprintf(stderr, "Zoom failed or timed out; camera zoom may have changed\n");
2457 goto cleanup;
2458 }
2459 if (configure_requested) {
2460 if (configure_camera(&transport, &settings)) result = 0;
2461 else fprintf(stderr, "Configuration failed; camera settings may have partially changed\n");
2462 goto cleanup;
2463 }
2464 if (!(romlog_requested ? download_romlog(&transport, file) : remote_download ? download_file(&transport, remote_download, file) :
2465 direct_requested ? capture_direct(&transport, file, &settings) : capture(&transport, file, &settings))) {
2466 fprintf(stderr, "Capture/download failed or timed out; no automatic shot retry\n");
2467 goto cleanup;
2468 }
2469 /* Flush storage before checking only the JPEG boundary markers. This does
2470 * not decode the image or establish full filesystem crash durability. */
2471 if (fflush(file) != 0 || fsync(fileno(file)) != 0 || fseek(file, 0, SEEK_SET) != 0)
2472 goto cleanup;
2473 uint8_t signature[2];
2474 if (!romlog_requested && (fread(signature, 1, 2, file) != 2 || signature[0] != 0xff || signature[1] != 0xd8 ||
2475 fseek(file, -2, SEEK_END) != 0 || fread(signature, 1, 2, file) != 2 ||
2476 signature[0] != 0xff || signature[1] != 0xd9)) {
2477 fprintf(stderr, "Downloaded file is not a complete JPEG\n");
2478 goto cleanup;
2479 }
2480 if (romlog_requested) {
2481 struct stat status;
2482 if (fstat(fileno(file), &status) != 0 || status.st_size < 1 || status.st_size > 65536) goto cleanup;
2483 }
2484 if (fclose(file) != 0) { file = NULL; goto cleanup; }
2485 file = NULL;
2486 /* link() atomically creates a new name without replacing an existing one;
2487 * cleanup removes the temporary name, leaving the published inode intact. */
2488 if (link(temporary, output) != 0) { perror("Publishing output without overwrite"); goto cleanup; }
2489 printf("Saved %s\n", output);
2490 result = 0;
2491cleanup:
2493 if (file) fclose(file);
2494 if (temporary_created) unlink(temporary);
2495 if (claimed) usb.release_interface(&handle, interface_number);
2496 if (opened) usb.close(&handle);
2497 usb.devices_close(&devices);
2498 return result;
2499}
static unsigned capacity[COVERAGE_CAMERAS]
static uint32_t session
size_t size
Definition chdk_pipe.c:143
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
int descriptor
Definition chdk_pipe.c:142
static void close_session(struct transport *transport)
Best-effort close of an owned session, even after cancellation, within one second.
Definition chdkbridge.c:429
int(* claim_interface)(struct usbfs_handle *, int)
Definition chdkbridge.c:58
static const char * script_error_name(uint32_t error)
Translate a CHDK script status for diagnostics.
Definition chdkbridge.c:521
static bool download_romlog(struct transport *transport, FILE *file)
Export and download the camera's bounded ROM crash log.
Definition chdkbridge.c:946
#define DESKTOP_SYMBOL(FIELD, NAME)
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static bool parse_signed(const char *text, int minimum, int maximum, int *value)
Parse a bounded signed decimal command-line value.
static bool download_direct_chunk(struct transport *transport, FILE *file, struct direct_download *download)
Receive one direct JPEG chunk into the private output stream.
Definition chdkbridge.c:961
static bool valid_script_message(const struct response *response, const uint8_t *message)
Validate known message types and payload lengths, including empty-message zero padding.
Definition chdkbridge.c:533
static void interrupt_handler(int signal_number)
Request cancellation without allocation, I/O, or USB calls in a signal handler.
Definition chdkbridge.c:134
static int claim_camera_interface(struct transport *transport, int interface_number, unsigned bus, unsigned address, bool(*release_mount)(struct transport *, unsigned, unsigned))
Claim an interface, optionally releasing its selected desktop mount.
static bool configure_script(const struct capture_settings *settings, char *body, size_t capacity)
Build a configuration-only script with an observed-state report.
static bool run_script(struct transport *transport, const char *body, char *result, size_t result_capacity)
Execute a capture-path script without direct-download output.
Definition chdkbridge.c:781
static unsigned remaining_ms(const struct transport *transport)
Compute the next USB call's timeout within the operation deadline.
Definition chdkbridge.c:156
static bool settings_requested(const struct capture_settings *settings)
Check whether a capture needs camera configuration before shooting.
static bool configure_camera(struct transport *transport, const struct capture_settings *settings)
Apply settings without capturing a picture.
int(* devices_open)(struct usbfs_devices *)
Definition chdkbridge.c:52
@ RECOVERY_DRAIN_MS
Definition chdkbridge.c:443
@ RECOVERY_DRAIN_READS
Definition chdkbridge.c:443
@ PTP_CLASS_IN
Definition chdkbridge.c:441
@ PTP_CLASS_OUT
Definition chdkbridge.c:441
@ RECOVERY_CONTROL_MS
Definition chdkbridge.c:443
@ PTP_REQUEST_DEVICE_STATUS
Definition chdkbridge.c:442
@ PTP_REQUEST_DEVICE_RESET
Definition chdkbridge.c:442
static bool capture_direct(struct transport *transport, FILE *file, const struct capture_settings *settings)
Capture and stream a JPEG via CHDK's direct-download protocol.
static struct @262112006143041137011017150364274145303116271316 usb
USB operations used by the application; tests substitute fakes.
static bool publish_control_reply(unsigned descriptor, uint8_t command, uint8_t observed, uint8_t evidence)
Emit the control operation's fixed-size binary receipt.
int main(int argc, char **argv)
Select one camera, execute one operation, and release owned resources.
static bool valid_camera_path(const char *path)
Validate a bounded printable camera pathname with no traversal components.
Definition chdkbridge.c:886
static void print_help(const char *program)
Print build identity and CLI usage without initializing USB.
static bool parse_scaled(const char *text, unsigned scale, unsigned minimum, unsigned maximum, unsigned *value)
Parse a decimal setting and convert it to rounded integer units.
static volatile sig_atomic_t interrupted
Signal-safe cancellation flag checked before blocking USB calls.
Definition chdkbridge.c:131
static bool parse_shutter(const char *text, struct exposure_policy *exposure)
Convert a decimal or rational shutter time to an exposure ratio.
static int unmount_desktop_camera(unsigned bus, unsigned address)
Resolve one optional desktop camera mount and invoke its unmount.
static void encode32(uint8_t *bytes, uint32_t value)
Encode a wire value into four writable bytes.
Definition chdkbridge.c:209
static bool power_status(struct transport *transport)
Print the camera's idle power-off policy and available telemetry.
Definition chdkbridge.c:867
static bool transaction(struct transport *transport, uint16_t operation, const uint32_t *parameters, size_t parameter_count, const uint8_t *outgoing, size_t outgoing_size, uint8_t *incoming, size_t capacity, FILE *file, struct response *response)
Perform command, optional data, and response phases for one PTP operation.
Definition chdkbridge.c:329
static const char * usb_failure_hint(int error)
Select a recovery hint for a USB transport failure.
Definition chdkbridge.c:170
static const char record_mode_script[]
Definition chdkbridge.c:600
#define CAMERA_SETTING_COUNT
static const char * ptp_response_name(uint16_t code)
Describe standard PTP response failures without triggering recovery actions.
Definition chdkbridge.c:298
static bool chdk_call(struct transport *transport, uint32_t command, uint32_t argument, const uint8_t *outgoing, size_t size, uint8_t *incoming, size_t capacity, FILE *file, struct response *response)
Place a CHDK subcommand and argument in vendor operation 0x9999.
Definition chdkbridge.c:419
focus_mode
@ FOCUS_AFLOCK
@ FOCUS_UNCHANGED
@ FOCUS_AF
@ FOCUS_AUTO
@ FOCUS_MANUAL
exposure_parameter
@ EXPOSURE_SV
@ EXPOSURE_AV
@ EXPOSURE_ND
@ EXPOSURE_TV
@ EXPOSURE_COUNT
static bool valid_ptp_interface(const struct usbfs_interface *descriptor, uint8_t *input, uint8_t *output)
Validate one USB still-image interface without opening the device.
static bool find_interface(const struct usbfs_device *device, int *interface_number, int *alternate, uint8_t *input, uint8_t *output, unsigned *output_packet_size)
Find a still-image PTP interface and its bulk endpoints.
static bool settings_script(const struct capture_settings *settings, char *body, size_t capacity)
Assemble bounded Lua for applying the requested camera settings.
static bool refill_buffer(struct transport *transport)
Refill empty bounded USB storage without replaying a command.
Definition chdkbridge.c:245
static bool direct_capture_script(const struct capture_settings *settings, unsigned timeout_ms, char *body, size_t capacity)
Build the direct JPEG handshake and its camera-side cleanup.
int(* set_alternate)(struct usbfs_handle *, int, int)
Definition chdkbridge.c:60
int(* control_transfer)(struct usbfs_handle *, uint8_t, uint8_t, uint16_t, uint16_t, unsigned char *, uint16_t, unsigned)
Definition chdkbridge.c:62
static void encode16(uint8_t *bytes, uint16_t value)
Encode a wire value into two writable bytes.
Definition chdkbridge.c:200
static bool retract_lens(struct transport *transport)
Ask the camera to enter playback and confirm the resulting mode.
Definition chdkbridge.c:807
static bool parse_range(const char *text, unsigned minimum, unsigned maximum, unsigned *value)
Parse unsigned decimal CLI input with inclusive bounds.
static bool release_desktop_camera(struct transport *transport, unsigned bus, unsigned address)
Supervise a targeted desktop unmount helper.
#define SCRIPT_BODY_CAPACITY
Definition chdkbridge.c:605
static bool set_zoom(struct transport *transport, unsigned level, uint8_t *observed)
Set normalized optical zoom without taking or downloading a photo.
static bool focus_script(const struct focus_policy *focus, char *body, size_t capacity, bool exposure_cleanup)
Build the focus setup and readback portion of a CHDK script.
static bool download_file(struct transport *transport, const char *remote_path, FILE *file)
Stream an existing SD-card file without executing a camera script.
Definition chdkbridge.c:913
static uint64_t monotonic_ms(void)
Read a wall-clock-independent time base; return zero if the clock fails.
Definition chdkbridge.c:141
static const char retract_lens_script[]
Definition chdkbridge.c:787
int(* release_interface)(struct usbfs_handle *, int)
Definition chdkbridge.c:59
static bool parse_usb_port(const char *text, struct usb_port_selection *selection)
Parse a stable USB bus and port-chain selector.
static bool run_script_operation(struct transport *transport, const char *body, char *result, size_t result_capacity, FILE *direct_file, bool enter_record)
Run camera-side Lua and wait for its correlated string return value.
Definition chdkbridge.c:621
static bool exposure_requested(const struct exposure_policy *exposure)
Check whether an explicit exposure override is present.
int(* active_config)(const struct usbfs_device *, uint8_t *, size_t, const uint8_t **, size_t *)
Definition chdkbridge.c:55
static bool send_packet(struct transport *transport, uint8_t *bytes, size_t length)
Submit one complete, small outbound PTP container.
Definition chdkbridge.c:223
static const char romlog_script[]
Definition chdkbridge.c:926
static bool camera_info(struct transport *transport)
Report CHDK protocol and script capabilities without executing a script.
Definition chdkbridge.c:502
void(* devices_close)(struct usbfs_devices *)
Definition chdkbridge.c:54
static uint32_t decode32(const uint8_t *bytes)
Decode a 32-bit little-endian value without native-endian casts.
Definition chdkbridge.c:191
static bool capture(struct transport *transport, FILE *file, const struct capture_settings *settings)
Capture to the camera's SD card and download the resulting JPEG.
static bool capture_script(const struct capture_settings *settings, char *body, size_t capacity)
Build the ordinary SD-backed still-capture script.
static uint16_t decode16(const uint8_t *bytes)
Decode a 16-bit little-endian value without alignment assumptions.
Definition chdkbridge.c:184
static bool parse_number(const char *text, unsigned maximum, unsigned *value)
Parse a positive CLI number; zero is reserved for unspecified selection.
static const struct camera_setting camera_settings[]
int(* bulk_transfer)(struct usbfs_handle *, unsigned char, unsigned char *, int, int *, unsigned)
Definition chdkbridge.c:61
static bool usb_port_matches(const struct usb_port_selection *selection, unsigned bus, const uint8_t *ports, int depth)
Compare a discovered device with the optional port selector.
exposure_iso_kind
@ EXPOSURE_ISO_SV96
@ EXPOSURE_ISO_MARKET
@ EXPOSURE_ISO_REAL
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
static bool desktop_camera_uri(const struct desktop_api *api, const char *device, char *uri, size_t capacity)
Find the unique desktop mount attached to the selected USB node.
static bool wait_script_poll(const struct transport *transport, unsigned interval_ms)
Sleep to a monotonic poll target without extending it on EINTR or exceeding the deadline.
Definition chdkbridge.c:566
int(* devices_next)(struct usbfs_devices *, struct usbfs_device *)
Definition chdkbridge.c:53
int(* clear_halt)(struct usbfs_handle *, unsigned char)
Definition chdkbridge.c:64
static bool receive_bytes(struct transport *transport, uint8_t *destination, size_t length)
Read an exact bounded payload across arbitrary USB transfer splits.
Definition chdkbridge.c:281
static bool recover_ptp(struct transport *transport, int interface_number)
Clear a session or stale data left by an interrupted earlier run.
Definition chdkbridge.c:454
@ CHDK_MESSAGE_RETURN
Definition chdkbridge.c:81
@ PTP_OK
Definition chdkbridge.c:75
@ CHDK_UNSUPPORTED
Definition chdkbridge.c:83
@ CHDK_ERROR_COMPILE
Definition chdkbridge.c:85
@ CHDK_TEMP_DATA
Definition chdkbridge.c:76
@ CHDK_TABLE
Definition chdkbridge.c:84
@ CHDK_CAPTURE_JPEG
Definition chdkbridge.c:80
@ SCRIPT_POLL_MAX_MS
Definition chdkbridge.c:89
@ DESKTOP_DISCOVERY_POLL_MS
Definition chdkbridge.c:91
@ CHDK_INTEGER
Definition chdkbridge.c:83
@ CHDK_CAPTURE_NOTSET
Definition chdkbridge.c:80
@ CHDK_ERROR_RUNTIME
Definition chdkbridge.c:85
@ CHDK_MESSAGE_USER
Definition chdkbridge.c:82
@ DESKTOP_RELEASE_MS
Definition chdkbridge.c:90
@ CHDK_STATUS
Definition chdkbridge.c:77
@ TRANSFER_SIZE
Definition chdkbridge.c:88
@ SCRIPT_CAPACITY
Definition chdkbridge.c:88
@ CHDK_ERROR_NONE
Definition chdkbridge.c:85
@ CHDK_CAPTURE_READY
Definition chdkbridge.c:79
@ CHDK_CAPTURE_DATA
Definition chdkbridge.c:79
@ MAX_DOWNLOAD
Definition chdkbridge.c:93
@ CHDK_SUPPORT
Definition chdkbridge.c:77
@ PTP_CHDK
Definition chdkbridge.c:75
@ PTP_DATA
Definition chdkbridge.c:73
@ CHDK_NIL
Definition chdkbridge.c:83
@ CHDK_MESSAGE
Definition chdkbridge.c:77
@ DESKTOP_RECLAIM_MS
Definition chdkbridge.c:92
@ DESKTOP_VOLUME_LIMIT
Definition chdkbridge.c:90
@ CHDK_DOWNLOAD
Definition chdkbridge.c:76
@ DESKTOP_RECLAIM_POLL_MS
Definition chdkbridge.c:92
@ PTP_OPEN_SESSION
Definition chdkbridge.c:74
@ CHDK_MESSAGE_ERROR
Definition chdkbridge.c:81
@ CHDK_SCRIPT_FLAGS
Definition chdkbridge.c:88
@ DESKTOP_DISCOVERY_POLLS
Definition chdkbridge.c:91
@ PTP_RESPONSE
Definition chdkbridge.c:73
@ CHDK_WRITE_MESSAGE
Definition chdkbridge.c:78
@ SCRIPT_POLL_MIN_MS
Definition chdkbridge.c:89
@ CHDK_ERROR_RUNNING
Definition chdkbridge.c:86
@ CHDK_BOOLEAN
Definition chdkbridge.c:83
@ PTP_CLOSE_SESSION
Definition chdkbridge.c:74
@ CHDK_EXECUTE
Definition chdkbridge.c:77
@ PTP_COMMAND
Definition chdkbridge.c:73
@ CHDK_MESSAGE_NONE
Definition chdkbridge.c:81
@ CHDK_VERSION
Definition chdkbridge.c:76
@ CHDK_STRING
Definition chdkbridge.c:84
static bool wait_script_idle(struct transport *transport)
Wait within the deadline until no camera script is running; never interrupts one.
Definition chdkbridge.c:586
static const char power_status_script[]
Definition chdkbridge.c:819
static pid_t child
static bool started
static bool ready
char evidence[8192]
Definition lwir_image.c:66
struct jpeg_error_mgr error
Definition lwir_image.c:60
Source fallback for CHDKbridge build identity.
#define CHDKBRIDGE_BUILD_VERSION
Definition version.h:30
#define PATH_MAX
Definition path_utils.h:39
static pthread_cond_t available
Definition pose_log.c:73
static const char header[]
Definition pose_log.c:87
static FILE * output
Definition pose_log.c:77
Shoot to the camera SD card and stream the resulting JPEG to a local file.
unsigned maximum
const char * option
const char * property
unsigned values[CAMERA_SETTING_COUNT]
unsigned keep_awake
struct focus_policy focus
struct exposure_policy exposure
bool present[CAMERA_SETTING_COUNT]
void(* free)(void *)
void *(* root_get)(void *)
int(* context_iteration)(void *, int)
char *(* identifier_get)(void *, const char *)
void *(* monitor_get)(void)
void(* unref)(void *)
void *(* list_nth)(void *, unsigned)
void *(* mount_get)(void *)
void *(* volumes_get)(void *)
char *(* uri_get)(void *)
void(* list_free_full)(void *, void(*)(void *))
uint32_t image_number
Definition chdkbridge.c:123
int values[EXPOSURE_COUNT]
unsigned timeout_ms
unsigned aperture_milli
unsigned shutter_numerator
bool present[EXPOSURE_COUNT]
unsigned tolerance96
enum exposure_iso_kind iso_kind
unsigned shutter_denominator
unsigned timeout_ms
enum focus_mode mode
bool distance_present
unsigned tolerance_mm
Validated successful PTP response and optional data-phase length.
Definition chdkbridge.c:116
size_t count
Definition chdkbridge.c:118
uint32_t parameters[5]
Definition chdkbridge.c:117
size_t data_size
Definition chdkbridge.c:118
Single-session USB transport with bounded input staging.
Definition chdkbridge.c:102
size_t offset
Definition chdkbridge.c:108
uint8_t buffered[TRANSFER_SIZE]
Definition chdkbridge.c:107
uint64_t deadline_ms
Definition chdkbridge.c:109
unsigned output_packet_size
Definition chdkbridge.c:105
unsigned usb_timeout_ms
Definition chdkbridge.c:110
uint32_t transaction_id
Definition chdkbridge.c:106
size_t available
Definition chdkbridge.c:108
uint8_t input_endpoint
Definition chdkbridge.c:104
size_t max_download
Definition chdkbridge.c:111
struct usbfs_handle * handle
Definition chdkbridge.c:103
bool closing_session
Definition chdkbridge.c:112
uint8_t output_endpoint
Definition chdkbridge.c:104
One enumerated USB device; a value copy, valid after enumeration ends.
Definition usbfs.h:73
uint16_t vendor
Definition usbfs.h:76
uint16_t product
Definition usbfs.h:76
uint8_t ports[USBFS_MAX_PORTS]
Definition usbfs.h:77
unsigned bus
Definition usbfs.h:75
unsigned address
Definition usbfs.h:75
int depth
Definition usbfs.h:78
uint16_t wMaxPacketSize
Definition usbfs.h:83
uint8_t bmAttributes
Definition usbfs.h:82
uint8_t bEndpointAddress
Definition usbfs.h:82
Open usbfs file; fd is -1 when closed or dropped after a lost URB.
Definition usbfs.h:97
const volatile sig_atomic_t * cancel
Definition usbfs.h:100
Minimal header-only Linux usbfs access for one CHDKbridge camera.
static bool usbfs_next_interface(const uint8_t *config, size_t length, size_t *offset, struct usbfs_interface *interface)
Return the next complete interface/alternate setting in a configuration.
Definition usbfs.h:293
static int usbfs_clear_halt(struct usbfs_handle *handle, unsigned char endpoint)
Clear a halted endpoint of a claimed interface; data toggles are reset by the kernel.
Definition usbfs.h:465
static bool usbfs_available(void)
True when sysfs device listing and usbfs nodes are reachable.
Definition usbfs.h:127
static const char * usbfs_error_name(int error)
Get the diagnostic name of a usbfs result.
Definition usbfs.h:107
@ USBFS_ERROR_ACCESS
Definition usbfs.h:56
@ USBFS_ERROR_BUSY
Definition usbfs.h:57
@ USBFS_ERROR_NO_DEVICE
Definition usbfs.h:56
@ USBFS_ERROR_TIMEOUT
Definition usbfs.h:57
@ USBFS_ERROR_INTERRUPTED
Definition usbfs.h:58
@ USBFS_ERROR_IO
Definition usbfs.h:55
static int usbfs_release_interface(struct usbfs_handle *handle, int interface)
Release the numbered interface on an open device.
Definition usbfs.h:411
static int usbfs_bulk_transfer(struct usbfs_handle *handle, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned timeout)
Synchronous bulk transfer with libusb_bulk_transfer() semantics.
Definition usbfs.h:563
static int usbfs_active_config(const struct usbfs_device *device, uint8_t *buffer, size_t capacity, const uint8_t **config, size_t *config_length)
Read the active configuration into buffer; config points inside it.
Definition usbfs.h:256
static void usbfs_devices_close(struct usbfs_devices *devices)
Release the sysfs enumeration stream.
Definition usbfs.h:225
static int usbfs_devices_open(struct usbfs_devices *devices)
Start a streaming sysfs enumeration.
Definition usbfs.h:192
#define USBFS_DEVICE_ROOT
Definition usbfs.h:51
static int usbfs_control_transfer(struct usbfs_handle *handle, uint8_t request_type, uint8_t request, uint16_t value, uint16_t index, unsigned char *data, uint16_t length, unsigned timeout)
Synchronous control transfer on endpoint zero.
Definition usbfs.h:444
@ USBFS_TRANSFER_TYPE_MASK
Definition usbfs.h:63
@ USBFS_TRANSFER_TYPE_BULK
Definition usbfs.h:64
@ USBFS_ENDPOINT_IN
Definition usbfs.h:63
@ USBFS_TRANSFER_TYPE_INTERRUPT
Definition usbfs.h:64
@ USBFS_DESCRIPTOR_CAPACITY
Definition usbfs.h:66
static int usbfs_open(const struct usbfs_device *device, struct usbfs_handle *handle)
Open the device node, rejecting a node now owned by a different device.
Definition usbfs.h:343
#define USBFS_SYSFS_ROOT
Definition usbfs.h:50
static int usbfs_set_alternate(struct usbfs_handle *handle, int interface, int alternate)
Select an alternate setting for an interface.
Definition usbfs.h:423
static int usbfs_devices_next(struct usbfs_devices *devices, struct usbfs_device *device)
Definition usbfs.h:200
static int usbfs_claim_interface(struct usbfs_handle *handle, int interface)
Claim without detaching another owner; EBUSY is reported to the caller.
Definition usbfs.h:400
static void usbfs_close(struct usbfs_handle *handle)
Close the node; the kernel releases claimed interfaces and kills pending URBs.
Definition usbfs.h:371
bool valid
Definition usher.c:537
struct usher_control_result result
Definition usher.c:377