Media devices
Single-page view · as markdown
Media subsystem kernel internal API
Peios Kernel / Hardware and drivers / Driver development / Media devices
This section contains usage information about media subsystem and its supported drivers.
Please see:
Documentation/admin-guide/media/index.rst
- for usage information about media subsystem and supported drivers;
Documentation/userspace-api/media/index.rst
- for the userspace APIs used on media devices.
Table of Contents
- Media Subsystem Profile
- Video4Linux devices
- Digital TV (DVB) devices
- Remote Controller devices
- Media Controller devices
- CEC Kernel Support
- Pixel data transmitter and receiver drivers
- Writing camera sensor drivers
- Media driver-specific documentation
Copyright © 2009-2020 : LinuxTV Developers
This documentation is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
For more details see the file COPYING in the source distribution of Linux.
Writing camera sensor drivers
Peios Kernel / Hardware and drivers / Driver development / Media devices
This document covers the in-kernel APIs only. For the best practices on userspace API implementation in camera sensor drivers, please see Using camera sensor drivers.
CSI-2, parallel and BT.656 buses #
Please see Pixel data transmitter and receiver drivers.
Handling clocks #
Camera sensors have an internal clock tree including a PLL and a number of divisors. The clock tree is generally configured by the driver based on a few input parameters that are specific to the hardware: the external clock frequency and the link frequency. The two parameters generally are obtained from system firmware. No other frequencies should be used in any circumstances.
The reason why the clock frequencies are so important is that the clock signals come out of the SoC, and in many cases a specific frequency is designed to be used in the system. Using another frequency may cause harmful effects elsewhere. Therefore only the pre-determined frequencies are configurable by the user.
The external clock frequency shall be retrieved by obtaining the external clock using the devm_v4l2_sensor_clk_get() helper function, and then getting its frequency with clk_get_rate(). Usage of the helper function guarantees correct behaviour regardless of whether the sensor is integrated in a DT-based or ACPI-based system.
ACPI #
ACPI-based systems typically don't register the sensor external clock with the kernel, but specify the external clock frequency in the clock-frequency _DSD property. The devm_v4l2_sensor_clk_get() helper creates and returns a fixed clock set at that rate.
Devicetree #
Devicetree-based systems declare the sensor external clock in the device tree and reference it from the sensor node. The preferred way to select the external clock frequency is to use the assigned-clocks, assigned-clock-parents and assigned-clock-rates properties in the sensor node to set the clock rate. See the clock device tree bindings for more information. The devm_v4l2_sensor_clk_get() helper retrieves and returns that clock.
This approach has the drawback that there's no guarantee that the frequency hasn't been modified directly or indirectly by another driver, or supported by the board's clock tree to begin with. Changes to the Common Clock Framework API are required to ensure reliability.
Power management #
Camera sensors are used in conjunction with other devices to form a camera pipeline. They must obey the rules listed herein to ensure coherent power management over the pipeline.
Camera sensor drivers are responsible for controlling the power state of the device they otherwise control as well. They shall use runtime PM to manage power states. Runtime PM shall be enabled at probe time and disabled at remove time. Drivers should enable runtime PM autosuspend. Also see async sub-device registration.
The runtime PM handlers shall handle clocks, regulators, GPIOs, and other system resources required to power the sensor up and down. For drivers that don't use any of those resources (such as drivers that support ACPI systems only), the runtime PM handlers may be left unimplemented.
In general, the device shall be powered on at least when its registers are being accessed and when it is streaming. Drivers should use pm_runtime_resume_and_get() when starting streaming and pm_runtime_put() or pm_runtime_put_autosuspend() when stopping streaming. They may power the device up at probe time (for example to read identification registers), but should not keep it powered unconditionally after probe.
At system suspend time, the whole camera pipeline must stop streaming, and restart when the system is resumed. This requires coordination between the camera sensor and the rest of the camera pipeline. Bridge drivers are responsible for this coordination, and instruct camera sensors to stop and restart streaming by calling the appropriate subdev operations (.enable_streams() or .disable_streams()). Camera sensor drivers shall therefore not keep track of the streaming state to stop streaming in the PM suspend handler and restart it in the resume handler. Drivers should in general not implement the system PM handlers.
Camera sensor drivers shall not implement the subdev .s_power() operation, as it is deprecated. While this operation is implemented in some existing drivers as they predate the deprecation, new drivers shall use runtime PM instead. If you feel you need to begin calling .s_power() from an ISP or a bridge driver, instead add runtime PM support to the sensor driver you are using and drop its .s_power() handler.
Please also see examples.
Control framework #
v4l2_ctrl_handler_setup() function may not be used in the device's runtime PM runtime_resume callback, as it has no way to figure out the power state of the device. This is because the power state of the device is only changed after the power state transition has taken place. The s_ctrl callback can be used to obtain device's power state after the power state transition:
int ;
The function returns a non-zero value if it succeeded getting the power count or runtime PM was disabled, in either of which cases the driver may proceed to access the device.
Rotation, orientation and flipping #
Use v4l2_fwnode_device_parse() to obtain rotation and orientation information from system firmware and v4l2_ctrl_new_fwnode_properties() to register the appropriate controls.
Example drivers #
Features implemented by sensor drivers vary, and depending on the set of supported features and other qualities, particular sensor drivers better serve the purpose of an example. The following drivers are known to be good examples:
|
Driver name |
File(s) |
Driver type |
Example topic |
|
CCS |
|
Freely configurable |
Power management (ACPI and DT), UAPI |
|
imx219 |
|
Register list based |
Power management (DT), UAPI, mode selection |
|
imx319 |
|
Register list based |
Power management (ACPI and DT) |
CEC Kernel Support
Peios Kernel / Hardware and drivers / Driver development / Media devices
The CEC framework provides a unified kernel interface for use with HDMI CEC hardware. It is designed to handle a multiple types of hardware (receivers, transmitters, USB dongles). The framework also gives the option to decide what to do in the kernel driver and what should be handled by userspace applications. In addition it integrates the remote control passthrough feature into the kernel's remote control framework.
The CEC Protocol #
The CEC protocol enables consumer electronic devices to communicate with each other through the HDMI connection. The protocol uses logical addresses in the communication. The logical address is strictly connected with the functionality provided by the device. The TV acting as the communication hub is always assigned address 0. The physical address is determined by the physical connection between devices.
The CEC framework described here is up to date with the CEC 2.0 specification. It is documented in the HDMI 1.4 specification with the new 2.0 bits documented in the HDMI 2.0 specification. But for most of the features the freely available HDMI 1.3a specification is sufficient:
https://www.hdmi.org/spec/index
CEC Adapter Interface #
The struct cec_adapter represents the CEC adapter hardware. It is created by calling cec_allocate_adapter() and deleted by calling cec_delete_adapter():
struct cec_adapter *;
void ;
To create an adapter you need to pass the following information:
-
ops:
adapter operations which are called by the CEC framework and that you have to implement.
-
priv:
will be stored in adap->priv and can be used by the adapter ops. Use cec_get_drvdata(adap) to get the priv pointer.
-
name:
the name of the CEC adapter. Note: this name will be copied.
-
caps:
capabilities of the CEC adapter. These capabilities determine the capabilities of the hardware and which parts are to be handled by userspace and which parts are handled by kernelspace. The capabilities are returned by CEC_ADAP_G_CAPS.
-
available_las:
the number of simultaneous logical addresses that this adapter can handle. Must be 1 <= available_las <= CEC_MAX_LOG_ADDRS.
To obtain the priv pointer use this helper function:
void *;
To register the /dev/cecX device node and the remote control device (if CEC_CAP_RC is set) you call:
int ;
where parent is the parent device.
To unregister the devices call:
void ;
Note: if cec_register_adapter() fails, then call cec_delete_adapter() to clean up. But if cec_register_adapter() succeeded, then only call cec_unregister_adapter() to clean up, never cec_delete_adapter(). The unregister function will delete the adapter automatically once the last user of that /dev/cecX device has closed its file handle.
Implementing the Low-Level CEC Adapter #
The following low-level adapter operations have to be implemented in your driver:
cec_adap_ops
struct cec_adap_ops
{
/* Low-level callbacks */
int (*adap_enable)(struct cec_adapter *adap, bool enable);
int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
void (*adap_unconfigured)(struct cec_adapter *adap);
int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
u32 signal_free_time, struct cec_msg *msg);
void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
const struct cec_msg *msg);
void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
void (*adap_free)(struct cec_adapter *adap);
/* Error injection callbacks */
...
/* High-level callback */
...
};
These low-level ops deal with various aspects of controlling the CEC adapter hardware. They are all called with the mutex adap->lock held.
To enable/disable the hardware:
int (*adap_enable)(struct cec_adapter *adap, bool enable);
This callback enables or disables the CEC hardware. Enabling the CEC hardware means powering it up in a state where no logical addresses are claimed. The physical address will always be valid if CEC_CAP_NEEDS_HPD is set. If that capability is not set, then the physical address can change while the CEC hardware is enabled. CEC drivers should not set CEC_CAP_NEEDS_HPD unless the hardware design requires that as this will make it impossible to wake up displays that pull the HPD low when in standby mode. The initial state of the CEC adapter after calling cec_allocate_adapter() is disabled.
Note that adap_enable must return 0 if enable is false.
To enable/disable the 'monitor all' mode:
int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
If enabled, then the adapter should be put in a mode to also monitor messages that are not for us. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_ALL capability is set. This callback is optional (some hardware may always be in 'monitor all' mode).
Note that adap_monitor_all_enable must return 0 if enable is false.
To enable/disable the 'monitor pin' mode:
int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
If enabled, then the adapter should be put in a mode to also monitor CEC pin changes. Not all hardware supports this and this function is only called if the CEC_CAP_MONITOR_PIN capability is set. This callback is optional (some hardware may always be in 'monitor pin' mode).
Note that adap_monitor_pin_enable must return 0 if enable is false.
To program a new logical address:
int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
If logical_addr == CEC_LOG_ADDR_INVALID then all programmed logical addresses are to be erased. Otherwise the given logical address should be programmed. If the maximum number of available logical addresses is exceeded, then it should return -ENXIO. Once a logical address is programmed the CEC hardware can receive directed messages to that address.
Note that adap_log_addr must return 0 if logical_addr is CEC_LOG_ADDR_INVALID.
Called when the adapter is unconfigured:
void (*adap_unconfigured)(struct cec_adapter *adap);
The adapter is unconfigured. If the driver has to take specific actions after unconfiguration, then that can be done through this optional callback.
To transmit a new message:
int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
u32 signal_free_time, struct cec_msg *msg);
This transmits a new message. The attempts argument is the suggested number of attempts for the transmit.
The signal_free_time is the number of data bit periods that the adapter should wait when the line is free before attempting to send a message. This value depends on whether this transmit is a retry, a message from a new initiator or a new message for the same initiator. Most hardware will handle this automatically, but in some cases this information is needed.
The CEC_FREE_TIME_TO_USEC macro can be used to convert signal_free_time to microseconds (one data bit period is 2.4 ms).
To pass on the result of a canceled non-blocking transmit:
void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
const struct cec_msg *msg);
This optional callback can be used to obtain the result of a canceled non-blocking transmit with sequence number msg->sequence. This is called if the transmit was aborted, the transmit timed out (i.e. the hardware never signaled that the transmit finished), or the transmit was successful, but the wait for the expected reply was either aborted or it timed out.
To log the current CEC hardware status:
void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
This optional callback can be used to show the status of the CEC hardware. The status is available through debugfs: cat /sys/kernel/debug/cec/cecX/status
To free any resources when the adapter is deleted:
void (*adap_free)(struct cec_adapter *adap);
This optional callback can be used to free any resources that might have been allocated by the driver. It's called from cec_delete_adapter.
Your adapter driver will also have to react to events (typically interrupt driven) by calling into the framework in the following situations:
When a transmit finished (successfully or otherwise):
void cec_transmit_done(struct cec_adapter *adap, u8 status,
u8 arb_lost_cnt, u8 nack_cnt, u8 low_drive_cnt,
u8 error_cnt);
or:
void cec_transmit_attempt_done(struct cec_adapter *adap, u8 status);
The status can be one of:
-
CEC_TX_STATUS_OK:
the transmit was successful.
-
CEC_TX_STATUS_ARB_LOST:
arbitration was lost: another CEC initiator took control of the CEC line and you lost the arbitration.
-
CEC_TX_STATUS_NACK:
the message was nacked (for a directed message) or acked (for a broadcast message). A retransmission is needed.
-
CEC_TX_STATUS_LOW_DRIVE:
low drive was detected on the CEC bus. This indicates that a follower detected an error on the bus and requested a retransmission.
-
CEC_TX_STATUS_ERROR:
some unspecified error occurred: this can be one of ARB_LOST or LOW_DRIVE if the hardware cannot differentiate or something else entirely. Some hardware only supports OK and FAIL as the result of a transmit, i.e. there is no way to differentiate between the different possible errors. In that case map FAIL to CEC_TX_STATUS_NACK and not to CEC_TX_STATUS_ERROR.
-
CEC_TX_STATUS_MAX_RETRIES:
could not transmit the message after trying multiple times. Should only be set by the driver if it has hardware support for retrying messages. If set, then the framework assumes that it doesn't have to make another attempt to transmit the message since the hardware did that already.
The hardware must be able to differentiate between OK, NACK and 'something else'.
The *_cnt arguments are the number of error conditions that were seen. This may be 0 if no information is available. Drivers that do not support hardware retry can just set the counter corresponding to the transmit error to 1, if the hardware does support retry then either set these counters to 0 if the hardware provides no feedback of which errors occurred and how many times, or fill in the correct values as reported by the hardware.
Be aware that calling these functions can immediately start a new transmit if there is one pending in the queue. So make sure that the hardware is in a state where new transmits can be started before calling these functions.
The cec_transmit_attempt_done() function is a helper for cases where the hardware never retries, so the transmit is always for just a single attempt. It will call cec_transmit_done() in turn, filling in 1 for the count argument corresponding to the status. Or all 0 if the status was OK.
When a CEC message was received:
void ;
Speaks for itself.
Implementing the interrupt handler #
Typically the CEC hardware provides interrupts that signal when a transmit finished and whether it was successful or not, and it provides and interrupt when a CEC message was received.
The CEC driver should always process the transmit interrupts first before handling the receive interrupt. The framework expects to see the cec_transmit_done call before the cec_received_msg call, otherwise it can get confused if the received message was in reply to the transmitted message.
Optional: Implementing Error Injection Support #
If the CEC adapter supports Error Injection functionality, then that can be exposed through the Error Injection callbacks:
struct cec_adap_ops {
/* Low-level callbacks */
...
/* Error injection callbacks */
int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
/* High-level CEC message callback */
...
};
If both callbacks are set, then an error-inj file will appear in debugfs. The basic syntax is as follows:
Leading spaces/tabs are ignored. If the next character is a # or the end of the line was reached, then the whole line is ignored. Otherwise a command is expected.
This basic parsing is done in the CEC Framework. It is up to the driver to decide what commands to implement. The only requirement is that the command clear without any arguments must be implemented and that it will remove all current error injection commands.
This ensures that you can always do echo clear >error-inj to clear any error injections without having to know the details of the driver-specific commands.
Note that the output of error-inj shall be valid as input to error-inj. So this must work:
$ cat error-inj >einj.txt
$ cat einj.txt >error-inj
The first callback is called when this file is read and it should show the current error injection state:
int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
It is recommended that it starts with a comment block with basic usage information. It returns 0 for success and an error otherwise.
The second callback will parse commands written to the error-inj file:
bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
The line argument points to the start of the command. Any leading spaces or tabs have already been skipped. It is a single line only (so there are no embedded newlines) and it is 0-terminated. The callback is free to modify the contents of the buffer. It is only called for lines containing a command, so this callback is never called for empty lines or comment lines.
Return true if the command was valid or false if there were syntax errors.
Implementing the High-Level CEC Adapter #
The low-level operations drive the hardware, the high-level operations are CEC protocol driven. The high-level callbacks are called without the adap->lock mutex being held. The following high-level callbacks are available:
struct cec_adap_ops {
/* Low-level callbacks */
...
/* Error injection callbacks */
...
/* High-level CEC message callback */
void (*configured)(struct cec_adapter *adap);
int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
};
Called when the adapter is configured:
void (*configured)(struct cec_adapter *adap);
The adapter is fully configured, i.e. all logical addresses have been successfully claimed. If the driver has to take specific actions after configuration, then that can be done through this optional callback.
The received() callback allows the driver to optionally handle a newly received CEC message:
int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
If the driver wants to process a CEC message, then it can implement this callback. If it doesn't want to handle this message, then it should return -ENOMSG, otherwise the CEC framework assumes it processed this message and it will not do anything with it.
CEC framework functions #
CEC Adapter drivers can call the following CEC framework functions:
int ;
Transmit a CEC message. If block is true, then wait until the message has been transmitted, otherwise just queue it and return.
void ;
Change the physical address. This function will set adap->phys_addr and send an event if it has changed. If cec_s_log_addrs() has been called and the physical address has become valid, then the CEC framework will start claiming the logical addresses. If block is true, then this function won't return until this process has finished.
When the physical address is set to a valid value the CEC adapter will be enabled (see the adap_enable op). When it is set to CEC_PHYS_ADDR_INVALID, then the CEC adapter will be disabled. If you change a valid physical address to another valid physical address, then this function will first set the address to CEC_PHYS_ADDR_INVALID before enabling the new physical address.
void ;
A helper function that extracts the physical address from the edid struct and calls cec_s_phys_addr() with that address, or CEC_PHYS_ADDR_INVALID if the EDID did not contain a physical address or edid was a NULL pointer.
int ;
Claim the CEC logical addresses. Should never be called if CEC_CAP_LOG_ADDRS is set. If block is true, then wait until the logical addresses have been claimed, otherwise just queue it and return. To unconfigure all logical addresses call this function with log_addrs set to NULL or with log_addrs->num_log_addrs set to 0. The block argument is ignored when unconfiguring. This function will just return if the physical address is invalid. Once the physical address becomes valid, then the framework will attempt to claim these logical addresses.
CEC Pin framework #
Most CEC hardware operates on full CEC messages where the software provides the message and the hardware handles the low-level CEC protocol. But some hardware only drives the CEC pin and software has to handle the low-level CEC protocol. The CEC pin framework was created to handle such devices.
Note that due to the close-to-realtime requirements it can never be guaranteed to work 100%. This framework uses highres timers internally, but if a timer goes off too late by more than 300 microseconds wrong results can occur. In reality it appears to be fairly reliable.
One advantage of this low-level implementation is that it can be used as a cheap CEC analyser, especially if interrupts can be used to detect CEC pin transitions from low to high or vice versa.
struct cec_pin_ops #
low-level CEC pin operations
Definition
;
Members
read: read the CEC pin. Returns > 0 if high, 0 if low, or an error if negative.low: drive the CEC pin low.high: stop driving the CEC pin. The pull-up will drive the pin high, unless someone else is driving the pin low.enable_irq: optional, enable the interrupt to detect pin voltage changes.disable_irq: optional, disable the interrupt.free: optional. Free any allocated resources. Called when the adapter is deleted.status: optional, log status information.read_hpd: optional. Read the HPD pin. Returns > 0 if high, 0 if low or an error if negative.read_5v: optional. Read the 5V pin. Returns > 0 if high, 0 if low or an error if negative.received: optional. High-level CEC message callback. Allows the driver to process CEC messages.
Description
These operations (except for the received op) are used by the cec pin framework to manipulate the CEC pin.
cec_pin_changed() #
void update pin state from interrupt
Parameters
struct cec_adapter *adap: pointer to the cec adapterbool value: when true the pin is high, otherwise it is low
Description
If changes of the CEC voltage are detected via an interrupt, then cec_pin_changed is called from the interrupt with the new value.
cec_pin_allocate_adapter() #
struct cec_adapter * allocate a pin-based cec adapter
Parameters
const struct cec_pin_ops *pin_ops: low-level pin operationsvoid *priv: will be stored in adap->priv and can be used by the adapter ops. Use cec_get_drvdata(adap) to get the priv pointer.const char *name: the name of the CEC adapter. Note: this name will be copied.u32 caps: capabilities of the CEC adapter. This will be ORed with CEC_CAP_MONITOR_ALL and CEC_CAP_MONITOR_PIN.
Description
Allocate a cec adapter using the cec pin framework.
Return
a pointer to the cec adapter or an error pointer
CEC Notifier framework #
Most drm HDMI implementations have an integrated CEC implementation and no notifier support is needed. But some have independent CEC implementations that have their own driver. This could be an IP block for an SoC or a completely separate chip that deals with the CEC pin. For those cases a drm driver can install a notifier and use the notifier to inform the CEC driver about changes in the physical address.
cec_notifier_conn_register() #
struct cec_notifier * find or create a new cec_notifier for the given HDMI device and connector tuple.
Parameters
struct device *hdmi_dev: HDMI device that sends the events.const char *port_name: the connector name from which the event occurs. May be NULL if there is always only one HDMI connector created by the HDMI device.const struct cec_connector_info *conn_info: the connector info from which the event occurs (may be NULL)
Description
If a notifier for device dev and connector port_name already exists, then increase the refcount and return that notifier.
If it doesn't exist, then allocate a new notifier struct and return a pointer to that new struct.
Return NULL if the memory could not be allocated.
cec_notifier_conn_unregister() #
void decrease refcount and delete when the refcount reaches 0.
Parameters
struct cec_notifier *n: notifier. If NULL, then this function does nothing.
cec_notifier_cec_adap_register() #
struct cec_notifier * find or create a new cec_notifier for the given device.
Parameters
struct device *hdmi_dev: HDMI device that sends the events.const char *port_name: the connector name from which the event occurs. May be NULL if there is always only one HDMI connector created by the HDMI device.struct cec_adapter *adap: the cec adapter that registered this notifier.
Description
If a notifier for device dev and connector port_name already exists, then increase the refcount and return that notifier.
If it doesn't exist, then allocate a new notifier struct and return a pointer to that new struct.
Return NULL if the memory could not be allocated.
cec_notifier_cec_adap_unregister() #
void decrease refcount and delete when the refcount reaches 0.
Parameters
struct cec_notifier *n: notifier. If NULL, then this function does nothing.struct cec_adapter *adap: the cec adapter that registered this notifier.
cec_notifier_set_phys_addr() #
void set a new physical address.
Parameters
struct cec_notifier *n: the CEC notifieru16 pa: the CEC physical address
Description
Set a new CEC physical address. Does nothing if n == NULL.
cec_notifier_set_phys_addr_from_edid() #
void set parse the PA from the EDID.
Parameters
struct cec_notifier *n: the CEC notifierconst struct edid *edid: the struct edid pointer
Description
Parses the EDID to obtain the new CEC physical address and set it. Does nothing if n == NULL.
cec_notifier_parse_hdmi_phandle() #
struct device * find the hdmi device from "hdmi-phandle"
Parameters
struct device *dev: the device with the "hdmi-phandle" device tree property
Description
Returns the device pointer referenced by the "hdmi-phandle" property. Note that the refcount of the returned device is not incremented. This device pointer is only used as a key value in the notifier list, but it is never accessed by the CEC driver.
cec_notifier_phys_addr_invalidate() #
void set the physical address to INVALID
Parameters
struct cec_notifier *n: the CEC notifier
Description
This is a simple helper function to invalidate the physical address. Does nothing if n == NULL.
Digital TV Conditional Access kABI
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct dvb_ca_en50221 #
Structure describing a CA interface
Definition
;
Members
owner: the module owning this structureread_attribute_mem: function for reading attribute memory on the CAMwrite_attribute_mem: function for writing attribute memory on the CAMread_cam_control: function for reading the control interface on the CAMwrite_cam_control: function for reading the control interface on the CAMread_data: function for reading data (block mode)write_data: function for writing data (block mode)slot_reset: function to reset the CAM slotslot_shutdown: function to shutdown a CAM slotslot_ts_enable: function to enable the Transport Stream on a CAM slotpoll_slot_status: function to poll slot status. Only necessary if DVB_CA_FLAG_EN50221_IRQ_CAMCHANGE is not set.data: private data, used by caller.private: Opaque data used by the dvb_ca core. Do not modify!
NOTE
the read_, write_ and poll_slot_status functions will be called for different slots concurrently and need to use locks where and if appropriate. There will be no concurrent access to one slot.
dvb_ca_en50221_camchange_irq() #
void A CAMCHANGE IRQ has occurred.
Parameters
struct dvb_ca_en50221 *pubca: CA instance.int slot: Slot concerned.int change_type: One of the DVB_CA_CAMCHANGE_* values
dvb_ca_en50221_camready_irq() #
void A CAMREADY IRQ has occurred.
Parameters
struct dvb_ca_en50221 *pubca: CA instance.int slot: Slot concerned.
dvb_ca_en50221_frda_irq() #
void An FR or a DA IRQ has occurred.
Parameters
struct dvb_ca_en50221 *ca: CA instance.int slot: Slot concerned.
dvb_ca_en50221_init() #
int Initialise a new DVB CA device.
Parameters
struct dvb_adapter *dvb_adapter: DVB adapter to attach the new CA device to.struct dvb_ca_en50221 *ca: The dvb_ca instance.int flags: Flags describing the CA device (DVB_CA_EN50221_FLAG_*).int slot_count: Number of slots supported.
Description
return 0 on success, nonzero on failure
dvb_ca_en50221_release() #
void Release a DVB CA device.
Parameters
struct dvb_ca_en50221 *ca: The associated dvb_ca instance.
Digital TV Common functions
Peios Kernel / Hardware and drivers / Driver development / Media devices
DVB devices #
Those functions are responsible for handling the DVB device nodes.
enum dvb_device_type #
type of the Digital TV device
Constants
DVB_DEVICE_SEC: Digital TV standalone Common Interface (CI)DVB_DEVICE_FRONTEND: Digital TV frontend.DVB_DEVICE_DEMUX: Digital TV demux.DVB_DEVICE_DVR: Digital TV digital video record (DVR).DVB_DEVICE_CA: Digital TV Conditional Access (CA).DVB_DEVICE_NET: Digital TV network.DVB_DEVICE_VIDEO: Digital TV video decoder. Deprecated. Used only on av7110-av.DVB_DEVICE_AUDIO: Digital TV audio decoder. Deprecated. Used only on av7110-av.DVB_DEVICE_OSD: Digital TV On Screen Display (OSD). Deprecated. Used only on av7110.
struct dvb_adapter #
represents a Digital TV adapter using Linux DVB API
Definition
;
Members
num: Number of the adapterlist_head: List with the DVB adaptersdevice_list: List with the DVB devicesname: Name of the adapterproposed_mac: proposed MAC address for the adapterpriv: private datadevice: pointer to struct devicemodule: pointer to struct modulemfe_shared: indicates mutually exclusive frontends. 1 = legacy exclusion behavior: blocking anyopen()call 2 = enhanced exclusion behavior, emulating the standard behavior of busy frontends: allowing read-only sharing and otherwise returning immediately with -EBUSY when any of the frontends is already opened with write access.mfe_dvbdev: Frontend device in use, in the case of MFEmfe_lock: Lock to prevent using the other frontends when MFE is used.mdev_lock: Protect access to the mdev pointer.mdev: pointer to struct media_device, used when the media controller is used.conn: RF connector. Used only if the device has no separate tuner.conn_pads: pointer to struct media_pad associated with conn;
struct dvb_device #
represents a DVB device node
Definition
;
Members
list_head: List head with all DVB devicesref: reference count for this devicefops: pointer to struct file_operationsadapter: pointer to the adapter that holds this device nodetype: type of the device, as defined byenum dvb_device_type.minor: devnode minor number. Major number is always DVB_MAJOR.id: device ID number, inside the adapterreaders: Initialized by the caller. Each call toopen()in Read Only mode decreases this counter by one.writers: Initialized by the caller. Each call toopen()in Read/Write mode decreases this counter by one.users: Initialized by the caller. Each call toopen()in any mode decreases this counter by one.wait_queue: wait queue, used to wait for certain events inside one of the DVB API callerskernel_ioctl: callback function used to handle ioctl calls from userspace.name: Name to be used for the device at the Media Controllerintf_devnode: Pointer to media_intf_devnode. Used by the dvbdev core to store the MC device node interfacetsout_num_entities: Number of Transport Stream output entitiesentity: pointer to struct media_entity associated with the device nodetsout_entity: array with MC entities associated to each TS output nodepads: pointer to struct media_pad associated with entity;tsout_pads: array with the source pads for each tsout_entitypriv: private data
Description
This structure is used by the DVB core (frontend, CA, net, demux) in order to create the device nodes. Usually, driver should not initialize this struct diretly.
struct dvbdevfops_node #
fops nodes registered in dvbdevfops_list
Definition
;
Members
fops: Dynamically allocated fops for ->owner registrationtype: type of dvb_devicetemplate: dvb_device used for registrationlist_head: list_head for dvbdevfops_list
dvb_device_get() #
struct dvb_device * Increase dvb_device reference
Parameters
struct dvb_device *dvbdev: pointer to struct dvb_device
dvb_device_put() #
void Decrease dvb_device reference
Parameters
struct dvb_device *dvbdev: pointer to struct dvb_device
dvb_register_adapter() #
int Registers a new DVB adapter
Parameters
struct dvb_adapter *adap: pointer to struct dvb_adapterconst char *name: Adapter's namestruct module *module: initialized with THIS_MODULE at the callerstruct device *device: pointer to struct device that corresponds to the device drivershort *adapter_nums: Array with a list of the numbers for dvb_register_adapter; to select among them. Typically, initialized with: DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nums)
dvb_unregister_adapter() #
int Unregisters a DVB adapter
Parameters
struct dvb_adapter *adap: pointer to struct dvb_adapter
dvb_register_device() #
int Registers a new DVB device
Parameters
struct dvb_adapter *adap: pointer to struct dvb_adapterstruct dvb_device **pdvbdev: pointer to the place where the new struct dvb_device will be storedconst struct dvb_device *template: Template used to createpdvbdev;void *priv: private dataenum dvb_device_type type: type of the device, as defined byenum dvb_device_type.int demux_sink_pads: Number of demux outputs, to be used to create the TS outputs via the Media Controller.
dvb_remove_device() #
void Remove a registered DVB device
Parameters
struct dvb_device *dvbdev: pointer to struct dvb_device
Description
This does not free memory. dvb_free_device() will do that when
reference counter is empty
dvb_unregister_device() #
void Unregisters a DVB device
Parameters
struct dvb_device *dvbdev: pointer to struct dvb_device
dvb_create_media_graph() #
int Creates media graph for the Digital TV part of the device.
Parameters
struct dvb_adapter *adap: pointer tostruct dvb_adapterbool create_rf_connector: if true, it creates the RF connector too
Description
This function checks all DVB-related functions at the media controller entities and creates the needed links for the media graph. It is capable of working with multiple tuners or multiple frontends, but it won't create links if the device has multiple tuners and multiple frontends or if the device has multiple muxes. In such case, the caller driver should manually create the remaining links.
dvb_register_media_controller() #
void registers a media controller at DVB adapter
Parameters
struct dvb_adapter *adap: pointer tostruct dvb_adapterstruct media_device *mdev: pointer tostruct media_device
dvb_get_media_controller() #
struct media_device * gets the associated media controller
Parameters
struct dvb_adapter *adap: pointer tostruct dvb_adapter
dvb_generic_open() #
int Digital TV open function, used by DVB devices
Parameters
struct inode *inode: pointer tostruct inode.struct file *file: pointer tostruct file.
Description
Checks if a DVB devnode is still valid, and if the permissions are OK and increment negative use count.
dvb_generic_release() #
int Digital TV close function, used by DVB devices
Parameters
struct inode *inode: pointer tostruct inode.struct file *file: pointer tostruct file.
Description
Checks if a DVB devnode is still valid, and if the permissions are OK and decrement negative use count.
dvb_generic_ioctl() #
long Digital TV close function, used by DVB devices
Parameters
struct file *file: pointer tostruct file.unsigned int cmd: Ioctl name.unsigned long arg: Ioctl argument.
Description
Checks if a DVB devnode and struct dvbdev.kernel_ioctl is still valid.
If so, calls dvb_usercopy().
dvb_usercopy() #
int copies data from/to userspace memory when an ioctl is issued.
Parameters
struct file *file: Pointer to structfile.unsigned int cmd: Ioctl name.unsigned long arg: Ioctl argument.int (*func)(struct file *file, unsigned int cmd, void *arg): function that will actually handle the ioctl
Description
Ancillary function that uses ioctl direction and size to copy from userspace. Then, it calls func, and, if needed, data is copied back to userspace.
dvb_module_probe() #
struct i2c_client * helper routine to probe an I2C module
Parameters
const char *module_name: Name of the I2C module to be probedconst char *name: Optional name for the I2C module. Used for debug purposes. IfNULL, defaults to module_name.struct i2c_adapter *adap: pointer tostruct i2c_adapterthat describes the I2C adapter where the module will be bound.unsigned char addr: I2C address of the adapter, in 7-bit notation.void *platform_data: Platform data to be passed to the I2C module probed.
Description
This function binds an I2C device into the DVB core. Should be used by
all drivers that use I2C bus to control the hardware. A module bound
with dvb_module_probe() should use dvb_module_release() to unbind.
Return
On success, return an struct i2c_client, pointing to the bound
I2C device. NULL otherwise.
dvb_module_release() #
void releases an I2C device allocated with dvb_module_probe().
Parameters
struct i2c_client *client: pointer tostruct i2c_clientwith the I2C client to be released. can beNULL.
Description
This function should be used to free all resources reserved by
dvb_module_probe() and unbinding the I2C hardware.
dvb_attach() #
attaches a DVB frontend into the DVB core.
Parameters
-
FUNCTION: function on a frontend module to be called. -
ARGS...:FUNCTION arguments.
Description
This ancillary function loads a frontend module in runtime and runs
the FUNCTION function there, with ARGS.
As it increments symbol usage cont, at unregister, dvb_detach()
should be called.
dvb_detach() #
detaches a DVB frontend loaded via dvb_attach()
Parameters
FUNC: attach function
Description
Decrements usage count for a function previously called via dvb_attach().
Digital TV Ring buffer #
Those routines implement ring buffers used to handle digital TV data and copy it from/to userspace.
struct dvb_ringbuffer #
Describes a ring buffer used at DVB framework
Definition
;
Members
data: Area were the ringbuffer data is writtensize: size of the ringbufferpread: next position to readpwrite: next position to writeerror: used by ringbuffer clients to indicate that an error happened.queue: Wait queue used by ringbuffer clients to indicate when buffer was filledlock: Spinlock used to protect the ringbuffer
dvb_ringbuffer_init() #
void initialize ring buffer, lock and queue
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffervoid *data: pointer to the buffer where the data will be storedsize_t len: bytes from ring buffer into buf
dvb_ringbuffer_empty() #
int test whether buffer is empty
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
dvb_ringbuffer_free() #
ssize_t returns the number of free bytes in the buffer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
Return
number of free bytes in the buffer
dvb_ringbuffer_avail() #
ssize_t returns the number of bytes waiting in the buffer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
Return
number of bytes waiting in the buffer
dvb_ringbuffer_reset() #
void resets the ringbuffer to initial state
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
Description
Resets the read and write pointers to zero and flush the buffer.
This counts as a read and write operation
dvb_ringbuffer_flush() #
void flush buffer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
dvb_ringbuffer_flush_spinlock_wakeup() #
void flush buffer protected by spinlock and wake-up waiting task(s)
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbuffer
DVB_RINGBUFFER_PEEK() #
peek at byte offs in the buffer
Parameters
rbuf: pointer to struct dvb_ringbufferoffs: offset inside the ringbuffer
DVB_RINGBUFFER_SKIP() #
advance read ptr by num bytes
Parameters
rbuf: pointer to struct dvb_ringbuffernum: number of bytes to advance
dvb_ringbuffer_read_user() #
ssize_t Reads a buffer into a user pointer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbufferu8 __user *buf: pointer to the buffer where the data will be storedsize_t len: bytes from ring buffer into buf
Description
This variant assumes that the buffer is a memory at the userspace. So,
it will internally call copy_to_user().
Return
number of bytes transferred or -EFAULT
dvb_ringbuffer_read() #
void Reads a buffer into a pointer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbufferu8 *buf: pointer to the buffer where the data will be storedsize_t len: bytes from ring buffer into buf
Description
This variant assumes that the buffer is a memory at the Kernel space
Return
number of bytes transferred or -EFAULT
DVB_RINGBUFFER_WRITE_BYTE() #
write single byte to ring buffer
Parameters
rbuf: pointer to struct dvb_ringbufferbyte: byte to write
dvb_ringbuffer_write() #
ssize_t Writes a buffer into the ringbuffer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbufferconst u8 *buf: pointer to the buffer where the data will be readsize_t len: bytes from ring buffer into buf
Description
This variant assumes that the buffer is a memory at the Kernel space
Return
number of bytes transferred or -EFAULT
dvb_ringbuffer_write_user() #
ssize_t Writes a buffer received via a user pointer
Parameters
struct dvb_ringbuffer *rbuf: pointer to struct dvb_ringbufferconst u8 __user *buf: pointer to the buffer where the data will be readsize_t len: bytes from ring buffer into buf
Description
This variant assumes that the buffer is a memory at the userspace. So,
it will internally call copy_from_user().
Return
number of bytes transferred or -EFAULT
dvb_ringbuffer_pkt_write() #
ssize_t Write a packet into the ringbuffer.
Parameters
struct dvb_ringbuffer *rbuf: Ringbuffer to write to.u8 *buf: Buffer to write.size_t len: Length of buffer (currently limited to 65535 bytes max).
Return
Number of bytes written, or -EFAULT, -ENOMEM, -EINVAL.
dvb_ringbuffer_pkt_read_user() #
ssize_t Read from a packet in the ringbuffer.
Parameters
struct dvb_ringbuffer *rbuf: Ringbuffer concerned.size_t idx: Packet index as returned bydvb_ringbuffer_pkt_next().int offset: Offset into packet to read from.u8 __user *buf: Destination buffer for data.size_t len: Size of destination buffer.
Return
Number of bytes read, or -EFAULT.
Description
dvb_ringbuffer_pkt_read() #
ssize_t Read from a packet in the ringbuffer.
Parameters
struct dvb_ringbuffer *rbuf: Ringbuffer concerned.size_t idx: Packet index as returned bydvb_ringbuffer_pkt_next().int offset: Offset into packet to read from.u8 *buf: Destination buffer for data.size_t len: Size of destination buffer.
Note
unlike dvb_ringbuffer_read_user(), this DOES update the read pointer
in the ringbuffer.
Return
Number of bytes read, or -EFAULT.
dvb_ringbuffer_pkt_dispose() #
void Dispose of a packet in the ring buffer.
Parameters
struct dvb_ringbuffer *rbuf: Ring buffer concerned.size_t idx: Packet index as returned bydvb_ringbuffer_pkt_next().
dvb_ringbuffer_pkt_next() #
ssize_t Get the index of the next packet in a ringbuffer.
Parameters
struct dvb_ringbuffer *rbuf: Ringbuffer concerned.size_t idx: Previous packet index, or -1 to return the first packet index.size_t *pktlen: On success, will be updated to contain the length of the packet in bytes. returns Packet index (if >=0), or -1 if no packets available.
Digital TV VB2 handler #
enum dvb_buf_type #
types of Digital TV memory-mapped buffers
Constants
DVB_BUF_TYPE_CAPTURE: buffer is filled by the Kernel, with a received Digital TV stream
enum dvb_vb2_states #
states to control VB2 state machine
Constants
DVB_VB2_STATE_NONE: VB2 engine not initialized yet, init failed or VB2 was released.DVB_VB2_STATE_INIT: VB2 engine initialized.DVB_VB2_STATE_REQBUFS: Buffers were requestedDVB_VB2_STATE_STREAMON: VB2 is streaming. Callers should not check it directly. Instead, they should usedvb_vb2_is_streaming().
Note
Callers should not touch at the state machine directly. This is handled inside dvb_vb2.c.
struct dvb_buffer #
video buffer information for v4l2.
Definition
;
Members
vb: embedded structvb2_buffer.list: list ofstruct dvb_buffer.
struct dvb_vb2_ctx #
control struct for VB2 handler
Definition
;
Members
vb_q: pointer tostruct vb2_queuewith videobuf2 queue.slock: spin lock used to protect buffer filling at dvb_vb2.c.dvb_q: List of buffers that are not filled yet.buf: Pointer to the buffer that are currently being filled.offset: index to the next position at the buf to be filled.remain: How many bytes are left to be filled at buf.state: bitmask of buffer states as defined byenum dvb_vb2_states.buf_siz: size of each VB2 buffer.buf_cnt: number of VB2 buffers.nonblocking: If different than zero, device is operating on non-blocking mode.flags: buffer flags as defined byenum dmx_buffer_flags. Filled only atDMX_DQBUF.DMX_QBUFshould zero this field.count: monotonic counter for filled buffers. Helps to identify data stream loses. Filled only atDMX_DQBUF.DMX_QBUFshould zero this field.name: name of the device type. Currently, it can either be "dvr" or "demux_filter".
dvb_vb2_init() #
int initializes VB2 handler
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerconst char *name: name for the VB2 handlerstruct mutex *mutex: pointer to the mutex that serializes vb2 ioctlsint non_blocking: if not zero, it means that the device is at non-blocking mode
dvb_vb2_release() #
int Releases the VB2 handler allocated resources and put ctx at DVB_VB2_STATE_NONE state.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handler
dvb_vb2_is_streaming() #
int checks if the VB2 handler is streaming
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handler
Return
0 if not streaming, 1 otherwise.
dvb_vb2_fill_buffer() #
int fills a VB2 buffer
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerconst unsigned char *src: place where the data is storedint len: number of bytes to be copied from srcenum dmx_buffer_flags *buffer_flags: pointer to buffer flags as defined byenum dmx_buffer_flags. can be NULL.bool flush: flush the buffer, even if it isn't full.
dvb_vb2_poll() #
__poll_t Wrapper to vb2_core_streamon() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct file *file:struct fileargument passed to the poll file operation handler.poll_table *wait:poll_tablewait argument passed to the poll file operation handler.
Description
Implements poll syscall() logic.
dvb_vb2_stream_on() #
int Wrapper to vb2_core_streamon() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handler
Description
Starts dvb streaming
dvb_vb2_stream_off() #
int Wrapper to vb2_core_streamoff() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handler
Description
Stops dvb streaming
dvb_vb2_reqbufs() #
int Wrapper to vb2_core_reqbufs() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct dmx_requestbuffers *req:struct dmx_requestbufferspassed from userspace in order to handleDMX_REQBUFS.
Description
Initiate streaming by requesting a number of buffers. Also used to
free previously requested buffers, is req->count is zero.
dvb_vb2_querybuf() #
int Wrapper to vb2_core_querybuf() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct dmx_buffer *b:struct dmx_bufferpassed from userspace in order to handleDMX_QUERYBUF.
dvb_vb2_expbuf() #
int Wrapper to vb2_core_expbuf() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct dmx_exportbuffer *exp:struct dmx_exportbufferpassed from userspace in order to handleDMX_EXPBUF.
Description
Export a buffer as a file descriptor.
dvb_vb2_qbuf() #
int Wrapper to vb2_core_qbuf() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct dmx_buffer *b:struct dmx_bufferpassed from userspace in order to handleDMX_QBUF.
Description
Queue a Digital TV buffer as requested by userspace
dvb_vb2_dqbuf() #
int Wrapper to vb2_core_dqbuf() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct dmx_buffer *b:struct dmx_bufferpassed from userspace in order to handleDMX_DQBUF.
Description
Dequeue a Digital TV buffer to the userspace
dvb_vb2_mmap() #
int Wrapper to vb2_mmap() for Digital TV buffer handling.
Parameters
struct dvb_vb2_ctx *ctx: control struct for VB2 handlerstruct vm_area_struct *vma: pointer tostruct vm_area_structwith the vma passed to the mmap file operation handler in the driver.
Description
map Digital TV video buffers into application address space.
Digital TV (DVB) devices
Peios Kernel / Hardware and drivers / Driver development / Media devices
Digital TV devices are implemented by several different drivers:
-
A bridge driver that is responsible to talk with the bus where the other devices are connected (PCI, USB, SPI), bind to the other drivers and implement the digital demux logic (either in software or in hardware);
-
Frontend drivers that are usually implemented as two separate drivers:
-
A tuner driver that implements the logic which commands the part of the hardware responsible for tuning into a digital TV transponder or physical channel. The output of a tuner is usually a baseband or Intermediate Frequency (IF) signal;
-
A demodulator driver (a.k.a "demod") that implements the logic which commands the digital TV decoding hardware. The output of a demod is a digital stream, with multiple audio, video and data channels typically multiplexed using MPEG Transport Stream 1.
-
On most hardware, the frontend drivers talk with the bridge driver using an I2C bus.
[1] Some standards use TCP/IP for multiplexing data, like DVB-H (an abandoned standard, not used anymore) and ATSC version 3.0 current proposals. Currently, the DVB subsystem doesn't implement those standards.
Digital TV Demux kABI
Peios Kernel / Hardware and drivers / Driver development / Media devices
Digital TV Demux #
The Kernel Digital TV Demux kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent demux layer. It is only of interest for Digital TV device driver writers. The header file for this kABI is named demux.h and located in include/media.
The demux kABI should be implemented for each demux in the system. It is used to select the TS source of a demux and to manage the demux resources. When the demux client allocates a resource via the demux kABI, it receives a pointer to the kABI of that resource.
Each demux receives its TS input from a DVB front-end or from memory, as set via this demux kABI. In a system with more than one front-end, the kABI can be used to select one of the DVB front-ends as a TS source for a demux, unless this is fixed in the HW platform.
The demux kABI only controls front-ends regarding to their connections with demuxes; the kABI used to set the other front-end parameters, such as tuning, are defined via the Digital TV Frontend kABI.
The functions that implement the abstract interface demux should be defined static or module private and registered to the Demux core for external access. It is not necessary to implement every function in the struct dmx_demux. For example, a demux interface might support Section filtering, but not PES filtering. The kABI client is expected to check the value of any function pointer before calling the function: the value of NULL means that the function is not available.
Whenever the functions of the demux API modify shared data, the possibilities of lost update and race condition problems should be addressed, e.g. by protecting parts of code with mutexes.
Note that functions called from a bottom half context must not sleep. Even a simple memory allocation without using GFP_ATOMIC can result in a kernel thread being put to sleep if swapping is needed. For example, the Linux Kernel calls the functions of a network device interface from a bottom half context. Thus, if a demux kABI function is called from network device code, the function must not sleep.
Demux Callback API #
This kernel-space API comprises the callback functions that deliver filtered data to the demux client. Unlike the other DVB kABIs, these functions are provided by the client and called from the demux code.
The function pointers of this abstract interface are not packed into a structure as in the other demux APIs, because the callback functions are registered and used independent of each other. As an example, it is possible for the API client to provide several callback functions for receiving TS packets and no callbacks for PES packets or sections.
The functions that implement the callback API need not be re-entrant: when a demux driver calls one of these functions, the driver is not allowed to call the function again before the original call returns. If a callback is triggered by a hardware interrupt, it is recommended to use the Linux bottom half mechanism or start a tasklet instead of making the callback function call directly from a hardware interrupt.
This mechanism is implemented by dmx_ts_cb() and dmx_section_cb() callbacks.
Digital TV Demux device registration functions and data structures #
enum dmxdev_type #
type of demux filter type.
Constants
DMXDEV_TYPE_NONE: no filter set.DMXDEV_TYPE_SEC: section filter.DMXDEV_TYPE_PES: Program Elementary Stream (PES) filter.
enum dmxdev_state #
state machine for the dmxdev.
Constants
DMXDEV_STATE_FREE: indicates that the filter is freed.DMXDEV_STATE_ALLOCATED: indicates that the filter was allocated to be used.DMXDEV_STATE_SET: indicates that the filter parameters are set.DMXDEV_STATE_GO: indicates that the filter is running.DMXDEV_STATE_DONE: indicates that a packet was already filtered and the filter is now disabled. Set only ifDMX_ONESHOT. Seedmx_sct_filter_params.DMXDEV_STATE_TIMEDOUT: Indicates a timeout condition.
struct dmxdev_feed #
digital TV dmxdev feed
Definition
;
Members
pid: Program ID to be filteredts: pointer tostruct dmx_ts_feednext:struct list_headpointing to the next feed.
struct dmxdev_filter #
digital TV dmxdev filter
Definition
;
Members
filter: a union describing a dmxdev filter. Currently used only for section filters.filter.sec: astruct dmx_section_filterpointer. For section filter only.feed: a union describing a dmxdev feed. Depending on the filter type, it can be either feed.ts or feed.sec.feed.ts: astruct list_headlist. For TS and PES feeds.feed.sec: astruct dmx_section_feedpointer. For section feed only.params: a union describing dmxdev filter parameters. Depending on the filter type, it can be either params.sec or params.pes.params.sec: astruct dmx_sct_filter_paramsembedded struct. For section filter only.params.pes: astruct dmx_pes_filter_paramsembedded struct. For PES filter only.type: type of the dmxdev filter, as defined byenum dmxdev_type.state: state of the dmxdev filter, as defined byenum dmxdev_state.dev: pointer tostruct dmxdev.buffer: an embeddedstruct dvb_ringbufferbuffer.vb2_ctx: control struct for VB2 handlermutex: protects the access tostruct dmxdev_filter.timer:struct timer_listembedded timer, used to check for feed timeouts. Only for section filter.todo: index for the secheader. Only for section filter.secheader: buffer cache to parse the section header. Only for section filter.
struct dmxdev #
Describes a digital TV demux device.
Definition
;
Members
dvbdev: pointer tostruct dvb_deviceassociated with the demux device node.dvr_dvbdev: pointer tostruct dvb_deviceassociated with the dvr device node.filter: pointer tostruct dmxdev_filter.demux: pointer tostruct dmx_demux.filternum: number of filters.capabilities: demux capabilities as defined byenum dmx_demux_caps.may_do_mmap: flag used to indicate if the device may do mmap.exit: flag to indicate that the demux is being released.dvr_orig_fe: pointer tostruct dmx_frontend.dvr_buffer: embeddedstruct dvb_ringbufferfor DVB output.dvr_vb2_ctx: control struct for VB2 handlermutex: protects the usage of this structure.lock: protects access todmxdev->filter->data.
dvb_dmxdev_init() #
int initializes a digital TV demux and registers both demux and DVR devices.
Parameters
struct dmxdev *dmxdev: pointer tostruct dmxdev.struct dvb_adapter *adap: pointer tostruct dvb_adapter.
dvb_dmxdev_release() #
void releases a digital TV demux and unregisters it.
Parameters
struct dmxdev *dmxdev: pointer tostruct dmxdev.
High-level Digital TV demux interface #
enum dvb_dmx_filter_type #
type of demux feed.
Constants
DMX_TYPE_TS: feed is in TS mode.DMX_TYPE_SEC: feed is in Section mode.
enum dvb_dmx_state #
state machine for a demux filter.
Constants
DMX_STATE_FREE: indicates that the filter is freed.DMX_STATE_ALLOCATED: indicates that the filter was allocated to be used.DMX_STATE_READY: indicates that the filter is ready to be used.DMX_STATE_GO: indicates that the filter is running.
struct dvb_demux_filter #
Describes a DVB demux section filter.
Definition
;
Members
filter: Section filter as defined bystruct dmx_section_filter.maskandmode: logicalandbit mask.maskandnotmode: logicaland notbit mask.doneq: flag that indicates when a filter is ready.next: pointer to the next section filter.feed:struct dvb_demux_feedpointer.index: index of the used demux filter.state: state of the filter as described byenum dvb_dmx_state.type: type of the filter as described byenum dvb_dmx_filter_type.
struct dvb_demux_feed #
describes a DVB field
Definition
;
Members
feed: a union describing a digital TV feed. Depending on the feed type, it can be either feed.ts or feed.sec.feed.ts: astruct dmx_ts_feedpointer. For TS feed only.feed.sec: astruct dmx_section_feedpointer. For section feed only.cb: a union describing digital TV callbacks. Depending on the feed type, it can be either cb.ts or cb.sec.cb.ts: admx_ts_cb()calback function pointer. For TS feed only.cb.sec: admx_section_cb()callback function pointer. For section feed only.demux: pointer tostruct dvb_demux.priv: private data that can optionally be used by a DVB driver.type: type of the filter, as defined byenum dvb_dmx_filter_type.state: state of the filter as defined byenum dvb_dmx_state.pid: PID to be filtered.timeout: feed timeout.filter: pointer tostruct dvb_demux_filter.buffer_flags: Buffer flags used to report discontinuity users via DVB memory mapped API, as defined byenum dmx_buffer_flags.ts_type: type of TS, as defined byenum ts_filter_type.pes_type: type of PES, as defined byenum dmx_ts_pes.cc: MPEG-TS packet continuity counterpusi_seen: if true, indicates that a discontinuity was detected. it is used to prevent feeding of garbage from previous section.peslen: length of the PES (Packet Elementary Stream).list_head: head for the list of digital TV demux feeds.index: a unique index for each feed. Can be used as hardware pid filter index.
struct dvb_demux #
represents a digital TV demux
Definition
;
Members
dmx: embeddedstruct dmx_demuxwith demux capabilities and callbacks.priv: private data that can optionally be used by a DVB driver.filternum: maximum amount of DVB filters.feednum: maximum amount of DVB feeds.start_feed: callback routine to be called in order to start a DVB feed.stop_feed: callback routine to be called in order to stop a DVB feed.write_to_decoder: callback routine to be called if the feed is TS and it is routed to an A/V decoder, when a new TS packet is received. Used only on av7110-av.c.check_crc32: callback routine to check CRC. If not initialized, dvb_demux will use an internal one.memcopy: callback routine to memcopy received data. If not initialized, dvb_demux will default tomemcpy().users: counter for the number of demux opened file descriptors. Currently, it is limited to 10 users.filter: pointer tostruct dvb_demux_filter.feed: pointer tostruct dvb_demux_feed.frontend_list:struct list_headwith frontends used by the demux.pesfilter: array ofstruct dvb_demux_feedwith the PES types that will be filtered.pids: list of filtered program IDs.feed_list:struct list_headwith feeds.tsbuf: temporary buffer used internally to store TS packets.tsbufp: temporary buffer index used internally.mutex: pointer tostruct mutexused to protect feed set logic.lock: pointer tospinlock_t, used to protect buffer handling.cnt_storage: buffer used for TS/TEI continuity check.speed_last_time:ktime_tused for TS speed check.speed_pkts_cnt: packets count used for TS speed check.
dvb_dmx_init() #
int initialize a digital TV demux struct.
Parameters
struct dvb_demux *demux:struct dvb_demuxto be initialized.
Description
Before being able to register a digital TV demux struct, drivers should call this routine. On its typical usage, some fields should be initialized at the driver before calling it.
A typical usecase is:
dvb->demux.dmx.capabilities =
DMX_TS_FILTERING | DMX_SECTION_FILTERING |
DMX_MEMORY_BASED_FILTERING;
dvb->demux.priv = dvb;
dvb->demux.filternum = 256;
dvb->demux.feednum = 256;
dvb->demux.start_feed = driver_start_feed;
dvb->demux.stop_feed = driver_stop_feed;
ret = dvb_dmx_init(&dvb->demux);
if (ret < 0)
return ret;
dvb_dmx_release() #
void releases a digital TV demux internal buffers.
Parameters
struct dvb_demux *demux:struct dvb_demuxto be released.
Description
The DVB core internally allocates data at demux. This routine releases those data. Please notice that the struct itelf is not released, as it can be embedded on other structs.
dvb_dmx_swfilter_packets() #
void use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.
Parameters
struct dvb_demux *demux: pointer tostruct dvb_demuxconst u8 *buf: buffer with data to be filteredsize_t count: number of MPEG-TS packets with size of 188.
Description
The routine will discard a DVB packet that don't start with 0x47.
Use this routine if the DVB demux fills MPEG-TS buffers that are already aligned.
NOTE
The buf size should have size equal to count * 188.
dvb_dmx_swfilter() #
void use dvb software filter for a buffer with multiple MPEG-TS packets with 188 bytes each.
Parameters
struct dvb_demux *demux: pointer tostruct dvb_demuxconst u8 *buf: buffer with data to be filteredsize_t count: number of MPEG-TS packets with size of 188.
Description
If a DVB packet doesn't start with 0x47, it will seek for the first byte that starts with 0x47.
Use this routine if the DVB demux fill buffers that may not start with a packet start mark (0x47).
NOTE
The buf size should have size equal to count * 188.
dvb_dmx_swfilter_204() #
void use dvb software filter for a buffer with multiple MPEG-TS packets with 204 bytes each.
Parameters
struct dvb_demux *demux: pointer tostruct dvb_demuxconst u8 *buf: buffer with data to be filteredsize_t count: number of MPEG-TS packets with size of 204.
Description
If a DVB packet doesn't start with 0x47, it will seek for the first byte that starts with 0x47.
Use this routine if the DVB demux fill buffers that may not start with a packet start mark (0x47).
NOTE
The buf size should have size equal to count * 204.
dvb_dmx_swfilter_raw() #
void make the raw data available to userspace without filtering
Parameters
struct dvb_demux *demux: pointer tostruct dvb_demuxconst u8 *buf: buffer with datasize_t count: number of packets to be passed. The actual size of each packet depends on thedvb_demux->feed->cb.ts logic.
Description
Use it if the driver needs to deliver the raw payload to userspace without passing through the kernel demux. That is meant to support some delivery systems that aren't based on MPEG-TS.
This function relies on dvb_demux->feed->cb.ts to actually handle the
buffer.
Driver-internal low-level hardware specific driver demux interface #
enum ts_filter_type #
filter type bitmap for dmx_ts_feed.set()
Constants
TS_PACKET: Send TS packets (188 bytes) to callback (default).TS_PAYLOAD_ONLY: In case TS_PACKET is set, only send the TS payload (<=184 bytes per packet) to callbackTS_DECODER: Send stream to built-in decoder (if present).TS_DEMUX: In case TS_PACKET is set, send the TS to the demux device, not to the dvr device
struct dmx_ts_feed #
Structure that contains a TS feed filter
Definition
;
Members
is_filtering: Set to non-zero when filtering in progressparent: pointer to struct dmx_demuxpriv: pointer to private data of the API clientset: sets the TS filterstart_filtering: starts TS filteringstop_filtering: stops TS filtering
Description
A TS feed is typically mapped to a hardware PID filter on the demux chip. Using this API, the client can set the filtering properties to start/stop filtering TS packets on a particular TS feed.
struct dmx_section_filter #
Structure that describes a section filter
Definition
;
Members
filter_value: Contains up to 16 bytes (128 bits) of the TS section header that will be matched by the section filterfilter_mask: Contains a 16 bytes (128 bits) filter mask with the bits specified by filter_value that will be used on the filter match logic.filter_mode: Contains a 16 bytes (128 bits) filter mode.parent: Back-pointer to struct dmx_section_feed.priv: Pointer to private data of the API client.
Description
The filter_mask controls which bits of filter_value are compared with the section headers/payload. On a binary value of 1 in filter_mask, the corresponding bits are compared. The filter only accepts sections that are equal to filter_value in all the tested bit positions.
struct dmx_section_feed #
Structure that contains a section feed filter
Definition
;
Members
is_filtering: Set to non-zero when filtering in progressparent: pointer to struct dmx_demuxpriv: pointer to private data of the API clientcheck_crc: If non-zero, check the CRC values of filtered sections.set: sets the section filterallocate_filter: This function is used to allocate a section filter on the demux. It should only be called when no filtering is in progress on this section feed. If a filter cannot be allocated, the function fails with -ENOSPC.release_filter: This function releases all the resources of a previously allocated section filter. The function should not be called while filtering is in progress on this section feed. After calling this function, the caller should not try to dereference the filter pointer.start_filtering: starts section filteringstop_filtering: stops section filtering
Description
A TS feed is typically mapped to a hardware PID filter on the demux chip. Using this API, the client can set the filtering properties to start/stop filtering TS packets on a particular TS feed.
dmx_ts_cb() #
typedef int
DVB demux TS filter callback function prototype
Parameters
const u8 *buffer1: Pointer to the start of the filtered TS packets.size_t buffer1_length: Length of the TS data in buffer1.const u8 *buffer2: Pointer to the tail of the filtered TS packets, or NULL.size_t buffer2_length: Length of the TS data in buffer2.struct dmx_ts_feed *source: Indicates which TS feed is the source of the callback.u32 *buffer_flags: Address where buffer flags are stored. Those are used to report discontinuity users via DVB memory mapped API, as defined byenum dmx_buffer_flags.
Description
This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when filtering
on a TS feed has been enabled using the start_filtering() function at
the dmx_demux.
Any TS packets that match the filter settings are copied to a circular
buffer. The filtered TS packets are delivered to the client using this
callback function.
It is expected that the buffer1 and buffer2 callback parameters point to
addresses within the circular buffer, but other implementations are also
possible. Note that the called party should not try to free the memory
the buffer1 and buffer2 parameters point to.
When this function is called, the buffer1 parameter typically points to
the start of the first undelivered TS packet within a circular buffer.
The buffer2 buffer parameter is normally NULL, except when the received
TS packets have crossed the last address of the circular buffer and
"wrapped" to the beginning of the buffer. In the latter case the buffer1
parameter would contain an address within the circular buffer, while the
buffer2 parameter would contain the first address of the circular buffer.
The number of bytes delivered with this function (i.e. buffer1_length +
buffer2_length) is usually equal to the value of callback_length parameter
given in the set() function, with one exception: if a timeout occurs before
receiving callback_length bytes of TS data, any undelivered packets are
immediately delivered to the client by calling this function. The timeout
duration is controlled by the set() function in the TS Feed API.
If a TS packet is received with errors that could not be fixed by the TS-level forward error correction (FEC), the Transport_error_indicator flag of the TS packet header should be set. The TS packet should not be discarded, as the error can possibly be corrected by a higher layer protocol. If the called party is slow in processing the callback, it is possible that the circular buffer eventually fills up. If this happens, the demux driver should discard any TS packets received while the buffer is full and return -EOVERFLOW.
The type of data returned to the callback can be selected by the
dmx_ts_feed.set function. The type parameter decides if the raw
TS packet (TS_PACKET) or just the payload (TS_PACKET|TS_PAYLOAD_ONLY)
should be returned. If additionally the TS_DECODER bit is set the stream
will also be sent to the hardware MPEG decoder.
-
0, on success;
-
-EOVERFLOW, on buffer overflow.
dmx_section_cb() #
typedef int
DVB demux TS filter callback function prototype
Parameters
const u8 *buffer1: Pointer to the start of the filtered section, e.g. within the circular buffer of the demux driver.size_t buffer1_len: Length of the filtered section data in buffer1, including headers and CRC.const u8 *buffer2: Pointer to the tail of the filtered section data, or NULL. Useful to handle the wrapping of a circular buffer.size_t buffer2_len: Length of the filtered section data in buffer2, including headers and CRC.struct dmx_section_filter *source: Indicates which section feed is the source of the callback.u32 *buffer_flags: Address where buffer flags are stored. Those are used to report discontinuity users via DVB memory mapped API, as defined byenum dmx_buffer_flags.
Description
This function callback prototype, provided by the client of the demux API,
is called from the demux code. The function is only called when
filtering of sections has been enabled using the function
dmx_ts_feed.start_filtering. When the demux driver has received a
complete section that matches at least one section filter, the client
is notified via this callback function. Normally this function is called
for each received section; however, it is also possible to deliver
multiple sections with one callback, for example when the system load
is high. If an error occurs while receiving a section, this
function should be called with the corresponding error type set in the
success field, whether or not there is data to deliver. The Section Feed
implementation should maintain a circular buffer for received sections.
However, this is not necessary if the Section Feed API is implemented as
a client of the TS Feed API, because the TS Feed implementation then
buffers the received data. The size of the circular buffer can be
configured using the dmx_ts_feed.set function in the Section Feed API.
If there is no room in the circular buffer when a new section is received,
the section must be discarded. If this happens, the value of the success
parameter should be DMX_OVERRUN_ERROR on the next callback.
enum dmx_frontend_source #
Used to identify the type of frontend
Constants
DMX_MEMORY_FE: The source of the demux is memory. It means that the MPEG-TS to be filtered comes from userspace, viawrite()syscall.DMX_FRONTEND_0: The source of the demux is a frontend connected to the demux.
struct dmx_frontend #
Structure that lists the frontends associated with a demux
Definition
;
Members
connectivity_list: List of front-ends that can be connected to a particular demux;source: Type of the frontend.
Description
-
FIXME: this structure should likely be replaced soon by some
media-controller based logic.
enum dmx_demux_caps #
MPEG-2 TS Demux capabilities bitmap
Constants
DMX_TS_FILTERING: set if TS filtering is supported;DMX_SECTION_FILTERING: set if section filtering is supported;DMX_MEMORY_BASED_FILTERING: set ifwrite()available.
Description
Those flags are OR'ed in the dmx_demux.capabilities field
DMX_FE_ENTRY() #
Casts elements in the list of registered front-ends from the generic type struct list_head to the type * struct dmx_frontend
Parameters
list: list of struct dmx_frontend
struct dmx_demux #
Structure that contains the demux capabilities and callbacks.
Definition
;
Members
capabilities: Bitfield of capability flags.frontend: Front-end connected to the demuxpriv: Pointer to private data of the API clientopen: This function reserves the demux for use by the caller and, if necessary, initializes the demux. When the demux is no longer needed, the function close should be called. It should be possible for multiple clients to access the demux at the same time. Thus, the function implementation should increment the demux usage count when open is called and decrement it when close is called. The demux function parameter contains a pointer to the demux API and instance data. It returns: 0 on success; -EUSERS, if maximum usage count was reached; -EINVAL, on bad parameter.close: This function reserves the demux for use by the caller and, if necessary, initializes the demux. When the demux is no longer needed, the function close should be called. It should be possible for multiple clients to access the demux at the same time. Thus, the function implementation should increment the demux usage count when open is called and decrement it when close is called. The demux function parameter contains a pointer to the demux API and instance data. It returns: 0 on success; -ENODEV, if demux was not in use (e. g. no users); -EINVAL, on bad parameter.write: This function provides the demux driver with a memory buffer containing TS packets. Instead of receiving TS packets from the DVB front-end, the demux driver software will read packets from memory. Any clients of this demux with active TS, PES or Section filters will receive filtered data via the Demux callback API (see 0). The function returns when all the data in the buffer has been consumed by the demux. Demux hardware typically cannot read TS from memory. If this is the case, memory-based filtering has to be implemented entirely in software. The demux function parameter contains a pointer to the demux API and instance data. The buf function parameter contains a pointer to the TS data in kernel-space memory. The count function parameter contains the length of the TS data. It returns: 0 on success; -ERESTARTSYS, if mutex lock was interrupted; -EINTR, if a signal handling is pending; -ENODEV, if demux was removed; -EINVAL, on bad parameter.allocate_ts_feed: Allocates a new TS feed, which is used to filter the TS packets carrying a certain PID. The TS feed normally corresponds to a hardware PID filter on the demux chip. The demux function parameter contains a pointer to the demux API and instance data. The feed function parameter contains a pointer to the TS feed API and instance data. The callback function parameter contains a pointer to the callback function for passing received TS packet. It returns: 0 on success; -ERESTARTSYS, if mutex lock was interrupted; -EBUSY, if no more TS feeds is available; -EINVAL, on bad parameter.release_ts_feed: Releases the resources allocated with allocate_ts_feed. Any filtering in progress on the TS feed should be stopped before calling this function. The demux function parameter contains a pointer to the demux API and instance data. The feed function parameter contains a pointer to the TS feed API and instance data. It returns: 0 on success; -EINVAL on bad parameter.allocate_section_feed: Allocates a new section feed, i.e. a demux resource for filtering and receiving sections. On platforms with hardware support for section filtering, a section feed is directly mapped to the demux HW. On other platforms, TS packets are first PID filtered in hardware and a hardware section filter then emulated in software. The caller obtains an API pointer of type dmx_section_feed_t as an out parameter. Using this API the caller can set filtering parameters and start receiving sections. The demux function parameter contains a pointer to the demux API and instance data. The feed function parameter contains a pointer to the TS feed API and instance data. The callback function parameter contains a pointer to the callback function for passing received TS packet. It returns: 0 on success; -EBUSY, if no more TS feeds is available; -EINVAL, on bad parameter.release_section_feed: Releases the resources allocated with allocate_section_feed, including allocated filters. Any filtering in progress on the section feed should be stopped before calling this function. The demux function parameter contains a pointer to the demux API and instance data. The feed function parameter contains a pointer to the TS feed API and instance data. It returns: 0 on success; -EINVAL, on bad parameter.add_frontend: Registers a connectivity between a demux and a front-end, i.e., indicates that the demux can be connected via a call to connect_frontend to use the given front-end as a TS source. The client of this function has to allocate dynamic or static memory for the frontend structure and initialize its fields before calling this function. This function is normally called during the driver initialization. The caller must not free the memory of the frontend struct before successfully calling remove_frontend. The demux function parameter contains a pointer to the demux API and instance data. The frontend function parameter contains a pointer to the front-end instance data. It returns: 0 on success; -EINVAL, on bad parameter.remove_frontend: Indicates that the given front-end, registered by a call to add_frontend, can no longer be connected as a TS source by this demux. The function should be called when a front-end driver or a demux driver is removed from the system. If the front-end is in use, the function fails with the return value of -EBUSY. After successfully calling this function, the caller can free the memory of the frontend struct if it was dynamically allocated before the add_frontend operation. The demux function parameter contains a pointer to the demux API and instance data. The frontend function parameter contains a pointer to the front-end instance data. It returns: 0 on success; -ENODEV, if the front-end was not found, -EINVAL, on bad parameter.get_frontends: Provides the APIs of the front-ends that have been registered for this demux. Any of the front-ends obtained with this call can be used as a parameter for connect_frontend. The include file demux.h contains the macroDMX_FE_ENTRY()for converting an element of the generic type structlist_head* to the type structdmx_frontend*. The caller must not free the memory of any of the elements obtained via this function call. The demux function parameter contains a pointer to the demux API and instance data. It returns a struct list_head pointer to the list of front-end interfaces, or NULL in the case of an empty list.connect_frontend: Connects the TS output of the front-end to the input of the demux. A demux can only be connected to a front-end registered to the demux with the function add_frontend. It may or may not be possible to connect multiple demuxes to the same front-end, depending on the capabilities of the HW platform. When not used, the front-end should be released by calling disconnect_frontend. The demux function parameter contains a pointer to the demux API and instance data. The frontend function parameter contains a pointer to the front-end instance data. It returns: 0 on success; -EINVAL, on bad parameter.disconnect_frontend: Disconnects the demux and a front-end previously connected by a connect_frontend call. The demux function parameter contains a pointer to the demux API and instance data. It returns: 0 on success; -EINVAL on bad parameter.get_pes_pids: Get the PIDs for DMX_PES_AUDIO0, DMX_PES_VIDEO0, DMX_PES_TELETEXT0, DMX_PES_SUBTITLE0 and DMX_PES_PCR0. The demux function parameter contains a pointer to the demux API and instance data. The pids function parameter contains an array with five u16 elements where the PIDs will be stored. It returns: 0 on success; -EINVAL on bad parameter.
Digital TV Frontend kABI
Peios Kernel / Hardware and drivers / Driver development / Media devices
Digital TV Frontend #
The Digital TV Frontend kABI defines a driver-internal interface for registering low-level, hardware specific driver to a hardware independent frontend layer. It is only of interest for Digital TV device driver writers. The header file for this API is named dvb_frontend.h and located in include/media/.
Demodulator driver #
The demodulator driver is responsible for talking with the decoding part of the hardware. Such driver should implement dvb_frontend_ops, which tells what type of digital TV standards are supported, and points to a series of functions that allow the DVB core to command the hardware via the code under include/media/dvb_frontend.c.
A typical example of such struct in a driver foo is:
static struct dvb_frontend_ops foo_ops = {
.delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
.info = {
.name = "foo DVB-T/T2/C driver",
.caps = FE_CAN_FEC_1_2 |
FE_CAN_FEC_2_3 |
FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 |
FE_CAN_FEC_7_8 |
FE_CAN_FEC_AUTO |
FE_CAN_QPSK |
FE_CAN_QAM_16 |
FE_CAN_QAM_32 |
FE_CAN_QAM_64 |
FE_CAN_QAM_128 |
FE_CAN_QAM_256 |
FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO |
FE_CAN_MUTE_TS |
FE_CAN_2G_MODULATION,
.frequency_min = 42000000, /* Hz */
.frequency_max = 1002000000, /* Hz */
.symbol_rate_min = 870000,
.symbol_rate_max = 11700000
},
.init = foo_init,
.sleep = foo_sleep,
.release = foo_release,
.set_frontend = foo_set_frontend,
.get_frontend = foo_get_frontend,
.read_status = foo_get_status_and_stats,
.tune = foo_tune,
.i2c_gate_ctrl = foo_i2c_gate_ctrl,
.get_frontend_algo = foo_get_algo,
};
A typical example of such struct in a driver bar meant to be used on Satellite TV reception is:
static const struct dvb_frontend_ops bar_ops = {
.delsys = { SYS_DVBS, SYS_DVBS2 },
.info = {
.name = "Bar DVB-S/S2 demodulator",
.frequency_min = 500000, /* KHz */
.frequency_max = 2500000, /* KHz */
.frequency_stepsize = 0,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.symbol_rate_tolerance = 500,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_AUTO |
FE_CAN_QPSK,
},
.init = bar_init,
.sleep = bar_sleep,
.release = bar_release,
.set_frontend = bar_set_frontend,
.get_frontend = bar_get_frontend,
.read_status = bar_get_status_and_stats,
.i2c_gate_ctrl = bar_i2c_gate_ctrl,
.get_frontend_algo = bar_get_algo,
.tune = bar_tune,
/* Satellite-specific */
.diseqc_send_master_cmd = bar_send_diseqc_msg,
.diseqc_send_burst = bar_send_burst,
.set_tone = bar_set_tone,
.set_voltage = bar_set_voltage,
};
The include/media/dvb_frontend.c has a kernel thread which is responsible for tuning the device. It supports multiple algorithms to detect a channel, as defined at enum dvbfe_algo().
The algorithm to be used is obtained via .get_frontend_algo. If the driver doesn't fill its field at struct dvb_frontend_ops, it will default to DVBFE_ALGO_SW, meaning that the dvb-core will do a zigzag when tuning, e. g. it will try first to use the specified center frequency f, then, it will do f + Δ, f - Δ, f + 2 x Δ, f - 2 x Δ and so on.
If the hardware has internally a some sort of zigzag algorithm, you should define a .get_frontend_algo function that would return DVBFE_ALGO_HW.
Attaching frontend driver to the bridge driver #
Before using the Digital TV frontend core, the bridge driver should attach the frontend demod, tuner and SEC devices and call dvb_register_frontend(), in order to register the new frontend at the subsystem. At device detach/removal, the bridge driver should call dvb_unregister_frontend() to remove the frontend from the core and then dvb_frontend_detach() to free the memory allocated by the frontend drivers.
The drivers should also call dvb_frontend_suspend() as part of their handler for the device_driver.suspend(), and dvb_frontend_resume() as part of their handler for device_driver.resume().
A few other optional functions are provided to handle some special cases.
Digital TV Frontend statistics #
Introduction #
Digital TV frontends provide a range of statistics meant to help tuning the device and measuring the quality of service.
For each statistics measurement, the driver should set the type of scale used, or FE_SCALE_NOT_AVAILABLE if the statistics is not available on a given time. Drivers should also provide the number of statistics for each type. that's usually 1 for most video standards 1.
Drivers should initialize each statistic counters with length and scale at its init code. For example, if the frontend provides signal strength, it should have, on its init code:
struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;
c->strength.len = 1;
c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
And, when the statistics got updated, set the scale:
c->strength.stat[0].scale = FE_SCALE_DECIBEL;
c->strength.stat[0].uvalue = strength;
[1] For ISDB-T, it may provide both a global statistics and a per-layer set of statistics. On such cases, len should be equal to 4. The first value corresponds to the global stat; the other ones to each layer, e. g.:
-
c->cnr.stat[0] for global S/N carrier ratio,
-
c->cnr.stat[1] for Layer A S/N carrier ratio,
-
c->cnr.stat[2] for layer B S/N carrier ratio,
-
c->cnr.stat[3] for layer C S/N carrier ratio.
Groups of statistics #
There are several groups of statistics currently supported:
-
Signal strength (DTV_STAT_SIGNAL_STRENGTH)
-
Measures the signal strength level at the analog part of the tuner or demod.
-
Typically obtained from the gain applied to the tuner and/or frontend in order to detect the carrier. When no carrier is detected, the gain is at the maximum value (so, strength is on its minimal).
-
As the gain is visible through the set of registers that adjust the gain, typically, this statistics is always available 2.
-
Drivers should try to make it available all the times, as these statistics can be used when adjusting an antenna position and to check for troubles at the cabling.
[2] On a few devices, the gain keeps floating if there is no carrier. On such devices, strength report should check first if carrier is detected at the tuner (
FE_HAS_CARRIER, seefe_status), and otherwise return the lowest possible value. -
-
Carrier Signal to Noise ratio (DTV_STAT_CNR)
-
Signal to Noise ratio for the main carrier.
-
Signal to Noise measurement depends on the device. On some hardware, it is available when the main carrier is detected. On those hardware, CNR measurement usually comes from the tuner (e. g. after
FE_HAS_CARRIER, seefe_status).On other devices, it requires inner FEC decoding, as the frontend measures it indirectly from other parameters (e. g. after
FE_HAS_VITERBI, seefe_status).Having it available after inner FEC is more common.
-
-
Bit counts post-FEC (DTV_STAT_POST_ERROR_BIT_COUNT and DTV_STAT_POST_TOTAL_BIT_COUNT)
-
Those counters measure the number of bits and bit errors after the forward error correction (FEC) on the inner coding block (after Viterbi, LDPC or other inner code).
-
Due to its nature, those statistics depend on full coding lock (e. g. after
FE_HAS_SYNCor afterFE_HAS_LOCK, seefe_status).
-
-
Bit counts pre-FEC (DTV_STAT_PRE_ERROR_BIT_COUNT and DTV_STAT_PRE_TOTAL_BIT_COUNT)
-
Those counters measure the number of bits and bit errors before the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).
-
Not all frontends provide this kind of statistics.
-
Due to its nature, those statistics depend on inner coding lock (e. g. after
FE_HAS_VITERBI, seefe_status).
-
-
Block counts (DTV_STAT_ERROR_BLOCK_COUNT and DTV-STAT_TOTAL_BLOCK_COUNT)
-
Those counters measure the number of blocks and block errors after the forward error correction (FEC) on the inner coding block (before Viterbi, LDPC or other inner code).
-
Due to its nature, those statistics depend on full coding lock (e. g. after
FE_HAS_SYNCor afterFE_HAS_LOCK, seefe_status).
-
A typical example of the logic that handle status and statistics is:
static int foo_get_status_and_stats(struct dvb_frontend *fe)
{
struct foo_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
int rc;
enum fe_status *status;
/* Both status and strength are always available */
rc = foo_read_status(fe, &status);
if (rc < 0)
return rc;
rc = foo_read_strength(fe);
if (rc < 0)
return rc;
/* Check if CNR is available */
if (!(fe->status & FE_HAS_CARRIER))
return 0;
rc = foo_read_cnr(fe);
if (rc < 0)
return rc;
/* Check if pre-BER stats are available */
if (!(fe->status & FE_HAS_VITERBI))
return 0;
rc = foo_get_pre_ber(fe);
if (rc < 0)
return rc;
/* Check if post-BER stats are available */
if (!(fe->status & FE_HAS_SYNC))
return 0;
rc = foo_get_post_ber(fe);
if (rc < 0)
return rc;
}
static const struct dvb_frontend_ops ops = {
/* ... */
.read_status = foo_get_status_and_stats,
};
Statistics collection #
On almost all frontend hardware, the bit and byte counts are stored by the hardware after a certain amount of time or after the total bit/block counter reaches a certain value (usually programmable), for example, on every 1000 ms or after receiving 1,000,000 bits.
So, if you read the registers too soon, you'll end by reading the same value as in the previous reading, causing the monotonic value to be incremented too often.
Drivers should take the responsibility to avoid too often reads. That can be done using two approaches:
if the driver have a bit that indicates when a collected data is ready #
Driver should check such bit before making the statistics available.
An example of such behavior can be found at this code snippet (adapted from mb86a20s driver's logic):
static int foo_get_pre_ber(struct dvb_frontend *fe)
{
struct foo_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
int rc, bit_error;
/* Check if the BER measures are already available */
rc = foo_read_u8(state, 0x54);
if (rc < 0)
return rc;
if (!rc)
return 0;
/* Read Bit Error Count */
bit_error = foo_read_u32(state, 0x55);
if (bit_error < 0)
return bit_error;
/* Read Total Bit Count */
rc = foo_read_u32(state, 0x51);
if (rc < 0)
return rc;
c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
c->pre_bit_error.stat[0].uvalue += bit_error;
c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
c->pre_bit_count.stat[0].uvalue += rc;
return 0;
}
If the driver doesn't provide a statistics available check bit #
A few devices, however, may not provide a way to check if the stats are available (or the way to check it is unknown). They may not even provide a way to directly read the total number of bits or blocks.
On those devices, the driver need to ensure that it won't be reading from the register too often and/or estimate the total number of bits/blocks.
On such drivers, a typical routine to get statistics would be like (adapted from dib8000 driver's logic):
struct foo_state {
/* ... */
unsigned long per_jiffies_stats;
}
static int foo_get_pre_ber(struct dvb_frontend *fe)
{
struct foo_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
int rc, bit_error;
u64 bits;
/* Check if time for stats was elapsed */
if (!time_after(jiffies, state->per_jiffies_stats))
return 0;
/* Next stat should be collected in 1000 ms */
state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);
/* Read Bit Error Count */
bit_error = foo_read_u32(state, 0x55);
if (bit_error < 0)
return bit_error;
/*
* On this particular frontend, there's no register that
* would provide the number of bits per 1000ms sample. So,
* some function would calculate it based on DTV properties
*/
bits = get_number_of_bits_per_1000ms(fe);
c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
c->pre_bit_error.stat[0].uvalue += bit_error;
c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
c->pre_bit_count.stat[0].uvalue += bits;
return 0;
}
Please notice that, on both cases, we're getting the statistics using the dvb_frontend_ops .read_status callback. The rationale is that the frontend core will automatically call this function periodically (usually, 3 times per second, when the frontend is locked).
That warrants that we won't miss to collect a counter and increment the monotonic stats at the right time.
Digital TV Frontend functions and types #
struct dvb_frontend_tune_settings #
parameters to adjust frontend tuning
Definition
;
Members
min_delay_ms: minimum delay for tuning, in msstep_size: step size between two consecutive frequenciesmax_drift: maximum drift
NOTE
step_size is in Hz, for terrestrial/cable or kHz for satellite
struct dvb_tuner_info #
Frontend name and min/max ranges/bandwidths
Definition
;
Members
name: name of the Frontendfrequency_min_hz: minimal frequency supported in Hzfrequency_max_hz: maximum frequency supported in Hzfrequency_step_hz: frequency step in Hzbandwidth_min: minimal frontend bandwidth supportedbandwidth_max: maximum frontend bandwidth supportedbandwidth_step: frontend bandwidth step
struct analog_parameters #
Parameters to tune into an analog/radio channel
Definition
;
Members
frequency: Frequency used by analog TV tuner (either in 62.5 kHz step, for TV, or 62.5 Hz for radio)mode: Tuner mode, as defined on enum v4l2_tuner_typeaudmode: Audio mode as defined for the rxsubchans field at videodev2.h, e. g. V4L2_TUNER_MODE_*std: TV standard bitmap as defined at videodev2.h, e. g. V4L2_STD_*
Description
Hybrid tuners should be supported by both V4L2 and DVB APIs. This struct contains the data that are used by the V4L2 side. To avoid dependencies from V4L2 headers, all enums here are declared as integers.
enum dvbfe_algo #
defines the algorithm used to tune into a channel
Constants
DVBFE_ALGO_HW: Hardware Algorithm - Devices that support this algorithm do everything in hardware and no software support is needed to handle them. Requesting these devices to LOCK is the only thing required, device is supposed to do everything in the hardware.DVBFE_ALGO_SW: Software Algorithm - These are dumb devices, that require software to do everythingDVBFE_ALGO_CUSTOM: Customizable Agorithm - Devices having this algorithm can be customized to have specific algorithms in the frontend driver, rather than simply doing a software zig-zag. In this case the zigzag maybe hardware assisted or it maybe completely done in hardware. In all cases, usage of this algorithm, in conjunction with the search and track callbacks, utilizes the driver specific algorithm.DVBFE_ALGO_RECOVERY: Recovery Algorithm - These devices have AUTO recovery capabilities from LOCK failure
enum dvbfe_search #
search callback possible return status
Constants
DVBFE_ALGO_SEARCH_SUCCESS: The frontend search algorithm completed and returned successfullyDVBFE_ALGO_SEARCH_ASLEEP: The frontend search algorithm is sleepingDVBFE_ALGO_SEARCH_FAILED: The frontend search for a signal failedDVBFE_ALGO_SEARCH_INVALID: The frontend search algorithm was probably supplied with invalid parameters and the search is an invalid oneDVBFE_ALGO_SEARCH_AGAIN: The frontend search algorithm was requested to search againDVBFE_ALGO_SEARCH_ERROR: The frontend search algorithm failed due to some error
struct dvb_tuner_ops #
Tuner information and callbacks
Definition
;
Members
info: embeddedstruct dvb_tuner_infowith tuner propertiesrelease: callback function called when frontend is detached. drivers should free any allocated memory.init: callback function used to initialize the tuner device.sleep: callback function used to put the tuner to sleep.suspend: callback function used to inform that the Kernel will suspend.resume: callback function used to inform that the Kernel is resuming from suspend.set_params: callback function used to inform the tuner to tune into a digital TV channel. The properties to be used are stored atstruct dvb_frontend.dtv_property_cache. The tuner demod can change the parameters to reflect the changes needed for the channel to be tuned, and update statistics. This is the recommended way to set the tuner parameters and should be used on newer drivers.set_analog_params: callback function used to tune into an analog TV channel on hybrid tuners. It passes analog_parameters to the driver.set_config: callback function used to send some tuner-specific parameters.get_frequency: get the actual tuned frequencyget_bandwidth: get the bandwidth used by the low pass filtersget_if_frequency: get the Intermediate Frequency, in Hz. For baseband, should return 0.get_status: returns the frontend lock statusget_rf_strength: returns the RF signal strength. Used mostly to support analog TV and radio. Digital TV should report, instead, via DVBv5 API (struct dvb_frontend.dtv_property_cache).get_afc: Used only by analog TV core. Reports the frequency drift due to AFC.calc_regs: callback function used to pass register data settings for simple tuners. Shouldn't be used on newer drivers.set_frequency: Set a new frequency. Shouldn't be used on newer drivers.set_bandwidth: Set a new frequency. Shouldn't be used on newer drivers.
NOTE
frequencies used on get_frequency and set_frequency are in Hz for terrestrial/cable or kHz for satellite.
struct analog_demod_info #
Information struct for analog TV part of the demod
Definition
;
Members
name: Name of the analog TV demodulator
struct analog_demod_ops #
Demodulation information and callbacks for analog TV and radio
Definition
;
Members
info: pointer to struct analog_demod_infoset_params: callback function used to inform the demod to set the demodulator parameters needed to decode an analog or radio channel. The properties are passed viastruct analog_params.has_signal: returns 0xffff if has signal, or 0 if it doesn't.get_afc: Used only by analog TV core. Reports the frequency drift due to AFC.tuner_status: callback function that returns tuner status bits, e. g.TUNER_STATUS_LOCKEDandTUNER_STATUS_STEREO.standby: set the tuner to standby mode.release: callback function called when frontend is detached. drivers should free any allocated memory.i2c_gate_ctrl: controls the I2C gate. Newer drivers should use I2C mux support instead.set_config: callback function used to send some tuner-specific parameters.
struct dvb_frontend_internal_info #
Frontend properties and capabilities
Definition
;
Members
name: Name of the frontendfrequency_min_hz: Minimal frequency supported by the frontend.frequency_max_hz: Minimal frequency supported by the frontend.frequency_stepsize_hz: All frequencies are multiple of this value.frequency_tolerance_hz: Frequency tolerance.symbol_rate_min: Minimal symbol rate, in bauds (for Cable/Satellite systems).symbol_rate_max: Maximal symbol rate, in bauds (for Cable/Satellite systems).symbol_rate_tolerance: Maximal symbol rate tolerance, in ppm (for Cable/Satellite systems).caps: Capabilities supported by the frontend, as specified inenum fe_caps.
struct dvb_frontend_ops #
Demodulation information and callbacks for ditialt TV
Definition
;
Members
info: embeddedstruct dvb_tuner_infowith tuner propertiesdelsys: Delivery systems supported by the frontenddetach: callback function called when frontend is detached. drivers should clean up, but not yet free thestruct dvb_frontendallocation.release: callback function called when frontend is ready to be freed. drivers should free any allocated memory.release_sec: callback function requesting that the Satellite Equipment Control (SEC) driver to release and free any memory allocated by the driver.init: callback function used to initialize the tuner device.sleep: callback function used to put the tuner to sleep.suspend: callback function used to inform that the Kernel will suspend.resume: callback function used to inform that the Kernel is resuming from suspend.write: callback function used by some demod legacy drivers to allow other drivers to write data into their registers. Should not be used on new drivers.tune: callback function used by demod drivers that use DVBFE_ALGO_HW to tune into a frequency.get_frontend_algo: returns the desired hardware algorithm.set_frontend: callback function used to inform the demod to set the parameters for demodulating a digital TV channel. The properties to be used are stored atstruct dvb_frontend.dtv_property_cache. The demod can change the parameters to reflect the changes needed for the channel to be decoded, and update statistics.get_tune_settings: callback functionget_frontend: callback function used to inform the parameters actuall in use. The properties to be used are stored atstruct dvb_frontend.dtv_property_cache and update statistics. Please notice that it should not return an error code if the statistics are not available because the demog is not locked.read_status: returns the locking status of the frontend.read_ber: legacy callback function to return the bit error rate. Newer drivers should provide such info via DVBv5 API, e. g. set_frontend;/get_frontend, implementing this callback only if DVBv3 API compatibility is wanted.read_signal_strength: legacy callback function to return the signal strength. Newer drivers should provide such info via DVBv5 API, e. g. set_frontend/get_frontend, implementing this callback only if DVBv3 API compatibility is wanted.read_snr: legacy callback function to return the Signal/Noise rate. Newer drivers should provide such info via DVBv5 API, e. g. set_frontend/get_frontend, implementing this callback only if DVBv3 API compatibility is wanted.read_ucblocks: legacy callback function to return the Uncorrected Error Blocks. Newer drivers should provide such info via DVBv5 API, e. g. set_frontend/get_frontend, implementing this callback only if DVBv3 API compatibility is wanted.diseqc_reset_overload: callback function to implement theFE_DISEQC_RESET_OVERLOAD()ioctl (only Satellite)diseqc_send_master_cmd: callback function to implement theFE_DISEQC_SEND_MASTER_CMD()ioctl (only Satellite).diseqc_recv_slave_reply: callback function to implement theFE_DISEQC_RECV_SLAVE_REPLY()ioctl (only Satellite)diseqc_send_burst: callback function to implement theFE_DISEQC_SEND_BURST()ioctl (only Satellite).set_tone: callback function to implement theFE_SET_TONE()ioctl (only Satellite).set_voltage: callback function to implement theFE_SET_VOLTAGE()ioctl (only Satellite).enable_high_lnb_voltage: callback function to implement theFE_ENABLE_HIGH_LNB_VOLTAGE()ioctl (only Satellite).dishnetwork_send_legacy_command: callback function to implement theFE_DISHNETWORK_SEND_LEGACY_CMD()ioctl (only Satellite). Drivers should not use this, except when the DVB core emulation fails to provide proper support (e.g. if set_voltage takes more than 8ms to work), and when backward compatibility with this legacy API is required.i2c_gate_ctrl: controls the I2C gate. Newer drivers should use I2C mux support instead.ts_bus_ctrl: callback function used to take control of the TS bus.set_lna: callback function to power on/off/auto the LNA.search: callback function used on some custom algo search algos.tuner_ops: pointer tostruct dvb_tuner_opsanalog_ops: pointer tostruct analog_demod_ops
struct dtv_frontend_properties #
contains a list of properties that are specific to a digital TV standard.
Definition
;
Members
frequency: frequency in Hz for terrestrial/cable or in kHz for Satellitemodulation: Frontend modulation typevoltage: SEC voltage (only Satellite)sectone: SEC tone mode (only Satellite)inversion: Spectral inversionfec_inner: Forward error correction inner Code Ratetransmission_mode: Transmission Modebandwidth_hz: Bandwidth, in Hz. A zero value means that userspace wants to autodetect.guard_interval: Guard Intervalhierarchy: Hierarchysymbol_rate: Symbol Ratecode_rate_HP: high priority stream code ratecode_rate_LP: low priority stream code ratepilot: Enable/disable/autodetect pilot tonesrolloff: Rolloff factor (alpha)delivery_system: FE delivery system (e. g. digital TV standard)interleaving: interleavingisdbt_partial_reception: ISDB-T partial reception (only ISDB standard)isdbt_sb_mode: ISDB-T Sound Broadcast (SB) mode (only ISDB standard)isdbt_sb_subchannel: ISDB-T SB subchannel (only ISDB standard)isdbt_sb_segment_idx: ISDB-T SB segment index (only ISDB standard)isdbt_sb_segment_count: ISDB-T SB segment count (only ISDB standard)isdbt_layer_enabled: ISDB Layer enabled (only ISDB standard)layer: ISDB per-layer data (only ISDB standard)layer.segment_count: Segment Count;layer.fec: per layer code rate;layer.modulation: per layer modulation;layer.interleaving: per layer interleaving.stream_id: If different than zero, enable substream filtering, if hardware supports (DVB-S2 and DVB-T2).scrambling_sequence_index: Carries the index of the DVB-S2 physical layer scrambling sequence.atscmh_fic_ver: Version number of the FIC (Fast Information Channel) signaling data (only ATSC-M/H)atscmh_parade_id: Parade identification number (only ATSC-M/H)atscmh_nog: Number of MH groups per MH subframe for a designated parade (only ATSC-M/H)atscmh_tnog: Total number of MH groups including all MH groups belonging to all MH parades in one MH subframe (only ATSC-M/H)atscmh_sgn: Start group number (only ATSC-M/H)atscmh_prc: Parade repetition cycle (only ATSC-M/H)atscmh_rs_frame_mode: Reed Solomon (RS) frame mode (only ATSC-M/H)atscmh_rs_frame_ensemble: RS frame ensemble (only ATSC-M/H)atscmh_rs_code_mode_pri: RS code mode pri (only ATSC-M/H)atscmh_rs_code_mode_sec: RS code mode sec (only ATSC-M/H)atscmh_sccc_block_mode: Series Concatenated Convolutional Code (SCCC) Block Mode (only ATSC-M/H)atscmh_sccc_code_mode_a: SCCC code mode A (only ATSC-M/H)atscmh_sccc_code_mode_b: SCCC code mode B (only ATSC-M/H)atscmh_sccc_code_mode_c: SCCC code mode C (only ATSC-M/H)atscmh_sccc_code_mode_d: SCCC code mode D (only ATSC-M/H)lna: Power ON/OFF/AUTO the Linear Now-noise Amplifier (LNA)strength: DVBv5 API statistics: Signal Strengthcnr: DVBv5 API statistics: Signal to Noise ratio of the (main) carrierpre_bit_error: DVBv5 API statistics: pre-Viterbi bit error countpre_bit_count: DVBv5 API statistics: pre-Viterbi bit countpost_bit_error: DVBv5 API statistics: post-Viterbi bit error countpost_bit_count: DVBv5 API statistics: post-Viterbi bit countblock_error: DVBv5 API statistics: block error countblock_count: DVBv5 API statistics: block count
NOTE
derivated statistics like Uncorrected Error blocks (UCE) are calculated on userspace.
Only a subset of the properties are needed for a given delivery system. For more info, consult the media_api.html with the documentation of the Userspace API.
struct dvb_frontend #
Frontend structure to be used on drivers.
Definition
;
Members
refcount: refcount to keep track ofstruct dvb_frontendreferencesops: embeddedstruct dvb_frontend_opsdvb: pointer tostruct dvb_adapterdemodulator_priv: demod private datatuner_priv: tuner private datafrontend_priv: frontend private datasec_priv: SEC private dataanalog_demod_priv: Analog demod private datadtv_property_cache: embeddedstruct dtv_frontend_propertiescallback: callback function used on some drivers to call either the tuner or the demodulator.id: Frontend IDexit: Used to inform the DVB core that the frontend thread should exit (usually, means that the hardware got disconnected.
dvb_register_frontend() #
int Registers a DVB frontend at the adapter
Parameters
struct dvb_adapter *dvb: pointer tostruct dvb_adapterstruct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
Allocate and initialize the private data needed by the frontend core to
manage the frontend and calls dvb_register_device() to register a new
frontend. It also cleans the property cache that stores the frontend
parameters and selects the first available delivery system.
dvb_unregister_frontend() #
int Unregisters a DVB frontend
Parameters
struct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
Stops the frontend kthread, calls dvb_unregister_device() and frees the
private frontend data allocated by dvb_register_frontend().
NOTE
This function doesn't frees the memory allocated by the demod,
by the SEC driver and by the tuner. In order to free it, an explicit call to
dvb_frontend_detach() is needed, after calling this function.
dvb_frontend_detach() #
void Detaches and frees frontend specific data
Parameters
struct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
This function should be called after dvb_unregister_frontend(). It
calls the SEC, tuner and demod release functions:
dvb_frontend_ops.release_sec, dvb_frontend_ops.tuner_ops.release,
dvb_frontend_ops.analog_ops.release and dvb_frontend_ops.release.
If the driver is compiled with CONFIG_MEDIA_ATTACH, it also decreases
the module reference count, needed to allow userspace to remove the
previously used DVB frontend modules.
dvb_frontend_suspend() #
int Suspends a Digital TV frontend
Parameters
struct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
This function prepares a Digital TV frontend to suspend.
In order to prepare the tuner to suspend, if
dvb_frontend_ops.tuner_ops.suspend() is available, it calls it. Otherwise,
it will call dvb_frontend_ops.tuner_ops.sleep(), if available.
It will also call dvb_frontend_ops.suspend() to put the demod to suspend,
if available. Otherwise it will call dvb_frontend_ops.sleep().
The drivers should also call dvb_frontend_suspend() as part of their
handler for the device_driver.suspend().
dvb_frontend_resume() #
int Resumes a Digital TV frontend
Parameters
struct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
This function resumes the usual operation of the tuner after resume.
In order to resume the frontend, it calls the demod
dvb_frontend_ops.resume() if available. Otherwise it calls demod
dvb_frontend_ops.init().
If dvb_frontend_ops.tuner_ops.resume() is available, It, it calls it.
Otherwise,t will call dvb_frontend_ops.tuner_ops.init(), if available.
Once tuner and demods are resumed, it will enforce that the SEC voltage and tone are restored to their previous values and wake up the frontend's kthread in order to retune the frontend.
The drivers should also call dvb_frontend_resume() as part of their
handler for the device_driver.resume().
dvb_frontend_reinitialise() #
void forces a reinitialisation at the frontend
Parameters
struct dvb_frontend *fe: pointer tostruct dvb_frontend
Description
Calls dvb_frontend_ops.init() and dvb_frontend_ops.tuner_ops.init(),
and resets SEC tone and voltage (for Satellite systems).
NOTE
Currently, this function is used only by one driver (budget-av). It seems to be due to address some special issue with that specific frontend.
dvb_frontend_sleep_until() #
void Sleep for the amount of time given by add_usec parameter
Parameters
ktime_t *waketime: pointer tostruct ktime_tu32 add_usec: time to sleep, in microseconds
Description
This function is used to measure the time required for the
FE_DISHNETWORK_SEND_LEGACY_CMD() ioctl to work. It needs to be as precise
as possible, as it affects the detection of the dish tone command at the
satellite subsystem.
Its used internally by the DVB frontend core, in order to emulate
FE_DISHNETWORK_SEND_LEGACY_CMD() using the dvb_frontend_ops.set_voltage()
callback.
NOTE
it should not be used at the drivers, as the emulation for the
legacy callback is provided by the Kernel. The only situation where this
should be at the drivers is when there are some bugs at the hardware that
would prevent the core emulation to work. On such cases, the driver would
be writing a dvb_frontend_ops.dishnetwork_send_legacy_command() and
calling this function directly.
Digital TV Network kABI
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct dvb_net #
describes a DVB network interface
Definition
;
Members
dvbdev: pointer tostruct dvb_device.device: array of pointers tostruct net_device.state: array of integers to each net device. A value different than zero means that the interface is in usage.exit: flag to indicate when the device is being removed.demux: pointer tostruct dmx_demux.ioctl_mutex: protect access to this struct.remove_mutex: mutex that avoids a race condition between a callback called when the hardware is disconnected and the file_operations of dvb_net.
Description
Currently, the core supports up to DVB_NET_DEVICES_MAX (10) network
devices.
dvb_net_init() #
int nitializes a digital TV network device and registers it.
Parameters
struct dvb_adapter *adap: pointer tostruct dvb_adapter.struct dvb_net *dvbnet: pointer tostruct dvb_net.struct dmx_demux *dmxdemux: pointer tostruct dmx_demux.
dvb_net_release() #
void releases a digital TV network device and unregisters it.
Parameters
struct dvb_net *dvbnet: pointer tostruct dvb_net.
Media Subsystem Profile
Peios Kernel / Hardware and drivers / Driver development / Media devices
Overview #
The media subsystem covers support for a variety of devices: stream capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC and media pipeline control.
It covers, mainly, the contents of those directories:
drivers/media
drivers/staging/media
Documentation/admin-guide/media
Documentation/driver-api/media
Documentation/userspace-api/media
Documentation/devicetree/bindings/media/1
include/media
[1] Device tree bindings are maintained by the OPEN FIRMWARE AND FLATTENED DEVICE TREE BINDINGS maintainers (see the MAINTAINERS file). So, changes there must be reviewed by them before being merged via the media subsystem's development tree.
Both media userspace and Kernel APIs are documented and the documentation must be kept in sync with the API changes. It means that all patches that add new features to the subsystem must also bring changes to the corresponding API files.
Due to the size and wide scope of the media subsystem, media's maintainership model is to have sub-maintainers that have a broad knowledge of a specific aspect of the subsystem. It is the sub-maintainers' task to review the patches, providing feedback to users if the patches are following the subsystem rules and are properly using the media kernel and userspace APIs.
Patches for the media subsystem must be sent to the media mailing list at linux-media@vger.kernel.org as plain text only e-mail. Emails with HTML will be automatically rejected by the mail server. It could be wise to also copy the sub-maintainer(s).
Media's workflow is heavily based on Patchwork, meaning that, once a patch is submitted, the e-mail will first be accepted by the mailing list server, and, after a while, it should appear at:
If it doesn't automatically appear there after a few minutes, then probably something went wrong on your submission. Please check if the email is in plain text2 only and if your emailer is not mangling whitespaces before complaining or submitting them again.
You can check if the mailing list server accepted your patch, by looking at:
[2] If your email contains HTML, the mailing list server will simply drop it, without any further notice.
Media maintainers #
At the media subsystem, we have a group of senior developers that are responsible for doing the code reviews at the drivers (also known as sub-maintainers), and another senior developer responsible for the subsystem as a whole. For core changes, whenever possible, multiple media maintainers do the review.
The media maintainers that work on specific areas of the subsystem are:
-
-
Remote Controllers (infrared):
Sean Young <sean@mess.org>
-
-
-
HDMI CEC:
Hans Verkuil <hverkuil@kernel.org>
-
-
-
Media controller drivers:
Laurent Pinchart <laurent.pinchart@ideasonboard.com>
-
-
-
ISP, v4l2-async, v4l2-fwnode, v4l2-flash-led-class and Sensor drivers:
Sakari Ailus <sakari.ailus@linux.intel.com>
-
-
-
V4L2 drivers and core V4L2 frameworks:
Hans Verkuil <hverkuil@kernel.org>
-
-
The subsystem maintainer is:
Mauro Carvalho Chehab <mchehab@kernel.org>
Media maintainers may delegate a patch to other media maintainers as needed. On such case, checkpatch's delegate field indicates who's currently responsible for reviewing a patch.
Submit Checklist Addendum #
Patches that change the Open Firmware/Device Tree bindings must be reviewed by the Device Tree maintainers. So, DT maintainers should be Cc:ed when those are submitted via devicetree@vger.kernel.org mailing list.
There is a set of compliance tools at https://git.linuxtv.org/v4l-utils.git/ that should be used in order to check if the drivers are properly implementing the media APIs:
|
Type |
Tool |
|---|---|
|
V4L2 drivers3 |
|
|
V4L2 virtual drivers |
|
|
CEC drivers |
|
[3] The v4l2-compliance also covers the media controller usage inside V4L2 drivers.
Other compliance tools are under development to check other parts of the subsystem.
Those tests need to pass before the patches go upstream.
Also, please notice that we build the Kernel with:
make CF=-D__CHECK_ENDIAN__ CONFIG_DEBUG_SECTION_MISMATCH=y C=1 W=1 CHECK=check_script
Where the check script is:
#!/bin/bash
/devel/smatch/smatch -p=kernel $@ >&2
/devel/sparse/sparse $@ >&2
Be sure to not introduce new warnings on your patches without a very good reason.
Style Cleanup Patches #
Style cleanups are welcome when they come together with other changes at the files where the style changes will affect.
We may accept pure standalone style cleanups, but they should ideally be one patch for the whole subsystem (if the cleanup is low volume), or at least be grouped per directory. So, for example, if you're doing a big cleanup change set at drivers under drivers/media, please send a single patch for all drivers under drivers/media/pci, another one for drivers/media/usb and so on.
Coding Style Addendum #
Media development uses checkpatch.pl on strict mode to verify the code style, e.g.:
$ ./scripts/checkpatch.pl --strict --max-line-length=80
In principle, patches should follow the coding style rules, but exceptions are allowed if there are good reasons. On such case, maintainers and reviewers may question about the rationale for not addressing the checkpatch.pl.
Please notice that the goal here is to improve code readability. On a few cases, checkpatch.pl may actually point to something that would look worse. So, you should use good sense.
Note that addressing one checkpatch.pl issue (of any kind) alone may lead to having longer lines than 80 characters per line. While this is not strictly prohibited, efforts should be made towards staying within 80 characters per line. This could include using re-factoring code that leads to less indentation, shorter variable or function names and last but not least, simply wrapping the lines.
In particular, we accept lines with more than 80 columns:
on strings, as they shouldn't be broken due to line length limits;
when a function or variable name need to have a big identifier name, which keeps hard to honor the 80 columns limit;
on arithmetic expressions, when breaking lines makes them harder to read;
when they avoid a line to end with an open parenthesis or an open bracket.
Key Cycle Dates #
New submissions can be sent at any time, but if they intend to hit the next merge window they should be sent before -rc5, and ideally stabilized in the linux-media branch by -rc6.
Review Cadence #
Provided that your patch is at https://patchwork.linuxtv.org, it should be sooner or later handled, so you don't need to re-submit a patch.
Except for bug fixes, we don't usually add new patches to the development tree between -rc6 and the next -rc1.
Please notice that the media subsystem is a high traffic one, so it could take a while for us to be able to review your patches. Feel free to ping if you don't get a feedback in a couple of weeks or to ask other developers to publicly add Reviewed-by and, more importantly, Tested-by: tags.
Please note that we expect a detailed description for Tested-by:, identifying what boards were used at the test and what it was tested.
Media Controller devices
Peios Kernel / Hardware and drivers / Driver development / Media devices
Media Controller #
The media controller userspace API is documented in the Media Controller uAPI book. This document focus on the kernel-side implementation of the media framework.
Abstract media device model #
Discovering a device internal topology, and configuring it at runtime, is one of the goals of the media framework. To achieve this, hardware devices are modelled as an oriented graph of building blocks called entities connected through pads.
An entity is a basic media hardware building block. It can correspond to a large variety of logical blocks such as physical hardware devices (CMOS sensor for instance), logical hardware devices (a building block in a System-on-Chip image processing pipeline), DMA channels or physical connectors.
A pad is a connection endpoint through which an entity can interact with other entities. Data (not restricted to video) produced by an entity flows from the entity's output to one or more entity inputs. Pads should not be confused with physical pins at chip boundaries.
A link is a point-to-point oriented connection between two pads, either on the same entity or on different entities. Data flows from a source pad to a sink pad.
Media device #
A media device is represented by a struct media_device instance, defined in include/media/media-device.h. Allocation of the structure is handled by the media device driver, usually by embedding the media_device instance in a larger driver-specific structure.
Drivers initialise media device instances by calling media_device_init(). After initialising a media device instance, it is registered by calling __media_device_register() via the macro media_device_register() and unregistered by calling media_device_unregister(). An initialised media device must be eventually cleaned up by calling media_device_cleanup().
Note that it is not allowed to unregister a media device instance that was not previously registered, or clean up a media device instance that was not previously initialised.
Entities #
Entities are represented by a struct media_entity instance, defined in include/media/media-entity.h. The structure is usually embedded into a higher-level structure, such as v4l2_subdev or video_device instances, although drivers can allocate entities directly.
Drivers initialize entity pads by calling media_entity_pads_init().
Drivers register entities with a media device by calling media_device_register_entity() and unregistered by calling media_device_unregister_entity().
Interfaces #
Interfaces are represented by a struct media_interface instance, defined in include/media/media-entity.h. Currently, only one type of interface is defined: a device node. Such interfaces are represented by a struct media_intf_devnode.
Drivers initialize and create device node interfaces by calling media_devnode_create() and remove them by calling: media_devnode_remove().
Pads #
Pads are represented by a struct media_pad instance, defined in include/media/media-entity.h. Each entity stores its pads in a pads array managed by the entity driver. Drivers usually embed the array in a driver-specific structure.
Pads are identified by their entity and their 0-based index in the pads array.
Both information are stored in the struct media_pad, making the struct media_pad pointer the canonical way to store and pass link references.
Pads have flags that describe the pad capabilities and state.
MEDIA_PAD_FL_SINK indicates that the pad supports sinking data. MEDIA_PAD_FL_SOURCE indicates that the pad supports sourcing data.
Links #
Links are represented by a struct media_link instance, defined in include/media/media-entity.h. There are two types of links:
1. pad to pad links:
Associate two entities via their PADs. Each entity has a list that points to all links originating at or targeting any of its pads. A given link is thus stored twice, once in the source entity and once in the target entity.
Drivers create pad to pad links by calling: media_create_pad_link() and remove with media_entity_remove_links().
2. interface to entity links:
Associate one interface to a Link.
Drivers create interface to entity links by calling: media_create_intf_link() and remove with media_remove_intf_links().
Links have flags that describe the link capabilities and state. The valid values are described at media_create_pad_link() and media_create_intf_link().
Graph traversal #
The media framework provides APIs to traverse media graphs, locating connected entities and links.
To iterate over all entities belonging to a media device, drivers can use the media_device_for_each_entity macro, defined in include/media/media-device.h.
struct media_entity *entity;
Helper functions can be used to find a link between two given pads, or a pad connected to another pad through an enabled link (media_entity_find_link(), media_pad_remote_pad_first(), media_entity_remote_source_pad_unique() and media_pad_remote_pad_unique()).
Use count and power handling #
Due to the wide differences between drivers regarding power management needs, the media controller does not implement power management. However, the struct media_entity includes a use_count field that media drivers can use to track the number of users of every entity for power management needs.
The media_entity<media_entity>.use_count field is owned by media drivers and must not be touched by entity drivers. Access to the field must be protected by the media_device.graph_mutex lock.
Links setup #
Link properties can be modified at runtime by calling media_entity_setup_link().
Pipelines and media streams #
A media stream is a stream of pixels or metadata originating from one or more source devices (such as a sensors) and flowing through media entity pads towards the final sinks. The stream can be modified on the route by the devices (e.g. scaling or pixel format conversions), or it can be split into multiple branches, or multiple branches can be merged.
A media pipeline is a set of media streams which are interdependent. This interdependency can be caused by the hardware (e.g. configuration of a second stream cannot be changed if the first stream has been enabled) or by the driver due to the software design. Most commonly a media pipeline consists of a single stream which does not branch.
When starting streaming, drivers must notify all entities in the pipeline to prevent link states from being modified during streaming by calling media_pipeline_start().
The function will mark all the pads which are part of the pipeline as streaming.
The struct media_pipeline instance pointed to by the pipe argument will be stored in every pad in the pipeline. Drivers should embed the struct media_pipeline in higher-level pipeline structures and can then access the pipeline through the struct media_pad pipe field.
Calls to media_pipeline_start() can be nested. The pipeline pointer must be identical for all nested calls to the function.
media_pipeline_start() may return an error. In that case, it will clean up any of the changes it did by itself.
When stopping the stream, drivers must notify the entities with media_pipeline_stop().
If multiple calls to media_pipeline_start() have been made the same number of media_pipeline_stop() calls are required to stop streaming. The media_entity.pipe field is reset to NULL on the last nested stop call.
Link configuration will fail with -EBUSY by default if either end of the link is a streaming entity. Links that can be modified while streaming must be marked with the MEDIA_LNK_FL_DYNAMIC flag.
If other operations need to be disallowed on streaming entities (such as changing entities configuration parameters) drivers can explicitly check the media_entity stream_count field to find out if an entity is streaming. This operation must be done with the media_device graph_mutex held.
Link validation #
Link validation is performed by media_pipeline_start() for any entity which has sink pads in the pipeline. The media_entity.link_validate() callback is used for that purpose. In link_validate() callback, entity driver should check that the properties of the source pad of the connected entity and its own sink pad match. It is up to the type of the entity (and in the end, the properties of the hardware) what matching actually means.
Subsystems should facilitate link validation by providing subsystem specific helper functions to provide easy access for commonly needed information, and in the end provide a way to use driver-specific callbacks.
Pipeline traversal #
Once a pipeline has been constructed with media_pipeline_start(), drivers can iterate over entities or pads in the pipeline with the :c:macro:´media_pipeline_for_each_entity` and :c:macro:´media_pipeline_for_each_pad` macros. Iterating over pads is straightforward:
media_pipeline_pad_iter iter;
struct media_pad *pad;
To iterate over entities, the iterator needs to be initialized and cleaned up as an additional steps:
media_pipeline_entity_iter iter;
struct media_entity *entity;
int ret;
ret = ;
if
...;
;
Media Controller Device Allocator API #
When the media device belongs to more than one driver, the shared media device is allocated with the shared struct device as the key for look ups.
The shared media device should stay in registered state until the last driver unregisters it. In addition, the media device should be released when all the references are released. Each driver gets a reference to the media device during probe, when it allocates the media device. If media device is already allocated, the allocate API bumps up the refcount and returns the existing media device. The driver puts the reference back in its disconnect routine when it calls media_device_delete().
The media device is unregistered and cleaned up from the kref put handler to ensure that the media device stays in registered state until the last driver unregisters the media device.
Driver Usage
Drivers should use the appropriate media-core routines to manage the shared media device life-time handling the two states: 1. allocate -> register -> delete 2. get reference to already registered device -> delete
call media_device_delete() routine to make sure the shared media device delete is handled correctly.
driver probe: Call media_device_usb_allocate() to allocate or get a reference Call media_device_register(), if media devnode isn't registered
driver disconnect: Call media_device_delete() to free the media_device. Freeing is handled by the kref put handler.
API Definitions #
struct media_entity_notify #
Media Entity Notify
Definition
;
Members
list: List headnotify_data: Input data to invoke the callbacknotify: Callback function pointer
Description
Drivers may register a callback to take action when new entities get registered with the media device. This handler is intended for creating links between existing entities and should not create entities and register them.
struct media_device_ops #
Media device operations
Definition
;
Members
link_notify: Link state change notification callback. This callback is called with the graph_mutex held.req_alloc: Allocate a request. Set this if you need to allocate a struct larger then struct media_request. req_alloc and req_free must either both be set or both be NULL.req_free: Free a request. Set this if req_alloc was set as well, leave to NULL otherwise.req_validate: Validate a request, but do not queue yet. The req_queue_mutex lock is held when this op is called.req_queue: Queue a validated request, cannot fail. If something goes wrong when queueing this request then it should be marked as such internally in the driver and any related buffers must eventually return to vb2 with state VB2_BUF_STATE_ERROR. The req_queue_mutex lock is held when this op is called. It is important that vb2 buffer objects are queued last after all other object types are queued: queueing a buffer kickstarts the request processing, so all other objects related to the request (and thus the buffer) must be available to the driver. And once a buffer is queued, then the driver can complete or delete objects from the request before req_queue exits.
struct media_device #
Media device
Definition
;
Members
dev: Parent devicedevnode: Media device nodemodel: Device model namedriver_name: Optional device driver name. If not set, calls toMEDIA_IOC_DEVICE_INFOwill returndev->driver->name. This is needed for USB drivers for example, as otherwise they'll all appear as if the driver name was "usb".serial: Device serial number (optional)bus_info: Unique and stable device location identifierhw_revision: Hardware device revisiontopology_version: Monotonic counter for storing the version of the graph topology. Should be incremented each time the topology changes.id: Unique ID used on the last registered graph objectentity_internal_idx: Unique internal entity ID used by the graph traversal algorithmsentity_internal_idx_max: Allocated internal entity indicesentities: List of registered entitiesinterfaces: List of registered interfacespads: List of registered padslinks: List of registered linksentity_notify: List of registered entity_notify callbacksgraph_mutex: Protects access to struct media_device datapm_count_walk: Graph walk for power state walk. Access serialised using graph_mutex.source_priv: Driver Private data for enable/disable source handlersenable_source: Enable Source Handler function pointerdisable_source: Disable Source Handler function pointerops: Operation handler callbacksreq_queue_mutex: Serialise the MEDIA_REQUEST_IOC_QUEUE ioctl w.r.t. other operations that stop or start streaming.num_requests: number of associated requestsnum_request_objects: number of associated request objectsmedia_dir: DebugFS media directoryrequest_id: Used to generate unique request IDs
Description
This structure represents an abstract high-level media device. It allows easy access to entities and provides basic media device-level support. The structure can be allocated directly or embedded in a larger structure.
The parent dev is a physical device. It must be set before registering the media device.
model is a descriptive model name exported through sysfs. It doesn't have to be unique.
enable_source is a handler to find source entity for the sink entity and activate the link between them if source entity is free. Drivers should call this handler before accessing the source.
disable_source is a handler to find source entity for the sink entity and deactivate the link between them. Drivers should call this handler to release the source.
Use-case: find tuner entity connected to the decoder entity and check if it is available, and activate the link between them from enable_source and deactivate from disable_source.
media_device_init() #
void Initializes a media device element
Parameters
struct media_device *mdev: pointer to structmedia_device
Description
This function initializes the media device prior to its registration. The media device initialization and registration is split in two functions to avoid race conditions and make the media device available to user-space before the media graph has been completed.
So drivers need to first initialize the media device, register any entity
within the media device, create pad to pad links and then finally register
the media device by calling media_device_register() as a final step.
The caller is responsible for initializing the media device before registration. The following fields must be set:
- dev must point to the parent device
- model must be filled with the device model name
The bus_info field is set by media_device_init() for PCI and platform devices
if the field begins with '\0'.
media_device_cleanup() #
void Cleanups a media device element
Parameters
struct media_device *mdev: pointer to structmedia_device
Description
This function that will destroy the graph_mutex that is
initialized in media_device_init().
__media_device_register() #
int Registers a media device element
Parameters
struct media_device *mdev: pointer to structmedia_devicestruct module *owner: should be filled withTHIS_MODULE
Description
Users, should, instead, call the media_device_register() macro.
The caller is responsible for initializing the media_device structure
before registration. The following fields of media_device must be set:
media_device.modelmust be filled with the device model name as a NUL-terminated UTF-8 string. The device/model revision must not be stored in this field.
The following fields are optional:
-
media_device.serialis a unique serial number stored as a NUL-terminated ASCII string. The field is big enough to store a GUID in text form. If the hardware doesn't provide a unique serial number this field must be left empty. -
media_device.bus_inforepresents the location of the device in the system as a NUL-terminated ASCII string. For PCI/PCIe devicesmedia_device.bus_infomust be set to "PCI:" (or "PCIe:") followed by the value ofpci_name(). For USB devices,theusb_make_path()function must be used. This field is used by applications to distinguish between otherwise identical devices that don't provide a serial number. -
media_device.hw_revisionis the hardware device revision in a driver-specific format. When possible the revision should be formatted with theKERNEL_VERSION()macro.
Return
returns zero on success or a negative error code.
media_device_register() #
Registers a media device element
Parameters
mdev: pointer to structmedia_device
Description
This macro calls __media_device_register() passing THIS_MODULE as
the __media_device_register() second argument (owner).
media_device_unregister() #
void Unregisters a media device element
Parameters
struct media_device *mdev: pointer to structmedia_device
Description
It is safe to call this function on an unregistered (but initialised) media device.
media_device_register_entity() #
int registers a media entity inside a previously registered media device.
Parameters
struct media_device *mdev: pointer to structmedia_devicestruct media_entity *entity: pointer to structmedia_entityto be registered
Description
Entities are identified by a unique positive integer ID. The media controller framework will such ID automatically. IDs are not guaranteed to be contiguous, and the ID number can change on newer Kernel versions. So, neither the driver nor userspace should hardcode ID numbers to refer to the entities, but, instead, use the framework to find the ID, when needed.
The media_entity name, type and flags fields should be initialized before
calling media_device_register_entity(). Entities embedded in higher-level
standard structures can have some of those fields set by the higher-level
framework.
If the device has pads, media_entity_pads_init() should be called before
this function. Otherwise, the media_entity.pad and media_entity.num_pads
should be zeroed before calling this function.
Entities have flags that describe the entity capabilities and state:
MEDIA_ENT_FL_DEFAULT: indicates the default entity for a given type. This can be used to report the default audio and video devices or the default camera sensor.
media_device_unregister_entity() #
void unregisters a media entity.
Parameters
struct media_entity *entity: pointer to structmedia_entityto be unregistered
Description
All links associated with the entity and all PADs are automatically unregistered from the media_device when this function is called.
Unregistering an entity will not change the IDs of the other entities and the previoully used ID will never be reused for a newly registered entities.
When a media device is unregistered, all its entities are unregistered automatically. No manual entities unregistration is then required.
media_device_register_entity_notify() #
void Registers a media entity_notify callback
Parameters
struct media_device *mdev: The media devicestruct media_entity_notify *nptr: The media_entity_notify
Description
media_device_unregister_entity_notify() #
void Unregister a media entity notify callback
Parameters
struct media_device *mdev: The media devicestruct media_entity_notify *nptr: The media_entity_notify
media_device_pci_init() #
void create and initialize a struct media_device from a PCI device.
Parameters
struct media_device *mdev: pointer to structmedia_devicestruct pci_dev *pci_dev: pointer to struct pci_devconst char *name: media device name. IfNULL, the routine will use the default name for the pci device, given bypci_name()macro.
__media_device_usb_init() #
void create and initialize a struct media_device from a PCI device.
Parameters
struct media_device *mdev: pointer to structmedia_devicestruct usb_device *udev: pointer to struct usb_deviceconst char *board_name: media device name. IfNULL, the routine will use the usb product name, if available.const char *driver_name: name of the driver. ifNULL, the routine will use the name given byudev->dev->driver->name, with is usually the wrong thing to do.
Description
media_device_usb_init() #
create and initialize a struct media_device from a PCI device.
Parameters
mdev: pointer to structmedia_deviceudev: pointer to struct usb_devicename: media device name. IfNULL, the routine will use the usb product name, if available.
Description
This macro calls media_device_usb_init() passing the
media_device_usb_init() driver_name parameter filled with
KBUILD_MODNAME.
media_set_bus_info() #
void Set bus_info field
Parameters
char *bus_info: Variable where to write the bus info (char array)size_t bus_info_size: Length of the bus_infostruct device *dev: Related struct device
Description
Sets bus information based on dev. This is currently done for PCI and
platform devices. dev is required to be non-NULL for this to happen.
This function is not meant to be called from drivers.
struct media_file_operations #
Media device file operations
Definition
;
Members
owner: should be filled withTHIS_MODULEread: pointer to the function that implementsread()syscallwrite: pointer to the function that implementswrite()syscallpoll: pointer to the function that implementspoll()syscallioctl: pointer to the function that implementsioctl()syscallcompat_ioctl: pointer to the function that will handle 32 bits userspace calls to theioctl()syscall on a Kernel compiled with 64 bits.open: pointer to the function that implementsopen()syscallrelease: pointer to the function that will release the resources allocated by the open function.
struct media_devnode #
Media device node
Definition
;
Members
media_dev: pointer to structmedia_devicefops: pointer to structmedia_file_operationswith media device opsdev: pointer to structdevicecontaining the media controller devicecdev: struct cdev pointer character deviceparent: parent deviceminor: device node minor numberflags: flags, combination of theMEDIA_FLAG_*constantsrelease: release callback called at the end ofmedia_devnode_release()routine at media-device.c.
Description
This structure represents a media-related device node.
The parent is a physical device. It must be set by core or device drivers before registering the node.
media_devnode_register() #
int register a media device node
Parameters
struct media_device *mdev: struct media_device we want to register a device nodestruct media_devnode *devnode: media device node structure we want to registerstruct module *owner: should be filled withTHIS_MODULE
Description
The registration code assigns minor numbers and registers the new device node with the kernel. An error is returned if no free minor number can be found, or if the registration of the device node fails.
Zero is returned on success.
Note that if the media_devnode_register call fails, the release() callback of
the media_devnode structure is not called, so the caller is responsible for
freeing any data.
media_devnode_unregister_prepare() #
void clear the media device node register bit
Parameters
struct media_devnode *devnode: the device node to prepare for unregister
Description
This clears the passed device register bit. Future open calls will be met
with errors. Should be called before media_devnode_unregister() to avoid
races with unregister and device file open calls.
This function can safely be called if the device node has never been registered or has already been unregistered.
media_devnode_unregister() #
void unregister a media device node
Parameters
struct media_devnode *devnode: the device node to unregister
Description
This unregisters the passed device. Future open calls will be met with errors.
Should be called after media_devnode_unregister_prepare()
media_devnode_data() #
struct media_devnode * returns a pointer to the media_devnode
Parameters
struct file *filp: pointer to structfile
media_devnode_is_registered() #
int returns true if media_devnode is registered; false otherwise.
Parameters
struct media_devnode *devnode: pointer to structmedia_devnode.
Note
If mdev is NULL, it also returns false.
enum media_gobj_type #
type of a graph object
Constants
MEDIA_GRAPH_ENTITY: Identify a media entityMEDIA_GRAPH_PAD: Identify a media padMEDIA_GRAPH_LINK: Identify a media linkMEDIA_GRAPH_INTF_DEVNODE: Identify a media Kernel API interface via a device node
struct media_gobj #
Define a graph object.
Definition
;
Members
mdev: Pointer to the structmedia_devicethat owns the objectid: Non-zero object ID identifier. The ID should be unique inside a media_device, as it is composed byMEDIA_BITS_PER_TYPEto store the type plusMEDIA_BITS_PER_IDto store the IDlist: List entry stored in one of the per-type mdev object lists
Description
All objects on the media graph should have this struct embedded
struct media_entity_enum #
An enumeration of media entities.
Definition
;
Members
bmap: Bit map in which each bit represents one entity at struct media_entity->internal_idx.idx_max: Number of bits in bmap
struct media_graph #
Media graph traversal state
Definition
;
Members
stack: Graph traversal stack; the stack contains information on the path the media entities to be walked and the links through which they were reached.stack.entity: pointer tostruct media_entityat the graph.stack.link: pointer tostruct list_head.ent_enum: Visited entitiestop: The top of the stack
struct media_pipeline #
Media pipeline related information
Definition
;
Members
allocated: Media pipeline allocated and freed by the frameworkmdev: The media device the pipeline is part ofpads: List of media_pipeline_padstart_count: Media pipeline start - stop count
struct media_pipeline_pad #
A pad part of a media pipeline
Definition
;
Members
list: Entry in the media_pad pads listpipe: The media_pipeline that the pad is part ofpad: The media pad
Description
This structure associate a pad with a media pipeline. Instances of
media_pipeline_pad are created by media_pipeline_start() when it builds the
pipeline, and stored in the media_pad.pads list. media_pipeline_stop()
removes the entries from the list and deletes them.
struct media_pipeline_pad_iter #
Iterator for media_pipeline_for_each_pad
Definition
;
Members
cursor: The current element
struct media_pipeline_entity_iter #
Iterator for media_pipeline_for_each_entity
Definition
;
Members
ent_enum: The entity enumeration trackercursor: The current element
struct media_link #
A link object part of a media graph.
Definition
;
Members
graph_obj: Embedded structure containing the media object common datalist: Linked list associated with an entity or an interface that owns the link.{unnamed_union}: anonymousgobj0: Part of a union. Used to get the pointer for the first graph_object of the link.source: Part of a union. Used only if the first object (gobj0) is a pad. In that case, it represents the source pad.intf: Part of a union. Used only if the first object (gobj0) is an interface.{unnamed_union}: anonymousgobj1: Part of a union. Used to get the pointer for the second graph_object of the link.sink: Part of a union. Used only if the second object (gobj1) is a pad. In that case, it represents the sink pad.entity: Part of a union. Used only if the second object (gobj1) is an entity.reverse: Pointer to the link for the reverse direction of a pad to pad link.flags: Link flags, as defined in uapi/media.h (MEDIA_LNK_FL_*)is_backlink: Indicate if the link is a backlink.
enum media_pad_signal_type #
type of the signal inside a media pad
Constants
PAD_SIGNAL_DEFAULT: Default signal. Use this when all inputs or all outputs are uniquely identified by the pad number.PAD_SIGNAL_ANALOG: The pad contains an analog signal. It can be Radio Frequency, Intermediate Frequency, a baseband signal or sub-carriers. Tuner inputs, IF-PLL demodulators, composite and s-video signals should use it.PAD_SIGNAL_DV: Contains a digital video signal, with can be a bitstream of samples taken from an analog TV video source. On such case, it usually contains the VBI data on it.PAD_SIGNAL_AUDIO: Contains an Intermediate Frequency analog signal from an audio sub-carrier or an audio bitstream. IF signals are provided by tuners and consumed by audio AM/FM decoders. Bitstream audio is provided by an audio decoder.
struct media_pad #
A media pad graph object.
Definition
;
Members
graph_obj: Embedded structure containing the media object common dataentity: Entity this pad belongs toindex: Pad index in the entity pads array, numbered from 0 to nnum_links: Number of links connected to this padsig_type: Type of the signal inside a media padflags: Pad flags, as defined in include/uapi/linux/media.h (seek forMEDIA_PAD_FL_*)pipe: Pipeline this pad belongs to. Usemedia_entity_pipeline()to access this field.
struct media_entity_operations #
Media entity operations
Definition
;
Members
get_fwnode_pad: Return the pad number based on a fwnode endpoint or a negative value on error. This operation can be used to map a fwnode to a media pad number. Optional.link_setup: Notify the entity of link changes. The operation can return an error, in which case link setup will be cancelled. Optional.link_validate: Return whether a link is valid from the entity point of view. Themedia_pipeline_start()function validates all links by calling this operation. Optional.has_pad_interdep: Return whether two pads of the entity are interdependent. If two pads are interdependent they are part of the same pipeline and enabling one of the pads means that the other pad will become "locked" and doesn't allow configuration changes. pad0 and pad1 are guaranteed to not both be sinks or sources. Never call the .has_pad_interdep()operation directly, always usemedia_entity_has_pad_interdep(). Optional: If the operation isn't implemented all pads will be considered as interdependent.
Description
enum media_entity_type #
Media entity type
Constants
MEDIA_ENTITY_TYPE_BASE: The entity isn't embedded in another subsystem structure.MEDIA_ENTITY_TYPE_VIDEO_DEVICE: The entity is embedded in a struct video_device instance.MEDIA_ENTITY_TYPE_V4L2_SUBDEV: The entity is embedded in a struct v4l2_subdev instance.
Description
Media entity objects are often not instantiated directly, but the media entity structure is inherited by (through embedding) other subsystem-specific structures. The media entity type identifies the type of the subclass structure that implements a media entity instance.
This allows runtime type identification of media entities and safe casting to
the correct object type. For instance, a media entity structure instance
embedded in a v4l2_subdev structure instance will have the type
MEDIA_ENTITY_TYPE_V4L2_SUBDEV and can safely be cast to a v4l2_subdev
structure using the container_of() macro.
struct media_entity #
A media entity graph object.
Definition
;
Members
graph_obj: Embedded structure containing the media object common data.name: Entity name.obj_type: Type of the object that implements the media_entity.function: Entity main function, as defined in include/uapi/linux/media.h (seek forMEDIA_ENT_F_*)flags: Entity flags, as defined in include/uapi/linux/media.h (seek forMEDIA_ENT_FL_*)num_pads: Number of sink and source pads.num_links: Total number of links, forward and back, enabled and disabled.num_backlinks: Number of backlinksinternal_idx: An unique internal entity specific number. The numbers are re-used if entities are unregistered or registered again.pads: Pads array with the size defined by num_pads.links: List of data links.ops: Entity operations.use_count: Use count for the entity.info: Union with devnode information. Kept just for backward compatibility.info.dev: Contains device major and minor info.info.dev.major: device node major, if the device is a devnode.info.dev.minor: device node minor, if the device is a devnode.
Description
media_entity_for_each_pad() #
Iterate on all pads in an entity
Parameters
entity: The entity the pads belong toiter: The iterator pad
Description
Iterate on all pads in a media entity.
struct media_interface #
A media interface graph object.
Definition
;
Members
graph_obj: embedded graph objectlinks: List of links pointing to graph entitiestype: Type of the interface as defined in include/uapi/linux/media.h (seek forMEDIA_INTF_T_*)flags: Interface flags as defined in include/uapi/linux/media.h (seek forMEDIA_INTF_FL_*)
Description
struct media_intf_devnode #
A media interface via a device node.
Definition
;
Members
intf: embedded interface objectmajor: Major number of a device nodeminor: Minor number of a device node
media_entity_id() #
u32 return the media entity graph object id
Parameters
struct media_entity *entity: pointer tomedia_entity
media_type() #
enum media_gobj_type return the media object type
Parameters
struct media_gobj *gobj: Pointer to the structmedia_gobjgraph object
media_id() #
u32 return the media object ID
Parameters
struct media_gobj *gobj: Pointer to the structmedia_gobjgraph object
media_gobj_gen_id() #
u32 encapsulates type and ID on at the object ID
Parameters
enum media_gobj_type type: object type as define at enummedia_gobj_type.u64 local_id: next ID, from structmedia_device.id.
is_media_entity_v4l2_video_device() #
bool Check if the entity is a video_device
Parameters
struct media_entity *entity: pointer to entity
Return
true if the entity is an instance of a video_device object and can
safely be cast to a struct video_device using the container_of() macro, or
false otherwise.
is_media_entity_v4l2_subdev() #
bool Check if the entity is a v4l2_subdev
Parameters
struct media_entity *entity: pointer to entity
Return
true if the entity is an instance of a v4l2_subdev object and can
safely be cast to a struct v4l2_subdev using the container_of() macro, or
false otherwise.
media_entity_enum_init() #
int Initialise an entity enumeration
Parameters
struct media_entity_enum *ent_enum: Entity enumeration to be initialisedstruct media_device *mdev: The related media device
Return
zero on success or a negative error code.
media_entity_enum_cleanup() #
void Release resources of an entity enumeration
Parameters
struct media_entity_enum *ent_enum: Entity enumeration to be released
media_entity_enum_zero() #
void Clear the entire enum
Parameters
struct media_entity_enum *ent_enum: Entity enumeration to be cleared
media_entity_enum_set() #
void Mark a single entity in the enum
Parameters
struct media_entity_enum *ent_enum: Entity enumerationstruct media_entity *entity: Entity to be marked
media_entity_enum_clear() #
void Unmark a single entity in the enum
Parameters
struct media_entity_enum *ent_enum: Entity enumerationstruct media_entity *entity: Entity to be unmarked
media_entity_enum_test() #
bool Test whether the entity is marked
Parameters
struct media_entity_enum *ent_enum: Entity enumerationstruct media_entity *entity: Entity to be tested
Description
Returns true if the entity was marked.
media_entity_enum_test_and_set() #
bool Test whether the entity is marked, and mark it
Parameters
struct media_entity_enum *ent_enum: Entity enumerationstruct media_entity *entity: Entity to be tested
Description
Returns true if the entity was marked, and mark it before doing so.
media_entity_enum_empty() #
bool Test whether the entire enum is empty
Parameters
struct media_entity_enum *ent_enum: Entity enumeration
Return
true if the entity was empty.
media_entity_enum_intersects() #
bool Test whether two enums intersect
Parameters
struct media_entity_enum *ent_enum1: First entity enumerationstruct media_entity_enum *ent_enum2: Second entity enumeration
Return
true if entity enumerations ent_enum1 and ent_enum2 intersect,
otherwise false.
gobj_to_entity() #
returns the struct media_entity pointer from the gobj contained on it.
Parameters
gobj: Pointer to the structmedia_gobjgraph object
gobj_to_pad() #
returns the struct media_pad pointer from the gobj contained on it.
Parameters
gobj: Pointer to the structmedia_gobjgraph object
gobj_to_link() #
returns the struct media_link pointer from the gobj contained on it.
Parameters
gobj: Pointer to the structmedia_gobjgraph object
gobj_to_intf() #
returns the struct media_interface pointer from the gobj contained on it.
Parameters
gobj: Pointer to the structmedia_gobjgraph object
intf_to_devnode() #
returns the struct media_intf_devnode pointer from the intf contained on it.
Parameters
intf: Pointer to structmedia_intf_devnode
media_gobj_create() #
void Initialize a graph object
Parameters
struct media_device *mdev: Pointer to themedia_devicethat contains the objectenum media_gobj_type type: Type of the objectstruct media_gobj *gobj: Pointer to the structmedia_gobjgraph object
Description
This routine initializes the embedded struct media_gobj inside a
media graph object. It is called automatically if media_*_create
function calls are used. However, if the object (entity, link, pad,
interface) is embedded on some other object, this function should be
called before registering the object at the media controller.
media_gobj_destroy() #
void Stop using a graph object on a media device
Parameters
struct media_gobj *gobj: Pointer to the structmedia_gobjgraph object
Description
This should be called by all routines like media_device_unregister()
that remove/destroy media graph objects.
media_entity_pads_init() #
int Initialize the entity pads
Parameters
struct media_entity *entity: entity where the pads belongu16 num_pads: total number of sink and source padsstruct media_pad *pads: Array of num_pads pads.
Description
The pads array is managed by the entity driver and passed to
media_entity_pads_init() where its pointer will be stored in the
media_entity structure.
If no pads are needed, drivers could either directly fill
media_entity->num_pads with 0 and media_entity->pads with NULL or call
this function that will do the same.
As the number of pads is known in advance, the pads array is not allocated dynamically but is managed by the entity driver. Most drivers will embed the pads array in a driver-specific structure, avoiding dynamic allocation.
Drivers must set the direction of every pad in the pads array before calling
media_entity_pads_init(). The function will initialize the other pads fields.
media_entity_cleanup() #
void free resources associated with an entity
Parameters
struct media_entity *entity: entity where the pads belong
Description
This function must be called during the cleanup phase after unregistering the entity (currently, it does nothing).
Calling media_entity_cleanup() on a media_entity whose memory has been
zeroed but that has not been initialized with media_entity_pad_init() is
valid and is a no-op.
media_get_pad_index() #
int retrieves a pad index from an entity
Parameters
struct media_entity *entity: entity where the pads belongu32 pad_type: the type of the pad, one of MEDIA_PAD_FL_* pad typesenum media_pad_signal_type sig_type: type of signal of the pad to be search
Description
This helper function finds the first pad index inside an entity that satisfies both is_sink and sig_type conditions.
On success, return the pad number. If the pad was not found or the media entity is a NULL pointer, return -EINVAL.
media_create_pad_link() #
int creates a link between two entities.
Parameters
struct media_entity *source: pointer tomedia_entityof the source pad.u16 source_pad: number of the source pad in the pads arraystruct media_entity *sink: pointer tomedia_entityof the sink pad.u16 sink_pad: number of the sink pad in the pads array.u32 flags: Link flags, as defined in include/uapi/linux/media.h ( seek forMEDIA_LNK_FL_*)
Description
Valid values for flags:
-
MEDIA_LNK_FL_ENABLED: Indicates that the link is enabled and can be used to transfer media data. When two or more links target a sink pad, only one of them can be enabled at a time. -
MEDIA_LNK_FL_IMMUTABLE: Indicates that the link enabled state can't be modified at runtime. IfMEDIA_LNK_FL_IMMUTABLEis set, thenMEDIA_LNK_FL_ENABLEDmust also be set, since an immutable link is always enabled.
media_create_pad_links() #
int creates a link between two entities.
Parameters
const struct media_device *mdev: Pointer to the media_device that contains the objectconst u32 source_function: Function of the source entities. Used only if source is NULL.struct media_entity *source: pointer tomedia_entityof the source pad. If NULL, it will use all entities that matches the sink_function.const u16 source_pad: number of the source pad in the pads arrayconst u32 sink_function: Function of the sink entities. Used only if sink is NULL.struct media_entity *sink: pointer tomedia_entityof the sink pad. If NULL, it will use all entities that matches the sink_function.const u16 sink_pad: number of the sink pad in the pads array.u32 flags: Link flags, as defined in include/uapi/linux/media.h.const bool allow_both_undefined: iftrue, then both source and sink can be NULL. In such case, it will create a crossbar between all entities that matches source_function to all entities that matches sink_function. Iffalse, it will return 0 and won't create any link if both source and sink are NULL.
Description
Valid values for flags:
-
A
MEDIA_LNK_FL_ENABLEDflag indicates that the link is enabled and can beused to transfer media data. If multiple links are created and this flag is passed as an argument, only the first created link will have this flag.
-
A
MEDIA_LNK_FL_IMMUTABLEflag indicates that the link enabled state can'tbe modified at runtime. If
MEDIA_LNK_FL_IMMUTABLEis set, thenMEDIA_LNK_FL_ENABLEDmust also be set since an immutable link is always enabled.
It is common for some devices to have multiple source and/or sink entities
of the same type that should be linked. While media_create_pad_link()
creates link by link, this function is meant to allow 1:n, n:1 and even
cross-bar (n:n) links.
media_entity_remove_links() #
void remove all links associated with an entity
Parameters
struct media_entity *entity: pointer tomedia_entity
Description
__media_entity_setup_link() #
int Configure a media link without locking
Parameters
struct media_link *link: The link being configuredu32 flags: Link configuration flags
Description
The bulk of link setup is handled by the two entities connected through the link. This function notifies both entities of the link configuration change.
If the link is immutable or if the current and new configuration are identical, return immediately.
The user is expected to hold link->source->parent->mutex. If not,
media_entity_setup_link() should be used instead.
media_entity_setup_link() #
int changes the link flags properties in runtime
Parameters
struct media_link *link: pointer tomedia_linku32 flags: the requested new link flags
Description
The only configurable property is the MEDIA_LNK_FL_ENABLED link flag
to enable/disable a link. Links marked with the
MEDIA_LNK_FL_IMMUTABLE link flag can not be enabled or disabled.
When a link is enabled or disabled, the media framework calls the link_setup operation for the two entities at the source and sink of the link, in that order. If the second link_setup call fails, another link_setup call is made on the first entity to restore the original link flags.
Media device drivers can be notified of link setup operations by setting the
media_device.link_notify pointer to a callback function. If provided, the
notification callback will be called before enabling and after disabling
links.
Entity drivers must implement the link_setup operation if any of their links is non-immutable. The operation must either configure the hardware or store the configuration information to be applied later.
Link configuration must not have any side effect on other links. If an
enabled link at a sink pad prevents another link at the same pad from
being enabled, the link_setup operation must return -EBUSY and can't
implicitly disable the first enabled link.
media_entity_find_link() #
struct media_link * Find a link between two pads
Parameters
struct media_pad *source: Source padstruct media_pad *sink: Sink pad
Return
returns a pointer to the link between the two entities. If no
such link exists, return NULL.
media_pad_remote_pad_first() #
struct media_pad * Find the first pad at the remote end of a link
Parameters
const struct media_pad *pad: Pad at the local end of the link
Description
Search for a remote pad connected to the given pad by iterating over all links originating or terminating at that pad until an enabled link is found.
Return
returns a pointer to the pad at the remote end of the first found
enabled link, or NULL if no enabled link has been found.
media_pad_remote_pad_unique() #
struct media_pad * Find a remote pad connected to a pad
Parameters
const struct media_pad *pad: The pad
Description
Search for and return a remote pad connected to pad through an enabled link. If multiple (or no) remote pads are found, an error is returned.
The uniqueness constraint makes this helper function suitable for entities that support a single active source at a time on a given pad.
- -ENOTUNIQ - Multiple links are enabled
- -ENOLINK - No connected pad found
Return
A pointer to the remote pad, or one of the following error pointers if an error occurs:
media_entity_remote_pad_unique() #
struct media_pad * Find a remote pad connected to an entity
Parameters
const struct media_entity *entity: The entityunsigned int type: The type of pad to find (MEDIA_PAD_FL_SINK or MEDIA_PAD_FL_SOURCE)
Description
Search for and return a remote pad of type connected to entity through an enabled link. If multiple (or no) remote pads match these criteria, an error is returned.
The uniqueness constraint makes this helper function suitable for entities that support a single active source or sink at a time.
- -ENOTUNIQ - Multiple links are enabled
- -ENOLINK - No connected pad found
Return
A pointer to the remote pad, or one of the following error pointers if an error occurs:
media_entity_remote_source_pad_unique() #
struct media_pad * Find a remote source pad connected to an entity
Parameters
const struct media_entity *entity: The entity
Description
Search for and return a remote source pad connected to entity through an enabled link. If multiple (or no) remote pads match these criteria, an error is returned.
The uniqueness constraint makes this helper function suitable for entities that support a single active source at a time.
- -ENOTUNIQ - Multiple links are enabled
- -ENOLINK - No connected pad found
Return
A pointer to the remote pad, or one of the following error pointers if an error occurs:
media_pad_is_streaming() #
bool Test if a pad is part of a streaming pipeline
Parameters
const struct media_pad *pad: The pad
Return
True if the pad is part of a pipeline started with the
media_pipeline_start() function, false otherwise.
media_entity_is_streaming() #
bool Test if an entity is part of a streaming pipeline
Parameters
const struct media_entity *entity: The entity
Return
True if the entity is part of a pipeline started with the
media_pipeline_start() function, false otherwise.
media_entity_pipeline() #
struct media_pipeline * Get the media pipeline an entity is part of
Parameters
struct media_entity *entity: The entity
Description
DEPRECATED: use media_pad_pipeline() instead.
This function returns the media pipeline that an entity has been associated
with when constructing the pipeline with media_pipeline_start(). The pointer
remains valid until media_pipeline_stop() is called.
In general, entities can be part of multiple pipelines, when carrying multiple streams (either on different pads, or on the same pad using multiplexed streams). This function is to be used only for entities that do not support multiple pipelines.
Return
The media_pipeline the entity is part of, or NULL if the entity is not part of any pipeline.
media_pad_pipeline() #
struct media_pipeline * Get the media pipeline a pad is part of
Parameters
struct media_pad *pad: The pad
Description
This function returns the media pipeline that a pad has been associated
with when constructing the pipeline with media_pipeline_start(). The pointer
remains valid until media_pipeline_stop() is called.
Return
The media_pipeline the pad is part of, or NULL if the pad is not part of any pipeline.
media_entity_get_fwnode_pad() #
int Get pad number from fwnode
Parameters
struct media_entity *entity: The entityconst struct fwnode_handle *fwnode: Pointer to the fwnode_handle which should be used to find the padunsigned long direction_flags: Expected direction of the pad, as defined in include/uapi/linux/media.h (seek forMEDIA_PAD_FL_*)
Description
This function can be used to resolve the media pad number from a fwnode. This is useful for devices which use more complex mappings of media pads.
If the entity does not implement the get_fwnode_pad() operation
then this function searches the entity for the first pad that
matches the direction_flags.
Return
returns the pad number on success or a negative error code.
media_graph_walk_init() #
int Allocate resources used by graph walk.
Parameters
struct media_graph *graph: Media graph structure that will be used to walk the graphstruct media_device *mdev: Pointer to themedia_devicethat contains the object
Description
This function is deprecated, use media_pipeline_for_each_pad() instead.
The caller is required to hold the media_device graph_mutex during the graph walk until the graph state is released.
Returns zero on success or a negative error code otherwise.
media_graph_walk_cleanup() #
void Release resources used by graph walk.
Parameters
struct media_graph *graph: Media graph structure that will be used to walk the graph
Description
This function is deprecated, use media_pipeline_for_each_pad() instead.
media_graph_walk_start() #
void Start walking the media graph at a given entity
Parameters
struct media_graph *graph: Media graph structure that will be used to walk the graphstruct media_entity *entity: Starting entity
Description
This function is deprecated, use media_pipeline_for_each_pad() instead.
Before using this function, media_graph_walk_init() must be
used to allocate resources used for walking the graph. This
function initializes the graph traversal structure to walk the
entities graph starting at the given entity. The traversal
structure must not be modified by the caller during graph
traversal. After the graph walk, the resources must be released
using media_graph_walk_cleanup().
media_graph_walk_next() #
struct media_entity * Get the next entity in the graph
Parameters
struct media_graph *graph: Media graph structure
Description
This function is deprecated, use media_pipeline_for_each_pad() instead.
Perform a depth-first traversal of the given media entities graph.
The graph structure must have been previously initialized with a call to
media_graph_walk_start().
Return
returns the next entity in the graph or NULL if the whole graph
have been traversed.
media_pipeline_start() #
int Mark a pipeline as streaming
Parameters
struct media_pad *origin: Starting padstruct media_pipeline *pipe: Media pipeline to be assigned to all pads in the pipeline.
Description
Mark all pads connected to pad origin through enabled links, either directly or indirectly, as streaming. The given pipeline object is assigned to every pad in the pipeline and stored in the media_pad pipe field.
Calls to this function can be nested, in which case the same number of
media_pipeline_stop() calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
media_pipeline_start().
__media_pipeline_start() #
int Mark a pipeline as streaming
Parameters
struct media_pad *origin: Starting padstruct media_pipeline *pipe: Media pipeline to be assigned to all pads in the pipeline.
Description
..note:: This is the non-locking version of media_pipeline_start()
media_pipeline_stop() #
void Mark a pipeline as not streaming
Parameters
struct media_pad *pad: Starting pad
Description
Mark all pads connected to a given pad through enabled links, either
directly or indirectly, as not streaming. The media_pad pipe field is
reset to NULL.
If multiple calls to media_pipeline_start() have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.
__media_pipeline_stop() #
void Mark a pipeline as not streaming
Parameters
struct media_pad *pad: Starting pad
Description
media_pipeline_for_each_pad() #
Iterate on all pads in a media pipeline
Parameters
pipe: The pipelineiter: The iterator (struct media_pipeline_pad_iter)pad: The iterator pad
Description
Iterate on all pads in a media pipeline. This is only valid after the
pipeline has been built with media_pipeline_start() and before it gets
destroyed with media_pipeline_stop().
media_pipeline_entity_iter_init() #
int Initialize a pipeline entity iterator
Parameters
struct media_pipeline *pipe: The pipelinestruct media_pipeline_entity_iter *iter: The iterator
Description
This function must be called to initialize the iterator before using it in a
media_pipeline_for_each_entity() loop. The iterator must be destroyed by a
call to media_pipeline_entity_iter_cleanup after the loop (including in code
paths that break from the loop).
The same iterator can be used in multiple consecutive loops without being destroyed and reinitialized.
Return
0 on success or a negative error code otherwise.
media_pipeline_entity_iter_cleanup() #
void Destroy a pipeline entity iterator
Parameters
struct media_pipeline_entity_iter *iter: The iterator
Description
This function must be called to destroy iterators initialized with
media_pipeline_entity_iter_init().
media_pipeline_for_each_entity() #
Iterate on all entities in a media pipeline
Parameters
pipe: The pipelineiter: The iterator (struct media_pipeline_entity_iter)entity: The iterator entity
Description
Iterate on all entities in a media pipeline. This is only valid after the
pipeline has been built with media_pipeline_start() and before it gets
destroyed with media_pipeline_stop(). The iterator must be initialized with
media_pipeline_entity_iter_init() before iteration, and destroyed with
media_pipeline_entity_iter_cleanup() after (including in code paths that
break from the loop).
media_pipeline_alloc_start() #
int Mark a pipeline as streaming
Parameters
struct media_pad *pad: Starting pad
Description
media_pipeline_alloc_start() is similar to media_pipeline_start() but instead
of working on a given pipeline the function will use an existing pipeline if
the pad is already part of a pipeline, or allocate a new pipeline.
Calls to media_pipeline_alloc_start() must be matched with
media_pipeline_stop().
media_devnode_create() #
struct media_intf_devnode * creates and initializes a device node interface
Parameters
struct media_device *mdev: pointer to structmedia_deviceu32 type: type of the interface, as given by include/uapi/linux/media.h ( seek forMEDIA_INTF_T_*) macros.u32 flags: Interface flags, as defined in include/uapi/linux/media.h ( seek forMEDIA_INTF_FL_*)u32 major: Device node major number.u32 minor: Device node minor number.
Return
if succeeded, returns a pointer to the newly allocated
media_intf_devnode pointer.
Description
media_devnode_remove() #
void removes a device node interface
Parameters
struct media_intf_devnode *devnode: pointer tomedia_intf_devnodeto be freed.
Description
When a device node interface is removed, all links to it are automatically removed.
media_create_intf_link() #
struct media_link * creates a link between an entity and an interface
Parameters
struct media_entity *entity: pointer tomedia_entitystruct media_interface *intf: pointer tomedia_interfaceu32 flags: Link flags, as defined in include/uapi/linux/media.h ( seek forMEDIA_LNK_FL_*)
Description
Valid values for flags:
-
MEDIA_LNK_FL_ENABLED: Indicates that the interface is connected to the entity hardware. That's the default value for interfaces. An interface may be disabled if the hardware is busy due to the usage of some other interface that it is currently controlling the hardware.A typical example is an hybrid TV device that handle only one type of stream on a given time. So, when the digital TV is streaming, the V4L2 interfaces won't be enabled, as such device is not able to also stream analog TV or radio.
__media_remove_intf_link() #
void remove a single interface link
Parameters
struct media_link *link: pointer tomedia_link.
Description
media_remove_intf_link() #
void remove a single interface link
Parameters
struct media_link *link: pointer tomedia_link.
Description
__media_remove_intf_links() #
void remove all links associated with an interface
Parameters
struct media_interface *intf: pointer tomedia_interface
Description
media_remove_intf_links() #
void remove all links associated with an interface
Parameters
struct media_interface *intf: pointer tomedia_interface
Description
media_entity_call() #
Calls a struct media_entity_operations operation on an entity
Parameters
entity: entity where the operation will be calledoperation: type of the operation. Should be the name of a member of structmedia_entity_operations.args...: variable arguments
Description
This helper function will check if operation is not NULL. On such case,
it will issue a call to operation(entity, args).
media_create_ancillary_link() #
struct media_link * create an ancillary link between two instances of media_entity
Parameters
struct media_entity *primary: pointer to the primarymedia_entitystruct media_entity *ancillary: pointer to the ancillarymedia_entity
Description
Create an ancillary link between two entities, indicating that they represent two connected pieces of hardware that form a single logical unit. A typical example is a camera lens controller being linked to the sensor that it is supporting.
The function sets both MEDIA_LNK_FL_ENABLED and MEDIA_LNK_FL_IMMUTABLE for the new link.
__media_entity_next_link() #
struct media_link * Iterate through a media_entity's links
Parameters
struct media_entity *entity: pointer to themedia_entitystruct media_link *link: pointer to amedia_linkto hold the iterated valuesunsigned long link_type: one of the MEDIA_LNK_FL_LINK_TYPE flags
Description
Return the next link against an entity matching a specific link type. This allows iteration through an entity's links whilst guaranteeing all of the returned links are of the given type.
for_each_media_entity_data_link() #
Iterate through an entity's data links
Parameters
entity: pointer to themedia_entitylink: pointer to amedia_linkto hold the iterated values
Description
Iterate over a media_entity's data links
enum media_request_state #
media request state
Constants
MEDIA_REQUEST_STATE_IDLE: IdleMEDIA_REQUEST_STATE_VALIDATING: Validating the request, no state changes allowedMEDIA_REQUEST_STATE_QUEUED: QueuedMEDIA_REQUEST_STATE_COMPLETE: Completed, the request is doneMEDIA_REQUEST_STATE_CLEANING: Cleaning, the request is being re-initedMEDIA_REQUEST_STATE_UPDATING: The request is being updated, i.e. request objects are being added, modified or removedNR_OF_MEDIA_REQUEST_STATE: The number of media request states, used internally for sanity check purposes
struct media_request #
Media device request
Definition
;
Members
mdev: Media device this request belongs tokref: Reference countdebug_str: Prefix for debug messages (process name:fd)state: The state of the requestupdating_count: count the number of request updates that are in progressaccess_count: count the number of request accesses that are in progressobjects: List of struct media_request_object request objectsnum_incomplete_objects: The number of incomplete objects in the requestmanual_completion: if true, then the request won't be marked as completed when num_incomplete_objects reaches 0. Callmedia_request_manual_complete()to complete the request after num_incomplete_objects == 0.poll_wait: Wait queue for polllock: Serializes access to this struct
media_request_lock_for_access() #
int Lock the request to access its objects
Parameters
struct media_request *req: The media request
Description
Use before accessing a completed request. A reference to the request must be held during the access. This usually takes place automatically through a file handle. Use media_request_unlock_for_access when done.
media_request_unlock_for_access() #
void Unlock a request previously locked for access
Parameters
struct media_request *req: The media request
Description
Unlock a request that has previously been locked using media_request_lock_for_access.
media_request_lock_for_update() #
int Lock the request for updating its objects
Parameters
struct media_request *req: The media request
Description
Use before updating a request, i.e. adding, modifying or removing a request object in it. A reference to the request must be held during the update. This usually takes place automatically through a file handle. Use media_request_unlock_for_update when done.
media_request_unlock_for_update() #
void Unlock a request previously locked for update
Parameters
struct media_request *req: The media request
Description
Unlock a request that has previously been locked using media_request_lock_for_update.
media_request_get() #
void Get the media request
Parameters
struct media_request *req: The media request
Description
Get the media request.
media_request_put() #
void Put the media request
Parameters
struct media_request *req: The media request
Description
Put the media request. The media request will be released when the refcount reaches 0.
media_request_get_by_fd() #
struct media_request * Get a media request by fd
Parameters
struct media_device *mdev: Media device this request belongs toint request_fd: The file descriptor of the request
Description
Get the request represented by request_fd that is owned by the media device.
Return a -EBADR error pointer if requests are not supported by this driver. Return -EINVAL if the request was not found. Return the pointer to the request if found: the caller will have to call media_request_put when it finished using the request.
media_request_alloc() #
int Allocate the media request
Parameters
struct media_device *mdev: Media device this request belongs toint *alloc_fd: Store the request's file descriptor in this int
Description
Allocated the media request and put the fd in alloc_fd.
media_request_mark_manual_completion() #
void Enable manual completion
Parameters
struct media_request *req: The request
Description
Mark that the request has to be manually completed by calling
media_request_manual_complete().
This function shall be called in the req_queue callback.
media_request_manual_complete() #
void Mark the request as completed
Parameters
struct media_request *req: The request
Description
This function completes a request that was marked for manual completion by an
earlier call to media_request_mark_manual_completion(). The request's
manual_completion field is reset to false.
All objects contained in the request must have been completed previously. It is an error to call this function otherwise. If such an error occurred, the function will WARN and the object completion will be delayed until num_incomplete_objects is 0.
struct media_request_object_ops #
Media request object operations
Definition
;
Members
prepare: Validate and prepare the request object, optional.unprepare: Unprepare the request object, optional.queue: Queue the request object, optional.unbind: Unbind the request object, optional.release: Release the request object, required.
struct media_request_object #
An opaque object that belongs to a media request
Definition
;
Members
mdev: Media device this object belongs toops: object's operationspriv: object's priv pointerreq: the request this object belongs to (can be NULL)list: List entry of the object for struct media_requestkref: Reference count of the object, acquire before releasing req->lockcompleted: If true, then this object was completed.
Description
An object related to the request. This struct is always embedded in another struct that contains the actual data for this request object.
media_request_object_get() #
void Get a media request object
Parameters
struct media_request_object *obj: The object
Description
Get a media request object.
media_request_object_put() #
void Put a media request object
Parameters
struct media_request_object *obj: The object
Description
Put a media request object. Once all references are gone, the object's memory is released.
media_request_object_find() #
struct media_request_object * Find an object in a request
Parameters
struct media_request *req: The media requestconst struct media_request_object_ops *ops: Find an object with this ops valuevoid *priv: Find an object with this priv value
Description
Both ops and priv must be non-NULL.
Returns the object pointer or NULL if not found. The caller must
call media_request_object_put() once it finished using the object.
Since this function needs to walk the list of objects it takes the req->lock spin lock to make this safe.
media_request_object_init() #
void Initialise a media request object
Parameters
struct media_request_object *obj: The object
Description
Initialise a media request object. The object will be released using the release callback of the ops once it has no references (this function initialises references to one).
media_request_object_bind() #
int Bind a media request object to a request
Parameters
struct media_request *req: The media requestconst struct media_request_object_ops *ops: The object ops for this objectvoid *priv: A driver-specific priv pointer associated with this objectbool is_buffer: Set to true if the object is a buffer object.struct media_request_object *obj: The object
Description
Bind this object to the request and set the ops and priv values of
the object so it can be found later with media_request_object_find().
Every bound object must be unbound or completed by the kernel at some point in time, otherwise the request will never complete. When the request is released all completed objects will be unbound by the request core code.
Buffer objects will be added to the end of the request's object list, non-buffer objects will be added to the front of the list. This ensures that all buffer objects are at the end of the list and that all non-buffer objects that they depend on are processed first.
media_request_object_unbind() #
void Unbind a media request object
Parameters
struct media_request_object *obj: The object
Description
Unbind the media request object from the request.
media_request_object_complete() #
void Mark the media request object as complete
Parameters
struct media_request_object *obj: The object
Description
Mark the media request object as complete. Only bound objects can be completed.
media_device_usb_allocate() #
struct media_device * Allocate and return struct media device
Parameters
struct usb_device *udev: structusb_devicepointerconst char *module_name: should be filled withKBUILD_MODNAMEstruct module *owner: struct module pointerTHIS_MODULEfor the driver.THIS_MODULEis null for a built-in driver. It is safe even whenTHIS_MODULEis null.
Description
This interface should be called to allocate a Media Device when multiple
drivers share usb_device and the media device. This interface allocates
media_device structure and calls media_device_usb_init() to initialize
it.
media_device_delete() #
void Release media device. Calls kref_put().
Parameters
struct media_device *mdev: structmedia_devicepointerconst char *module_name: should be filled withKBUILD_MODNAMEstruct module *owner: struct module pointerTHIS_MODULEfor the driver.THIS_MODULEis null for a built-in driver. It is safe even whenTHIS_MODULEis null.
Description
This interface should be called to put Media Device Instance kref.
Remote Controller devices
Peios Kernel / Hardware and drivers / Driver development / Media devices
Remote Controller core #
The remote controller core implements infrastructure to receive and send remote controller keyboard keystrokes and mouse events.
Every time a key is pressed on a remote controller, a scan code is produced. Also, on most hardware, keeping a key pressed for more than a few dozens of milliseconds produce a repeat key event. That's somewhat similar to what a normal keyboard or mouse is handled internally on Linux1. So, the remote controller core is implemented on the top of the linux input/evdev interface.
[1] The main difference is that, on keyboard events, the keyboard controller produces one event for a key press and another one for key release. On infrared-based remote controllers, there's no key release event. Instead, an extra code is produced to indicate key repeats.
However, most of the remote controllers use infrared (IR) to transmit signals. As there are several protocols used to modulate infrared signals, one important part of the core is dedicated to adjust the driver and the core system to support the infrared protocol used by the emitter.
The infrared transmission is done by blinking a infrared emitter using a carrier. The carrier can be switched on or off by the IR transmitter hardware. When the carrier is switched on, it is called PULSE. When the carrier is switched off, it is called SPACE.
In other words, a typical IR transmission can be viewed as a sequence of PULSE and SPACE events, each with a given duration.
The carrier parameters (frequency, duty cycle) and the intervals for PULSE and SPACE events depend on the protocol. For example, the NEC protocol uses a carrier of 38kHz, and transmissions start with a 9ms PULSE and a 4.5ms SPACE. It then transmits 16 bits of scan code, being 8 bits for address (usually it is a fixed number for a given remote controller), followed by 8 bits of code. A bit "1" is modulated with 560µs PULSE followed by 1690µs SPACE and a bit "0" is modulated with 560µs PULSE followed by 560µs SPACE.
At receiver, a simple low-pass filter can be used to convert the received signal in a sequence of PULSE/SPACE events, filtering out the carrier frequency. Due to that, the receiver doesn't care about the carrier's actual frequency parameters: all it has to do is to measure the amount of time it receives PULSE/SPACE events. So, a simple IR receiver hardware will just provide a sequence of timings for those events to the Kernel. The drivers for hardware with such kind of receivers are identified by RC_DRIVER_IR_RAW, as defined by rc_driver_type2. Other hardware come with a microcontroller that decode the PULSE/SPACE sequence and return scan codes to the Kernel. Such kind of receivers are identified by RC_DRIVER_SCANCODE.
[2] The RC core also supports devices that have just IR emitters, without any receivers. Right now, all such devices work only in raw TX mode. Such kind of hardware is identified as RC_DRIVER_IR_RAW_TX.
When the RC core receives events produced by RC_DRIVER_IR_RAW IR receivers, it needs to decode the IR protocol, in order to obtain the corresponding scan code. The protocols supported by the RC core are defined at enum rc_proto.
When the RC code receives a scan code (either directly, by a driver of the type RC_DRIVER_SCANCODE, or via its IR decoders), it needs to convert into a Linux input event code. This is done via a mapping table.
The Kernel has support for mapping tables available on most media devices. It also supports loading a table in runtime, via some sysfs nodes. See the RC userspace API for more details.
Remote controller data structures and functions #
enum rc_driver_type #
type of the RC driver.
Constants
RC_DRIVER_SCANCODE: Driver or hardware generates a scancode.RC_DRIVER_IR_RAW: Driver or hardware generates pulse/space sequences. It needs a Infra-Red pulse/space decoderRC_DRIVER_IR_RAW_TX: Device transmitter only, driver requires pulse/space data sequence.
struct rc_scancode_filter #
Filter scan codes.
Definition
;
Members
data: Scancode data to match.mask: Mask of bits of scancode to compare.
enum rc_filter_type #
Filter type constants.
Constants
RC_FILTER_NORMAL: Filter for normal operation.RC_FILTER_WAKEUP: Filter for waking from suspend.RC_FILTER_MAX: Number of filter types.
struct lirc_fh #
represents an open lirc file
Definition
;
Members
list: list of open file handlesrc: rcdev for this lirc chardevrawir: queue for incoming raw IRscancodes: queue for incoming decoded scancodeswait_poll: poll struct for lirc devicecarrier_low: when setting the carrier range, first the low end must be set with an ioctl and then the high end with another ioctlsend_mode: lirc mode for sending, either LIRC_MODE_SCANCODE or LIRC_MODE_PULSErec_mode: lirc mode for receiving, either LIRC_MODE_SCANCODE or LIRC_MODE_MODE2
struct rc_dev #
represents a remote control device
Definition
;
Members
dev: driver model's view of this devicemanaged_alloc: devm_rc_allocate_device was used to create rc_devregistered: set to true byrc_register_device(), false by rc_unregister_deviceidle: used to keep track of RX stateencode_wakeup: wakeup filtering uses IR encode API, therefore the allowed wakeup protocols is the set of all raw encodersminor: unique minor remote control device numbersysfs_groups: sysfs attribute groupsdevice_name: name of the rc child deviceinput_phys: physical path to the input child deviceinput_id: id of the input child device (struct input_id)driver_name: name of the hardware driver which registered this devicemap_name: name of the default keymaprc_map: current scan/key tablelock: used to ensure we've filled in all protocol details before anyone can call show_protocols or store_protocolsraw: additional data for raw pulse/space devicesinput_dev: the input child device used to communicate events to userspacedriver_type: specifies if protocol decoding is done in hardware or softwareusers: number of current users of the deviceallowed_protocols: bitmask with the supported RC_PROTO_BIT_* protocolsenabled_protocols: bitmask with the enabled RC_PROTO_BIT_* protocolsallowed_wakeup_protocols: bitmask with the supported RC_PROTO_BIT_* wakeup protocolswakeup_protocol: the enabled RC_PROTO_* wakeup protocol or RC_PROTO_UNKNOWN if disabled.scancode_filter: scancode filterscancode_wakeup_filter: scancode wakeup filtersscancode_mask: some hardware decoders are not capable of providing the full scancode to the application. As this is a hardware limit, we can't do anything with it. Yet, as the same keycode table can be used with other devices, a mask is provided to allow its usage. Drivers should generally leave this field in blankpriv: driver-specific datakeylock: protects the remaining members of the structkeypressed: whether a key is currently pressedlast_toggle: toggle value of last commandlast_keycode: keycode of last keypresslast_protocol: protocol of last keypresslast_scancode: scancode of last keypresskeyup_jiffies: time (in jiffies) when the current keypress should be releasedtimer_keyup: timer for releasing a keypresstimer_repeat: timer for autorepeat events. This is needed for CEC, which has non-standard repeats.timeout: optional time after which device stops sending datamin_timeout: minimum timeout supported by devicemax_timeout: maximum timeout supported by devicerx_resolution: resolution (in us) of input samplerlirc_dev: lirc devicelirc_cdev: lirc char cdevgap_start: start time for gap after timeout if non-zerolirc_fh_lock: protects lirc_fh listlirc_fh: list of open fileschange_protocol: allow changing the protocol used on hardware decodersopen: callback to allow drivers to enable polling/irq when IR input device is opened.close: callback to allow drivers to disable polling/irq when IR input device is opened.s_tx_mask: set transmitter mask (for devices with multiple tx outputs)s_tx_carrier: set transmit carrier frequencys_tx_duty_cycle: set transmit duty cycle (0% - 100%)s_rx_carrier_range: inform driver about carrier it is expected to handletx_ir: transmit IRs_idle: enable/disable hardware idle mode, upon which, device doesn't interrupt host until it sees IR pulsess_wideband_receiver: enable wide band receiver used for learnings_carrier_report: enable carrier reportss_filter: set the scancode filters_wakeup_filter: set the wakeup scancode filter. If the mask is zero then wakeup should be disabled. wakeup_protocol will be set to a valid protocol if mask is nonzero.s_timeout: set hardware timeout in us
rc_allocate_device() #
struct rc_dev * Allocates a RC device
Parameters
enum rc_driver_type: specifies the type of the RC output to be allocated returns a pointer to struct rc_dev.
devm_rc_allocate_device() #
struct rc_dev * Managed RC device allocation
Parameters
struct device *dev: pointer to struct deviceenum rc_driver_type: specifies the type of the RC output to be allocated returns a pointer to struct rc_dev.
rc_free_device() #
void Frees a RC device
Parameters
struct rc_dev *dev: pointer to struct rc_dev.
rc_register_device() #
int Registers a RC device
Parameters
struct rc_dev *dev: pointer to struct rc_dev.
devm_rc_register_device() #
int Manageded registering of a RC device
Parameters
struct device *parent: pointer to struct device.struct rc_dev *dev: pointer to struct rc_dev.
rc_unregister_device() #
void Unregisters a RC device
Parameters
struct rc_dev *dev: pointer to struct rc_dev.
struct rc_map_table #
represents a scancode/keycode pair
Definition
;
Members
scancode: scan code (u64)keycode: Linux input keycode
struct rc_map #
represents a keycode map table
Definition
;
Members
scan: pointer to structrc_map_tablesize: Max number of entrieslen: Number of entries that are in usealloc: size of *scan, in bytesrc_proto: type of the remote controller protocol, as defined at enumrc_protoname: name of the key map tablelock: lock to protect access to this structure
struct rc_map_list #
list of the registered rc_map maps
Definition
;
Members
list: pointer to structlist_headmap: pointer to structrc_map
rc_map_register() #
int Registers a Remote Controller scancode map
Parameters
struct rc_map_list *map: pointer to struct rc_map_list
rc_map_unregister() #
void Unregisters a Remote Controller scancode map
Parameters
struct rc_map_list *map: pointer to struct rc_map_list
rc_map_get() #
struct rc_map * gets an RC map from its name
Parameters
const char *name: name of the RC scancode map
Pixel data transmitter and receiver drivers
Peios Kernel / Hardware and drivers / Driver development / Media devices
V4L2 supports various devices that transmit and receive pixel data. Examples of these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a CSI-2 receiver in an SoC.
Bus types #
The following buses are the most common. This section discusses these two only.
MIPI CSI-2 #
CSI-2 is a data bus intended for transferring images from cameras to the host SoC. It is defined by the MIPI alliance.
Parallel and BT.656 #
The parallel and BT.656 buses transport one bit of data on each clock cycle per data line. The parallel bus uses synchronisation and other additional signals whereas BT.656 embeds synchronisation.
Transmitter drivers #
Transmitter drivers generally need to provide the receiver drivers with the configuration of the transmitter. What is required depends on the type of the bus. These are common for both buses.
Media bus pixel code #
See v4l2-mbus-pixelcode.
Link frequency #
The V4L2_CID_LINK_FREQ control is used to tell the receiver the frequency of the bus (i.e. it is not the same as the symbol rate).
Drivers that do not have user-configurable link frequency should report it through the .get_mbus_config() subdev pad operation, in the link_freq field of struct v4l2_mbus_config, instead of through controls.
Receiver drivers should use v4l2_get_link_freq() helper to obtain the link frequency from the transmitter sub-device.
.enable_streams() and .disable_streams() callbacks #
The struct v4l2_subdev_pad_ops->enable_streams() and struct v4l2_subdev_pad_ops->disable_streams() callbacks are used by the receiver driver to control the transmitter driver's streaming state. These callbacks may not be called directly, but by using v4l2_subdev_enable_streams() and v4l2_subdev_disable_streams().
Stopping the transmitter #
A transmitter stops sending the stream of images as a result of calling the .disable_streams() callback. Some transmitters may stop the stream at a frame boundary whereas others stop immediately, effectively leaving the current frame unfinished. The receiver driver should not make assumptions either way, but function properly in both cases.
CSI-2 transmitter drivers #
Pixel rate #
The pixel rate on the bus is calculated as follows:
pixel_rate = link_freq * 2 * nr_of_lanes * 16 / k / bits_per_sample
where
|
variable or constant |
description |
|---|---|
|
link_freq |
The value of the |
|
nr_of_lanes |
Number of data lanes used on the CSI-2 link. |
|
2 |
Data is transferred on both rising and falling edge of the signal. |
|
bits_per_sample |
Number of bits per sample. |
|
k |
16 for D-PHY and 7 for C-PHY. |
Information on whether D-PHY or C-PHY is used, and the value of nr_of_lanes, can be obtained from the OF endpoint configuration.
LP-11 and LP-111 states #
As part of transitioning to high speed mode, a CSI-2 transmitter typically briefly sets the bus to LP-11 or LP-111 state, depending on the PHY. This period may be as short as 100 µs, during which the receiver observes this state and proceeds its own part of high speed mode transition.
Most receivers are capable of autonomously handling this once the software has configured them to do so, but there are receivers which require software involvement in observing LP-11 or LP-111 state. 100 µs is a brief period to hit in software, especially when there is no interrupt telling something is happening.
One way to address this is to configure the transmitter side explicitly to LP-11 or LP-111 state, which requires support from the transmitter hardware. This is not universally available. Many devices return to this state once streaming is stopped while the state after power-on is LP-00 or LP-000.
The .pre_streamon() callback may be used to prepare a transmitter for transitioning to streaming state, but not yet start streaming. Similarly, the .post_streamoff() callback is used to undo what was done by the .pre_streamon() callback. The caller of .pre_streamon() is thus required to call .post_streamoff() for each successful call of .pre_streamon().
In the context of CSI-2, the .pre_streamon() callback is used to transition the transmitter to the LP-11 or LP-111 state. This also requires powering on the device, so this should be only done when it is needed.
Receiver drivers that do not need explicit LP-11 or LP-111 state setup are waived from calling the two callbacks.
V4L2 async kAPI
Peios Kernel / Hardware and drivers / Driver development / Media devices
enum v4l2_async_match_type #
type of asynchronous subdevice logic to be used in order to identify a match
Constants
V4L2_ASYNC_MATCH_TYPE_I2C: Match will check for I2C adapter ID and addressV4L2_ASYNC_MATCH_TYPE_FWNODE: Match will use firmware node
Description
This enum is used by the asynchronous connection logic to define the algorithm that will be used to match an asynchronous device.
struct v4l2_async_match_desc #
async connection match information
Definition
;
Members
type: type of match that will be used{unnamed_union}: anonymousfwnode: pointer tostruct fwnode_handleto be matched. Used if match_type isV4L2_ASYNC_MATCH_TYPE_FWNODE.i2c: embedded struct with I2C parameters to be matched. Both match.i2c.adapter_id and match.i2c.address should be matched. Used if match_type isV4L2_ASYNC_MATCH_TYPE_I2C.i2c.adapter_id: I2C adapter ID to be matched. Used if match_type isV4L2_ASYNC_MATCH_TYPE_I2C.i2c.address: I2C address to be matched. Used if match_type isV4L2_ASYNC_MATCH_TYPE_I2C.
struct v4l2_async_connection #
sub-device connection descriptor, as known to a bridge
Definition
;
Members
match: struct of match type and per-bus type matching data setsnotifier: the async notifier the connection is related toasc_entry: used to add struct v4l2_async_connection objects to the notifier waiting_list or done_listasc_subdev_entry: entry in struct v4l2_async_subdev.asc_list listsd: the related sub-device
Description
When this struct is used as a member in a driver specific struct, the driver
specific struct shall contain the struct v4l2_async_connection as its first
member.
struct v4l2_async_notifier_operations #
Asynchronous V4L2 notifier operations
Definition
;
Members
bound: a sub-device has been bound by the given connectioncomplete: All connections have been bound successfully. The complete callback is only executed for the root notifier.unbind: a subdevice is leavingdestroy: the asc is about to be freed
struct v4l2_async_notifier #
v4l2_device notifier data
Definition
;
Members
ops: notifier operationsv4l2_dev: v4l2_device of the root notifier, NULL otherwisesd: sub-device that registered the notifier, NULL otherwiseparent: parent notifierwaiting_list: list of struct v4l2_async_connection, waiting for their driversdone_list: list of struct v4l2_subdev, already probednotifier_entry: member in a global list of notifiers
struct v4l2_async_subdev_endpoint #
Entry in sub-device's fwnode list
Definition
;
Members
async_subdev_endpoint_entry: An entry in async_subdev_endpoint_list ofstruct v4l2_subdevendpoint: Endpoint fwnode agains which to match the sub-device
v4l2_async_debug_init() #
void Initialize debugging tools.
Parameters
struct dentry *debugfs_dir: pointer to the parent debugfsstruct dentry
v4l2_async_nf_init() #
void Initialize a notifier.
Parameters
struct v4l2_async_notifier *notifier: pointer tostruct v4l2_async_notifierstruct v4l2_device *v4l2_dev: pointer tostruct v4l2_device
Description
This function initializes the notifier asc_entry. It must be called
before adding a subdevice to a notifier, using one of:
v4l2_async_nf_add_fwnode_remote(),
v4l2_async_nf_add_fwnode() or
v4l2_async_nf_add_i2c().
v4l2_async_subdev_nf_init() #
void Initialize a sub-device notifier.
Parameters
struct v4l2_async_notifier *notifier: pointer tostruct v4l2_async_notifierstruct v4l2_subdev *sd: pointer tostruct v4l2_subdev
Description
This function initializes the notifier asc_list. It must be called
before adding a subdevice to a notifier, using one of:
v4l2_async_nf_add_fwnode_remote(), v4l2_async_nf_add_fwnode() or
v4l2_async_nf_add_i2c().
v4l2_async_nf_add_fwnode() #
Allocate and add a fwnode async subdev to the notifier's master asc_list.
Parameters
notifier: pointer tostruct v4l2_async_notifierfwnode: fwnode handle of the sub-device to be matched, pointer tostruct fwnode_handletype: Type of the driver's async sub-device or connection struct. Thestruct v4l2_async_connectionshall be the first member of the driver's async struct, i.e. both begin at the same memory address.
Description
Allocate a fwnode-matched asc of size asc_struct_size, and add it to the notifiers asc_list. The function also gets a reference of the fwnode which is released later at notifier cleanup time.
v4l2_async_nf_add_fwnode_remote() #
Allocate and add a fwnode remote async subdev to the notifier's master asc_list.
Parameters
notifier: pointer tostruct v4l2_async_notifierep: local endpoint pointing to the remote connection to be matched, pointer tostruct fwnode_handletype: Type of the driver's async connection struct. Thestruct v4l2_async_connectionshall be the first member of the driver's async connection struct, i.e. both begin at the same memory address.
Description
Gets the remote endpoint of a given local endpoint, set it up for fwnode matching and adds the async connection to the notifier's asc_list. The function also gets a reference of the fwnode which is released later at notifier cleanup time.
This is just like v4l2_async_nf_add_fwnode(), but with the
exception that the fwnode refers to a local endpoint, not the remote one.
v4l2_async_nf_add_i2c() #
Allocate and add an i2c async subdev to the notifier's master asc_list.
Parameters
notifier: pointer tostruct v4l2_async_notifieradapter: I2C adapter ID to be matchedaddress: I2C address of connection to be matchedtype: Type of the driver's async connection struct. Thestruct v4l2_async_connectionshall be the first member of the driver's async connection struct, i.e. both begin at the same memory address.
Description
Same as v4l2_async_nf_add_fwnode() but for I2C matched
connections.
v4l2_async_subdev_endpoint_add() #
int Add an endpoint fwnode to async sub-device matching list
Parameters
struct v4l2_subdev *sd: the sub-devicestruct fwnode_handle *fwnode: the endpoint fwnode to match
Description
Add a fwnode to the async sub-device's matching list. This allows registering multiple async sub-devices from a single device.
Note that calling v4l2_subdev_cleanup() as part of the sub-device's cleanup
if endpoints have been added to the sub-device's fwnode matching list.
Returns an error on failure, 0 on success.
v4l2_async_connection_unique() #
struct v4l2_async_connection * return a unique struct v4l2_async_connection for a sub-device
Parameters
struct v4l2_subdev *sd: the sub-device
Description
Return an async connection for a sub-device, when there is a single one only.
v4l2_async_nf_register() #
int registers a subdevice asynchronous notifier
Parameters
struct v4l2_async_notifier *notifier: pointer tostruct v4l2_async_notifier
v4l2_async_nf_unregister() #
void unregisters a subdevice asynchronous notifier
Parameters
struct v4l2_async_notifier *notifier: pointer tostruct v4l2_async_notifier
v4l2_async_nf_cleanup() #
void clean up notifier resources
Parameters
struct v4l2_async_notifier *notifier: the notifier the resources of which are to be cleaned up
Description
Release memory resources related to a notifier, including the async
connections allocated for the purposes of the notifier but not the notifier
itself. The user is responsible for calling this function to clean up the
notifier after calling v4l2_async_nf_add_fwnode_remote(),
v4l2_async_nf_add_fwnode() or v4l2_async_nf_add_i2c().
There is no harm from calling v4l2_async_nf_cleanup() in other
cases as long as its memory has been zeroed after it has been
allocated.
v4l2_async_register_subdev() #
registers a sub-device to the asynchronous subdevice framework
Parameters
sd: pointer tostruct v4l2_subdev
v4l2_async_register_subdev_sensor() #
int registers a sensor sub-device to the asynchronous sub-device framework and parse set up common sensor related devices
Parameters
struct v4l2_subdev *sd: pointer to structv4l2_subdev
Description
This function is just like v4l2_async_register_subdev() with the exception
that calling it will also parse firmware interfaces for remote references
using v4l2_async_nf_parse_fwnode_sensor() and registers the
async sub-devices. The sub-device is similarly unregistered by calling
v4l2_async_unregister_subdev().
While registered, the subdev module is marked as in-use.
An error is returned if the module is no longer loaded on any attempts to register it.
v4l2_async_unregister_subdev() #
void unregisters a sub-device to the asynchronous subdevice framework
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
V4L2 CCI kAPI
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct cci_reg_sequence #
An individual write from a sequence of CCI writes
Definition
;
Members
reg: Register address, use CCI_REG#() macros to encode reg widthval: Register value
Description
Register/value pairs for sequences of writes.
cci_read() #
int Read a value from a single CCI register
Parameters
struct regmap *map: Register map to read fromu32 reg: Register address to read, use CCI_REG#() macros to encode reg widthu64 *val: Pointer to store read valueint *err: Optional pointer to store errors, if a previous error is set then the read will be skipped
Return
0 on success or a negative error code on failure.
cci_write() #
int Write a value to a single CCI register
Parameters
struct regmap *map: Register map to write tou32 reg: Register address to write, use CCI_REG#() macros to encode reg widthu64 val: Value to be writtenint *err: Optional pointer to store errors, if a previous error is set then the write will be skipped
Return
0 on success or a negative error code on failure.
cci_update_bits() #
int Perform a read/modify/write cycle on a single CCI register
Parameters
struct regmap *map: Register map to updateu32 reg: Register address to update, use CCI_REG#() macros to encode reg widthu64 mask: Bitmask to changeu64 val: New value for bitmaskint *err: Optional pointer to store errors, if a previous error is set then the update will be skipped
Description
Note this uses read-modify-write to update the bits, atomicity with regards to other cci_*() register access functions is NOT guaranteed.
Return
0 on success or a negative error code on failure.
cci_multi_reg_write() #
int Write multiple registers to the device
Parameters
struct regmap *map: Register map to write toconst struct cci_reg_sequence *regs: Array of structures containing register-address, -value pairs to be written, register-addresses use CCI_REG#() macros to encode reg widthunsigned int num_regs: Number of registers to writeint *err: Optional pointer to store errors, if a previous error is set then the write will be skipped
Description
Write multiple registers to the device where the set of register, value pairs are supplied in any order, possibly not all in a single range.
Use of the CCI_REG#() macros to encode reg width is mandatory.
For raw lists of register-address, -value pairs with only 8 bit
wide writes regmap_multi_reg_write() can be used instead.
Return
0 on success or a negative error code on failure.
devm_cci_regmap_init_i2c() #
struct regmap * Create regmap to use with cci_*() register access functions
Parameters
struct i2c_client *client: i2c_client to create the regmap forint reg_addr_bits: register address width to use (8 or 16)
Description
Note the memory for the created regmap is devm() managed, tied to the client.
Return
0 on success or a negative error code on failure.
V4L2 common functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
v4l2_ctrl_query_fill() #
int Fill in a struct v4l2_queryctrl
Parameters
struct v4l2_queryctrl *qctrl: pointer to thestruct v4l2_queryctrlto be filleds32 min: minimum value for the controls32 max: maximum value for the controls32 step: control steps32 def: default value for the control
Description
Fills the struct v4l2_queryctrl fields for the query control.
Returns -EINVAL if the control is not known by the V4L2 core, 0 on success.
enum v4l2_i2c_tuner_type #
specifies the range of tuner address that should be used when seeking for I2C devices.
Constants
ADDRS_RADIO: Radio tuner addresses. Represent the following I2C addresses: 0x10 (if compiled with tea5761 support) and 0x60.ADDRS_DEMOD: Demod tuner addresses. Represent the following I2C addresses: 0x42, 0x43, 0x4a and 0x4b.ADDRS_TV: TV tuner addresses. Represent the following I2C addresses: 0x42, 0x43, 0x4a, 0x4b, 0x60, 0x61, 0x62, 0x63 and 0x64.ADDRS_TV_WITH_DEMOD: TV tuner addresses if demod is present, this excludes addresses used by the demodulator from the list of candidates. Represent the following I2C addresses: 0x60, 0x61, 0x62, 0x63 and 0x64.
NOTE
All I2C addresses above use the 7-bit notation.
v4l2_i2c_new_subdev() #
struct v4l2_subdev * Load an i2c module and return an initialized struct v4l2_subdev.
Parameters
struct v4l2_device *v4l2_dev: pointer tostruct v4l2_devicestruct i2c_adapter *adapter: pointer to struct i2c_adapterconst char *client_type: name of the chip that's on the adapter.u8 addr: I2C address. If zero, it will use probe_addrsconst unsigned short *probe_addrs: array with a list of address. The last entry at such array should beI2C_CLIENT_END.
Description
returns a struct v4l2_subdev pointer.
v4l2_i2c_new_subdev_board() #
struct v4l2_subdev * Load an i2c module and return an initialized struct v4l2_subdev.
Parameters
struct v4l2_device *v4l2_dev: pointer tostruct v4l2_devicestruct i2c_adapter *adapter: pointer to struct i2c_adapterstruct i2c_board_info *info: pointer to struct i2c_board_info used to replace the irq, platform_data and addr arguments.const unsigned short *probe_addrs: array with a list of address. The last entry at such array should beI2C_CLIENT_END.
Description
returns a struct v4l2_subdev pointer.
v4l2_i2c_subdev_set_name() #
void Set name for an I²C sub-device
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct i2c_client *client: pointer to struct i2c_clientconst char *devname: the name of the device; if NULL, the I²C device drivers's name will be usedconst char *postfix: sub-device specific string to put right after the I²C device name; may be NULL
v4l2_i2c_subdev_init() #
void Initializes a struct v4l2_subdev with data from an i2c_client struct.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct i2c_client *client: pointer to struct i2c_clientconst struct v4l2_subdev_ops *ops: pointer tostruct v4l2_subdev_ops
v4l2_i2c_subdev_addr() #
unsigned short returns i2c client address of struct v4l2_subdev.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
Description
Returns the address of an I2C sub-device
v4l2_i2c_tuner_addrs() #
const unsigned short * Return a list of I2C tuner addresses to probe.
Parameters
enum v4l2_i2c_tuner_type type: type of the tuner to seek, as defined byenum v4l2_i2c_tuner_type.
NOTE
Use only if the tuner addresses are unknown.
v4l2_i2c_subdev_unregister() #
void Unregister a v4l2_subdev
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
v4l2_spi_new_subdev() #
struct v4l2_subdev * Load an spi module and return an initialized struct v4l2_subdev.
Parameters
struct v4l2_device *v4l2_dev: pointer tostruct v4l2_device.struct spi_controller *ctlr: pointer to struct spi_controller.struct spi_board_info *info: pointer to struct spi_board_info.
Description
returns a struct v4l2_subdev pointer.
v4l2_spi_subdev_init() #
void Initialize a v4l2_subdev with data from an spi_device struct.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct spi_device *spi: pointer to struct spi_device.const struct v4l2_subdev_ops *ops: pointer tostruct v4l2_subdev_ops
v4l2_spi_subdev_unregister() #
void Unregister a v4l2_subdev
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
v4l_bound_align_image() #
void adjust video dimensions according to a given constraints.
Parameters
unsigned int *width: pointer to width that will be adjusted if needed.unsigned int wmin: minimum width.unsigned int wmax: maximum width.unsigned int walign: least significant bit on width.unsigned int *height: pointer to height that will be adjusted if needed.unsigned int hmin: minimum height.unsigned int hmax: maximum height.unsigned int halign: least significant bit on height.unsigned int salign: least significant bit for the image size (e. g. width * height).
Description
Clip an image to have width between wmin and wmax, and height between hmin and hmax, inclusive.
Additionally, the width will be a multiple of 2^{walign}, the height will be a multiple of 2^{halign}, and the overall size width * height will be a multiple of 2^{salign}.
v4l2_find_nearest_size_conditional() #
Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct, with conditionally exlusion of certain modes
Parameters
array: a driver specific array of image sizesarray_size: the length of the driver specific array of image sizeswidth_field: the name of the width field in the driver specific structheight_field: the name of the height field in the driver specific structwidth: desired widthheight: desired heightfunc: ignores mode if returns falsecontext: context for the function
Description
Finds the closest resolution to minimize the width and height differences between what requested and the supported resolutions. The size of the width and height fields in the driver specific must equal to that of u32, i.e. four bytes. func is called for each mode considered, a mode is ignored if func returns false for it.
Returns the best match or NULL if the length of the array is zero.
v4l2_find_nearest_size() #
Find the nearest size among a discrete set of resolutions contained in an array of a driver specific struct
Parameters
array: a driver specific array of image sizesarray_size: the length of the driver specific array of image sizeswidth_field: the name of the width field in the driver specific structheight_field: the name of the height field in the driver specific structwidth: desired widthheight: desired height
Description
Finds the closest resolution to minimize the width and height differences between what requested and the supported resolutions. The size of the width and height fields in the driver specific must equal to that of u32, i.e. four bytes.
Returns the best match or NULL if the length of the array is zero.
v4l2_g_parm_cap() #
int helper routine for vidioc_g_parm to fill this in by calling the get_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.
Parameters
struct video_device *vdev: the struct video_device pointer. Used to determine the device caps.struct v4l2_subdev *sd: the sub-device pointer.struct v4l2_streamparm *a: the VIDIOC_G_PARM argument.
v4l2_s_parm_cap() #
int helper routine for vidioc_s_parm to fill this in by calling the set_frame_interval op of the given subdev. It only works for V4L2_BUF_TYPE_VIDEO_CAPTURE(_MPLANE), hence the _cap in the function name.
Parameters
struct video_device *vdev: the struct video_device pointer. Used to determine the device caps.struct v4l2_subdev *sd: the sub-device pointer.struct v4l2_streamparm *a: the VIDIOC_S_PARM argument.
enum v4l2_pixel_encoding #
specifies the pixel encoding value
Constants
V4L2_PIXEL_ENC_UNKNOWN: Pixel encoding is unknown/un-initializedV4L2_PIXEL_ENC_YUV: Pixel encoding is YUVV4L2_PIXEL_ENC_RGB: Pixel encoding is RGBV4L2_PIXEL_ENC_BAYER: Pixel encoding is Bayer
struct v4l2_format_info #
information about a V4L2 format
Definition
;
Members
format: 4CC format identifier (V4L2_PIX_FMT_*)pixel_enc: Pixel encoding (see enum v4l2_pixel_encoding above)mem_planes: Number of memory planes, which includes the alpha plane (1 to 4).comp_planes: Number of component planes, which includes the alpha plane (1 to 4).bpp: Array of per-plane bytes per pixelbpp_div: Array of per-plane bytes per pixel divisors to support fractional pixel sizes.hdiv: Horizontal chroma subsampling factorvdiv: Vertical chroma subsampling factorblock_w: Per-plane macroblock pixel width (optional)block_h: Per-plane macroblock pixel height (optional)
v4l2_get_link_freq() #
s64 Get link rate from transmitter
Parameters
const struct media_pad *pad: The transmitter's media padunsigned int mul: The multiplier between pixel rate and link frequency. Bits per pixel on D-PHY, samples per clock on parallel. 0 otherwise.unsigned int div: The divisor between pixel rate and link frequency. Number of data lanes times two on D-PHY, 1 on parallel. 0 otherwise.
Description
This function obtains and returns the link frequency from the transmitter sub-device's pad. The link frequency is retrieved using the get_mbus_config sub-device pad operation. If this fails, the function falls back to obtaining the frequency either directly from the V4L2_CID_LINK_FREQ control if implemented by the transmitter, or by calculating it from the pixel rate obtained from the V4L2_CID_PIXEL_RATE control.
Return
-
0: Link frequency
-ENOENT: Link frequency or pixel rate control not found-EINVAL: Invalid link frequency value
v4l2_get_active_data_lanes() #
int Get number of active data lanes from driver
Parameters
const struct media_pad *pad: The transmitter's media pad.unsigned int max_data_lanes: The maximum number of active data lanes supported by the MIPI CSI link in hardware.
Description
This function is intended for obtaining the number of data lanes that are actively being used by the driver for a MIPI CSI-2 device on a given media pad. This information is derived from a mbus_config fetched from a device driver using the get_mbus_config v4l2_subdev pad op.
Return
-
0: Number of active data lanes
-EINVAL: Number of active data lanes is invalid, as it exceeds the maximum supported data lanes.
v4l2_link_freq_to_bitmap() #
int Figure out platform-supported link frequencies
Parameters
struct device *dev: The struct deviceconst u64 *fw_link_freqs: Array of link frequencies from firmwareunsigned int num_of_fw_link_freqs: Number of entries in fw_link_freqsconst s64 *driver_link_freqs: Array of link frequencies supported by the driverunsigned int num_of_driver_link_freqs: Number of entries in driver_link_freqsunsigned long *bitmap: Bitmap of driver-supported link frequencies found in fw_link_freqs
Description
This function checks which driver-supported link frequencies are enabled in system firmware and sets the corresponding bits in bitmap (after first zeroing it).
Return
0: Success-ENOENT: No match found between driver-supported link frequencies and those available in firmware.-ENODATA: No link frequencies were specified in firmware.
devm_v4l2_sensor_clk_get() #
struct clk * lookup and obtain a reference to a clock producer for a camera sensor
Parameters
struct device *dev: device for v4l2 sensor clock "consumer"const char *id: clock consumer ID
Description
This function behaves the same way as devm_clk_get() except where there
is no clock producer like in ACPI-based platforms.
For ACPI-based platforms, the function will read the "clock-frequency" ACPI _DSD property and register a fixed-clock with the frequency indicated in the property.
This function also handles the special ACPI-based system case where:
- The clock-frequency _DSD property is present.
- A reference to the clock producer is present, where the clock is provided by a camera sensor PMIC driver (e.g. int3472/tps68470.c)
In this case try to set the clock-frequency value to the provided clock.
As the name indicates, this function may only be used on camera sensor devices. This is because generally only camera sensors do need a clock to query the frequency from, due to the requirement to configure the PLL for a given CSI-2 interface frequency where the sensor's external clock frequency is a factor. Additionally, the clock frequency tends to be available on ACPI firmware based systems for camera sensors specifically (if e.g. DisCo for Imaging compliant).
Returns a pointer to a struct clk on success or an error pointer on failure.
devm_v4l2_sensor_clk_get_legacy() #
struct clk * lookup and obtain a reference to a clock producer for a camera sensor.
Parameters
struct device *dev: device for v4l2 sensor clock "consumer"const char *id: clock consumer IDbool fixed_rate: interpret the clk_rate as a fixed rate or default rateunsigned long clk_rate: the clock rate
Description
This function behaves the same way as devm_v4l2_sensor_clk_get() except that
it extends the behaviour on ACPI platforms to all platforms.
The function also provides the ability to set the clock rate to a fixed frequency by setting fixed_rate to true and specifying the fixed frequency in clk_rate, or to use a default clock rate when the "clock-frequency" property is absent by setting fixed_rate to false and specifying the default frequency in clk_rate. Setting fixed_rate to true and clk_rate to 0 is an error.
This function is meant to support legacy behaviour in existing drivers only. It must not be used in any new driver.
Returns a pointer to a struct clk on success or an error pointer on failure.
struct v4l2_ioctl_ops #
describe operations for each V4L2 ioctl
Definition
;
Members
vidioc_querycap: pointer to the function that implements VIDIOC_QUERYCAP ioctlvidioc_enum_fmt_vid_cap: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for video capture in single and multi plane modevidioc_enum_fmt_vid_overlay: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for video overlayvidioc_enum_fmt_vid_out: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for video output in single and multi plane modevidioc_enum_fmt_sdr_cap: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for Software Defined Radio capturevidioc_enum_fmt_sdr_out: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for Software Defined Radio outputvidioc_enum_fmt_meta_cap: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for metadata capturevidioc_enum_fmt_meta_out: pointer to the function that implements VIDIOC_ENUM_FMT ioctl logic for metadata outputvidioc_g_fmt_vid_cap: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video capture in single plane modevidioc_g_fmt_vid_overlay: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video overlayvidioc_g_fmt_vid_out: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video out in single plane modevidioc_g_fmt_vid_out_overlay: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video overlay outputvidioc_g_fmt_vbi_cap: pointer to the function that implements VIDIOC_G_FMT ioctl logic for raw VBI capturevidioc_g_fmt_vbi_out: pointer to the function that implements VIDIOC_G_FMT ioctl logic for raw VBI outputvidioc_g_fmt_sliced_vbi_cap: pointer to the function that implements VIDIOC_G_FMT ioctl logic for sliced VBI capturevidioc_g_fmt_sliced_vbi_out: pointer to the function that implements VIDIOC_G_FMT ioctl logic for sliced VBI outputvidioc_g_fmt_vid_cap_mplane: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video capture in multiple plane modevidioc_g_fmt_vid_out_mplane: pointer to the function that implements VIDIOC_G_FMT ioctl logic for video out in multiplane plane modevidioc_g_fmt_sdr_cap: pointer to the function that implements VIDIOC_G_FMT ioctl logic for Software Defined Radio capturevidioc_g_fmt_sdr_out: pointer to the function that implements VIDIOC_G_FMT ioctl logic for Software Defined Radio outputvidioc_g_fmt_meta_cap: pointer to the function that implements VIDIOC_G_FMT ioctl logic for metadata capturevidioc_g_fmt_meta_out: pointer to the function that implements VIDIOC_G_FMT ioctl logic for metadata outputvidioc_s_fmt_vid_cap: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video capture in single plane modevidioc_s_fmt_vid_overlay: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video overlayvidioc_s_fmt_vid_out: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video out in single plane modevidioc_s_fmt_vid_out_overlay: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video overlay outputvidioc_s_fmt_vbi_cap: pointer to the function that implements VIDIOC_S_FMT ioctl logic for raw VBI capturevidioc_s_fmt_vbi_out: pointer to the function that implements VIDIOC_S_FMT ioctl logic for raw VBI outputvidioc_s_fmt_sliced_vbi_cap: pointer to the function that implements VIDIOC_S_FMT ioctl logic for sliced VBI capturevidioc_s_fmt_sliced_vbi_out: pointer to the function that implements VIDIOC_S_FMT ioctl logic for sliced VBI outputvidioc_s_fmt_vid_cap_mplane: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video capture in multiple plane modevidioc_s_fmt_vid_out_mplane: pointer to the function that implements VIDIOC_S_FMT ioctl logic for video out in multiplane plane modevidioc_s_fmt_sdr_cap: pointer to the function that implements VIDIOC_S_FMT ioctl logic for Software Defined Radio capturevidioc_s_fmt_sdr_out: pointer to the function that implements VIDIOC_S_FMT ioctl logic for Software Defined Radio outputvidioc_s_fmt_meta_cap: pointer to the function that implements VIDIOC_S_FMT ioctl logic for metadata capturevidioc_s_fmt_meta_out: pointer to the function that implements VIDIOC_S_FMT ioctl logic for metadata outputvidioc_try_fmt_vid_cap: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video capture in single plane modevidioc_try_fmt_vid_overlay: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video overlayvidioc_try_fmt_vid_out: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video out in single plane modevidioc_try_fmt_vid_out_overlay: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video overlay outputvidioc_try_fmt_vbi_cap: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for raw VBI capturevidioc_try_fmt_vbi_out: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for raw VBI outputvidioc_try_fmt_sliced_vbi_cap: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for sliced VBI capturevidioc_try_fmt_sliced_vbi_out: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for sliced VBI outputvidioc_try_fmt_vid_cap_mplane: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video capture in multiple plane modevidioc_try_fmt_vid_out_mplane: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for video out in multiplane plane modevidioc_try_fmt_sdr_cap: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for Software Defined Radio capturevidioc_try_fmt_sdr_out: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for Software Defined Radio outputvidioc_try_fmt_meta_cap: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for metadata capturevidioc_try_fmt_meta_out: pointer to the function that implements VIDIOC_TRY_FMT ioctl logic for metadata outputvidioc_reqbufs: pointer to the function that implements VIDIOC_REQBUFS ioctlvidioc_querybuf: pointer to the function that implements VIDIOC_QUERYBUF ioctlvidioc_qbuf: pointer to the function that implements VIDIOC_QBUF ioctlvidioc_expbuf: pointer to the function that implements VIDIOC_EXPBUF ioctlvidioc_dqbuf: pointer to the function that implements VIDIOC_DQBUF ioctlvidioc_create_bufs: pointer to the function that implements VIDIOC_CREATE_BUFS ioctlvidioc_prepare_buf: pointer to the function that implements VIDIOC_PREPARE_BUF ioctlvidioc_remove_bufs: pointer to the function that implements VIDIOC_REMOVE_BUFS ioctlvidioc_overlay: pointer to the function that implements VIDIOC_OVERLAY ioctlvidioc_g_fbuf: pointer to the function that implements VIDIOC_G_FBUF ioctlvidioc_s_fbuf: pointer to the function that implements VIDIOC_S_FBUF ioctlvidioc_streamon: pointer to the function that implements VIDIOC_STREAMON ioctlvidioc_streamoff: pointer to the function that implements VIDIOC_STREAMOFF ioctlvidioc_g_std: pointer to the function that implements VIDIOC_G_STD ioctlvidioc_s_std: pointer to the function that implements VIDIOC_S_STD ioctlvidioc_querystd: pointer to the function that implements VIDIOC_QUERYSTD ioctlvidioc_enum_input: pointer to the function that implements VIDIOC_ENUM_INPUT ioctlvidioc_g_input: pointer to the function that implements VIDIOC_G_INPUT ioctlvidioc_s_input: pointer to the function that implements VIDIOC_S_INPUT ioctlvidioc_enum_output: pointer to the function that implements VIDIOC_ENUM_OUTPUT ioctlvidioc_g_output: pointer to the function that implements VIDIOC_G_OUTPUT ioctlvidioc_s_output: pointer to the function that implements VIDIOC_S_OUTPUT ioctlvidioc_query_ext_ctrl: pointer to the function that implements VIDIOC_QUERY_EXT_CTRL ioctlvidioc_g_ext_ctrls: pointer to the function that implements VIDIOC_G_EXT_CTRLS ioctlvidioc_s_ext_ctrls: pointer to the function that implements VIDIOC_S_EXT_CTRLS ioctlvidioc_try_ext_ctrls: pointer to the function that implements VIDIOC_TRY_EXT_CTRLS ioctlvidioc_querymenu: pointer to the function that implements VIDIOC_QUERYMENU ioctlvidioc_enumaudio: pointer to the function that implements VIDIOC_ENUMAUDIO ioctlvidioc_g_audio: pointer to the function that implements VIDIOC_G_AUDIO ioctlvidioc_s_audio: pointer to the function that implements VIDIOC_S_AUDIO ioctlvidioc_enumaudout: pointer to the function that implements VIDIOC_ENUMAUDOUT ioctlvidioc_g_audout: pointer to the function that implements VIDIOC_G_AUDOUT ioctlvidioc_s_audout: pointer to the function that implements VIDIOC_S_AUDOUT ioctlvidioc_g_modulator: pointer to the function that implements VIDIOC_G_MODULATOR ioctlvidioc_s_modulator: pointer to the function that implements VIDIOC_S_MODULATOR ioctlvidioc_g_pixelaspect: pointer to the function that implements the pixelaspect part of the VIDIOC_CROPCAP ioctlvidioc_g_selection: pointer to the function that implements VIDIOC_G_SELECTION ioctlvidioc_s_selection: pointer to the function that implements VIDIOC_S_SELECTION ioctlvidioc_g_jpegcomp: pointer to the function that implements VIDIOC_G_JPEGCOMP ioctlvidioc_s_jpegcomp: pointer to the function that implements VIDIOC_S_JPEGCOMP ioctlvidioc_g_enc_index: pointer to the function that implements VIDIOC_G_ENC_INDEX ioctlvidioc_encoder_cmd: pointer to the function that implements VIDIOC_ENCODER_CMD ioctlvidioc_try_encoder_cmd: pointer to the function that implements VIDIOC_TRY_ENCODER_CMD ioctlvidioc_decoder_cmd: pointer to the function that implements VIDIOC_DECODER_CMD ioctlvidioc_try_decoder_cmd: pointer to the function that implements VIDIOC_TRY_DECODER_CMD ioctlvidioc_g_parm: pointer to the function that implements VIDIOC_G_PARM ioctlvidioc_s_parm: pointer to the function that implements VIDIOC_S_PARM ioctlvidioc_g_tuner: pointer to the function that implements VIDIOC_G_TUNER ioctlvidioc_s_tuner: pointer to the function that implements VIDIOC_S_TUNER ioctlvidioc_g_frequency: pointer to the function that implements VIDIOC_G_FREQUENCY ioctlvidioc_s_frequency: pointer to the function that implements VIDIOC_S_FREQUENCY ioctlvidioc_enum_freq_bands: pointer to the function that implements VIDIOC_ENUM_FREQ_BANDS ioctlvidioc_g_sliced_vbi_cap: pointer to the function that implements VIDIOC_G_SLICED_VBI_CAP ioctlvidioc_log_status: pointer to the function that implements VIDIOC_LOG_STATUS ioctlvidioc_s_hw_freq_seek: pointer to the function that implements VIDIOC_S_HW_FREQ_SEEK ioctlvidioc_g_register: pointer to the function that implements VIDIOC_DBG_G_REGISTER ioctlvidioc_s_register: pointer to the function that implements VIDIOC_DBG_S_REGISTER ioctlvidioc_g_chip_info: pointer to the function that implements VIDIOC_DBG_G_CHIP_INFO ioctlvidioc_enum_framesizes: pointer to the function that implements VIDIOC_ENUM_FRAMESIZES ioctlvidioc_enum_frameintervals: pointer to the function that implements VIDIOC_ENUM_FRAMEINTERVALS ioctlvidioc_s_dv_timings: pointer to the function that implements VIDIOC_S_DV_TIMINGS ioctlvidioc_g_dv_timings: pointer to the function that implements VIDIOC_G_DV_TIMINGS ioctlvidioc_query_dv_timings: pointer to the function that implements VIDIOC_QUERY_DV_TIMINGS ioctlvidioc_enum_dv_timings: pointer to the function that implements VIDIOC_ENUM_DV_TIMINGS ioctlvidioc_dv_timings_cap: pointer to the function that implements VIDIOC_DV_TIMINGS_CAP ioctlvidioc_g_edid: pointer to the function that implements VIDIOC_G_EDID ioctlvidioc_s_edid: pointer to the function that implements VIDIOC_S_EDID ioctlvidioc_subscribe_event: pointer to the function that implements VIDIOC_SUBSCRIBE_EVENT ioctlvidioc_unsubscribe_event: pointer to the function that implements VIDIOC_UNSUBSCRIBE_EVENT ioctlvidioc_default: pointed used to allow other ioctls
v4l2_norm_to_name() #
const char * Ancillary routine to analog TV standard name from its ID.
Parameters
v4l2_std_id id: analog TV standard ID.
Return
returns a string with the name of the analog TV standard. If the standard is not found or if id points to multiple standard, it returns "Unknown".
v4l2_video_std_frame_period() #
void Ancillary routine that fills a struct v4l2_fract pointer with the default framerate fraction.
Parameters
int id: analog TV standard ID.struct v4l2_fract *frameperiod: structv4l2_fractpointer to be filled
v4l2_video_std_construct() #
int Ancillary routine that fills in the fields of a v4l2_standard structure according to the id parameter.
Parameters
struct v4l2_standard *vs: structv4l2_standardpointer to be filledint id: analog TV standard ID.const char *name: name of the standard to be used
Description
v4l_video_std_enumstd() #
int Ancillary routine that fills in the fields of a v4l2_standard structure according to the id and vs->index parameters.
Parameters
struct v4l2_standard *vs: structv4l2_standardpointer to be filled.v4l2_std_id id: analog TV standard ID.
v4l_printk_ioctl() #
void Ancillary routine that prints the ioctl in a human-readable format.
Parameters
const char *prefix: prefix to be added at the ioctl prints.unsigned int cmd: ioctl name
Description
v4l2_field_names #
extern const char *v4l2_field_names;
Helper array mapping V4L2_FIELD_* to strings.
Initialization
default: v4l2_field_names
Description
Specially when printing debug messages, it is interesting to output the field order at the V4L2 buffers. This array associates all possible values of field pix format from V4L2 API into a string.
v4l2_type_names #
extern const char *v4l2_type_names;
Helper array mapping V4L2_BUF_TYPE_* to strings.
Initialization
default: v4l2_type_names
Description
When printing debug messages, it is interesting to output the V4L2 buffer type number with a name that represents its content.
v4l2_compat_ioctl32() #
long int 32 Bits compatibility layer for 64 bits processors
Parameters
struct file *file: Pointer to structfile.unsigned int cmd: Ioctl name.unsigned long arg: Ioctl argument.
v4l2_kioctl() #
typedef long
Typedef used to pass an ioctl handler.
Parameters
struct file *file: Pointer to structfile.unsigned int cmd: Ioctl name.void *arg: Ioctl argument.
video_usercopy() #
long int copies data from/to userspace memory when an ioctl is issued.
Parameters
struct file *file: Pointer to structfile.unsigned int cmd: Ioctl name.unsigned long int arg: Ioctl argument.v4l2_kioctl func: function that will handle the ioctl
Description
video_ioctl2() #
long int Handles a V4L2 ioctl.
Parameters
struct file *file: Pointer to structfile.unsigned int cmd: Ioctl name.unsigned long int arg: Ioctl argument.
Description
Method used to hancle an ioctl. Should be used to fill the
v4l2_ioctl_ops.unlocked_ioctl on all V4L2 drivers.
V4L2 Controls
Peios Kernel / Hardware and drivers / Driver development / Media devices
Introduction #
The V4L2 control API seems simple enough, but quickly becomes very hard to implement correctly in drivers. But much of the code needed to handle controls is actually not driver specific and can be moved to the V4L core framework.
After all, the only part that a driver developer is interested in is:
-
How do I add a control?
-
How do I set the control's value? (i.e. s_ctrl)
And occasionally:
-
How do I get the control's value? (i.e. g_volatile_ctrl)
-
How do I validate the user's proposed control value? (i.e. try_ctrl)
All the rest is something that can be done centrally.
The control framework was created in order to implement all the rules of the V4L2 specification with respect to controls in a central place. And to make life as easy as possible for the driver developer.
Note that the control framework relies on the presence of a struct v4l2_device for V4L2 drivers and struct v4l2_subdev for sub-device drivers.
Objects in the framework #
There are two main objects:
The v4l2_ctrl object describes the control properties and keeps track of the control's value (both the current value and the proposed new value).
v4l2_ctrl_handler is the object that keeps track of controls. It maintains a list of v4l2_ctrl objects that it owns and another list of references to controls, possibly to controls owned by other handlers.
Basic usage for V4L2 and sub-device drivers #
- Prepare the driver:
1.1) Add the handler to your driver's top-level struct:
For V4L2 drivers:
;
For sub-device drivers:
;
1.2) Initialize the handler:
;
The second argument is a hint telling the function how many controls this handler is expected to handle. It will allocate a hashtable based on this information. It is a hint only.
1.3) Hook the control handler into the driver:
For V4L2 drivers:
foo->v4l2_dev.ctrl_handler = &foo->ctrl_handler;
For sub-device drivers:
foo->sd.ctrl_handler = &foo->ctrl_handler;
1.4) Clean up the handler at the end:
;
v4l2_ctrl_handler_free() does not touch the handler's error field.
- Add controls:
You add non-menu controls by calling v4l2_ctrl_new_std():
struct v4l2_ctrl *;
Menu and integer menu controls are added by calling v4l2_ctrl_new_std_menu():
struct v4l2_ctrl *;
Menu controls with a driver specific menu are added by calling v4l2_ctrl_new_std_menu_items():
struct v4l2_ctrl *;
Standard compound controls can be added by calling v4l2_ctrl_new_std_compound():
struct v4l2_ctrl *;
Integer menu controls with a driver specific menu can be added by calling v4l2_ctrl_new_int_menu():
struct v4l2_ctrl *;
These functions are typically called right after the v4l2_ctrl_handler_init():
static const s64 exp_bias_qmenu = ;
static const char * const test_pattern = ;
;
;
;
;
;
;
...
if
return ;
The v4l2_ctrl_new_std() function returns the v4l2_ctrl pointer to the new control, but if you do not need to access the pointer outside the control ops, then there is no need to store it.
The v4l2_ctrl_new_std() function will fill in most fields based on the control ID except for the min, max, step and default values. These are passed in the last four arguments. These values are driver specific while control attributes like type, name, flags are all global. The control's current value will be set to the default value.
The v4l2_ctrl_new_std_menu() function is very similar but it is used for menu controls. There is no min argument since that is always 0 for menu controls, and instead of a step there is a skip_mask argument: if bit X is 1, then menu item X is skipped.
The v4l2_ctrl_new_int_menu() function creates a new standard integer menu control with driver-specific items in the menu. It differs from v4l2_ctrl_new_std_menu in that it doesn't have the mask argument and takes as the last argument an array of signed 64-bit integers that form an exact menu item list.
The v4l2_ctrl_new_std_menu_items() function is very similar to v4l2_ctrl_new_std_menu but takes an extra parameter qmenu, which is the driver specific menu for an otherwise standard menu control. A good example for this control is the test pattern control for capture/display/sensors devices that have the capability to generate test patterns. These test patterns are hardware specific, so the contents of the menu will vary from device to device.
Note that if something fails, the function will return NULL or an error and set ctrl_handler->error to the error code. If ctrl_handler->error was already set, then it will just return and do nothing. This is also true for v4l2_ctrl_handler_init if it cannot allocate the internal data structure.
This makes it easy to init the handler and just add all controls and only check the error code at the end. Saves a lot of repetitive error checking.
It is recommended to add controls in ascending control ID order: it will be a bit faster that way.
- Optionally force initial control setup:
;
This will call s_ctrl for all controls unconditionally. Effectively this initializes the hardware to the default control values. It is recommended that you do this as this ensures that both the internal data structures and the hardware are in sync.
- Finally: implement the
v4l2_ctrl_ops
static const struct v4l2_ctrl_ops foo_ctrl_ops = ;
Usually all you need is s_ctrl:
static int
The control ops are called with the v4l2_ctrl pointer as argument. The new control value has already been validated, so all you need to do is to actually update the hardware registers.
You're done! And this is sufficient for most of the drivers we have. No need to do any validation of control values, or implement QUERYCTRL, QUERY_EXT_CTRL and QUERYMENU. And G/S_CTRL as well as G/TRY/S_EXT_CTRLS are automatically supported.
Inheriting Sub-device Controls #
When a sub-device is registered with a V4L2 driver by calling v4l2_device_register_subdev() and the ctrl_handler fields of both v4l2_subdev and v4l2_device are set, then the controls of the subdev will become automatically available in the V4L2 driver as well. If the subdev driver contains controls that already exist in the V4L2 driver, then those will be skipped (so a V4L2 driver can always override a subdev control).
What happens here is that v4l2_device_register_subdev() calls v4l2_ctrl_add_handler() adding the controls of the subdev to the controls of v4l2_device.
Accessing Control Values #
The following union is used inside the control framework to access control values:
;
The v4l2_ctrl struct contains these fields that can be used to access both current and new values:
s32 val;
cur;
union v4l2_ctrl_ptr p_new;
union v4l2_ctrl_ptr p_cur;
If the control has a simple s32 type, then:
&ctrl->val == ctrl->p_new.p_s32
&ctrl->cur.val == ctrl->p_cur.p_s32
For all other types use ctrl->p_cur.p<something>. Basically the val and cur.val fields can be considered an alias since these are used so often.
Within the control ops you can freely use these. The val and cur.val speak for themselves. The p_char pointers point to character buffers of length ctrl->maximum + 1, and are always 0-terminated.
Unless the control is marked volatile the p_cur field points to the current cached control value. When you create a new control this value is made identical to the default value. After calling v4l2_ctrl_handler_setup() this value is passed to the hardware. It is generally a good idea to call this function.
Whenever a new value is set that new value is automatically cached. This means that most drivers do not need to implement the g_volatile_ctrl() op. The exception is for controls that return a volatile register such as a signal strength read-out that changes continuously. In that case you will need to implement g_volatile_ctrl like this:
static int
Note that you use the 'new value' union as well in g_volatile_ctrl. In general controls that need to implement g_volatile_ctrl are read-only controls. If they are not, a V4L2_EVENT_CTRL_CH_VALUE will not be generated when the control changes.
To mark a control as volatile you have to set V4L2_CTRL_FLAG_VOLATILE:
ctrl = ;
if
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
For try/s_ctrl the new values (i.e. as passed by the user) are filled in and you can modify them in try_ctrl or set them in s_ctrl. The 'cur' union contains the current value, which you can use (but not change!) as well.
If s_ctrl returns 0 (OK), then the control framework will copy the new final values to the 'cur' union.
While in g_volatile/s/try_ctrl you can access the value of all controls owned by the same handler since the handler's lock is held. If you need to access the value of controls owned by other handlers, then you have to be very careful not to introduce deadlocks.
Outside of the control ops you have to go through to helper functions to get or set a single control value safely in your driver:
s32 ;
int ;
These functions go through the control framework just as VIDIOC_G/S_CTRL ioctls do. Don't use these inside the control ops g_volatile/s/try_ctrl, though, that will result in a deadlock since these helpers lock the handler as well.
You can also take the handler lock yourself:
;
;
;
;
Menu Controls #
The v4l2_ctrl struct contains this union:
;
For menu controls menu_skip_mask is used. What it does is that it allows you to easily exclude certain menu items. This is used in the VIDIOC_QUERYMENU implementation where you can return -EINVAL if a certain menu item is not present. Note that VIDIOC_QUERYCTRL always returns a step value of 1 for menu controls.
A good example is the MPEG Audio Layer II Bitrate menu control where the menu is a list of standardized possible bitrates. But in practice hardware implementations will only support a subset of those. By setting the skip mask you can tell the framework which menu items should be skipped. Setting it to 0 means that all menu items are supported.
You set this mask either through the v4l2_ctrl_config struct for a custom control, or by calling v4l2_ctrl_new_std_menu().
Custom Controls #
Driver specific controls can be created using v4l2_ctrl_new_custom():
static const struct v4l2_ctrl_config ctrl_filter = ;
ctrl = ;
The last argument is the priv pointer which can be set to driver-specific private data.
The v4l2_ctrl_config struct also has a field to set the is_private flag.
If the name field is not set, then the framework will assume this is a standard control and will fill in the name, type and flags fields accordingly.
Active and Grabbed Controls #
If you get more complex relationships between controls, then you may have to activate and deactivate controls. For example, if the Chroma AGC control is on, then the Chroma Gain control is inactive. That is, you may set it, but the value will not be used by the hardware as long as the automatic gain control is on. Typically user interfaces can disable such input fields.
You can set the 'active' status using v4l2_ctrl_activate(). By default all controls are active. Note that the framework does not check for this flag. It is meant purely for GUIs. The function is typically called from within s_ctrl.
The other flag is the 'grabbed' flag. A grabbed control means that you cannot change it because it is in use by some resource. Typical examples are MPEG bitrate controls that cannot be changed while capturing is in progress.
If a control is set to 'grabbed' using v4l2_ctrl_grab(), then the framework will return -EBUSY if an attempt is made to set this control. The v4l2_ctrl_grab() function is typically called from the driver when it starts or stops streaming.
Control Clusters #
By default all controls are independent from the others. But in more complex scenarios you can get dependencies from one control to another. In that case you need to 'cluster' them:
;
state->audio_cluster =
;
state->audio_cluster =
;
;
From now on whenever one or more of the controls belonging to the same cluster is set (or 'gotten', or 'tried'), only the control ops of the first control ('volume' in this example) is called. You effectively create a new composite control. Similar to how a 'struct' works in C.
So when s_ctrl is called with V4L2_CID_AUDIO_VOLUME as argument, you should set all two controls belonging to the audio_cluster:
static int
In the example above the following are equivalent for the VOLUME case:
ctrl == ctrl->cluster == state->audio_cluster
ctrl->cluster == state->audio_cluster
In practice using cluster arrays like this becomes very tiresome. So instead the following equivalent method is used:
;
The anonymous struct is used to clearly 'cluster' these two control pointers, but it serves no other purpose. The effect is the same as creating an array with two control pointers. So you can just do:
state->volume = ;
state->mute = ;
;
And in foo_s_ctrl you can use these pointers directly: state->mute->val.
Note that controls in a cluster may be NULL. For example, if for some reason mute was never added (because the hardware doesn't support that particular feature), then mute will be NULL. So in that case we have a cluster of 2 controls, of which only 1 is actually instantiated. The only restriction is that the first control of the cluster must always be present, since that is the 'master' control of the cluster. The master control is the one that identifies the cluster and that provides the pointer to the v4l2_ctrl_ops struct that is used for that cluster.
Obviously, all controls in the cluster array must be initialized to either a valid control or to NULL.
In rare cases you might want to know which controls of a cluster actually were set explicitly by the user. For this you can check the 'is_new' flag of each control. For example, in the case of a volume/mute cluster the 'is_new' flag of the mute control would be set if the user called VIDIOC_S_CTRL for mute only. If the user would call VIDIOC_S_EXT_CTRLS for both mute and volume controls, then the 'is_new' flag would be 1 for both controls.
The 'is_new' flag is always 1 when called from v4l2_ctrl_handler_setup().
Handling autogain/gain-type Controls with Auto Clusters #
A common type of control cluster is one that handles 'auto-foo/foo'-type controls. Typical examples are autogain/gain, autoexposure/exposure, autowhitebalance/red balance/blue balance. In all cases you have one control that determines whether another control is handled automatically by the hardware, or whether it is under manual control from the user.
If the cluster is in automatic mode, then the manual controls should be marked inactive and volatile. When the volatile controls are read the g_volatile_ctrl operation should return the value that the hardware's automatic mode set up automatically.
If the cluster is put in manual mode, then the manual controls should become active again and the volatile flag is cleared (so g_volatile_ctrl is no longer called while in manual mode). In addition just before switching to manual mode the current values as determined by the auto mode are copied as the new manual values.
Finally the V4L2_CTRL_FLAG_UPDATE should be set for the auto control since changing that control affects the control flags of the manual controls.
In order to simplify this a special variation of v4l2_ctrl_cluster was introduced:
void ;
The first two arguments are identical to v4l2_ctrl_cluster. The third argument tells the framework which value switches the cluster into manual mode. The last argument will optionally set V4L2_CTRL_FLAG_VOLATILE for the non-auto controls. If it is false, then the manual controls are never volatile. You would typically use that if the hardware does not give you the option to read back to values as determined by the auto mode (e.g. if autogain is on, the hardware doesn't allow you to obtain the current gain value).
The first control of the cluster is assumed to be the 'auto' control.
Using this function will ensure that you don't need to handle all the complex flag and volatile handling.
VIDIOC_LOG_STATUS Support #
This ioctl allow you to dump the current status of a driver to the kernel log. The v4l2_ctrl_handler_log_status(ctrl_handler, prefix) can be used to dump the value of the controls owned by the given handler to the log. You can supply a prefix as well. If the prefix didn't end with a space, then ': ' will be added for you.
Different Handlers for Different Video Nodes #
Usually the V4L2 driver has just one control handler that is global for all video nodes. But you can also specify different control handlers for different video nodes. You can do that by manually setting the ctrl_handler field of struct video_device.
That is no problem if there are no subdevs involved but if there are, then you need to block the automatic merging of subdev controls to the global control handler. You do that by simply setting the ctrl_handler field in struct v4l2_device to NULL. Now v4l2_device_register_subdev() will no longer merge subdev controls.
After each subdev was added, you will then have to call v4l2_ctrl_add_handler manually to add the subdev's control handler (sd->ctrl_handler) to the desired control handler. This control handler may be specific to the video_device or for a subset of video_device's. For example: the radio device nodes only have audio controls, while the video and vbi device nodes share the same control handler for the audio and video controls.
If you want to have one handler (e.g. for a radio device node) have a subset of another handler (e.g. for a video device node), then you should first add the controls to the first handler, add the other controls to the second handler and finally add the first handler to the second. For example:
;
;
;
;
;
The last argument to v4l2_ctrl_add_handler() is a filter function that allows you to filter which controls will be added. Set it to NULL if you want to add all controls.
Or you can add specific controls to a handler:
volume = ;
;
;
What you should not do is make two identical controls for two handlers. For example:
;
;
This would be bad since muting the radio would not change the video mute control. The rule is to have one control for each hardware 'knob' that you can twiddle.
Finding Controls #
Normally you have created the controls yourself and you can store the struct v4l2_ctrl pointer into your own struct.
But sometimes you need to find a control from another handler that you do not own. For example, if you have to find a volume control from a subdev.
You can do that by calling v4l2_ctrl_find:
struct v4l2_ctrl *volume;
volume = ;
Since v4l2_ctrl_find will lock the handler you have to be careful where you use it. For example, this is not a good idea:
struct v4l2_ctrl_handler ctrl_handler;
;
;
...and in video_ops.s_ctrl:
case V4L2_CID_BRIGHTNESS:
contrast = ;
...
When s_ctrl is called by the framework the ctrl_handler.lock is already taken, so attempting to find another control from the same handler will deadlock.
It is recommended not to use this function from inside the control ops.
Preventing Controls inheritance #
When one control handler is added to another using v4l2_ctrl_add_handler, then by default all controls from one are merged to the other. But a subdev might have low-level controls that make sense for some advanced embedded system, but not when it is used in consumer-level hardware. In that case you want to keep those low-level controls local to the subdev. You can do this by simply setting the 'is_private' flag of the control to 1:
static const struct v4l2_ctrl_config ctrl_private = ;
ctrl = ;
These controls will now be skipped when v4l2_ctrl_add_handler is called.
V4L2_CTRL_TYPE_CTRL_CLASS Controls #
Controls of this type can be used by GUIs to get the name of the control class. A fully featured GUI can make a dialog with multiple tabs with each tab containing the controls belonging to a particular control class. The name of each tab can be found by querying a special control with ID <control class | 1>.
Drivers do not have to care about this. The framework will automatically add a control of this type whenever the first control belonging to a new control class is added.
Adding Notify Callbacks #
Sometimes the platform or bridge driver needs to be notified when a control from a sub-device driver changes. You can set a notify callback by calling this function:
void ;
Whenever the give control changes value the notify callback will be called with a pointer to the control and the priv pointer that was passed with v4l2_ctrl_notify. Note that the control's handler lock is held when the notify function is called.
There can be only one notify function per control handler. Any attempt to set another notify function will cause a WARN_ON.
v4l2_ctrl functions and data structures #
union v4l2_ctrl_ptr #
A pointer to a control value.
Definition
;
Members
p_s32: Pointer to a 32-bit signed value.p_s64: Pointer to a 64-bit signed value.p_u8: Pointer to a 8-bit unsigned value.p_u16: Pointer to a 16-bit unsigned value.p_u32: Pointer to a 32-bit unsigned value.p_char: Pointer to a string.p_mpeg2_sequence: Pointer to a MPEG2 sequence structure.p_mpeg2_picture: Pointer to a MPEG2 picture structure.p_mpeg2_quantisation: Pointer to a MPEG2 quantisation data structure.p_fwht_params: Pointer to a FWHT stateless parameters structure.p_h264_sps: Pointer to a struct v4l2_ctrl_h264_sps.p_h264_pps: Pointer to a struct v4l2_ctrl_h264_pps.p_h264_scaling_matrix: Pointer to a struct v4l2_ctrl_h264_scaling_matrix.p_h264_slice_params: Pointer to a struct v4l2_ctrl_h264_slice_params.p_h264_decode_params: Pointer to a struct v4l2_ctrl_h264_decode_params.p_h264_pred_weights: Pointer to a struct v4l2_ctrl_h264_pred_weights.p_vp8_frame: Pointer to a VP8 frame params structure.p_hevc_sps: Pointer to an HEVC sequence parameter set structure.p_hevc_pps: Pointer to an HEVC picture parameter set structure.p_hevc_slice_params: Pointer to an HEVC slice parameters structure.p_vp9_compressed_hdr_probs: Pointer to a VP9 frame compressed header probs structure.p_vp9_frame: Pointer to a VP9 frame params structure.p_hdr10_cll: Pointer to an HDR10 Content Light Level structure.p_hdr10_mastering: Pointer to an HDR10 Mastering Display structure.p_area: Pointer to an area.p_av1_sequence: Pointer to an AV1 sequence structure.p_av1_tile_group_entry: Pointer to an AV1 tile group entry structure.p_av1_frame: Pointer to an AV1 frame structure.p_av1_film_grain: Pointer to an AV1 film grain structure.p_rect: Pointer to a rectangle.p: Pointer to a compound value.p_const: Pointer to a constant compound value.
v4l2_ctrl_ptr_create() #
union v4l2_ctrl_ptr Helper function to return a v4l2_ctrl_ptr from a void pointer
Parameters
void *ptr: The void pointer
struct v4l2_ctrl_ops #
The control operations that the driver has to provide.
Definition
;
Members
g_volatile_ctrl: Get a new value for this control. Generally only relevant for volatile (and usually read-only) controls such as a control that returns the current signal strength which changes continuously. If not set, then the currently cached value will be returned.try_ctrl: Test whether the control's value is valid. Only relevant when the usual min/max/step checks are not sufficient.s_ctrl: Actually set the new control value. s_ctrl is compulsory. The ctrl->handler->lock is held when these ops are called, so no one else can access controls owned by that handler.
struct v4l2_ctrl_type_ops #
The control type operations that the driver has to provide.
Definition
;
Members
equal: return true if all ctrl->elems array elements are equal.init: initialize the value for array elements from from_idx to ctrl->elems.minimum: set the value to the minimum value of the control.maximum: set the value to the maximum value of the control.log: log the value.validate: validate the value for ctrl->new_elems array elements. Return 0 on success and a negative value otherwise.
v4l2_ctrl_notify_fnc() #
typedef void
typedef for a notify argument with a function that should be called when a control value has changed.
Parameters
struct v4l2_ctrl *ctrl: pointer to structv4l2_ctrlvoid *priv: control private data
Description
This typedef definition is used as an argument to v4l2_ctrl_notify()
and as an argument at struct v4l2_ctrl_handler.
struct v4l2_ctrl #
The control structure.
Definition
;
Members
node: The list node.ev_subs: The list of control event subscriptions.handler: The handler that owns the control.cluster: Point to start of cluster array.ncontrols: Number of controls in cluster array.done: Internal flag: set for each processed control.is_new: Set when the user specified a new value for this control. It is also set when called fromv4l2_ctrl_handler_setup(). Drivers should never set this flag.has_changed: Set when the current value differs from the new value. Drivers should never use this flag.is_private: If set, then this control is private to its handler and it will not be added to any other handlers. Drivers can set this flag.is_auto: If set, then this control selects whether the other cluster members are in 'automatic' mode or 'manual' mode. This is used for autogain/gain type clusters. Drivers should never set this flag directly.is_int: If set, then this control has a simple integer value (i.e. it uses ctrl->val).is_string: If set, then this control has typeV4L2_CTRL_TYPE_STRING.is_ptr: If set, then this control is an array and/or has type >=V4L2_CTRL_COMPOUND_TYPESand/or has typeV4L2_CTRL_TYPE_STRING. In other words,struct v4l2_ext_controluses field p to point to the data.is_array: If set, then this control contains an N-dimensional array.is_dyn_array: If set, then this control contains a dynamically sized 1-dimensional array. If this is set, then is_array is also set.has_volatiles: If set, then one or more members of the cluster are volatile. Drivers should never touch this flag.call_notify: If set, then call the handler's notify function whenever the control's value changes.manual_mode_value: If the is_auto flag is set, then this is the value of the auto control that determines if that control is in manual mode. So if the value of the auto control equals this value, then the whole cluster is in manual mode. Drivers should never set this flag directly.ops: The control ops.type_ops: The control type ops.id: The control ID.name: The control name.type: The control type.minimum: The control's minimum value.maximum: The control's maximum value.default_value: The control's default value.elems: The number of elements in the N-dimensional array.elem_size: The size in bytes of the control.new_elems: The number of elements in p_new. This is the same as elems, except for dynamic arrays. In that case it is in the range of 1 to p_array_alloc_elems.dims: The size of each dimension.nr_of_dims: The number of dimensions in dims.{unnamed_union}: anonymousstep: The control's step value for non-menu controls.menu_skip_mask: The control's skip mask for menu controls. This makes it easy to skip menu items that are not valid. If bit X is set, then menu item X is skipped. Of course, this only works for menus with <= 32 menu items. There are no menus that come close to that number, so this is OK. Should we ever need more, then this will have to be extended to a u64 or a bit array.{unnamed_union}: anonymousqmenu: A const char * array for all menu items. Array entries that are empty strings ("") correspond to non-existing menu items (this is in addition to the menu_skip_mask above). The last entry must be NULL. Used only if the type isV4L2_CTRL_TYPE_MENU.qmenu_int: A 64-bit integer array for with integer menu items. The size of array must be equal to the menu size, e. g.: ceil(\frac{maximum - minimum}{step}) + 1. Used only if the type isV4L2_CTRL_TYPE_INTEGER_MENU.flags: The control's flags.priv: The control's private pointer. For use by the driver. It is untouched by the control framework. Note that this pointer is not freed when the control is deleted. Should this be needed then a new internal bitfield can be added to tell the framework to free this pointer.p_array: Pointer to the allocated array. Only valid if is_array is true.p_array_alloc_elems: The number of elements in the allocated array for both the cur and new values. So p_array is actually sized for 2 * p_array_alloc_elems * elem_size. Only valid if is_array is true.val: The control's new s32 value.cur: Structure to store the current value.cur.val: The control's current value, if the type is represented via a u32 integer (seeenum v4l2_ctrl_type).p_def: The control's default value represented via a union which provides a standard way of accessing control types through a pointer (for compound controls only).p_min: The control's minimum value represented via a union which provides a standard way of accessing control types through a pointer (for compound controls only).p_max: The control's maximum value represented via a union which provides a standard way of accessing control types through a pointer (for compound controls only).p_new: The control's new value represented via a union which provides a standard way of accessing control types through a pointer.p_cur: The control's current value represented via a union which provides a standard way of accessing control types through a pointer.
struct v4l2_ctrl_ref #
The control reference.
Definition
;
Members
node: List node for the sorted list.next: Single-link list node for the hash.ctrl: The actual control information.helper: Pointer to helper struct. Used internally inprepare_ext_ctrlsfunction atv4l2-ctrl.c.from_other_dev: If true, then ctrl was defined in another device than thestruct v4l2_ctrl_handler.req_done: Internal flag: if the control handler containing this control reference is bound to a media request, then this is set when the control has been applied. This prevents applying controls from a cluster with multiple controls twice (when the first control of a cluster is applied, they all are).p_req_valid: If set, then p_req contains the control value for the request.p_req_array_enomem: If set, then p_req is invalid since allocating space for an array failed. Attempting to read this value shall result in ENOMEM. Only valid if ctrl->is_array is true.p_req_array_alloc_elems: The number of elements allocated for the array. Only valid if p_req_valid and ctrl->is_array are true.p_req_elems: The number of elements in p_req. This is the same as ctrl->elems, except for dynamic arrays. In that case it is in the range of 1 to p_req_array_alloc_elems. Only valid if p_req_valid is true.p_req: If the control handler containing this control reference is bound to a media request, then this points to the value of the control that must be applied when the request is executed, or to the value of the control at the time that the request was completed. If p_req_valid is false, then this control was never set for this request and the control will not be updated when this request is applied.
Description
Each control handler has a list of these refs. The list_head is used to keep a sorted-by-control-ID list of all controls, while the next pointer is used to link the control in the hash's bucket.
struct v4l2_ctrl_handler #
The control handler keeps track of all the controls: both the controls owned by the handler and those inherited from other handlers.
Definition
;
Members
_lock: Default for "lock".lock: Lock to control access to this handler and its controls. May be replaced by the user right after init.ctrls: The list of controls owned by this handler.ctrl_refs: The list of control references.cached: The last found control reference. It is common that the same control is needed multiple times, so this is a simple optimization.buckets: Buckets for the hashing. Allows for quick control lookup.notify: A notify callback that is called whenever the control changes value. Note that the handler's lock is held when the notify function is called!notify_priv: Passed as argument to the v4l2_ctrl notify callback.nr_of_buckets: Total number of buckets in the array.error: The error code of the first failed control addition.request_is_queued: True if the request was queued.requests: List to keep track of open control handler request objects. For the parent control handler (req_obj.ops == NULL) this is the list header. When the parent control handler is removed, it has to unbind and put all these requests since they refer to the parent.requests_queued: List of the queued requests. This determines the order in which these controls are applied. Once the request is completed it is removed from this list.req_obj: Thestruct media_request_object, used to link into astruct media_request. This request object has a refcount.
struct v4l2_ctrl_config #
Control configuration structure.
Definition
;
Members
ops: The control ops.type_ops: The control type ops. Only needed for compound controls.id: The control ID.name: The control name.type: The control type.min: The control's minimum value.max: The control's maximum value.step: The control's step value for non-menu controls.def: The control's default value.p_def: The control's default value for compound controls.p_min: The control's minimum value for compound controls.p_max: The control's maximum value for compound controls.dims: The size of each dimension.elem_size: The size in bytes of the control.flags: The control's flags.menu_skip_mask: The control's skip mask for menu controls. This makes it easy to skip menu items that are not valid. If bit X is set, then menu item X is skipped. Of course, this only works for menus with <= 64 menu items. There are no menus that come close to that number, so this is OK. Should we ever need more, then this will have to be extended to a bit array.qmenu: A const char * array for all menu items. Array entries that are empty strings ("") correspond to non-existing menu items (this is in addition to the menu_skip_mask above). The last entry must be NULL.qmenu_int: A const s64 integer array for all menu items of the type V4L2_CTRL_TYPE_INTEGER_MENU.is_private: If set, then this control is private to its handler and it will not be added to any other handlers.
v4l2_ctrl_fill() #
void Fill in the control fields based on the control ID.
Parameters
u32 id: ID of the controlconst char **name: pointer to be filled with a string with the name of the controlenum v4l2_ctrl_type *type: pointer for storing the type of the controls64 *min: pointer for storing the minimum value for the controls64 *max: pointer for storing the maximum value for the controlu64 *step: pointer for storing the control steps64 *def: pointer for storing the default value for the controlu32 *flags: pointer for storing the flags to be used on the control
Description
This works for all standard V4L2 controls.
For non-standard controls it will only fill in the given arguments
and name content will be set to NULL.
This function will overwrite the contents of name, type and flags. The contents of min, max, step and def may be modified depending on the type.
v4l2_ctrl_handler_init_class() #
int Initialize the control handler.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.unsigned int nr_of_controls_hint: A hint of how many controls this handler is expected to refer to. This is the total number, so including any inherited controls. It doesn't have to be precise, but if it is way off, then you either waste memory (too many buckets are allocated) or the control lookup becomes slower (not enough buckets are allocated, so there are more slow list lookups). It will always work, though.struct lock_class_key *key: Used by the lock validator if CONFIG_LOCKDEP is set.const char *name: Used by the lock validator if CONFIG_LOCKDEP is set.
Description
Return
returns an error if the buckets could not be allocated. This error will also be stored in hdl->error.
v4l2_ctrl_handler_init() #
helper function to create a static struct lock_class_key and calls v4l2_ctrl_handler_init_class()
Parameters
hdl: The control handler.nr_of_controls_hint: A hint of how many controls this handler is expected to refer to. This is the total number, so including any inherited controls. It doesn't have to be precise, but if it is way off, then you either waste memory (too many buckets are allocated) or the control lookup becomes slower (not enough buckets are allocated, so there are more slow list lookups). It will always work, though.
Description
This helper function creates a static struct lock_class_key and
calls v4l2_ctrl_handler_init_class(), providing a proper name for the lock
validador.
Use this helper function to initialize a control handler.
v4l2_ctrl_handler_free() #
int Free all controls owned by the handler and free the control list.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.
Description
Does nothing if hdl == NULL.
Return
hdl's error field or 0 if hdl is NULL.
v4l2_ctrl_lock() #
void Helper function to lock the handler associated with the control.
Parameters
struct v4l2_ctrl *ctrl: The control to lock.
v4l2_ctrl_unlock() #
void Helper function to unlock the handler associated with the control.
Parameters
struct v4l2_ctrl *ctrl: The control to unlock.
__v4l2_ctrl_handler_setup() #
int Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values. The caller is responsible for acquiring the control handler mutex on behalf of __v4l2_ctrl_handler_setup().
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.
Description
Button controls will be skipped, as are read-only controls.
If hdl == NULL, then this just returns 0.
v4l2_ctrl_handler_setup() #
int Call the s_ctrl op for all controls belonging to the handler to initialize the hardware to the current control values.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.
Description
Button controls will be skipped, as are read-only controls.
If hdl == NULL, then this just returns 0.
v4l2_ctrl_handler_log_status() #
void Log all controls owned by the handler.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const char *prefix: The prefix to use when logging the control values. If the prefix does not end with a space, then ": " will be added after the prefix. If prefix == NULL, then no prefix will be used.
Description
For use with VIDIOC_LOG_STATUS.
Does nothing if hdl == NULL.
v4l2_ctrl_new_custom() #
struct v4l2_ctrl * Allocate and initialize a new custom V4L2 control.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_config *cfg: The control's configuration data.void *priv: The control's driver-specific private data.
Description
If the v4l2_ctrl struct could not be allocated then NULL is returned
and hdl->error is set to the error code (if it wasn't set already).
v4l2_ctrl_new_std() #
struct v4l2_ctrl * Allocate and initialize a new standard V4L2 non-menu control.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_ops *ops: The control ops.u32 id: The control ID.s64 min: The control's minimum value.s64 max: The control's maximum value.u64 step: The control's step values64 def: The control's default value.
Description
If the v4l2_ctrl struct could not be allocated, or the control
ID is not known, then NULL is returned and hdl->error is set to the
appropriate error code (if it wasn't set already).
If id refers to a menu control, then this function will return NULL.
Use v4l2_ctrl_new_std_menu() when adding menu controls.
v4l2_ctrl_new_std_menu() #
struct v4l2_ctrl * Allocate and initialize a new standard V4L2 menu control.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_ops *ops: The control ops.u32 id: The control ID.u8 max: The control's maximum value.u64 mask: The control's skip mask for menu controls. This makes it easy to skip menu items that are not valid. If bit X is set, then menu item X is skipped. Of course, this only works for menus with <= 64 menu items. There are no menus that come close to that number, so this is OK. Should we ever need more, then this will have to be extended to a bit array.u8 def: The control's default value.
Description
Same as v4l2_ctrl_new_std(), but min is set to 0 and the mask value
determines which menu items are to be skipped.
If id refers to a non-menu control, then this function will return NULL.
v4l2_ctrl_new_std_menu_items() #
struct v4l2_ctrl * Create a new standard V4L2 menu control with driver specific menu.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_ops *ops: The control ops.u32 id: The control ID.u8 max: The control's maximum value.u64 mask: The control's skip mask for menu controls. This makes it easy to skip menu items that are not valid. If bit X is set, then menu item X is skipped. Of course, this only works for menus with <= 64 menu items. There are no menus that come close to that number, so this is OK. Should we ever need more, then this will have to be extended to a bit array.u8 def: The control's default value.const char * const *qmenu: The new menu.
Description
Same as v4l2_ctrl_new_std_menu(), but qmenu will be the driver specific
menu of this control.
v4l2_ctrl_new_std_compound() #
struct v4l2_ctrl * Allocate and initialize a new standard V4L2 compound control.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_ops *ops: The control ops.u32 id: The control ID.const union v4l2_ctrl_ptr p_def: The control's default value.const union v4l2_ctrl_ptr p_min: The control's minimum value.const union v4l2_ctrl_ptr p_max: The control's maximum value.
Description
Same as v4l2_ctrl_new_std(), but with support for compound controls.
To fill in the p_def, p_min and p_max fields, use v4l2_ctrl_ptr_create()
to convert a pointer to a const union v4l2_ctrl_ptr.
Use v4l2_ctrl_ptr_create(NULL) if you want the default, minimum or maximum
value of the compound control to be all zeroes.
If the compound control does not set the V4L2_CTRL_FLAG_HAS_WHICH_MIN_MAX
flag, then it does not has minimum and maximum values. In that case just use
v4l2_ctrl_ptr_create(NULL) for the p_min and p_max arguments.
v4l2_ctrl_new_int_menu() #
struct v4l2_ctrl * Create a new standard V4L2 integer menu control.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.const struct v4l2_ctrl_ops *ops: The control ops.u32 id: The control ID.u8 max: The control's maximum value.u8 def: The control's default value.const s64 *qmenu_int: The control's menu entries.
Description
Same as v4l2_ctrl_new_std_menu(), but mask is set to 0 and it additionally
takes as an argument an array of integers determining the menu items.
If id refers to a non-integer-menu control, then this function will
return NULL.
v4l2_ctrl_filter() #
typedef bool
Typedef to define the filter function to be used when adding a control handler.
Parameters
const struct v4l2_ctrl *ctrl: pointer to structv4l2_ctrl.
v4l2_ctrl_add_handler() #
int Add all controls from handler add to handler hdl.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.struct v4l2_ctrl_handler *add: The control handler whose controls you want to add to the hdl control handler.v4l2_ctrl_filter filter: This function will filter which controls should be added.bool from_other_dev: If true, then the controls in add were defined in another device than hdl.
Description
Does nothing if either of the two handlers is a NULL pointer. If filter is NULL, then all controls are added. Otherwise only those controls for which filter returns true will be added. In case of an error hdl->error will be set to the error code (if it wasn't set already).
v4l2_ctrl_radio_filter() #
bool Standard filter for radio controls.
Parameters
const struct v4l2_ctrl *ctrl: The control that is filtered.
Description
This will return true for any controls that are valid for radio device nodes. Those are all of the V4L2_CID_AUDIO_* user controls and all FM transmitter class controls.
This function is to be used with v4l2_ctrl_add_handler().
v4l2_ctrl_cluster() #
void Mark all controls in the cluster as belonging to that cluster.
Parameters
unsigned int ncontrols: The number of controls in this cluster.struct v4l2_ctrl **controls: The cluster control array of size ncontrols.
v4l2_ctrl_auto_cluster() #
void Mark all controls in the cluster as belonging to that cluster and set it up for autofoo/foo-type handling.
Parameters
unsigned int ncontrols: The number of controls in this cluster.struct v4l2_ctrl **controls: The cluster control array of size ncontrols. The first control must be the 'auto' control (e.g. autogain, autoexposure, etc.)u8 manual_val: The value for the first control in the cluster that equals the manual setting.bool set_volatile: If true, then all controls except the first auto control will be volatile.
Description
Use for control groups where one control selects some automatic feature and the other controls are only active whenever the automatic feature is turned off (manual mode). Typical examples: autogain vs gain, auto-whitebalance vs red and blue balance, etc.
The behavior of such controls is as follows:
When the autofoo control is set to automatic, then any manual controls are set to inactive and any reads will call g_volatile_ctrl (if the control was marked volatile).
When the autofoo control is set to manual, then any manual controls will be marked active, and any reads will just return the current value without going through g_volatile_ctrl.
In addition, this function will set the V4L2_CTRL_FLAG_UPDATE flag
on the autofoo control and V4L2_CTRL_FLAG_INACTIVE on the foo control(s)
if autofoo is in auto mode.
v4l2_ctrl_find() #
struct v4l2_ctrl * Find a control with the given ID.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler.u32 id: The control ID to find.
Description
If hdl == NULL this will return NULL as well. Will lock the handler so
do not use from inside v4l2_ctrl_ops.
v4l2_ctrl_activate() #
void Make the control active or inactive.
Parameters
struct v4l2_ctrl *ctrl: The control to (de)activate.bool active: True if the control should become active.
Description
This sets or clears the V4L2_CTRL_FLAG_INACTIVE flag atomically. Does nothing if ctrl == NULL. This will usually be called from within the s_ctrl op. The V4L2_EVENT_CTRL event will be generated afterwards.
This function assumes that the control handler is locked.
__v4l2_ctrl_grab() #
void Unlocked variant of v4l2_ctrl_grab.
Parameters
struct v4l2_ctrl *ctrl: The control to (de)activate.bool grabbed: True if the control should become grabbed.
Description
This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically. Does nothing if ctrl == NULL. The V4L2_EVENT_CTRL event will be generated afterwards. This will usually be called when starting or stopping streaming in the driver.
This function assumes that the control handler is locked by the caller.
v4l2_ctrl_grab() #
void Mark the control as grabbed or not grabbed.
Parameters
struct v4l2_ctrl *ctrl: The control to (de)activate.bool grabbed: True if the control should become grabbed.
Description
This sets or clears the V4L2_CTRL_FLAG_GRABBED flag atomically. Does nothing if ctrl == NULL. The V4L2_EVENT_CTRL event will be generated afterwards. This will usually be called when starting or stopping streaming in the driver.
This function assumes that the control handler is not locked and will take the lock itself.
__v4l2_ctrl_modify_range() #
int Unlocked variant of v4l2_ctrl_modify_range()
Parameters
struct v4l2_ctrl *ctrl: The control to update.s64 min: The control's minimum value.s64 max: The control's maximum value.u64 step: The control's step values64 def: The control's default value.
Description
Update the range of a control on the fly. This works for control types INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the step value is interpreted as a menu_skip_mask.
An error is returned if one of the range arguments is invalid for this control type.
The caller is responsible for acquiring the control handler mutex on behalf
of __v4l2_ctrl_modify_range().
v4l2_ctrl_modify_range() #
int Update the range of a control.
Parameters
struct v4l2_ctrl *ctrl: The control to update.s64 min: The control's minimum value.s64 max: The control's maximum value.u64 step: The control's step values64 def: The control's default value.
Description
Update the range of a control on the fly. This works for control types INTEGER, BOOLEAN, MENU, INTEGER MENU and BITMASK. For menu controls the step value is interpreted as a menu_skip_mask.
An error is returned if one of the range arguments is invalid for this control type.
This function assumes that the control handler is not locked and will take the lock itself.
__v4l2_ctrl_modify_dimensions() #
int Unlocked variant of v4l2_ctrl_modify_dimensions()
Parameters
struct v4l2_ctrl *ctrl: The control to update.u32 dims[V4L2_CTRL_MAX_DIMS]: The control's new dimensions.
Description
Update the dimensions of an array control on the fly. The elements of the array are reset to their default value, even if the dimensions are unchanged.
An error is returned if dims is invalid for this control.
The caller is responsible for acquiring the control handler mutex on behalf
of __v4l2_ctrl_modify_dimensions().
Note
calling this function when the same control is used in pending requests is untested. It should work (a request with the wrong size of the control will drop that control silently), but it will be very confusing.
v4l2_ctrl_modify_dimensions() #
int Update the dimensions of an array control.
Parameters
struct v4l2_ctrl *ctrl: The control to update.u32 dims[V4L2_CTRL_MAX_DIMS]: The control's new dimensions.
Description
Update the dimensions of an array control on the fly. The elements of the array are reset to their default value, even if the dimensions are unchanged.
An error is returned if dims is invalid for this control type.
This function assumes that the control handler is not locked and will take the lock itself.
Note
calling this function when the same control is used in pending requests is untested. It should work (a request with the wrong size of the control will drop that control silently), but it will be very confusing.
v4l2_ctrl_notify() #
void Function to set a notify callback for a control.
Parameters
struct v4l2_ctrl *ctrl: The control.v4l2_ctrl_notify_fnc notify: The callback function.void *priv: The callback private handle, passed as argument to the callback.
Description
This function sets a callback function for the control. If ctrl is NULL, then it will do nothing. If notify is NULL, then the notify callback will be removed.
There can be only one notify. If another already exists, then a WARN_ON will be issued and the function will do nothing.
v4l2_ctrl_get_name() #
const char * Get the name of the control
Parameters
u32 id: The control ID.
Description
This function returns the name of the given control ID or NULL if it isn't a known control.
v4l2_ctrl_get_menu() #
const char * const * Get the menu string array of the control
Parameters
u32 id: The control ID.
Description
This function returns the NULL-terminated menu string array name of the given control ID or NULL if it isn't a known menu control.
v4l2_ctrl_get_int_menu() #
const s64 * Get the integer menu array of the control
Parameters
u32 id: The control ID.u32 *len: The size of the integer array.
Description
This function returns the integer array of the given control ID or NULL if it if it isn't a known integer menu control.
v4l2_ctrl_g_ctrl() #
s32 Helper function to get the control's value from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.
Description
This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the v4l2_ctrl_ops functions.
This function is for integer type controls only.
__v4l2_ctrl_s_ctrl() #
int Unlocked variant of v4l2_ctrl_s_ctrl().
Parameters
struct v4l2_ctrl *ctrl: The control.s32 val: The new value.
Description
This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the v4l2_ctrl_ops functions.
This function is for integer type controls only.
v4l2_ctrl_s_ctrl() #
int Helper function to set the control's value from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.s32 val: The new value.
Description
This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the v4l2_ctrl_ops functions.
This function is for integer type controls only.
v4l2_ctrl_g_ctrl_int64() #
s64 Helper function to get a 64-bit control's value from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.
Description
This returns the control's value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the v4l2_ctrl_ops functions.
This function is for 64-bit integer type controls only.
__v4l2_ctrl_s_ctrl_int64() #
int Unlocked variant of v4l2_ctrl_s_ctrl_int64().
Parameters
struct v4l2_ctrl *ctrl: The control.s64 val: The new value.
Description
This sets the control's new value safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the v4l2_ctrl_ops functions.
This function is for 64-bit integer type controls only.
v4l2_ctrl_s_ctrl_int64() #
int Helper function to set a 64-bit control's value from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.s64 val: The new value.
Description
This sets the control's new value safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the v4l2_ctrl_ops functions.
This function is for 64-bit integer type controls only.
__v4l2_ctrl_s_ctrl_string() #
int Unlocked variant of v4l2_ctrl_s_ctrl_string().
Parameters
struct v4l2_ctrl *ctrl: The control.const char *s: The new string.
Description
This sets the control's new string safely by going through the control
framework. This function assumes the control's handler is already locked,
allowing it to be used from within the v4l2_ctrl_ops functions.
This function is for string type controls only.
v4l2_ctrl_s_ctrl_string() #
int Helper function to set a control's string value from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.const char *s: The new string.
Description
This sets the control's new string safely by going through the control
framework. This function will lock the control's handler, so it cannot be
used from within the v4l2_ctrl_ops functions.
This function is for string type controls only.
__v4l2_ctrl_s_ctrl_compound() #
int Unlocked variant to set a compound control
Parameters
struct v4l2_ctrl *ctrl: The control.enum v4l2_ctrl_type type: The type of the data.const void *p: The new compound payload.
Description
This sets the control's new compound payload safely by going through the
control framework. This function assumes the control's handler is already
locked, allowing it to be used from within the v4l2_ctrl_ops functions.
This function is for compound type controls only.
v4l2_ctrl_s_ctrl_compound() #
int Helper function to set a compound control from within a driver.
Parameters
struct v4l2_ctrl *ctrl: The control.enum v4l2_ctrl_type type: The type of the data.const void *p: The new compound payload.
Description
This sets the control's new compound payload safely by going through the
control framework. This function will lock the control's handler, so it
cannot be used from within the v4l2_ctrl_ops functions.
This function is for compound type controls only.
v4l2_ctrl_replace() #
void Function to be used as a callback to struct v4l2_subscribed_event_ops replace()
Parameters
struct v4l2_event *old: pointer to structv4l2_eventwith the reported event;const struct v4l2_event *new: pointer to structv4l2_eventwith the modified event;
v4l2_ctrl_merge() #
void Function to be used as a callback to struct v4l2_subscribed_event_ops merge()
Parameters
const struct v4l2_event *old: pointer to structv4l2_eventwith the reported event;struct v4l2_event *new: pointer to structv4l2_eventwith the merged event;
v4l2_ctrl_log_status() #
int helper function to implement VIDIOC_LOG_STATUS ioctl
Parameters
struct file *file: pointer to struct filevoid *priv: unused. Kept just to be compatible to the arguments expected bystruct v4l2_ioctl_ops.vidioc_log_status.
Description
Can be used as a vidioc_log_status function that just dumps all controls associated with the filehandle.
v4l2_ctrl_subscribe_event() #
int Subscribes to an event
Parameters
struct v4l2_fh *fh: pointer to struct v4l2_fhconst struct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
Description
Can be used as a vidioc_subscribe_event function that just subscribes control events.
v4l2_ctrl_poll() #
__poll_t function to be used as a callback to the poll() That just polls for control events.
Parameters
struct file *file: pointer to struct filestruct poll_table_struct *wait: pointer to struct poll_table_struct
v4l2_ctrl_request_setup() #
int helper function to apply control values in a request
Parameters
struct media_request *req: The requeststruct v4l2_ctrl_handler *parent: The parent control handler ('priv' inmedia_request_object_find())
Description
This is a helper function to call the control handler's s_ctrl callback with the control values contained in the request. Do note that this approach of applying control values in a request is only applicable to memory-to-memory devices.
v4l2_ctrl_request_complete() #
void Complete a control handler request object
Parameters
struct media_request *req: The requeststruct v4l2_ctrl_handler *parent: The parent control handler ('priv' inmedia_request_object_find())
Description
This function is to be called on each control handler that may have had a request object associated with it, i.e. control handlers of a driver that supports requests.
The function first obtains the values of any volatile controls in the control handler and attach them to the request. Then, the function completes the request object.
v4l2_ctrl_request_hdl_find() #
struct v4l2_ctrl_handler * Find the control handler in the request
Parameters
struct media_request *req: The requeststruct v4l2_ctrl_handler *parent: The parent control handler ('priv' inmedia_request_object_find())
Description
This function finds the control handler in the request. It may return
NULL if not found. When done, you must call v4l2_ctrl_request_hdl_put()
with the returned handler pointer.
If the request is not in state VALIDATING or QUEUED, then this function will always return NULL.
Note that in state VALIDATING the req_queue_mutex is held, so no objects can be added or deleted from the request.
In state QUEUED it is the driver that will have to ensure this.
v4l2_ctrl_request_hdl_put() #
void Put the control handler
Parameters
struct v4l2_ctrl_handler *hdl: Put this control handler
Description
This function released the control handler previously obtained from'
v4l2_ctrl_request_hdl_find().
v4l2_ctrl_request_hdl_ctrl_find() #
struct v4l2_ctrl * Find a control with the given ID.
Parameters
struct v4l2_ctrl_handler *hdl: The control handler from the request.u32 id: The ID of the control to find.
Description
This function returns a pointer to the control if this control is part of the request or NULL otherwise.
v4l2_queryctrl() #
int Helper function to implement VIDIOC_QUERYCTRL ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct v4l2_queryctrl *qc: pointer tostruct v4l2_queryctrl
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_query_ext_ctrl_to_v4l2_queryctrl() #
void Convert a qec to qe.
Parameters
struct v4l2_queryctrl *to: The v4l2_queryctrl to write to.const struct v4l2_query_ext_ctrl *from: The v4l2_query_ext_ctrl to read from.
Description
This function is a helper to convert a v4l2_query_ext_ctrl into a v4l2_queryctrl.
v4l2_query_ext_ctrl() #
int Helper function to implement VIDIOC_QUERY_EXT_CTRL ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct v4l2_query_ext_ctrl *qc: pointer tostruct v4l2_query_ext_ctrl
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_querymenu() #
int Helper function to implement VIDIOC_QUERYMENU ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct v4l2_querymenu *qm: pointer tostruct v4l2_querymenu
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_g_ctrl() #
int Helper function to implement VIDIOC_G_CTRL ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct v4l2_control *ctrl: pointer tostruct v4l2_control
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_s_ctrl() #
int Helper function to implement VIDIOC_S_CTRL ioctl
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhstruct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct v4l2_control *ctrl: pointer tostruct v4l2_control
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_g_ext_ctrls() #
int Helper function to implement VIDIOC_G_EXT_CTRLS ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct video_device *vdev: pointer tostruct video_devicestruct media_device *mdev: pointer tostruct media_devicestruct v4l2_ext_controls *c: pointer tostruct v4l2_ext_controls
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_try_ext_ctrls() #
int Helper function to implement VIDIOC_TRY_EXT_CTRLS ioctl
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct video_device *vdev: pointer tostruct video_devicestruct media_device *mdev: pointer tostruct media_devicestruct v4l2_ext_controls *c: pointer tostruct v4l2_ext_controls
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_s_ext_ctrls() #
int Helper function to implement VIDIOC_S_EXT_CTRLS ioctl
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhstruct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerstruct video_device *vdev: pointer tostruct video_devicestruct media_device *mdev: pointer tostruct media_devicestruct v4l2_ext_controls *c: pointer tostruct v4l2_ext_controls
Description
If hdl == NULL then they will all return -EINVAL.
v4l2_ctrl_subdev_subscribe_event() #
int Helper function to implement as a struct v4l2_subdev_core_ops subscribe_event function that just subscribes control events.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct v4l2_fh *fh: pointer tostruct v4l2_fhstruct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
v4l2_ctrl_subdev_log_status() #
int Log all controls owned by subdev's control handler.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
v4l2_ctrl_new_fwnode_properties() #
int Register controls for the device properties
Parameters
struct v4l2_ctrl_handler *hdl: pointer tostruct v4l2_ctrl_handlerto register controls onconst struct v4l2_ctrl_ops *ctrl_ops: pointer tostruct v4l2_ctrl_opsto register controls withconst struct v4l2_fwnode_device_properties *p: pointer tostruct v4l2_fwnode_device_properties
Description
This function registers controls associated to device properties, using the property values contained in p parameter, if the property has been set to a value.
Currently the following v4l2 controls are parsed and registered:
- V4L2_CID_CAMERA_ORIENTATION
- V4L2_CID_CAMERA_SENSOR_ROTATION;
Controls already registered by the caller with the hdl control handler are not overwritten. Callers should register the controls they want to handle themselves before calling this function.
This function will set the control handler's error field on failure, just as other functions adding controls to the handler.
Return
0 on success, a negative error code on failure.
v4l2_ctrl_type_op_equal() #
bool Default v4l2_ctrl_type_ops equal callback.
Parameters
const struct v4l2_ctrl *ctrl: The v4l2_ctrl pointer.union v4l2_ctrl_ptr ptr1: A v4l2 control value.union v4l2_ctrl_ptr ptr2: A v4l2 control value.
Return
true if values are equal, otherwise false.
v4l2_ctrl_type_op_init() #
void Default v4l2_ctrl_type_ops init callback.
Parameters
const struct v4l2_ctrl *ctrl: The v4l2_ctrl pointer.u32 from_idx: Starting element index.union v4l2_ctrl_ptr ptr: The v4l2 control value.
Return
void
v4l2_ctrl_type_op_log() #
void Default v4l2_ctrl_type_ops log callback.
Parameters
const struct v4l2_ctrl *ctrl: The v4l2_ctrl pointer.
Return
void
v4l2_ctrl_type_op_validate() #
int Default v4l2_ctrl_type_ops validate callback.
Parameters
const struct v4l2_ctrl *ctrl: The v4l2_ctrl pointer.union v4l2_ctrl_ptr ptr: The v4l2 control value.
Return
0 on success, a negative error code on failure.
Video4Linux devices
Peios Kernel / Hardware and drivers / Driver development / Media devices
- Introduction
- Video device' s internal representation
- V4L2 device instance
- V4L2 File handles
- V4L2 sub-devices
- V4L2 events
- V4L2 Controls
- V4L2 videobuf2 functions and data structures
- V4L2 DV Timings functions
- V4L2 flash functions and data structures
- V4L2 Media Controller functions and data structures
- V4L2 Media Bus functions and data structures
- V4L2 Memory to Memory functions and data structures
- V4L2 async kAPI
- V4L2 fwnode kAPI
- V4L2 CCI kAPI
- V4L2 rect helper functions
- Tuner functions and data structures
- V4L2 common functions and data structures
- Hauppauge TV EEPROM functions and data structures
- V4L2 JPEG header related functions and data structures
- V4L2 generic ISP parameters and statistics support
Video device' s internal representation
Peios Kernel / Hardware and drivers / Driver development / Media devices
The actual device nodes in the /dev directory are created using the video_device struct (v4l2-dev.h). This struct can either be allocated dynamically or embedded in a larger struct.
To allocate it dynamically use video_device_alloc():
struct video_device *vdev = ;
if
return -ENOMEM;
vdev->release = video_device_release;
If you embed it in a larger struct, then you must set the release() callback to your own function:
struct video_device *vdev = &my_vdev->vdev;
vdev->release = my_vdev_release;
The release() callback must be set and it is called when the last user of the video device exits.
The default video_device_release() callback currently just calls kfree to free the allocated memory.
There is also a video_device_release_empty() function that does nothing (is empty) and should be used if the struct is embedded and there is nothing to do when it is released.
You should also set these fields of video_device:
-
video_device->v4l2_dev: must be set to thev4l2_deviceparent device. -
video_device->name: set to something descriptive and unique. -
video_device->vfl_dir: set this toVFL_DIR_RXfor capture devices (VFL_DIR_RXhas value 0, so this is normally already the default), set toVFL_DIR_TXfor output devices andVFL_DIR_M2Mfor mem2mem (codec) devices. -
video_device->fops: set to thev4l2_file_operationsstruct. -
video_device->ioctl_ops: if you use thev4l2_ioctl_opsto simplify ioctl maintenance (highly recommended to use this and it might become compulsory in the future!), then set this to yourv4l2_ioctl_opsstruct. Thevideo_device->vfl_type andvideo_device->vfl_dir fields are used to disable ops that do not match the type/dir combination. E.g. VBI ops are disabled for non-VBI nodes, and output ops are disabled for a capture device. This makes it possible to provide just onev4l2_ioctl_opsstruct for both vbi and video nodes. -
video_device->lock: leave toNULLif you want to do all the locking in the driver. Otherwise you give it a pointer to a structmutex_lockand before thevideo_device->unlocked_ioctl file operation is called this lock will be taken by the core and released afterwards. See the next section for more details. -
video_device->queue: a pointer to the struct vb2_queue associated with this device node. If queue is notNULL, and queue->lock is notNULL, then queue->lock is used for the queuing ioctls (VIDIOC_REQBUFS,CREATE_BUFS,QBUF,DQBUF,QUERYBUF,PREPARE_BUF,STREAMONandSTREAMOFF) instead of the lock above. That way the vb2 queuing framework does not have to wait for other ioctls. This queue pointer is also used by the vb2 helper functions to check for queuing ownership (i.e. is the filehandle calling it allowed to do the operation). -
video_device->prio: keeps track of the priorities. Used to implementVIDIOC_G_PRIORITYandVIDIOC_S_PRIORITY. If left toNULL, then it will use the struct v4l2_prio_state inv4l2_device. If you want to have a separate priority state per (group of) device node(s), then you can point it to your own structv4l2_prio_state. -
video_device->dev_parent: you only set this if v4l2_device was registered withNULLas the parentdevicestruct. This only happens in cases where one hardware device has multiple PCI devices that all share the samev4l2_devicecore.The cx88 driver is an example of this: one core
v4l2_devicestruct, but it is used by both a raw video PCI device (cx8800) and a MPEG PCI device (cx8802). Since thev4l2_devicecannot be associated with two PCI devices at the same time it is setup without a parent device. But when the struct video_device is initialized you do know which parent PCI device to use and so you setdev_deviceto the correct PCI device.
If you use v4l2_ioctl_ops, then you should set video_device->unlocked_ioctl to video_ioctl2() in your v4l2_file_operations struct.
In some cases you want to tell the core that a function you had specified in your v4l2_ioctl_ops should be ignored. You can mark such ioctls by calling this function before video_register_device() is called:
v4l2_disable_ioctl <v4l2_disable_ioctl>()(vdev <video_device>, cmd).
This tends to be needed if based on external factors (e.g. which card is being used) you want to turns off certain features in v4l2_ioctl_ops without having to make a new struct.
The v4l2_file_operations struct is a subset of file_operations. The main difference is that the inode argument is omitted since it is never used.
If integration with the media framework is needed, you must initialize the media_entity struct embedded in the video_device struct (entity field) by calling media_entity_pads_init():
struct media_pad *pad = &my_vdev->pad;
int err;
err = ;
The pads array must have been previously initialized. There is no need to manually set the struct media_entity type and name fields.
A reference to the entity will be automatically acquired/released when the video device is opened/closed.
ioctls and locking #
The V4L core provides optional locking services. The main service is the lock field in struct video_device, which is a pointer to a mutex. If you set this pointer, then that will be used by unlocked_ioctl to serialize all ioctls.
If you are using the videobuf2 framework, then there is a second lock that you can set: video_device->queue->lock. If set, then this lock will be used instead of video_device->lock to serialize all queuing ioctls (see the previous section for the full list of those ioctls).
The advantage of using a different lock for the queuing ioctls is that for some drivers (particularly USB drivers) certain commands such as setting controls can take a long time, so you want to use a separate lock for the buffer queuing ioctls. That way your VIDIOC_DQBUF doesn't stall because the driver is busy changing the e.g. exposure of the webcam.
Of course, you can always do all the locking yourself by leaving both lock pointers at NULL.
In the case of videobuf2 you must set the queue->lock pointer to the lock you use to serialize the queuing ioctls. This ensures that that lock is released while waiting in VIDIOC_DQBUF for a buffer to arrive, and it is retaken afterwards.
The implementation of a hotplug disconnect should also take the lock from video_device before calling v4l2_device_disconnect. If you are also using video_device->queue->lock, then you have to first lock video_device->queue->lock followed by video_device->lock. That way you can be sure no ioctl is running when you call v4l2_device_disconnect().
Video device registration #
Next you register the video device with video_register_device(). This will create the character device for you.
err = ;
if
If the v4l2_device parent device has a not NULL mdev field, the video device entity will be automatically registered with the media device.
Which device is registered depends on the type argument. The following types exist:
|
|
Device name |
Usage |
|---|---|---|
|
|
|
for video input/output devices |
|
|
|
for vertical blank data (i.e. closed captions, teletext) |
|
|
|
for radio tuners |
|
|
|
for V4L2 subdevices |
|
|
|
for Software Defined Radio (SDR) tuners |
|
|
|
for touch sensors |
The last argument gives you a certain amount of control over the device node number used (i.e. the X in videoX). Normally you will pass -1 to let the v4l2 framework pick the first free number. But sometimes users want to select a specific node number. It is common that drivers allow the user to select a specific device node number through a driver module option. That number is then passed to this function and video_register_device will attempt to select that device node number. If that number was already in use, then the next free device node number will be selected and it will send a warning to the kernel log.
Another use-case is if a driver creates many devices. In that case it can be useful to place different video devices in separate ranges. For example, video capture devices start at 0, video output devices start at 16. So you can use the last argument to specify a minimum device node number and the v4l2 framework will try to pick the first free number that is equal or higher to what you passed. If that fails, then it will just pick the first free number.
Since in this case you do not care about a warning about not being able to select the specified device node number, you can call the function video_register_device_no_warn() instead.
Whenever a device node is created some attributes are also created for you. If you look in /sys/class/video4linux you see the devices. Go into e.g. video0 and you will see 'name', 'dev_debug' and 'index' attributes. The 'name' attribute is the 'name' field of the video_device struct. The 'dev_debug' attribute can be used to enable core debugging. See the next section for more detailed information on this.
The 'index' attribute is the index of the device node: for each call to video_register_device() the index is just increased by 1. The first video device node you register always starts with index 0.
Users can setup udev rules that utilize the index attribute to make fancy device names (e.g. 'mpegX' for MPEG video capture device nodes).
After the device was successfully registered, then you can use these fields:
-
video_device->vfl_type: the device type passed tovideo_register_device(). -
video_device->minor: the assigned device minor number. -
video_device->num: the device node number (i.e. the X invideoX). -
video_device->index: the device index number.
If the registration failed, then you need to call video_device_release() to free the allocated video_device struct, or free your own struct if the video_device was embedded in it. The vdev->release() callback will never be called if the registration failed, nor should you ever attempt to unregister the device if the registration failed.
video device debugging #
The 'dev_debug' attribute that is created for each video, vbi, radio or swradio device in /sys/class/video4linux/<devX>/ allows you to enable logging of file operations.
It is a bitmask and the following bits can be set:
|
Mask |
Description |
|---|---|
|
0x01 |
Log the ioctl name and error code. VIDIOC_(D)QBUF ioctls are only logged if bit 0x08 is also set. |
|
0x02 |
Log the ioctl name arguments and error code. VIDIOC_(D)QBUF ioctls are only logged if bit 0x08 is also set. |
|
0x04 |
Log the file operations open, release, read, write, mmap and get_unmapped_area. The read and write operations are only logged if bit 0x08 is also set. |
|
0x08 |
Log the read and write file operations and the VIDIOC_QBUF and VIDIOC_DQBUF ioctls. |
|
0x10 |
Log the poll file operation. |
|
0x20 |
Log error and messages in the control operations. |
Video device cleanup #
When the video device nodes have to be removed, either during the unload of the driver or because the USB device was disconnected, then you should unregister them with:
video_unregister_device()(vdev <video_device>);
This will remove the device nodes from sysfs (causing udev to remove them from /dev).
After video_unregister_device() returns no new opens can be done. However, in the case of USB devices some application might still have one of these device nodes open. So after the unregister all file operations (except release, of course) will return an error as well.
When the last user of the video device node exits, then the vdev->release() callback is called and you can do the final cleanup there.
Don't forget to cleanup the media entity associated with the video device if it has been initialized:
media_entity_cleanup <media_entity_cleanup>()(&vdev->entity);
This can be done from the release callback.
helper functions #
There are a few useful helper functions:
- file and
video_deviceprivate data
You can set/get driver private data in the video_device struct using:
video_get_drvdata <video_get_drvdata>()(vdev <video_device>);
video_set_drvdata <video_set_drvdata>()(vdev <video_device>);
Note that you can safely call video_set_drvdata() before calling video_register_device().
And this function:
video_devdata <video_devdata>()(struct file *file);
returns the video_device belonging to the file struct.
The video_devdata() function combines video_get_drvdata() with video_devdata():
video_drvdata <video_drvdata>()(struct file *file);
You can go from a video_device struct to the v4l2_device struct using:
struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
- Device node name
The video_device node kernel name can be retrieved using:
video_device_node_name <video_device_node_name>()(vdev <video_device>);
The name is used as a hint by userspace tools such as udev. The function should be used where possible instead of accessing the video_device::num and video_device::minor fields.
video_device functions and data structures #
enum vfl_devnode_type #
type of V4L2 device node
Constants
VFL_TYPE_VIDEO: for video input/output devicesVFL_TYPE_VBI: for vertical blank data (i.e. closed captions, teletext)VFL_TYPE_RADIO: for radio tunersVFL_TYPE_SUBDEV: for V4L2 subdevicesVFL_TYPE_SDR: for Software Defined Radio tunersVFL_TYPE_TOUCH: for touch sensorsVFL_TYPE_MAX: number of VFL types, must always be last in the enum
enum vfl_devnode_direction #
Identifies if a struct video_device corresponds to a receiver, a transmitter or a mem-to-mem device.
Constants
VFL_DIR_RX: device is a receiver.VFL_DIR_TX: device is a transmitter.VFL_DIR_M2M: device is a memory to memory device.
Note
Ignored if enum vfl_devnode_type is VFL_TYPE_SUBDEV.
enum v4l2_video_device_flags #
Flags used by struct video_device
Constants
V4L2_FL_REGISTERED: indicates that astruct video_deviceis registered. Drivers can clear this flag if they want to block all future device access. It is cleared by video_unregister_device.V4L2_FL_USES_V4L2_FH: indicates that file->private_data points tostruct v4l2_fh. This flag is set by the core whenv4l2_fh_init()is called. All drivers must use it.V4L2_FL_QUIRK_INVERTED_CROP: some old M2M drivers use g/s_crop/cropcap incorrectly: crop and compose are swapped. If this flag is set, then the selection targets are swapped in the g/s_crop/cropcap functions in v4l2-ioctl.c. This allows those drivers to correctly implement the selection API, but the old crop API will still work as expected in order to preserve backwards compatibility. Never set this flag for new drivers.V4L2_FL_SUBDEV_RO_DEVNODE: indicates that the video device node is registered in read-only mode. The flag only applies to device nodes registered for sub-devices, it is set by the core when the sub-devices device nodes are registered withv4l2_device_register_ro_subdev_nodes()and used by the sub-device ioctl handler to restrict access to some ioctl calls.
struct v4l2_prio_state #
stores the priority states
Definition
;
Members
prios: array with elements to store the array priorities
Description
v4l2_prio_init() #
void initializes a struct v4l2_prio_state
Parameters
struct v4l2_prio_state *global: pointer tostruct v4l2_prio_state
v4l2_prio_change() #
int changes the v4l2 file handler priority
Parameters
struct v4l2_prio_state *global: pointer to thestruct v4l2_prio_stateof the device node.enum v4l2_priority *local: pointer to the desired priority, as defined by enumv4l2_priorityenum v4l2_priority new: Priority type requested, as defined by enumv4l2_priority.
Description
v4l2_prio_open() #
void Implements the priority logic for a file handler open
Parameters
struct v4l2_prio_state *global: pointer to thestruct v4l2_prio_stateof the device node.enum v4l2_priority *local: pointer to the desired priority, as defined by enumv4l2_priority
Description
v4l2_prio_close() #
void Implements the priority logic for a file handler close
Parameters
struct v4l2_prio_state *global: pointer to thestruct v4l2_prio_stateof the device node.enum v4l2_priority local: priority to be released, as defined by enumv4l2_priority
Description
v4l2_prio_max() #
enum v4l2_priority Return the maximum priority, as stored at the global array.
Parameters
struct v4l2_prio_state *global: pointer to thestruct v4l2_prio_stateof the device node.
Description
v4l2_prio_check() #
int Implements the priority logic for a file handler close
Parameters
struct v4l2_prio_state *global: pointer to thestruct v4l2_prio_stateof the device node.enum v4l2_priority local: desired priority, as defined by enumv4l2_prioritylocal
Description
struct v4l2_file_operations #
fs operations used by a V4L2 device
Definition
;
Members
owner: pointer to struct moduleread: operations needed to implement theread()syscallwrite: operations needed to implement thewrite()syscallpoll: operations needed to implement thepoll()syscallunlocked_ioctl: operations needed to implement theioctl()syscallcompat_ioctl32: operations needed to implement theioctl()syscall for the special case where the Kernel uses 64 bits instructions, but the userspace uses 32 bits.get_unmapped_area: called by themmap()syscall, used when %!CONFIG_MMUmmap: operations needed to implement themmap()syscallopen: operations needed to implement theopen()syscallrelease: operations needed to implement therelease()syscall
Description
struct video_device #
Structure used to create and manage the V4L2 device nodes.
Definition
;
Members
entity:struct media_entityintf_devnode: pointer tostruct media_intf_devnodepipe:struct media_pipelinefops: pointer tostruct v4l2_file_operationsfor the video devicedevice_caps: device capabilities as used in v4l2_capabilitiesdev:struct devicefor the video devicecdev: character devicev4l2_dev: pointer tostruct v4l2_deviceparentdev_parent: pointer tostruct deviceparentctrl_handler: Control handler associated with this device node. May be NULL.queue:struct vb2_queueassociated with this device node. May be NULL.prio: pointer tostruct v4l2_prio_statewith device's Priority state. If NULL, then v4l2_dev->prio will be used.name: video device namevfl_type: V4L device type, as defined byenum vfl_devnode_typevfl_dir: V4L receiver, transmitter or m2mminor: device node 'minor'. It is set to -1 if the registration failednum: number of the video device nodeflags: video device flags. Use bitops to set/clear/test flags. Contains a set ofenum v4l2_video_device_flags.index: attribute to differentiate multiple indices on one physical devicefh_lock: Lock for all v4l2_fhsfh_list: List ofstruct v4l2_fhdev_debug: Internal device debug flags, not for use by driverstvnorms: Supported tv normsrelease: video devicerelease()callbackioctl_ops: pointer tostruct v4l2_ioctl_opswith ioctl callbacksvalid_ioctls: bitmap with the valid ioctls for this devicelock: pointer tostruct mutexserialization lock
Description
media_entity_to_video_device() #
Returns a struct video_device from the struct media_entity embedded on it.
Parameters
__entity: pointer tostruct media_entity, may be NULL
to_video_device() #
Returns a struct video_device from the struct device embedded on it.
Parameters
cd: pointer tostruct device
__video_register_device() #
int register video4linux devices
Parameters
struct video_device *vdev: struct video_device to registerenum vfl_devnode_type type: type of device to register, as defined byenum vfl_devnode_typeint nr: which device node number is desired: (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)int warn_if_nr_in_use: warn if the desired device node number was already in use and another number was chosen instead.struct module *owner: module that owns the video device node
Description
The registration code assigns minor numbers and device node numbers based on the requested type and registers the new device node with the kernel.
This function assumes that struct video_device was zeroed when it was allocated and does not contain any stale date.
An error is returned if no free minor or device node number could be found, or if the registration of the device node failed.
Returns 0 on success.
video_register_device() #
int register video4linux devices
Parameters
struct video_device *vdev: struct video_device to registerenum vfl_devnode_type type: type of device to register, as defined byenum vfl_devnode_typeint nr: which device node number is desired: (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)
Description
Internally, it calls __video_register_device(). Please see its
documentation for more details.
video_register_device_no_warn() #
int register video4linux devices
Parameters
struct video_device *vdev: struct video_device to registerenum vfl_devnode_type type: type of device to register, as defined byenum vfl_devnode_typeint nr: which device node number is desired: (0 == /dev/video0, 1 == /dev/video1, ..., -1 == first free)
Description
This function is identical to video_register_device() except that no
warning is issued if the desired device node number was already in use.
Internally, it calls __video_register_device(). Please see its
documentation for more details.
video_unregister_device() #
void Unregister video devices.
Parameters
struct video_device *vdev:struct video_deviceto register
Description
Does nothing if vdev == NULL or if video_is_registered() returns false.
video_device_alloc() #
struct video_device * helper function to alloc struct video_device
Parameters
void: no arguments
Description
Returns NULL if -ENOMEM or a struct video_device on success.
video_device_release() #
void helper function to release struct video_device
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
Can also be used for video_device->release().
video_device_release_empty() #
void helper function to implement the video_device->release() callback.
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
This release function does nothing.
It should be used when the video_device is a static global struct.
v4l2_disable_ioctl() #
void mark that a given command isn't implemented. shouldn't use core locking
Parameters
struct video_device *vdev: pointer tostruct video_deviceunsigned int cmd: ioctl command
Description
This function allows drivers to provide just one v4l2_ioctl_ops struct, but disable ioctls based on the specific card that is actually found.
video_get_drvdata() #
void * gets private data from struct video_device.
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
returns a pointer to the private data
video_set_drvdata() #
void sets private data from struct video_device.
Parameters
struct video_device *vdev: pointer tostruct video_devicevoid *data: private data pointer
video_devdata() #
struct video_device * gets struct video_device from struct file.
Parameters
struct file *file: pointer to struct file
video_drvdata() #
void * gets private data from struct video_device using the struct file.
Parameters
struct file *file: pointer to struct file
Description
This is function combines both video_get_drvdata() and video_devdata()
as this is used very often.
video_device_node_name() #
const char * returns the video device name
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
Returns the device name string
video_is_registered() #
int returns true if the struct video_device is registered.
Parameters
struct video_device *vdev: pointer tostruct video_device
v4l2_debugfs_root() #
struct dentry * returns the dentry of the top-level "v4l2" debugfs dir
Parameters
void: no arguments
Description
If this directory does not yet exist, then it will be created.
video_device_pipeline_start() #
int Mark a pipeline as streaming
Parameters
struct video_device *vdev: Starting video devicestruct media_pipeline *pipe: Media pipeline to be assigned to all entities in the pipeline.
Description
Mark all entities connected to a given video device through enabled links, either directly or indirectly, as streaming. The given pipeline object is assigned to every pad in the pipeline and stored in the media_pad pipe field.
Calls to this function can be nested, in which case the same number of
video_device_pipeline_stop() calls will be required to stop streaming. The
pipeline pointer must be identical for all nested calls to
video_device_pipeline_start().
The video device must contain a single pad.
This is a convenience wrapper around media_pipeline_start().
__video_device_pipeline_start() #
int Mark a pipeline as streaming
Parameters
struct video_device *vdev: Starting video devicestruct media_pipeline *pipe: Media pipeline to be assigned to all entities in the pipeline.
Description
..note:: This is the non-locking version of video_device_pipeline_start()
The video device must contain a single pad.
This is a convenience wrapper around __media_pipeline_start().
video_device_pipeline_stop() #
void Mark a pipeline as not streaming
Parameters
struct video_device *vdev: Starting video device
Description
Mark all entities connected to a given video device through enabled links,
either directly or indirectly, as not streaming. The media_pad pipe field
is reset to NULL.
If multiple calls to media_pipeline_start() have been made, the same
number of calls to this function are required to mark the pipeline as not
streaming.
The video device must contain a single pad.
This is a convenience wrapper around media_pipeline_stop().
__video_device_pipeline_stop() #
void Mark a pipeline as not streaming
Parameters
struct video_device *vdev: Starting video device
Description
The video device must contain a single pad.
This is a convenience wrapper around __media_pipeline_stop().
video_device_pipeline_alloc_start() #
int Mark a pipeline as streaming
Parameters
struct video_device *vdev: Starting video device
Description
video_device_pipeline_alloc_start() is similar to video_device_pipeline_start()
but instead of working on a given pipeline the function will use an
existing pipeline if the video device is already part of a pipeline, or
allocate a new pipeline.
Calls to video_device_pipeline_alloc_start() must be matched with
video_device_pipeline_stop().
video_device_pipeline() #
struct media_pipeline * Get the media pipeline a video device is part of
Parameters
struct video_device *vdev: The video device
Description
This function returns the media pipeline that a video device has been
associated with when constructing the pipeline with
video_device_pipeline_start(). The pointer remains valid until
video_device_pipeline_stop() is called.
The video device must contain a single pad.
This is a convenience wrapper around media_entity_pipeline().
Return
The media_pipeline the video device is part of, or NULL if the video device is not part of any pipeline.
V4L2 device instance
Peios Kernel / Hardware and drivers / Driver development / Media devices
Each device instance is represented by a struct v4l2_device. Very simple devices can just allocate this struct, but most of the time you would embed this struct inside a larger struct.
You must register the device instance by calling:
v4l2_device_register <v4l2_device_register>()(dev,v4l2_dev <v4l2_device>).
Registration will initialize the v4l2_device struct. If the dev->driver_data field is NULL, it will be linked to v4l2_dev <v4l2_device> argument.
Drivers that want integration with the media device framework need to set dev->driver_data manually to point to the driver-specific device structure that embed the struct v4l2_device instance. This is achieved by a dev_set_drvdata() call before registering the V4L2 device instance. They must also set the struct v4l2_device mdev field to point to a properly initialized and registered media_device instance.
If v4l2_dev <v4l2_device>->name is empty then it will be set to a value derived from dev (driver name followed by the bus_id, to be precise). If you set it up before calling v4l2_device_register() then it will be untouched. If dev is NULL, then you must setup v4l2_dev <v4l2_device>->name before calling v4l2_device_register().
You can use v4l2_device_set_name() to set the name based on a driver name and a driver-global atomic_t instance. This will generate names like ivtv0, ivtv1, etc. If the name ends with a digit, then it will insert a dash: cx18-0, cx18-1, etc. This function returns the instance number.
The first dev argument is normally the struct device pointer of a pci_dev, usb_interface or platform_device. It is rare for dev to be NULL, but it happens with ISA devices or when one device creates multiple PCI devices, thus making it impossible to associate v4l2_dev <v4l2_device> with a particular parent.
You can also supply a notify() callback that can be called by sub-devices to notify you of events. Whether you need to set this depends on the sub-device. Any notifications a sub-device supports must be defined in a header in include/media/subdevice.h.
V4L2 devices are unregistered by calling:
v4l2_device_unregister()(v4l2_dev <v4l2_device>).
If the dev->driver_data field points to v4l2_dev <v4l2_device>, it will be reset to NULL. Unregistering will also automatically unregister all subdevs from the device.
If you have a hotpluggable device (e.g. a USB device), then when a disconnect happens the parent device becomes invalid. Since v4l2_device has a pointer to that parent device it has to be cleared as well to mark that the parent is gone. To do this call:
v4l2_device_disconnect()(v4l2_dev <v4l2_device>).
This does not unregister the subdevs, so you still need to call the v4l2_device_unregister() function for that. If your driver is not hotpluggable, then there is no need to call v4l2_device_disconnect().
Sometimes you need to iterate over all devices registered by a specific driver. This is usually the case if multiple device drivers use the same hardware. E.g. the ivtvfb driver is a framebuffer driver that uses the ivtv hardware. The same is true for alsa drivers for example.
You can iterate over all registered devices as follows:
static int
int
Sometimes you need to keep a running counter of the device instance. This is commonly used to map a device instance to an index of a module option array.
The recommended approach is as follows:
static atomic_t drv_instance = ;
static int
If you have multiple device nodes then it can be difficult to know when it is safe to unregister v4l2_device for hotpluggable devices. For this purpose v4l2_device has refcounting support. The refcount is increased whenever video_register_device() is called and it is decreased whenever that device node is released. When the refcount reaches zero, then the v4l2_device release() callback is called. You can do your final cleanup there.
If other device nodes (e.g. ALSA) are created, then you can increase and decrease the refcount manually as well by calling:
v4l2_device_get()(v4l2_dev <v4l2_device>).
or:
v4l2_device_put()(v4l2_dev <v4l2_device>).
Since the initial refcount is 1 you also need to call v4l2_device_put() in the disconnect() callback (for USB devices) or in the remove() callback (for e.g. PCI devices), otherwise the refcount will never reach 0.
v4l2_device functions and data structures #
struct v4l2_device #
main struct to for V4L2 device drivers
Definition
;
Members
dev: pointer to struct device.mdev: pointer to struct media_device, may be NULL.subdevs: used to keep track of the registered subdevslock: lock this struct; can be used by the driver as well if this struct is embedded into a larger struct.name: unique device name, by default the driver name + bus IDnotify: notify operation called by some sub-devices.ctrl_handler: The control handler. May beNULL.prio: Device's priority stateref: Keep track of the references to this struct.release: Release function that is called when the ref count goes to 0.
Description
Each instance of a V4L2 device should create the v4l2_device struct, either stand-alone or embedded in a larger struct.
It allows easy access to sub-devices (see v4l2-subdev.h) and provides basic V4L2 device-level support.
v4l2_device_get() #
void gets a V4L2 device reference
Parameters
struct v4l2_device *v4l2_dev: pointer to structv4l2_device
Description
This is an ancillary routine meant to increment the usage for the
struct v4l2_device pointed by v4l2_dev.
v4l2_device_put() #
int puts a V4L2 device reference
Parameters
struct v4l2_device *v4l2_dev: pointer to structv4l2_device
Description
This is an ancillary routine meant to decrement the usage for the
struct v4l2_device pointed by v4l2_dev.
v4l2_device_register() #
int Initialize v4l2_dev and make dev->driver_data point to v4l2_dev.
Parameters
struct device *dev: pointer to structdevicestruct v4l2_device *v4l2_dev: pointer to structv4l2_device
Description
v4l2_device_set_name() #
int Optional function to initialize the name field of struct v4l2_device
Parameters
struct v4l2_device *v4l2_dev: pointer to structv4l2_deviceconst char *basename: base name for the device nameatomic_t *instance: pointer to a static atomic_t var with the instance usage for the device driver.
Description
v4l2_device_set_name() initializes the name field of struct v4l2_device
using the driver name and a driver-global atomic_t instance.
This function will increment the instance counter and returns the instance value used in the name.
Example
static atomic_t drv_instance = ATOMIC_INIT(0);
...
instance = v4l2_device_set_name(&\ v4l2_dev, "foo", &\ drv_instance);
The first time this is called the name field will be set to foo0 and this function returns 0. If the name ends with a digit (e.g. cx18), then the name will be set to cx18-0 since cx180 would look really odd.
v4l2_device_disconnect() #
void Change V4L2 device state to disconnected.
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_device
Description
Should be called when the USB parent disconnects. Since the parent disappears, this ensures that v4l2_dev doesn't have an invalid parent pointer.
v4l2_device_unregister() #
void Unregister all sub-devices and any other resources related to v4l2_dev.
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_device
v4l2_device_register_subdev() #
Registers a subdev with a v4l2 device.
Parameters
v4l2_dev: pointer to structv4l2_devicesd: pointer tostruct v4l2_subdev
Description
While registered, the subdev module is marked as in-use.
An error is returned if the module is no longer loaded on any attempts to register it.
v4l2_device_unregister_subdev() #
void Unregisters a subdev with a v4l2 device.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
Description
__v4l2_device_register_subdev_nodes() #
int Registers device nodes for all subdevs of the v4l2 device that are marked with the V4L2_SUBDEV_FL_HAS_DEVNODE flag.
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_devicebool read_only: subdevices read-only flag. True to register the subdevices device nodes in read-only mode, false to allow full access to the subdevice userspace API.
v4l2_device_register_subdev_nodes() #
int Registers subdevices device nodes with unrestricted access to the subdevice userspace operations
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_device
Description
Internally calls __v4l2_device_register_subdev_nodes(). See its documentation
for more details.
v4l2_device_register_ro_subdev_nodes() #
int Registers subdevices device nodes in read-only mode
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_device
Description
Internally calls __v4l2_device_register_subdev_nodes(). See its documentation
for more details.
v4l2_subdev_notify() #
void Sends a notification to v4l2_device.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevunsigned int notification: type of notification. Please notice that the notification type is driver-specific.void *arg: arguments for the notification. Those are specific to each notification type.
v4l2_device_supports_requests() #
bool Test if requests are supported.
Parameters
struct v4l2_device *v4l2_dev: pointer to struct v4l2_device
v4l2_device_for_each_subdev() #
Helper macro that interates over all sub-devices of a given v4l2_device.
Parameters
sd: pointer that will be filled by the macro with allstruct v4l2_subdevpointer used as an iterator by the loop.v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.
Description
This macro iterates over all sub-devices owned by the v4l2_dev device. It acts as a for loop iterator and executes the next statement with the sd variable pointing to each sub-device in turn.
__v4l2_device_call_subdevs_p() #
Calls the specified operation for all subdevs matching the condition.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.sd: pointer that will be filled by the macro with allstruct v4l2_subdevpointer used as an iterator by the loop.cond: condition to be matcho: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
Ignore any errors.
Note
subdevs cannot be added or deleted while walking the subdevs list.
__v4l2_device_call_subdevs() #
Calls the specified operation for all subdevs matching the condition.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.cond: condition to be matcho: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
Ignore any errors.
Note
subdevs cannot be added or deleted while walking the subdevs list.
__v4l2_device_call_subdevs_until_err_p() #
Calls the specified operation for all subdevs matching the condition.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.sd: pointer that will be filled by the macro with allstruct v4l2_subdevsub-devices associated with v4l2_dev.cond: condition to be matcho: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
If the operation returns an error other than 0 or -ENOIOCTLCMD
for any subdevice, then abort and return with that error code, zero
otherwise.
Note
subdevs cannot be added or deleted while walking the subdevs list.
__v4l2_device_call_subdevs_until_err() #
Calls the specified operation for all subdevs matching the condition.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.cond: condition to be matcho: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
If the operation returns an error other than 0 or -ENOIOCTLCMD
for any subdevice, then abort and return with that error code,
zero otherwise.
Note
subdevs cannot be added or deleted while walking the subdevs list.
v4l2_device_call_all() #
Calls the specified operation for all subdevs matching the v4l2_subdev.grp_id, as assigned by the bridge driver.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpid:struct v4l2_subdev->grp_id group ID to match. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
Ignore any errors.
Note
subdevs cannot be added or deleted while walking the subdevs list.
v4l2_device_call_until_err() #
Calls the specified operation for all subdevs matching the v4l2_subdev.grp_id, as assigned by the bridge driver, until an error occurs.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpid:struct v4l2_subdev->grp_id group ID to match. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
If the operation returns an error other than 0 or -ENOIOCTLCMD
for any subdevice, then abort and return with that error code,
zero otherwise.
Note
subdevs cannot be added or deleted while walking the subdevs list.
v4l2_device_mask_call_all() #
Calls the specified operation for all subdevices where a group ID matches a specified bitmask.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpmsk: bitmask to be checked againststruct v4l2_subdev->grp_id group ID to be matched. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
Ignore any errors.
Note
subdevs cannot be added or deleted while walking the subdevs list.
v4l2_device_mask_call_until_err() #
Calls the specified operation for all subdevices where a group ID matches a specified bitmask.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpmsk: bitmask to be checked againststruct v4l2_subdev->grp_id group ID to be matched. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
If the operation returns an error other than 0 or -ENOIOCTLCMD
for any subdevice, then abort and return with that error code,
zero otherwise.
Note
subdevs cannot be added or deleted while walking the subdevs list.
v4l2_device_has_op() #
checks if any subdev with matching grpid has a given ops.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpid:struct v4l2_subdev->grp_id group ID to match. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.
v4l2_device_mask_has_op() #
checks if any subdev with matching group mask has a given ops.
Parameters
v4l2_dev:struct v4l2_deviceowning the sub-devices to iterate over.grpmsk: bitmask to be checked againststruct v4l2_subdev->grp_id group ID to be matched. Use 0 to match them all.o: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of operations functions.f: operation function that will be called if cond matches. The operation functions are defined in groups, according to each element atstruct v4l2_subdev_ops.
V4L2 DV Timings functions
Peios Kernel / Hardware and drivers / Driver development / Media devices
v4l2_calc_timeperframe() #
struct v4l2_fract helper function to calculate timeperframe based v4l2_dv_timings fields.
Parameters
const struct v4l2_dv_timings *t: Timings for the video mode.
Description
Calculates the expected timeperframe using the pixel clock value and horizontal/vertical measures. This means that v4l2_dv_timings structure must be correctly and fully filled.
v4l2_check_dv_timings_fnc() #
typedef bool
timings check callback
Parameters
const struct v4l2_dv_timings *t: the v4l2_dv_timings struct.void *handle: a handle from the driver.
Description
Returns true if the given timings are valid.
v4l2_valid_dv_timings() #
bool are these timings valid?
Parameters
const struct v4l2_dv_timings *t: the v4l2_dv_timings struct.const struct v4l2_dv_timings_cap *cap: the v4l2_dv_timings_cap capabilities.v4l2_check_dv_timings_fnc fnc: callback to check if this timing is OK. May be NULL.void *fnc_handle: a handle that is passed on to fnc.
Description
Returns true if the given dv_timings struct is supported by the hardware capabilities and the callback function (if non-NULL), returns false otherwise.
v4l2_enum_dv_timings_cap() #
int Helper function to enumerate possible DV timings based on capabilities
Parameters
struct v4l2_enum_dv_timings *t: the v4l2_enum_dv_timings struct.const struct v4l2_dv_timings_cap *cap: the v4l2_dv_timings_cap capabilities.v4l2_check_dv_timings_fnc fnc: callback to check if this timing is OK. May be NULL.void *fnc_handle: a handle that is passed on to fnc.
Description
This enumerates dv_timings using the full list of possible CEA-861 and DMT timings, filtering out any timings that are not supported based on the hardware capabilities and the callback function (if non-NULL).
If a valid timing for the given index is found, it will fill in t and return 0, otherwise it returns -EINVAL.
v4l2_find_dv_timings_cap() #
bool Find the closest timings struct
Parameters
struct v4l2_dv_timings *t: the v4l2_enum_dv_timings struct.const struct v4l2_dv_timings_cap *cap: the v4l2_dv_timings_cap capabilities.unsigned pclock_delta: maximum delta between t->pixelclock and the timing struct under consideration.v4l2_check_dv_timings_fnc fnc: callback to check if a given timings struct is OK. May be NULL.void *fnc_handle: a handle that is passed on to fnc.
Description
This function tries to map the given timings to an entry in the full list of possible CEA-861 and DMT timings, filtering out any timings that are not supported based on the hardware capabilities and the callback function (if non-NULL).
On success it will fill in t with the found timings and it returns true. On failure it will return false.
v4l2_find_dv_timings_cea861_vic() #
bool find timings based on CEA-861 VIC
Parameters
struct v4l2_dv_timings *t: the timings data.u8 vic: CEA-861 VIC code
Description
On success it will fill in t with the found timings and it returns true. On failure it will return false.
v4l2_match_dv_timings() #
bool do two timings match?
Parameters
const struct v4l2_dv_timings *measured: the measured timings data.const struct v4l2_dv_timings *standard: the timings according to the standard.unsigned pclock_delta: maximum delta in Hz between standard->pixelclock and the measured timings.bool match_reduced_fps: if true, then fail if V4L2_DV_FL_REDUCED_FPS does not match.
Description
Returns true if the two timings match, returns false otherwise.
v4l2_print_dv_timings() #
void log the contents of a dv_timings struct
Parameters
const char *dev_prefix: device prefix for each log line.const char *prefix: additional prefix for each log line, may be NULL.const struct v4l2_dv_timings *t: the timings data.bool detailed: if true, give a detailed log.
v4l2_detect_cvt() #
bool detect if the given timings follow the CVT standard
Parameters
unsigned int frame_height: the total height of the frame (including blanking) in lines.unsigned int hfreq: the horizontal frequency in Hz.unsigned int vsync: the height of the vertical sync in lines.unsigned int active_width: active width of image (does not include blanking). This information is needed only in case of version 2 of reduced blanking. In other cases, this parameter does not have any effect on timings.u32 polarities: the horizontal and vertical polarities (same as struct v4l2_bt_timings polarities).bool interlaced: if this flag is true, it indicates interlaced formatconst struct v4l2_dv_timings_cap *cap: the v4l2_dv_timings_cap capabilities.struct v4l2_dv_timings *fmt: the resulting timings.
Description
This function will attempt to detect if the given values correspond to a valid CVT format. If so, then it will return true, and fmt will be filled in with the found CVT timings.
v4l2_detect_gtf() #
bool detect if the given timings follow the GTF standard
Parameters
unsigned int frame_height: the total height of the frame (including blanking) in lines.unsigned int hfreq: the horizontal frequency in Hz.unsigned int vsync: the height of the vertical sync in lines.u32 polarities: the horizontal and vertical polarities (same as struct v4l2_bt_timings polarities).bool interlaced: if this flag is true, it indicates interlaced formatstruct v4l2_fract aspect: preferred aspect ratio. GTF has no method of determining the aspect ratio in order to derive the image width from the image height, so it has to be passed explicitly. Usually the native screen aspect ratio is used for this. If it is not filled in correctly, then 16:9 will be assumed.const struct v4l2_dv_timings_cap *cap: the v4l2_dv_timings_cap capabilities.struct v4l2_dv_timings *fmt: the resulting timings.
Description
This function will attempt to detect if the given values correspond to a valid GTF format. If so, then it will return true, and fmt will be filled in with the found GTF timings.
v4l2_calc_aspect_ratio() #
struct v4l2_fract calculate the aspect ratio based on bytes 0x15 and 0x16 from the EDID.
Parameters
u8 hor_landscape: byte 0x15 from the EDID.u8 vert_portrait: byte 0x16 from the EDID.
Description
Determines the aspect ratio from the EDID. See VESA Enhanced EDID standard, release A, rev 2, section 3.6.2: "Horizontal and Vertical Screen Size or Aspect Ratio"
v4l2_dv_timings_aspect_ratio() #
struct v4l2_fract calculate the aspect ratio based on the v4l2_dv_timings information.
Parameters
const struct v4l2_dv_timings *t: the timings data.
can_reduce_fps() #
bool check if conditions for reduced fps are true.
Parameters
struct v4l2_bt_timings *bt: v4l2 timing structure
Description
For different timings reduced fps is allowed if the following conditions are met:
- For CVT timings: if reduced blanking v2 (vsync == 8) is true.
- For CEA861 timings: if
V4L2_DV_FL_CAN_REDUCE_FPSflag is true.
struct v4l2_hdmi_colorimetry #
describes the HDMI colorimetry information
Definition
;
Members
colorspace: enum v4l2_colorspace, the colorspaceycbcr_enc: enum v4l2_ycbcr_encoding, Y'CbCr encodingquantization: enum v4l2_quantization, colorspace quantizationxfer_func: enum v4l2_xfer_func, colorspace transfer function
V4L2 events
Peios Kernel / Hardware and drivers / Driver development / Media devices
The V4L2 events provide a generic way to pass events to user space. The driver must use v4l2_fh to be able to support V4L2 events.
Events are subscribed per-filehandle. An event specification consists of a type and is optionally associated with an object identified through the id field. If unused, then the id is 0. So an event is uniquely identified by the (type, id) tuple.
The v4l2_fh struct has a list of subscribed events on its subscribed field.
When the user subscribes to an event, a v4l2_subscribed_event struct is added to v4l2_fh.subscribed, one for every subscribed event.
Each v4l2_subscribed_event struct ends with a v4l2_kevent ringbuffer, with the size given by the caller of v4l2_event_subscribe(). This ringbuffer is used to store any events raised by the driver.
So every (type, ID) event tuple will have its own v4l2_kevent ringbuffer. This guarantees that if a driver is generating lots of events of one type in a short time, then that will not overwrite events of another type.
But if you get more events of one type than the size of the v4l2_kevent ringbuffer, then the oldest event will be dropped and the new one added.
The v4l2_kevent struct links into the available list of the v4l2_fh struct so vidioc_dqevent will know which event to dequeue first.
Finally, if the event subscription is associated with a particular object such as a V4L2 control, then that object needs to know about that as well so that an event can be raised by that object. So the node field can be used to link the v4l2_subscribed_event struct into a list of such objects.
So to summarize:
-
struct v4l2_fh has two lists: one of the
subscribedevents, and one of theavailableevents. -
struct v4l2_subscribed_event has a ringbuffer of raised (pending) events of that particular type.
-
If struct v4l2_subscribed_event is associated with a specific object, then that object will have an internal list of struct v4l2_subscribed_event so it knows who subscribed an event to that object.
Furthermore, the internal struct v4l2_subscribed_event has merge() and replace() callbacks which drivers can set. These callbacks are called when a new event is raised and there is no more room.
The replace() callback allows you to replace the payload of the old event with that of the new event, merging any relevant data from the old payload into the new payload that replaces it. It is called when this event type has a ringbuffer with size is one, i.e. only one event can be stored in the ringbuffer.
The merge() callback allows you to merge the oldest event payload into that of the second-oldest event payload. It is called when the ringbuffer has size is greater than one.
This way no status information is lost, just the intermediate steps leading up to that state.
A good example of these replace/merge callbacks is in v4l2-event.c: ctrls_replace() and ctrls_merge() callbacks for the control event.
In order to queue events to video device, drivers should call:
v4l2_event_queue <v4l2_event_queue>()(vdev <video_device>,ev <v4l2_event>)
The driver's only responsibility is to fill in the type and the data fields. The other fields will be filled in by V4L2.
Event subscription #
Subscribing to an event is via:
v4l2_event_subscribe <v4l2_event_subscribe>()(fh <v4l2_fh>,sub <v4l2_event_subscription>, elems,ops <v4l2_subscribed_event_ops>)
This function is used to implement video_device-> ioctl_ops <v4l2_ioctl_ops>-> vidioc_subscribe_event, but the driver must check first if the driver is able to produce events with specified event id, and then should call v4l2_event_subscribe() to subscribe the event.
The elems argument is the size of the event queue for this event. If it is 0, then the framework will fill in a default value (this depends on the event type).
The ops argument allows the driver to specify a number of callbacks:
|
Callback |
Description |
|---|---|
|
add |
called when a new listener gets added (subscribing to the same event twice will only cause this callback to get called once) |
|
del |
called when a listener stops listening |
|
replace |
replace event 'old' with event 'new'. |
|
merge |
merge event 'old' into event 'new'. |
All 4 callbacks are optional, if you don't want to specify any callbacks the ops argument itself maybe NULL.
Unsubscribing an event #
Unsubscribing to an event is via:
v4l2_event_unsubscribe <v4l2_event_unsubscribe>()(fh <v4l2_fh>,sub <v4l2_event_subscription>)
This function is used to implement video_device-> ioctl_ops <v4l2_ioctl_ops>-> vidioc_unsubscribe_event. A driver may call v4l2_event_unsubscribe() directly unless it wants to be involved in unsubscription process.
The special type V4L2_EVENT_ALL may be used to unsubscribe all events. The drivers may want to handle this in a special way.
Check if there's a pending event #
Checking if there's a pending event is via:
v4l2_event_pending <v4l2_event_pending>()(fh <v4l2_fh>)
This function returns the number of pending events. Useful when implementing poll.
How events work #
Events are delivered to user space through the poll system call. The driver can use v4l2_fh->wait (a wait_queue_head_t) as the argument for poll_wait().
There are standard and private events. New standard events must use the smallest available event type. The drivers must allocate their events from their own class starting from class base. Class base is V4L2_EVENT_PRIVATE_START + n * 1000 where n is the lowest available number. The first event type in the class is reserved for future use, so the first available event type is 'class base + 1'.
An example on how the V4L2 events may be used can be found in the OMAP 3 ISP driver (drivers/media/platform/ti/omap3isp).
A subdev can directly send an event to the v4l2_device notify function with V4L2_DEVICE_NOTIFY_EVENT. This allows the bridge to map the subdev that sends the event to the video node(s) associated with the subdev that need to be informed about such an event.
V4L2 event functions and data structures #
struct v4l2_kevent #
Internal kernel event struct.
Definition
;
Members
list: List node for the v4l2_fh->available list.sev: Pointer to parent v4l2_subscribed_event.event: The event itself.ts: The timestamp of the event.
struct v4l2_subscribed_event_ops #
Subscribed event operations.
Definition
;
Members
add: Optional callback, called when a new listener is addeddel: Optional callback, called when a listener stops listeningreplace: Optional callback that can replace event 'old' with event 'new'.merge: Optional callback that can merge event 'old' into event 'new'.
struct v4l2_subscribed_event #
Internal struct representing a subscribed event.
Definition
;
Members
list: List node for the v4l2_fh->subscribed list.type: Event type.id: Associated object ID (e.g. control ID). 0 if there isn't any.flags: Copy of v4l2_event_subscription->flags.fh: Filehandle that subscribed to this event.node: List node that hooks into the object's event list (if there is one).ops: v4l2_subscribed_event_opselems: The number of elements in the events array.first: The index of the events containing the oldest available event.in_use: The number of queued events.events: An array of elems events.
v4l2_event_dequeue() #
int Dequeue events from video device.
Parameters
struct v4l2_fh *fh: pointer to struct v4l2_fhstruct v4l2_event *event: pointer to struct v4l2_eventint nonblocking: if not zero, waits for an event to arrive
v4l2_event_queue() #
void Queue events to video device.
Parameters
struct video_device *vdev: pointer tostruct video_deviceconst struct v4l2_event *ev: pointer tostruct v4l2_event
Description
The event will be queued for all struct v4l2_fh file handlers.
v4l2_event_queue_fh() #
void Queue events to video device.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhconst struct v4l2_event *ev: pointer tostruct v4l2_event
Description
The event will be queued only for the specified struct v4l2_fh file handler.
v4l2_event_wake_all() #
void Wake all filehandles.
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
Used when unregistering a video device.
v4l2_event_pending() #
int Check if an event is available
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fh
Description
Returns the number of pending events.
v4l2_event_subscribe() #
int Subscribes to an event
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhconst struct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscriptionunsigned int elems: size of the events queueconst struct v4l2_subscribed_event_ops *ops: pointer tov4l2_subscribed_event_ops
Description
v4l2_event_unsubscribe() #
int Unsubscribes to an event
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhconst struct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
v4l2_event_unsubscribe_all() #
void Unsubscribes to all events
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fh
v4l2_event_subdev_unsubscribe() #
int Subdev variant of v4l2_event_unsubscribe()
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct v4l2_fh *fh: pointer tostruct v4l2_fhstruct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
Description
v4l2_src_change_event_subscribe() #
int helper function that calls v4l2_event_subscribe() if the event is V4L2_EVENT_SOURCE_CHANGE.
Parameters
struct v4l2_fh *fh: pointer to struct v4l2_fhconst struct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
v4l2_src_change_event_subdev_subscribe() #
int Variant of v4l2_event_subscribe(), meant to subscribe only events of the type V4L2_EVENT_SOURCE_CHANGE.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct v4l2_fh *fh: pointer tostruct v4l2_fhstruct v4l2_event_subscription *sub: pointer tostruct v4l2_event_subscription
V4L2 File handles
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct v4l2_fh provides a way to easily keep file handle specific data that is used by the V4L2 framework. Its usage is mandatory in all drivers.
struct v4l2_fh is allocated in the driver's open() file operation handler. It is typically embedded in a larger driver-specific structure. The v4l2_fh must be initialized with a call to v4l2_fh_init(), and added to the video device with v4l2_fh_add(). This associates the v4l2_fh with the file by setting file->private_data to point to the v4l2_fh.
Similarly, the struct v4l2_fh is freed in the driver's release() file operation handler. It must be removed from the video device with v4l2_fh_del() and cleaned up with v4l2_fh_exit() before being freed.
Drivers must not access file->private_data directly. They can retrieve the v4l2_fh associated with a file by calling file_to_v4l2_fh(). Drivers can extract their own file handle structure by using the container_of macro.
Example:
;
...
int
int
Below is a short description of the v4l2_fh functions used:
v4l2_fh_init <v4l2_fh_init>() (fh <v4l2_fh>, vdev <video_device>)
- Initialise the file handle. This MUST be performed in the driver's
v4l2_file_operations->open() handler.
v4l2_fh_add <v4l2_fh_add>() (fh <v4l2_fh>, struct file *filp)
- Add a
v4l2_fhtovideo_devicefile handle list. Must be called once the file handle is completely initialized.
v4l2_fh_del <v4l2_fh_del>() (fh <v4l2_fh>, struct file *filp)
- Unassociate the file handle from
video_device. The file handle exit function may now be called.
v4l2_fh_exit <v4l2_fh_exit>() (fh <v4l2_fh>)
- Uninitialise the file handle. After uninitialisation the
v4l2_fhmemory can be freed.
file_to_v4l2_fh <file_to_v4l2_fh>() (struct file *filp)
- Retrieve the
v4l2_fhinstance associated with afile.
If struct v4l2_fh is not embedded, then you can use these helper functions:
v4l2_fh_open <v4l2_fh_open>() (struct file *filp)
- This allocates a struct v4l2_fh, initializes it and adds it to the struct video_device associated with the file struct.
v4l2_fh_release <v4l2_fh_release>() (struct file *filp)
- This deletes it from the struct video_device associated with the file struct, uninitialised the
v4l2_fhand frees it.
These two functions can be plugged into the v4l2_file_operation's open() and release() ops.
Several drivers need to do something when the first file handle is opened and when the last file handle closes. Two helper functions were added to check whether the v4l2_fh struct is the only open filehandle of the associated device node:
v4l2_fh_is_singular <v4l2_fh_is_singular>() (fh <v4l2_fh>)
- Returns 1 if the file handle is the only open file handle, else 0.
v4l2_fh_is_singular_file <v4l2_fh_is_singular_file>() (struct file *filp)
- Same, but it calls v4l2_fh_is_singular with filp->private_data.
V4L2 fh functions and data structures #
struct v4l2_fh #
Describes a V4L2 file handler
Definition
;
Members
list: list of file handlersvdev: pointer tostruct video_devicectrl_handler: pointer tostruct v4l2_ctrl_handlerprio: priority of the file handler, as defined byenum v4l2_prioritywait: event' s wait queuesubscribe_lock: serialise changes to the subscribed list; guarantee that the add and del event callbacks are orderly calledsubscribed: list of subscribed eventsavailable: list of events waiting to be dequeuednavailable: number of available events at available listsequence: event sequence numberm2m_ctx: pointer tostruct v4l2_m2m_ctx
file_to_v4l2_fh() #
struct v4l2_fh * Return the v4l2_fh associated with a struct file
Parameters
struct file *filp: pointer tostruct file
Description
This function should be used by drivers to retrieve the struct v4l2_fh
instance pointer stored in the file private_data instead of accessing the
private_data field directly.
v4l2_fh_init() #
void Initialise the file handle.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhstruct video_device *vdev: pointer tostruct video_device
Description
Parts of the V4L2 framework using the
file handles should be initialised in this function. Must be called
from driver's v4l2_file_operations->open() handler if the driver
uses struct v4l2_fh.
v4l2_fh_add() #
void Add the fh to the list of file handles on a video_device.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhstruct file *filp: pointer tostruct fileassociated with fh
Description
The function sets filp->private_data to point to fh.
v4l2_fh_open() #
int Ancillary routine that can be used as the open() op of v4l2_file_operations.
Parameters
struct file *filp: pointer to struct file
Description
It allocates a v4l2_fh and inits and adds it to the struct video_device
associated with the file pointer.
On error filp->private_data will be NULL, otherwise it will point to
the struct v4l2_fh.
v4l2_fh_del() #
void Remove file handle from the list of file handles.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fhstruct file *filp: pointer tostruct fileassociated with fh
Description
The function resets filp->private_data to NULL.
v4l2_fh_exit() #
void Release resources related to a file handle.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fh
Description
Parts of the V4L2 framework using the v4l2_fh must release their resources here, too.
v4l2_fh_release() #
int Ancillary routine that can be used as the release() op of v4l2_file_operations.
Parameters
struct file *filp: pointer to struct file
Description
It deletes and exits the v4l2_fh associated with the file pointer and
frees it. It will do nothing if filp->private_data (the pointer to the
v4l2_fh struct) is NULL.
This function always returns 0.
v4l2_fh_is_singular() #
int Returns 1 if this filehandle is the only filehandle opened for the associated video_device.
Parameters
struct v4l2_fh *fh: pointer tostruct v4l2_fh
Description
If fh is NULL, then it returns 0.
v4l2_fh_is_singular_file() #
int Returns 1 if this filehandle is the only filehandle opened for the associated video_device.
Parameters
struct file *filp: pointer to struct file
Description
This is a helper function variant of v4l2_fh_is_singular() with uses
struct file as argument.
If filp->private_data is NULL, then it will return 0.
V4L2 flash functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct v4l2_flash_ctrl_data #
flash control initialization data, filled basing on the features declared by the LED flash class driver in the v4l2_flash_config
Definition
;
Members
config: initialization data for a controlcid: contains v4l2 flash control id if the config field was initialized, 0 otherwise
struct v4l2_flash_ops #
V4L2 flash operations
Definition
;
Members
external_strobe_set: Setup strobing the flash by hardware pin state assertion.intensity_to_led_brightness: Convert intensity to brightness in a device specific mannerled_brightness_to_intensity: convert brightness to intensity in a device specific manner.
struct v4l2_flash_config #
V4L2 Flash sub-device initialization data
Definition
;
Members
dev_name: the name of the media entity, unique in the systemintensity: non-flash strobe constraints for the LEDflash_faults: bitmask of flash faults that the LED flash class device can report; corresponding LED_FAULT* bit definitions are available in the header file <linux/led-class-flash.h>has_external_strobe: external strobe capability
struct v4l2_flash #
Flash sub-device context
Definition
;
Members
fled_cdev: LED flash class device controlled by this sub-deviceiled_cdev: LED class device representing indicator LED associated with the LED flash class deviceops: V4L2 specific flash opssd: V4L2 sub-devicehdl: flash controls handlerctrls: array of pointers to controls, whose values define the sub-device state
v4l2_subdev_to_v4l2_flash() #
struct v4l2_flash * Returns a struct v4l2_flash from the struct v4l2_subdev embedded on it.
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
v4l2_ctrl_to_v4l2_flash() #
struct v4l2_flash * Returns a struct v4l2_flash from the struct v4l2_ctrl embedded on it.
Parameters
struct v4l2_ctrl *c: pointer tostruct v4l2_ctrl
v4l2_flash_init() #
struct v4l2_flash * initialize V4L2 flash led sub-device
Parameters
struct device *dev: flash device, e.g. an I2C devicestruct fwnode_handle *fwn: fwnode_handle of the LED, may be NULL if the same as device'sstruct led_classdev_flash *fled_cdev: LED flash class device to wrapconst struct v4l2_flash_ops *ops: V4L2 Flash device opsstruct v4l2_flash_config *config: initialization data for V4L2 Flash sub-device
Description
Create V4L2 Flash sub-device wrapping given LED subsystem device. The ops pointer is stored by the V4L2 flash framework. No references are held to config nor its contents once this function has returned.
Return
A valid pointer, or, when an error occurs, the return
value is encoded using ERR_PTR(). Use IS_ERR() to check and
PTR_ERR() to obtain the numeric return value.
v4l2_flash_indicator_init() #
struct v4l2_flash * initialize V4L2 indicator sub-device
Parameters
struct device *dev: flash device, e.g. an I2C devicestruct fwnode_handle *fwn: fwnode_handle of the LED, may be NULL if the same as device'sstruct led_classdev *iled_cdev: LED flash class device representing the indicator LEDstruct v4l2_flash_config *config: initialization data for V4L2 Flash sub-device
Description
Create V4L2 Flash sub-device wrapping given LED subsystem device. The ops pointer is stored by the V4L2 flash framework. No references are held to config nor its contents once this function has returned.
Return
A valid pointer, or, when an error occurs, the return
value is encoded using ERR_PTR(). Use IS_ERR() to check and
PTR_ERR() to obtain the numeric return value.
v4l2_flash_release() #
void release V4L2 Flash sub-device
Parameters
struct v4l2_flash *v4l2_flash: the V4L2 Flash sub-device to release
Description
Release V4L2 Flash sub-device.
V4L2 fwnode kAPI
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct v4l2_fwnode_endpoint #
the endpoint data structure
Definition
;
Members
base: fwnode endpoint of the v4l2_fwnodebus_type: bus typebus: bus configuration data structurebus.parallel: embeddedstruct v4l2_mbus_config_parallel. Used if the bus is parallel.bus.mipi_csi1: embeddedstruct v4l2_mbus_config_mipi_csi1. Used if the bus is MIPI Alliance's Camera Serial Interface version 1 (MIPI CSI1) or Standard Mobile Imaging Architecture's Compact Camera Port 2 (SMIA CCP2).bus.mipi_csi2: embeddedstruct v4l2_mbus_config_mipi_csi2. Used if the bus is MIPI Alliance's Camera Serial Interface version 2 (MIPI CSI2).link_frequencies: array of supported link frequenciesnr_of_link_frequencies: number of elements in link_frequenccies array
V4L2_FWNODE_PROPERTY_UNSET #
identify a non initialized property
Description
All properties in struct v4l2_fwnode_device_properties are initialized
to this value.
enum v4l2_fwnode_orientation #
possible device orientation
Constants
V4L2_FWNODE_ORIENTATION_FRONT: device installed on the front sideV4L2_FWNODE_ORIENTATION_BACK: device installed on the back sideV4L2_FWNODE_ORIENTATION_EXTERNAL: device externally located
struct v4l2_fwnode_device_properties #
fwnode device properties
Definition
;
Members
orientation: device orientation. Seeenum v4l2_fwnode_orientationrotation: device rotation
struct v4l2_fwnode_link #
a link between two endpoints
Definition
;
Members
local_node: pointer to device_node of this endpointlocal_port: identifier of the port this endpoint belongs tolocal_id: identifier of the id this endpoint belongs toremote_node: pointer to device_node of the remote endpointremote_port: identifier of the port the remote endpoint belongs toremote_id: identifier of the id the remote endpoint belongs to
enum v4l2_connector_type #
connector type
Constants
V4L2_CONN_UNKNOWN: unknown connector type, no V4L2 connector configurationV4L2_CONN_COMPOSITE: analog composite connectorV4L2_CONN_SVIDEO: analog svideo connector
struct v4l2_connector_link #
connector link data structure
Definition
;
Members
head: structure to be used to add the link to thestruct v4l2_fwnode_connectorfwnode_link:struct v4l2_fwnode_linklink between the connector and the device the connector belongs to.
struct v4l2_fwnode_connector_analog #
analog connector data structure
Definition
;
Members
sdtv_stds: sdtv standards this connector supports, set to V4L2_STD_ALL if no restrictions are specified.
struct v4l2_fwnode_connector #
the connector data structure
Definition
;
Members
name: the connector device namelabel: optional connector labeltype: connector typelinks: list of all connectorstruct v4l2_connector_linklinksnr_of_links: total number of linksconnector: connector configurationconnector.analog: analog connector configurationstruct v4l2_fwnode_connector_analog
enum v4l2_fwnode_bus_type #
Video bus types defined by firmware properties
Constants
V4L2_FWNODE_BUS_TYPE_GUESS: Default value if no bus-type fwnode propertyV4L2_FWNODE_BUS_TYPE_CSI2_CPHY: MIPI CSI-2 bus, C-PHY physical layerV4L2_FWNODE_BUS_TYPE_CSI1: MIPI CSI-1 busV4L2_FWNODE_BUS_TYPE_CCP2: SMIA Compact Camera Port 2 busV4L2_FWNODE_BUS_TYPE_CSI2_DPHY: MIPI CSI-2 bus, D-PHY physical layerV4L2_FWNODE_BUS_TYPE_PARALLEL: Camera Parallel Interface busV4L2_FWNODE_BUS_TYPE_BT656: BT.656 video format bus-typeV4L2_FWNODE_BUS_TYPE_DPI: Video Parallel Interface busNR_OF_V4L2_FWNODE_BUS_TYPE: Number of bus-types
v4l2_fwnode_endpoint_parse() #
int parse all fwnode node properties
Parameters
struct fwnode_handle *fwnode: pointer to the endpoint's fwnode handle (may be NULL)struct v4l2_fwnode_endpoint *vep: pointer to the V4L2 fwnode data structure
Description
This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the vep.bus_type field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the enum v4l2_mbus_type types.
When vep.bus_type is V4L2_MBUS_UNKNOWN, the function will use the "bus-type" property to determine the type when it is available. The caller is responsible for validating the contents of vep.bus_type field after the call returns.
As a deprecated functionality to support older DT bindings without "bus-type" property for devices that support multiple types, if the "bus-type" property does not exist, the function will attempt to guess the type based on the endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW DRIVERS OR BINDINGS.
It is also possible to set vep.bus_type corresponding to an actual bus. In this case the function will only attempt to parse properties related to this bus, and it will return an error if the value of the "bus-type" property corresponds to a different bus.
The caller is required to initialise all fields of vep, either with explicitly values, or by zeroing them.
The function does not change the V4L2 fwnode endpoint state if it fails.
NOTE
This function does not parse "link-frequencies" property as its size is
not known in advance. Please use v4l2_fwnode_endpoint_alloc_parse() if you
need properties of variable size.
Return
0 on success or a negative error code on failure:
-ENOMEM on memory allocation failure
-EINVAL on parsing failure, including fwnode == NULL
-ENXIO on mismatching bus types
v4l2_fwnode_endpoint_free() #
void free the V4L2 fwnode acquired by v4l2_fwnode_endpoint_alloc_parse()
Parameters
struct v4l2_fwnode_endpoint *vep: the V4L2 fwnode the resources of which are to be released
Description
It is safe to call this function with NULL argument or on a V4L2 fwnode the parsing of which failed.
v4l2_fwnode_endpoint_alloc_parse() #
int parse all fwnode node properties
Parameters
struct fwnode_handle *fwnode: pointer to the endpoint's fwnode handle (may be NULL)struct v4l2_fwnode_endpoint *vep: pointer to the V4L2 fwnode data structure
Description
This function parses the V4L2 fwnode endpoint specific parameters from the
firmware. There are two ways to use this function, either by letting it
obtain the type of the bus (by setting the vep.bus_type field to
V4L2_MBUS_UNKNOWN) or specifying the bus type explicitly to one of the enum v4l2_mbus_type types.
When vep.bus_type is V4L2_MBUS_UNKNOWN, the function will use the "bus-type" property to determine the type when it is available. The caller is responsible for validating the contents of vep.bus_type field after the call returns.
As a deprecated functionality to support older DT bindings without "bus-type" property for devices that support multiple types, if the "bus-type" property does not exist, the function will attempt to guess the type based on the endpoint properties available. NEVER RELY ON GUESSING THE BUS TYPE IN NEW DRIVERS OR BINDINGS.
It is also possible to set vep.bus_type corresponding to an actual bus. In this case the function will only attempt to parse properties related to this bus, and it will return an error if the value of the "bus-type" property corresponds to a different bus.
The caller is required to initialise all fields of vep, either with explicitly values, or by zeroing them.
The function does not change the V4L2 fwnode endpoint state if it fails.
v4l2_fwnode_endpoint_alloc_parse() has two important differences to
v4l2_fwnode_endpoint_parse():
-
It also parses variable size data.
-
The memory it has allocated to store the variable size data must be freed using
v4l2_fwnode_endpoint_free()when no longer needed.
Return
0 on success or a negative error code on failure:
-ENOMEM on memory allocation failure
-EINVAL on parsing failure, including fwnode == NULL
-ENXIO on mismatching bus types
v4l2_fwnode_parse_link() #
int parse a link between two endpoints
Parameters
struct fwnode_handle *fwnode: pointer to the endpoint's fwnode at the local end of the linkstruct v4l2_fwnode_link *link: pointer to the V4L2 fwnode link data structure
Description
Fill the link structure with the local and remote nodes and port numbers. The local_node and remote_node fields are set to point to the local and remote port's parent nodes respectively (the port parent node being the parent node of the port node if that node isn't a 'ports' node, or the grand-parent node of the port node otherwise).
A reference is taken to both the local and remote nodes, the caller must use
v4l2_fwnode_put_link() to drop the references when done with the
link.
Return
0 on success, or -ENOLINK if the remote endpoint fwnode can't be found.
v4l2_fwnode_put_link() #
void drop references to nodes in a link
Parameters
struct v4l2_fwnode_link *link: pointer to the V4L2 fwnode link data structure
Description
Drop references to the local and remote nodes in the link. This function
must be called on every link parsed with v4l2_fwnode_parse_link().
v4l2_fwnode_connector_free() #
void free the V4L2 connector acquired memory
Parameters
struct v4l2_fwnode_connector *connector: the V4L2 connector resources of which are to be released
Description
Free all allocated memory and put all links acquired by
v4l2_fwnode_connector_parse() and v4l2_fwnode_connector_add_link().
It is safe to call this function with NULL argument or on a V4L2 connector the parsing of which failed.
v4l2_fwnode_connector_parse() #
int initialize the 'struct v4l2_fwnode_connector'
Parameters
struct fwnode_handle *fwnode: pointer to the subdev endpoint's fwnode handle where the connector is connected to or to the connector endpoint fwnode handle.struct v4l2_fwnode_connector *connector: pointer to the V4L2 fwnode connector data structure
Description
Fill the struct v4l2_fwnode_connector with the connector type, label and
all enum v4l2_connector_type specific connector data. The label is optional
so it is set to NULL if no one was found. The function initialize the links
to zero. Adding links to the connector is done by calling
v4l2_fwnode_connector_add_link().
The memory allocated for the label must be freed when no longer needed.
Freeing the memory is done by v4l2_fwnode_connector_free().
Return
0on success or a negative error code on failure:-EINVALif fwnode is invalid-ENOTCONNif connector type is unknown or connector device can't be found
v4l2_fwnode_connector_add_link() #
int add a link between a connector node and a v4l2-subdev node.
Parameters
struct fwnode_handle *fwnode: pointer to the subdev endpoint's fwnode handle where the connector is connected tostruct v4l2_fwnode_connector *connector: pointer to the V4L2 fwnode connector data structure
Description
Add a new struct v4l2_connector_link link to the
struct v4l2_fwnode_connector connector links list. The link local_node
points to the connector node, the remote_node to the host v4l2 (sub)dev.
The taken references to remote_node and local_node must be dropped and the
allocated memory must be freed when no longer needed. Both is done by calling
v4l2_fwnode_connector_free().
Return
0on success or a negative error code on failure:-EINVALif fwnode or connector is invalid or connector type is unknown-ENOMEMon link memory allocation failure-ENOTCONNif remote connector device can't be found-ENOLINKif link parsing between v4l2 (sub)dev and connector fails
v4l2_fwnode_device_parse() #
int parse fwnode device properties
Parameters
struct device *dev: pointer tostruct devicestruct v4l2_fwnode_device_properties *props: pointer tostruct v4l2_fwnode_device_propertieswhere to store the parsed properties values
Description
This function parses and validates the V4L2 fwnode device properties from the firmware interface, and fills the struct v4l2_fwnode_device_properties provided by the caller.
Return
% 0 on success
-EINVAL if a parsed property value is not valid
Introduction
Peios Kernel / Hardware and drivers / Driver development / Media devices
Introduction #
The V4L2 drivers tend to be very complex due to the complexity of the hardware: most devices have multiple ICs, export multiple device nodes in /dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input (IR) devices.
Especially the fact that V4L2 drivers have to setup supporting ICs to do audio/video muxing/encoding/decoding makes it more complex than most. Usually these ICs are connected to the main bridge driver through one or more I2C buses, but other buses can also be used. Such devices are called 'sub-devices'.
For a long time the framework was limited to the video_device struct for creating V4L device nodes and video_buf for handling the video buffers (note that this document does not discuss the video_buf framework).
This meant that all drivers had to do the setup of device instances and connecting to sub-devices themselves. Some of this is quite complicated to do right and many drivers never did do it correctly.
There is also a lot of common code that could never be refactored due to the lack of a framework.
So this framework sets up the basic building blocks that all drivers need and this same framework should make it much easier to refactor common code into utility functions shared by all drivers.
A good example to look at as a reference is the v4l2-pci-skeleton.c source that is available in samples/v4l/. It is a skeleton driver for a PCI capture card, and demonstrates how to use the V4L2 driver framework. It can be used as a template for real PCI video capture driver.
Structure of a V4L driver #
All drivers have the following structure:
-
A struct for each device instance containing the device state.
-
A way of initializing and commanding sub-devices (if any).
-
Creating V4L2 device nodes (/dev/videoX, /dev/vbiX and /dev/radioX) and keeping track of device-node specific data.
-
Filehandle-specific structs containing per-filehandle data;
-
video buffer handling.
This is a rough schematic of how it all relates:
device instances
|
+-sub-device instances
|
\-V4L2 device nodes
|
\-filehandle instances
Structure of the V4L2 framework #
The framework closely resembles the driver structure: it has a v4l2_device struct for the device instance data, a v4l2_subdev struct to refer to sub-device instances, the video_device struct stores V4L2 device node data and the v4l2_fh struct keeps track of filehandle instances.
The V4L2 framework also optionally integrates with the media framework. If a driver sets the struct v4l2_device mdev field, sub-devices and video nodes will automatically appear in the media framework as entities.
V4L2 generic ISP parameters and statistics support
Peios Kernel / Hardware and drivers / Driver development / Media devices
Design rationale #
ISP configuration parameters and statistics are processed and collected by drivers and exchanged with userspace through data types that usually reflect the ISP peripheral registers layout.
Each ISP driver defines its own metadata output format for parameters and a metadata capture format for statistics. The buffer layout is realized by a set of C structures that reflects the registers layout. The number and types of C structures is fixed by the format definition and becomes part of the Linux kernel uAPI/uABI interface.
Because of the hard requirement of backward compatibility when extending the user API/ABI interface, modifying an ISP driver capture or output metadata format after it has been accepted by mainline is very hard if not impossible.
It generally happens, in fact, that after the first accepted revision of an ISP driver the buffers layout need to be modified, either to support new hardware blocks, to fix bugs or to support different revisions of the hardware.
Each of these situations would require defining a new metadata format, making it really hard to maintain and extend drivers and requiring userspace to use the correct format depending on the kernel revision in use.
V4L2 ISP configuration parameters #
For these reasons, Video4Linux2 defines generic types for ISP configuration parameters and statistics. Drivers are still expected to define their own formats for their metadata output and capture nodes, but the buffers layout can be defined using the extensible and versioned types defined by include/uapi/linux/media/v4l2-isp.h.
Drivers are expected to provide the definitions of their supported ISP blocks and the expected maximum size of a buffer.
For driver developers a set of helper functions to assist them with validation of the buffer received from userspace is available in drivers/media/v4l2-core/v4l2-isp.c
V4L2 ISP support driver documentation #
v4l2_isp_params_buffer_size() #
Calculate size of v4l2_isp_params_buffer
Parameters
max_params_size: The total size of the ISP configuration blocks
Description
Users of the v4l2 extensible parameters will have differing sized data arrays depending on their specific parameter buffers. Drivers and userspace will need to be able to calculate the appropriate size of the struct to accommodate all ISP configuration blocks provided by the platform. This macro provides a convenient tool for the calculation.
v4l2_isp_params_validate_buffer_size() #
int Validate a V4L2 ISP buffer sizes
Parameters
struct device *dev: the driver's device pointerstruct vb2_buffer *vb: the videobuf2 buffersize_t max_size: the maximum allowed buffer size
Description
This function performs validation of the size of a V4L2 ISP parameters buffer before the driver can access the actual data buffer content.
After the sizes validation, drivers should copy the buffer content to a
kernel-only memory area to prevent userspace from modifying it,
before completing validation using v4l2_isp_params_validate_buffer().
The vb buffer as received from the vb2 .buf_prepare() operation is checked
against max_size and it's validated to be large enough to accommodate at
least one ISP configuration block.
struct v4l2_isp_params_block_type_info #
V4L2 ISP per-block-type info
Definition
;
Members
size: the block type expected size
Description
The v4l2_isp_params_block_type_info collects information of the ISP configuration block types for validation purposes. It currently only contains the expected block type size.
Drivers shall prepare a list of block type info, indexed by block type, one for each supported ISP block type and correctly populate them with the expected block type size.
v4l2_isp_params_validate_buffer() #
int Validate a V4L2 ISP parameters buffer
Parameters
struct device *dev: the driver's device pointerstruct vb2_buffer *vb: the videobuf2 bufferconst struct v4l2_isp_params_buffer *buffer: the V4L2 ISP parameters bufferconst struct v4l2_isp_params_block_type_info *type_info: the array of per-block-type validation infosize_t num_block_types: the number of block types in the type_info array
Description
This function completes the validation of a V4L2 ISP parameters buffer, verifying each configuration block correctness before the driver can use them to program the hardware.
Drivers should use this function after having validated the correctness of
the vb2 buffer sizes by using the v4l2_isp_params_validate_buffer_size()
helper first. Once the buffer size has been validated, drivers should
perform a copy of the user provided buffer into a kernel-only memory buffer
to prevent userspace from modifying its content after it has been submitted
to the driver, and then call this function to complete validation.
V4L2 JPEG header related functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct v4l2_jpeg_reference #
reference into the JPEG buffer
Definition
;
Members
start: pointer to the start of the referenced segment or tablelength: size of the referenced segment or table
Description
Wnen referencing marker segments, start points right after the marker code, and length is the size of the segment parameters, excluding the marker code.
struct v4l2_jpeg_frame_component_spec #
frame component-specification
Definition
;
Members
component_identifier: C[i]horizontal_sampling_factor: H[i]vertical_sampling_factor: V[i]quantization_table_selector: quantization table destination selector Tq[i]
struct v4l2_jpeg_frame_header #
JPEG frame header
Definition
;
Members
height: Ywidth: Xprecision: Pnum_components: Nfcomponent: component-specification, see v4l2_jpeg_frame_component_specsubsampling: decoded subsampling from component-specification
struct v4l2_jpeg_scan_component_spec #
scan component-specification
Definition
;
Members
component_selector: Cs[j]dc_entropy_coding_table_selector: Td[j]ac_entropy_coding_table_selector: Ta[j]
struct v4l2_jpeg_scan_header #
JPEG scan header
Definition
;
Members
num_components: Nscomponent: component-specification, see v4l2_jpeg_scan_component_spec
enum v4l2_jpeg_app14_tf #
APP14 transform flag According to Rec. ITU-T T.872 (06/2012) 6.5.3 APP14 segment is for color encoding, it contains a transform flag, which may have values of 0, 1 and 2 and are interpreted as follows:
Constants
V4L2_JPEG_APP14_TF_CMYK_RGB: CMYK for images encoded with four components RGB for images encoded with three componentsV4L2_JPEG_APP14_TF_YCBCR: an image encoded with three components using YCbCrV4L2_JPEG_APP14_TF_YCCK: an image encoded with four components using YCCKV4L2_JPEG_APP14_TF_UNKNOWN: indicate app14 is not present
struct v4l2_jpeg_header #
parsed JPEG header
Definition
;
Members
sof: pointer to frame header and sizesos: pointer to scan header and sizenum_dht: number of entries in dhtdht: pointers to huffman tables and sizesnum_dqt: number of entries in dqtdqt: pointers to quantization tables and sizesframe: parsed frame headerscan: pointer to parsed scan header, optionalquantization_tables: references to four quantization tables, optionalhuffman_tables: references to four Huffman tables in DC0, DC1, AC0, AC1 order, optionalrestart_interval: number of MCU per restart interval, Riecs_offset: buffer offset in bytes to the entropy coded segmentapp14_tf: transform flag from app14 data
Description
When this structure is passed to v4l2_jpeg_parse_header, the optional scan, quantization_tables, and huffman_tables pointers must be initialized to NULL or point at valid memory.
v4l2_jpeg_parse_header() #
int locate marker segments and optionally parse headers
Parameters
void *buf: address of the JPEG buffer, should start with a SOI markersize_t len: length of the JPEG bufferstruct v4l2_jpeg_header *out: returns marker segment positions and optionally parsed headers
Description
The out->scan_header pointer must be initialized to NULL or point to a valid v4l2_jpeg_scan_header structure. The out->huffman_tables and out->quantization_tables pointers must be initialized to NULL or point to a valid array of 4 v4l2_jpeg_reference structures each.
Returns 0 or negative error if parsing failed.
V4L2 Media Controller functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
v4l2_mc_create_media_graph() #
int create Media Controller links at the graph.
Parameters
struct media_device *mdev: pointer to themedia_devicestruct.
Description
Add links between the entities commonly found on PC customer's hardware at the V4L2 side: camera sensors, audio and video PLL-IF decoders, tuners, analog TV decoder and I/O entities (video, VBI and Software Defined Radio).
v4l_enable_media_source() #
int Hold media source for exclusive use if free
Parameters
struct video_device *vdev: pointer to struct video_device
Description
This interface calls enable_source handler to determine if media source is free for use. The enable_source handler is responsible for checking is the media source is free and start a pipeline between the media source and the media entity associated with the video device. This interface should be called from v4l2-core and dvb-core interfaces that change the source configuration.
Return
returns zero on success or a negative error code.
v4l_disable_media_source() #
void Release media source
Parameters
struct video_device *vdev: pointer to struct video_device
Description
This interface calls disable_source handler to release the media source. The disable_source handler stops the active media pipeline between the media source and the media entity associated with the video device.
Return
returns zero on success or a negative error code.
v4l2_create_fwnode_links_to_pad() #
int Create fwnode-based links from a source subdev to a sink pad.
Parameters
struct v4l2_subdev *src_sd: pointer to a source subdevstruct media_pad *sink: pointer to a sink padu32 flags: the link flags
Description
This function searches for fwnode endpoint connections from a source subdevice to a single sink pad, and if suitable connections are found, translates them into media links to that pad. The function can be called by the sink, in its v4l2-async notifier bound callback, to create links from a bound source subdevice.
The flags argument specifies the link flags. The caller shall ensure that the flags are valid regardless of the number of links that may be created. For instance, setting the MEDIA_LNK_FL_ENABLED flag will cause all created links to be enabled, which isn't valid if more than one link is created.
Return 0 on success or a negative error code on failure.
v4l2_create_fwnode_links() #
int Create fwnode-based links from a source subdev to a sink subdev.
Parameters
struct v4l2_subdev *src_sd: pointer to a source subdevicestruct v4l2_subdev *sink_sd: pointer to a sink subdevice
Description
This function searches for any and all fwnode endpoint connections between source and sink subdevices, and translates them into media links. The function can be called by the sink subdevice, in its v4l2-async notifier subdev bound callback, to create all links from a bound source subdevice.
Return 0 on success or a negative error code on failure.
v4l2_pipeline_pm_get() #
int Increase the use count of a pipeline
Parameters
struct media_entity *entity: The root entity of a pipeline
Description
THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM ON SUB-DEVICE DRIVERS INSTEAD.
Update the use count of all entities in the pipeline and power entities on.
This function is intended to be called in video node open. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with v4l2_pipeline_link_notify().
Return 0 on success or a negative error code on failure.
v4l2_pipeline_pm_put() #
void Decrease the use count of a pipeline
Parameters
struct media_entity *entity: The root entity of a pipeline
Description
THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM ON SUB-DEVICE DRIVERS INSTEAD.
Update the use count of all entities in the pipeline and power entities off.
This function is intended to be called in video node release. It uses
struct media_entity.use_count to track the power status. The use
of this function should be paired with v4l2_pipeline_link_notify().
v4l2_pipeline_link_notify() #
int Link management notification callback
Parameters
struct media_link *link: The linku32 flags: New link flags that will be appliedunsigned int notification: The link's state change notification type (MEDIA_DEV_NOTIFY_*)
Description
THIS FUNCTION IS DEPRECATED. DO NOT USE IN NEW DRIVERS. USE RUNTIME PM ON SUB-DEVICE DRIVERS INSTEAD.
React to link management on powered pipelines by updating the use count of all entities in the source and sink sides of the link. Entities are powered on or off accordingly. The use of this function should be paired with v4l2_pipeline_pm_{get,put}().
Return 0 on success or a negative error code on failure. Powering entities off is assumed to never fail. This function will not fail for disconnection events.
V4L2 Media Bus functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
enum v4l2_mbus_csi2_cphy_line_orders_type #
CSI-2 C-PHY line order
Constants
V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ABC: C-PHY line order ABC (default)V4L2_MBUS_CSI2_CPHY_LINE_ORDER_ACB: C-PHY line order ACBV4L2_MBUS_CSI2_CPHY_LINE_ORDER_BAC: C-PHY line order BACV4L2_MBUS_CSI2_CPHY_LINE_ORDER_BCA: C-PHY line order BCAV4L2_MBUS_CSI2_CPHY_LINE_ORDER_CAB: C-PHY line order CABV4L2_MBUS_CSI2_CPHY_LINE_ORDER_CBA: C-PHY line order CBA
struct v4l2_mbus_config_mipi_csi2 #
MIPI CSI-2 data bus configuration
Definition
;
Members
flags: media bus (V4L2_MBUS_*) flagsdata_lanes: an array of physical data lane indexesclock_lane: physical lane index of the clock lanenum_data_lanes: number of data laneslane_polarities: polarity of the lanes. The order is the same of the physical lanes.line_orders: line order of the data lanes. The order is the same of the physical lanes.
struct v4l2_mbus_config_parallel #
parallel data bus configuration
Definition
;
Members
flags: media bus (V4L2_MBUS_*) flagsbus_width: bus width in bitsdata_shift: data shift in bits
struct v4l2_mbus_config_mipi_csi1 #
CSI-1/CCP2 data bus configuration
Definition
;
Members
clock_inv: polarity of clock/strobe signal false - not inverted, true - invertedstrobe: false - data/clock, true - data/strobelane_polarity: the polarities of the clock (index 0) and data lanes index (1)data_lane: the number of the data laneclock_lane: the number of the clock lane
enum v4l2_mbus_type #
media bus type
Constants
V4L2_MBUS_UNKNOWN: unknown bus type, no V4L2 mediabus configurationV4L2_MBUS_PARALLEL: parallel interface with hsync and vsyncV4L2_MBUS_BT656: parallel interface with embedded synchronisation, can also be used for BT.1120V4L2_MBUS_CSI1: MIPI CSI-1 serial interfaceV4L2_MBUS_CCP2: CCP2 (Compact Camera Port 2)V4L2_MBUS_CSI2_DPHY: MIPI CSI-2 serial interface, with D-PHYV4L2_MBUS_CSI2_CPHY: MIPI CSI-2 serial interface, with C-PHYV4L2_MBUS_DPI: MIPI VIDEO DPI interfaceV4L2_MBUS_INVALID: invalid bus type (keep as last)
struct v4l2_mbus_config #
media bus configuration
Definition
;
Members
type: interface typelink_freq: The link frequency. See also V4L2_CID_LINK_FREQ control.bus: bus configuration data structurebus.parallel: embeddedstruct v4l2_mbus_config_parallel. Used if the bus is parallel or BT.656.bus.mipi_csi1: embeddedstruct v4l2_mbus_config_mipi_csi1. Used if the bus is MIPI Alliance's Camera Serial Interface version 1 (MIPI CSI1) or Standard Mobile Imaging Architecture's Compact Camera Port 2 (SMIA CCP2).bus.mipi_csi2: embeddedstruct v4l2_mbus_config_mipi_csi2. Used if the bus is MIPI Alliance's Camera Serial Interface version 2 (MIPI CSI2).
v4l2_fill_pix_format() #
void Ancillary routine that fills a struct v4l2_pix_format fields from a struct v4l2_mbus_framefmt.
Parameters
struct v4l2_pix_format *pix_fmt: pointer tostruct v4l2_pix_formatto be filledconst struct v4l2_mbus_framefmt *mbus_fmt: pointer tostruct v4l2_mbus_framefmtto be used as model
v4l2_fill_mbus_format() #
void Ancillary routine that fills a struct v4l2_mbus_framefmt from a struct v4l2_pix_format and a data format code.
Parameters
struct v4l2_mbus_framefmt *mbus_fmt: pointer tostruct v4l2_mbus_framefmtto be filledconst struct v4l2_pix_format *pix_fmt: pointer tostruct v4l2_pix_formatto be used as modelu32 code: data format code (fromenum v4l2_mbus_pixelcode)
v4l2_fill_pix_format_mplane() #
void Ancillary routine that fills a struct v4l2_pix_format_mplane fields from a media bus structure.
Parameters
struct v4l2_pix_format_mplane *pix_mp_fmt: pointer tostruct v4l2_pix_format_mplaneto be filledconst struct v4l2_mbus_framefmt *mbus_fmt: pointer tostruct v4l2_mbus_framefmtto be used as model
v4l2_fill_mbus_format_mplane() #
void Ancillary routine that fills a struct v4l2_mbus_framefmt from a struct v4l2_pix_format_mplane.
Parameters
struct v4l2_mbus_framefmt *mbus_fmt: pointer tostruct v4l2_mbus_framefmtto be filledconst struct v4l2_pix_format_mplane *pix_mp_fmt: pointer tostruct v4l2_pix_format_mplaneto be used as model
V4L2 Memory to Memory functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
struct v4l2_m2m_ops #
mem-to-mem device driver callbacks
Definition
;
Members
device_run: required. Begin the actual job (transaction) inside this callback. The job does NOT have to end before this callback returns (and it will be the usual case). When the job finishes,v4l2_m2m_job_finish()orv4l2_m2m_buf_done_and_job_finish()has to be called.job_ready: optional. Should return 0 if the driver does not have a job fully prepared to run yet (i.e. it will not be able to finish a transaction without sleeping). If not provided, it will be assumed that one source and one destination buffer are all that is required for the driver to perform one full transaction. This method may not sleep.job_abort: optional. Informs the driver that it has to abort the currently running transaction as soon as possible (i.e. as soon as it can stop the device safely; e.g. in the next interrupt handler), even if the transaction would not have been finished by then. After the driver performs the necessary steps, it has to callv4l2_m2m_job_finish()orv4l2_m2m_buf_done_and_job_finish()as if the transaction ended normally. This function does not have to (and will usually not) wait until the device enters a state when it can be stopped.
struct v4l2_m2m_queue_ctx #
represents a queue for buffers ready to be processed
Definition
;
Members
q: pointer to structvb2_queuerdy_queue: List of V4L2 mem-to-mem queuesrdy_spinlock: spin lock to protect the struct usagenum_rdy: number of buffers ready to be processedbuffered: is the queue buffered?
Description
Queue for buffers ready to be processed as soon as this instance receives access to the device.
struct v4l2_m2m_ctx #
Memory to memory context structure
Definition
;
Members
q_lock: structmutexlocknew_frame: valid in the device_run callback: if true, then this starts a new frame; if false, then this is a new slice for an existing frame. This is always true unless V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF is set, which indicates slicing support.is_draining: indicates device is in draining phaselast_src_buf: indicate the last source buffer for drainingnext_buf_last: next capture queud buffer will be tagged as lasthas_stopped: indicate the device has been stoppedignore_cap_streaming: If true, job_ready can be called even if the CAPTURE queue is not streaming. This allows firmware to analyze the bitstream header which arrives on the OUTPUT queue. The driver must implement the job_ready callback correctly to make sure that the requirements for actual decoding are met.m2m_dev: opaque pointer to the internal data to handle M2M contextcap_q_ctx: Capture (output to memory) queue contextout_q_ctx: Output (input from memory) queue contextqueue: List of memory to memory contextsjob_flags: Job queue flags, used internally by v4l2-mem2mem.c:TRANS_QUEUED,TRANS_RUNNINGandTRANS_ABORT.finished: Wait queue used to signalize when a job queue finished.priv: Instance private data
Description
The memory to memory context is specific to a file handle, NOT to e.g. a device.
struct v4l2_m2m_buffer #
Memory to memory buffer
Definition
;
Members
vb: pointer to structvb2_v4l2_bufferlist: list of m2m buffers
v4l2_m2m_get_curr_priv() #
void * return driver private data for the currently running instance or NULL if no instance is running
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
v4l2_m2m_get_vq() #
struct vb2_queue * return vb2_queue for the given type
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxenum v4l2_buf_type type: type of the V4L2 buffer, as defined by enumv4l2_buf_type
Description
This function returns the capture queue when type is a capture type, and the output queue otherwise. It never returns a NULL pointer.
v4l2_m2m_try_schedule() #
void check whether an instance is ready to be added to the pending job queue and add it if so.
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
Description
There are three basic requirements an instance has to meet to be able to run:
- at least one source buffer has to be queued,
- at least one destination buffer has to be queued,
- streaming has to be on.
If a queue is buffered (for example a decoder hardware ringbuffer that has to be drained before doing streamoff), allow scheduling without v4l2 buffers on that queue.
There may also be additional, custom requirements. In such case the driver should supply a custom callback (job_ready in v4l2_m2m_ops) that should return 1 if the instance is ready. An example of the above could be an instance that requires more than one src/dst buffer per transaction.
v4l2_m2m_job_finish() #
void inform the framework that a job has been finished and have it clean up
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M contextstruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
Description
Called by a driver to yield back the device after it has finished with it. Should be called as soon as possible after reaching a state which allows other instances to take control of the device.
This function has to be called only after v4l2_m2m_ops->device_run
callback has been called on the driver.
v4l2_m2m_buf_done_and_job_finish() #
void return source/destination buffers with state and inform the framework that a job has been finished and have it clean up
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M contextstruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxenum vb2_buffer_state state: vb2 buffer state passed tov4l2_m2m_buf_done().
Description
Drivers that set V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF must use this
function instead of job_finish() to take held buffers into account. It is
optional for other drivers.
This function removes the source buffer from the ready list and returns it with the given state. The same is done for the destination buffer, unless it is marked 'held'. In that case the buffer is kept on the ready list.
After that the job is finished (see job_finish()).
This allows for multiple output buffers to be used to fill in a single capture buffer. This is typically used by stateless decoders where multiple e.g. H.264 slices contribute to a single decoded frame.
v4l2_m2m_clear_state() #
void clear encoding/decoding state
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_mark_stopped() #
void set current encoding/decoding state as stopped
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_dst_buf_is_last() #
bool return the current encoding/decoding session draining management state of next queued capture buffer
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
Description
This last capture buffer should be tagged with V4L2_BUF_FLAG_LAST to notify the end of the capture session.
v4l2_m2m_has_stopped() #
bool return the current encoding/decoding session stopped state
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_is_last_draining_src_buf() #
bool return the output buffer draining state in the current encoding/decoding session
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_v4l2_buffer *vbuf: pointer to structv4l2_buffer
Description
This will identify the last output buffer queued before a session stop was required, leading to an actual encoding/decoding session stop state in the encoding/decoding process after being processed.
v4l2_m2m_last_buffer_done() #
void marks the buffer with LAST flag and DONE
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_v4l2_buffer *vbuf: pointer to structv4l2_buffer
v4l2_m2m_suspend() #
void stop new jobs from being run and wait for current job to finish
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
Description
Called by a driver in the suspend hook. Stop new jobs from being run, and wait for current running job to finish.
v4l2_m2m_resume() #
void resume job running and try to run a queued job
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
Description
Called by a driver in the resume hook. This reverts the operation of
v4l2_m2m_suspend() and allows job to be run. Also try to run a queued job if
there is any.
v4l2_m2m_reqbufs() #
int multi-queue-aware REQBUFS multiplexer
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_requestbuffers *reqbufs: pointer to structv4l2_requestbuffers
v4l2_m2m_querybuf() #
int multi-queue-aware QUERYBUF multiplexer
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_buffer *buf: pointer to structv4l2_buffer
Description
See v4l2_m2m_mmap() documentation for details.
v4l2_m2m_qbuf() #
int enqueue a source or destination buffer, depending on the type
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_buffer *buf: pointer to structv4l2_buffer
v4l2_m2m_dqbuf() #
int dequeue a source or destination buffer, depending on the type
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_buffer *buf: pointer to structv4l2_buffer
v4l2_m2m_prepare_buf() #
int prepare a source or destination buffer, depending on the type
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_buffer *buf: pointer to structv4l2_buffer
v4l2_m2m_create_bufs() #
int create a source or destination buffer, depending on the type
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_create_buffers *create: pointer to structv4l2_create_buffers
v4l2_m2m_expbuf() #
int export a source or destination buffer, depending on the type
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_exportbuffer *eb: pointer to structv4l2_exportbuffer
v4l2_m2m_streamon() #
int turn on streaming for a video queue
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxenum v4l2_buf_type type: type of the V4L2 buffer, as defined by enumv4l2_buf_type
v4l2_m2m_streamoff() #
int turn off streaming for a video queue
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxenum v4l2_buf_type type: type of the V4L2 buffer, as defined by enumv4l2_buf_type
v4l2_m2m_update_start_streaming_state() #
void update the encoding/decoding session state when a start of streaming of a video queue is requested
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_queue *q: queue
v4l2_m2m_update_stop_streaming_state() #
void update the encoding/decoding session state when a stop of streaming of a video queue is requested
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_queue *q: queue
v4l2_m2m_encoder_cmd() #
int execute an encoder command
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_encoder_cmd *ec: pointer to the encoder command
v4l2_m2m_decoder_cmd() #
int execute a decoder command
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct v4l2_decoder_cmd *dc: pointer to the decoder command
v4l2_m2m_poll() #
__poll_t poll replacement, for destination buffers only
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct poll_table_struct *wait: pointer to structpoll_table_struct
Description
Call from the driver's poll() function. Will poll both queues. If a buffer
is available to dequeue (with dqbuf) from the source queue, this will
indicate that a non-blocking write can be performed, while read will be
returned in case of the destination queue.
v4l2_m2m_mmap() #
int source and destination queues-aware mmap multiplexer
Parameters
struct file *file: pointer to structfilestruct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vm_area_struct *vma: pointer to structvm_area_struct
Description
Call from driver's mmap() function. Will handle mmap() for both queues
seamlessly for the video buffer, which will receive normal per-queue offsets
and proper vb2 queue pointers. The differentiation is made outside
vb2 by adding a predefined offset to buffers from one of the queues
and subtracting it before passing it back to vb2. Only drivers (and
thus applications) receive modified offsets.
v4l2_m2m_init() #
struct v4l2_m2m_dev * initialize per-driver m2m data
Parameters
const struct v4l2_m2m_ops *m2m_ops: pointer to struct v4l2_m2m_ops
Description
Usually called from driver's probe() function.
Return
returns an opaque pointer to the internal data to handle M2M context
v4l2_m2m_release() #
void cleans up and frees a m2m_dev structure
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
Description
Usually called from driver's remove() function.
v4l2_m2m_get() #
void take a reference to the m2m_dev structure
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
Description
This is used to share the M2M device across multiple devices. This can be used to avoid scheduling two hardware nodes concurrently.
v4l2_m2m_put() #
void remove a reference to the m2m_dev structure
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M context
Description
Once the M2M device has no more references, v4l2_m2m_release() will be
called automatically. Users of this method should never call
v4l2_m2m_release() directly. See v4l2_m2m_get() for more details.
v4l2_m2m_ctx_init() #
struct v4l2_m2m_ctx * allocate and initialize a m2m context
Parameters
struct v4l2_m2m_dev *m2m_dev: opaque pointer to the internal data to handle M2M contextvoid *drv_priv: driver's instance private dataint (*queue_init)(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq): a callback for queue type-specific initialization function to be used for initializing vb2_queues
Description
Usually called from driver's open() function.
v4l2_m2m_ctx_release() #
void release m2m context
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
Description
Usually called from driver's release() function.
v4l2_m2m_buf_queue() #
void add a buffer to the proper ready buffers list.
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_v4l2_buffer *vbuf: pointer to structvb2_v4l2_buffer
Description
Call from vb2_queue_ops->ops->buf_queue, vb2_queue_ops callback.
v4l2_m2m_num_src_bufs_ready() #
unsigned int return the number of source buffers ready for use
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_num_dst_bufs_ready() #
unsigned int return the number of destination buffers ready for use
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_next_buf() #
struct vb2_v4l2_buffer * return next buffer from the list of ready buffers
Parameters
struct v4l2_m2m_queue_ctx *q_ctx: pointer to struct v4l2_m2m_queue_ctx
v4l2_m2m_next_src_buf() #
struct vb2_v4l2_buffer * return next source buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_next_dst_buf() #
struct vb2_v4l2_buffer * return next destination buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_last_buf() #
struct vb2_v4l2_buffer * return last buffer from the list of ready buffers
Parameters
struct v4l2_m2m_queue_ctx *q_ctx: pointer to struct v4l2_m2m_queue_ctx
v4l2_m2m_last_src_buf() #
struct vb2_v4l2_buffer * return last source buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_last_dst_buf() #
struct vb2_v4l2_buffer * return last destination buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_for_each_dst_buf() #
iterate over a list of destination ready buffers
Parameters
m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxb: current buffer of type struct v4l2_m2m_buffer
v4l2_m2m_for_each_src_buf() #
iterate over a list of source ready buffers
Parameters
m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxb: current buffer of type struct v4l2_m2m_buffer
v4l2_m2m_for_each_dst_buf_safe() #
iterate over a list of destination ready buffers safely
Parameters
m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxb: current buffer of type struct v4l2_m2m_buffern: used as temporary storage
v4l2_m2m_for_each_src_buf_safe() #
iterate over a list of source ready buffers safely
Parameters
m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxb: current buffer of type struct v4l2_m2m_buffern: used as temporary storage
v4l2_m2m_get_src_vq() #
struct vb2_queue * return vb2_queue for source buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_get_dst_vq() #
struct vb2_queue * return vb2_queue for destination buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_buf_remove() #
struct vb2_v4l2_buffer * take off a buffer from the list of ready buffers and return it
Parameters
struct v4l2_m2m_queue_ctx *q_ctx: pointer to struct v4l2_m2m_queue_ctx
v4l2_m2m_src_buf_remove() #
struct vb2_v4l2_buffer * take off a source buffer from the list of ready buffers and return it
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_dst_buf_remove() #
struct vb2_v4l2_buffer * take off a destination buffer from the list of ready buffers and return it
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctx
v4l2_m2m_buf_remove_by_buf() #
void take off exact buffer from the list of ready buffers
Parameters
struct v4l2_m2m_queue_ctx *q_ctx: pointer to struct v4l2_m2m_queue_ctxstruct vb2_v4l2_buffer *vbuf: the buffer to be removed
v4l2_m2m_src_buf_remove_by_buf() #
void take off exact source buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_v4l2_buffer *vbuf: the buffer to be removed
v4l2_m2m_dst_buf_remove_by_buf() #
void take off exact destination buffer from the list of ready buffers
Parameters
struct v4l2_m2m_ctx *m2m_ctx: m2m context assigned to the instance given by structv4l2_m2m_ctxstruct vb2_v4l2_buffer *vbuf: the buffer to be removed
v4l2_m2m_buf_copy_metadata() #
void copy buffer metadata from the output buffer to the capture buffer
Parameters
const struct vb2_v4l2_buffer *out_vb: the output buffer that is the source of the metadata.struct vb2_v4l2_buffer *cap_vb: the capture buffer that will receive the metadata.
Description
This helper function copies the timestamp, timecode (if the TIMECODE buffer flag was set), field, and the TIMECODE and TSTAMP_SRC_MASK flags from out_vb to cap_vb.
V4L2 rect helper functions
Peios Kernel / Hardware and drivers / Driver development / Media devices
v4l2_rect_set_size_to() #
void copy the width/height values.
Parameters
struct v4l2_rect *r: rect whose width and height fields will be setconst struct v4l2_rect *size: rect containing the width and height fields you need.
v4l2_rect_set_min_size() #
void width and height of r should be >= min_size.
Parameters
struct v4l2_rect *r: rect whose width and height will be modifiedconst struct v4l2_rect *min_size: rect containing the minimal width and height
v4l2_rect_set_max_size() #
void width and height of r should be <= max_size
Parameters
struct v4l2_rect *r: rect whose width and height will be modifiedconst struct v4l2_rect *max_size: rect containing the maximum width and height
v4l2_rect_map_inside() #
void r should be inside boundary.
Parameters
struct v4l2_rect *r: rect that will be modifiedconst struct v4l2_rect *boundary: rect containing the boundary for r
v4l2_rect_same_size() #
bool return true if r1 has the same size as r2
Parameters
const struct v4l2_rect *r1: rectangle.const struct v4l2_rect *r2: rectangle.
Description
Return true if both rectangles have the same size.
v4l2_rect_same_position() #
bool return true if r1 has the same position as r2
Parameters
const struct v4l2_rect *r1: rectangle.const struct v4l2_rect *r2: rectangle.
Description
Return true if both rectangles have the same position
v4l2_rect_equal() #
bool return true if r1 equals r2
Parameters
const struct v4l2_rect *r1: rectangle.const struct v4l2_rect *r2: rectangle.
Description
Return true if both rectangles have the same size and position.
v4l2_rect_intersect() #
void calculate the intersection of two rects.
Parameters
struct v4l2_rect *r: intersection of r1 and r2.const struct v4l2_rect *r1: rectangle.const struct v4l2_rect *r2: rectangle.
v4l2_rect_scale() #
void scale rect r by to/from
Parameters
struct v4l2_rect *r: rect to be scaled.const struct v4l2_rect *from: from rectangle.const struct v4l2_rect *to: to rectangle.
Description
This scales rectangle r horizontally by to->width / from->width and vertically by to->height / from->height.
Typically r is a rectangle inside from and you want the rectangle as it would appear after scaling from to to. So the resulting r will be the scaled rectangle inside to.
v4l2_rect_overlap() #
bool do r1 and r2 overlap?
Parameters
const struct v4l2_rect *r1: rectangle.const struct v4l2_rect *r2: rectangle.
Description
Returns true if r1 and r2 overlap.
v4l2_rect_enclosed() #
bool is r1 enclosed in r2?
Parameters
struct v4l2_rect *r1: rectangle.struct v4l2_rect *r2: rectangle.
Description
Returns true if r1 is enclosed in r2.
V4L2 sub-devices
Peios Kernel / Hardware and drivers / Driver development / Media devices
V4L2 sub-devices #
Many drivers need to communicate with sub-devices. These devices can do all sort of tasks, but most commonly they handle audio and/or video muxing, encoding or decoding. For webcams common sub-devices are sensors and camera controllers.
Usually these are I2C devices, but not necessarily. In order to provide the driver with a consistent interface to these sub-devices the v4l2_subdev struct (v4l2-subdev.h) was created.
Each sub-device driver must have a v4l2_subdev struct. This struct can be stand-alone for simple sub-devices or it might be embedded in a larger struct if more state information needs to be stored. Usually there is a low-level device struct (e.g. i2c_client) that contains the device data as setup by the kernel. It is recommended to store that pointer in the private data of v4l2_subdev using v4l2_set_subdevdata(). That makes it easy to go from a v4l2_subdev to the actual low-level bus-specific device data.
You also need a way to go from the low-level struct to v4l2_subdev. For the common i2c_client struct the i2c_set_clientdata() call is used to store a v4l2_subdev pointer, for other buses you may have to use other methods.
Bridges might also need to store per-subdev private data, such as a pointer to bridge-specific per-subdev private data. The v4l2_subdev structure provides host private data for that purpose that can be accessed with v4l2_get_subdev_hostdata() and v4l2_set_subdev_hostdata().
From the bridge driver perspective, you load the sub-device module and somehow obtain the v4l2_subdev pointer. For i2c devices this is easy: you call i2c_get_clientdata(). For other buses something similar needs to be done. Helper functions exist for sub-devices on an I2C bus that do most of this tricky work for you.
Each v4l2_subdev contains function pointers that sub-device drivers can implement (or leave NULL if it is not applicable). Since sub-devices can do so many different things and you do not want to end up with a huge ops struct of which only a handful of ops are commonly implemented, the function pointers are sorted according to category and each category has its own ops struct.
The top-level ops struct contains pointers to the category ops structs, which may be NULL if the subdev driver does not support anything from that category.
It looks like this:
;
;
;
;
;
;
The core ops are common to all subdevs, the other categories are implemented depending on the sub-device. E.g. a video device is unlikely to support the audio ops and vice versa.
This setup limits the number of function pointers while still making it easy to add new ops and categories.
A sub-device driver initializes the v4l2_subdev struct using:
v4l2_subdev_init <v4l2_subdev_init>()(sd <v4l2_subdev>, &ops <v4l2_subdev_ops>).
Afterwards you need to initialize sd <v4l2_subdev>->name with a unique name and set the module owner. This is done for you if you use the i2c helper functions.
If integration with the media framework is needed, you must initialize the media_entity struct embedded in the v4l2_subdev struct (entity field) by calling media_entity_pads_init(), if the entity has pads:
struct media_pad *pads = &my_sd->pads;
int err;
err = ;
The pads array must have been previously initialized. There is no need to manually set the struct media_entity function and name fields, but the revision field must be initialized if needed.
A reference to the entity will be automatically acquired/released when the subdev device node (if any) is opened/closed.
Don't forget to cleanup the media entity before the sub-device is destroyed:
;
If a sub-device driver implements sink pads, the subdev driver may set the link_validate field in v4l2_subdev_pad_ops to provide its own link validation function. For every link in the pipeline, the link_validate pad operation of the sink end of the link is called. In both cases the driver is still responsible for validating the correctness of the format configuration between sub-devices and video nodes.
If link_validate op is not set, the default function v4l2_subdev_link_validate_default() is used instead. This function ensures that width, height and the media bus pixel code are equal on both source and sink of the link. Subdev drivers are also free to use this function to perform the checks mentioned above in addition to their own checks.
Subdev registration #
There are currently two ways to register subdevices with the V4L2 core. The first (traditional) possibility is to have subdevices registered by bridge drivers. This can be done when the bridge driver has the complete information about subdevices connected to it and knows exactly when to register them. This is typically the case for internal subdevices, like video data processing units within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected to SoCs, which pass information about them to bridge drivers, usually in their platform data.
There are however also situations where subdevices have to be registered asynchronously to bridge devices. An example of such a configuration is a Device Tree based system where information about subdevices is made available to the system independently from the bridge devices, e.g. when subdevices are defined in DT as I2C device nodes. The API used in this second case is described further below.
Using one or the other registration method only affects the probing process, the run-time bridge-subdevice interaction is in both cases the same.
Registering synchronous sub-devices #
In the synchronous case a device (bridge) driver needs to register the v4l2_subdev with the v4l2_device:
v4l2_device_register_subdev <v4l2_device_register_subdev>()(v4l2_dev <v4l2_device>,sd <v4l2_subdev>).
This can fail if the subdev module disappeared before it could be registered. After this function was called successfully the subdev->dev field points to the v4l2_device.
If the v4l2_device parent device has a non-NULL mdev field, the sub-device entity will be automatically registered with the media device.
You can unregister a sub-device using:
v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>()(sd <v4l2_subdev>).
Afterwards the subdev module can be unloaded and sd <v4l2_subdev>->dev == NULL.
Registering asynchronous sub-devices #
In the asynchronous case subdevice probing can be invoked independently of the bridge driver availability. The subdevice driver then has to verify whether all the requirements for a successful probing are satisfied. This can include a check for a master clock availability. If any of the conditions aren't satisfied the driver might decide to return -EPROBE_DEFER to request further reprobing attempts. Once all conditions are met the subdevice shall be registered using the v4l2_async_register_subdev() function. Unregistration is performed using the v4l2_async_unregister_subdev() call. Subdevices registered this way are stored in a global list of subdevices, ready to be picked up by bridge drivers.
Drivers must complete all initialization of the sub-device before registering it using v4l2_async_register_subdev(), including enabling runtime PM. This is because the sub-device becomes accessible as soon as it gets registered.
Asynchronous sub-device notifiers #
Bridge drivers in turn have to register a notifier object. This is performed using the v4l2_async_nf_register() call. To unregister the notifier the driver has to call v4l2_async_nf_unregister(). Before releasing memory of an unregister notifier, it must be cleaned up by calling v4l2_async_nf_cleanup().
Before registering the notifier, bridge drivers must do two things: first, the notifier must be initialized using the v4l2_async_nf_init(). Second, bridge drivers can then begin to form a list of async connection descriptors that the bridge device needs for its operation. v4l2_async_nf_add_fwnode(), v4l2_async_nf_add_fwnode_remote() and v4l2_async_nf_add_i2c()
Async connection descriptors describe connections to external sub-devices the drivers for which are not yet probed. Based on an async connection, a media data or ancillary link may be created when the related sub-device becomes available. There may be one or more async connections to a given sub-device but this is not known at the time of adding the connections to the notifier. Async connections are bound as matching async sub-devices are found, one by one.
Asynchronous sub-device notifier for sub-devices #
A driver that registers an asynchronous sub-device may also register an asynchronous notifier. This is called an asynchronous sub-device notifier and the process is similar to that of a bridge driver apart from that the notifier is initialised using v4l2_async_subdev_nf_init() instead. A sub-device notifier may complete only after the V4L2 device becomes available, i.e. there's a path via async sub-devices and notifiers to a notifier that is not an asynchronous sub-device notifier.
Asynchronous sub-device registration helper for camera sensor drivers #
v4l2_async_register_subdev_sensor() is a helper function for sensor drivers registering their own async connection, but it also registers a notifier and further registers async connections for lens and flash devices found in firmware. The notifier for the sub-device is unregistered and cleaned up with the async sub-device, using v4l2_async_unregister_subdev().
Asynchronous sub-device notifier example #
These functions allocate an async connection descriptor which is of type struct v4l2_async_connection embedded in a driver-specific struct. The &struct v4l2_async_connection shall be the first member of this struct:
;
struct my_async_connection *my_asc;
struct fwnode_handle *ep;
...
my_asc = ;
;
if
return ;
Asynchronous sub-device notifier callbacks #
The V4L2 core will then use these connection descriptors to match asynchronously registered subdevices to them. If a match is detected the .bound() notifier callback is called. After all connections have been bound the .complete() callback is called. When a connection is removed from the system the .unbind() method is called. All three callbacks are optional.
Drivers can store any type of custom data in their driver-specific v4l2_async_connection wrapper. If any of that data requires special handling when the structure is freed, drivers must implement the .destroy() notifier callback. The framework will call it right before freeing the v4l2_async_connection.
Calling subdev operations #
The advantage of using v4l2_subdev is that it is a generic struct and does not contain any knowledge about the underlying hardware. So a driver might contain several subdevs that use an I2C bus, but also a subdev that is controlled through GPIO pins. This distinction is only relevant when setting up the device, but once the subdev is registered it is completely transparent.
Once the subdev has been registered you can call an ops function either directly:
err = sd->ops->core->;
but it is better and easier to use this macro:
err = ;
The macro will do the right NULL pointer checks and returns -ENODEV if sd <v4l2_subdev> is NULL, -ENOIOCTLCMD if either sd <v4l2_subdev>->core or sd <v4l2_subdev>->core->g_std is NULL, or the actual result of the sd <v4l2_subdev>->ops->core->g_std ops.
It is also possible to call all or a subset of the sub-devices:
;
Any subdev that does not support this ops is skipped and error results are ignored. If you want to check for errors use this:
err = ;
Any error except -ENOIOCTLCMD will exit the loop with that error. If no errors (except -ENOIOCTLCMD) occurred, then 0 is returned.
The second argument to both calls is a group ID. If 0, then all subdevs are called. If non-zero, then only those whose group ID match that value will be called. Before a bridge driver registers a subdev it can set sd <v4l2_subdev>->grp_id to whatever value it wants (it's 0 by default). This value is owned by the bridge driver and the sub-device driver will never modify or use it.
The group ID gives the bridge driver more control how callbacks are called. For example, there may be multiple audio chips on a board, each capable of changing the volume. But usually only one will actually be used when the user want to change the volume. You can set the group ID for that subdev to e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling v4l2_device_call_all(). That ensures that it will only go to the subdev that needs it.
If the sub-device needs to notify its v4l2_device parent of an event, then it can call v4l2_subdev_notify(sd, notification, arg). This macro checks whether there is a notify() callback defined and returns -ENODEV if not. Otherwise the result of the notify() call is returned.
V4L2 sub-device userspace API #
Bridge drivers traditionally expose one or multiple video nodes to userspace, and control subdevices through the v4l2_subdev_ops operations in response to video node operations. This hides the complexity of the underlying hardware from applications. For complex devices, finer-grained control of the device than what the video nodes offer may be required. In those cases, bridge drivers that implement the media controller API may opt for making the subdevice operations directly accessible from userspace.
Device nodes named v4l-subdevX can be created in /dev to access sub-devices directly. If a sub-device supports direct userspace configuration it must set the V4L2_SUBDEV_FL_HAS_DEVNODE flag before being registered.
After registering sub-devices, the v4l2_device driver can create device nodes for all registered sub-devices marked with V4L2_SUBDEV_FL_HAS_DEVNODE by calling v4l2_device_register_subdev_nodes(). Those device nodes will be automatically removed when sub-devices are unregistered.
The device node handles a subset of the V4L2 API.
VIDIOC_QUERYCTRL, VIDIOC_QUERYMENU, VIDIOC_G_CTRL, VIDIOC_S_CTRL, VIDIOC_G_EXT_CTRLS, VIDIOC_S_EXT_CTRLS and VIDIOC_TRY_EXT_CTRLS:
The controls ioctls are identical to the ones defined in V4L2. They behave identically, with the only exception that they deal only with controls implemented in the sub-device. Depending on the driver, those controls can be also be accessed through one (or several) V4L2 device nodes.
VIDIOC_DQEVENT, VIDIOC_SUBSCRIBE_EVENT and VIDIOC_UNSUBSCRIBE_EVENT
The events ioctls are identical to the ones defined in V4L2. They behave identically, with the only exception that they deal only with events generated by the sub-device. Depending on the driver, those events can also be reported by one (or several) V4L2 device nodes.
Sub-device drivers that want to use events need to set the
V4L2_SUBDEV_FL_HAS_EVENTSv4l2_subdev.flags before registering the sub-device. After registration events can be queued as usual on thev4l2_subdev.devnode device node.To properly support events, the
poll()file operation is also implemented.
Private ioctls
All ioctls not in the above list are passed directly to the sub-device driver through the core::ioctl operation.
Read-only sub-device userspace API #
Bridge drivers that control their connected subdevices through direct calls to the kernel API realized by v4l2_subdev_ops structure do not usually want userspace to be able to change the same parameters through the subdevice device node and thus do not usually register any.
It is sometimes useful to report to userspace the current subdevice configuration through a read-only API, that does not permit applications to change to the device parameters but allows interfacing to the subdevice device node to inspect them.
For instance, to implement cameras based on computational photography, userspace needs to know the detailed camera sensor configuration (in terms of skipping, binning, cropping and scaling) for each supported output resolution. To support such use cases, bridge drivers may expose the subdevice operations to userspace through a read-only API.
To create a read-only device node for all the subdevices registered with the V4L2_SUBDEV_FL_HAS_DEVNODE set, the v4l2_device driver should call v4l2_device_register_ro_subdev_nodes().
Access to the following ioctls for userspace applications is restricted on sub-device device nodes registered with v4l2_device_register_ro_subdev_nodes().
VIDIOC_SUBDEV_S_FMT, VIDIOC_SUBDEV_S_CROP, VIDIOC_SUBDEV_S_SELECTION:
These ioctls are only allowed on a read-only subdevice device node for the V4L2_SUBDEV_FORMAT_TRY formats and selection rectangles.
VIDIOC_SUBDEV_S_FRAME_INTERVAL, VIDIOC_SUBDEV_S_DV_TIMINGS, VIDIOC_SUBDEV_S_STD:
These ioctls are not allowed on a read-only subdevice node.
In case the ioctl is not allowed, or the format to modify is set to V4L2_SUBDEV_FORMAT_ACTIVE, the core returns a negative error code and the errno variable is set to -EPERM.
I2C sub-device drivers #
Since these drivers are so common, special helper functions are available to ease the use of these drivers (v4l2-common.h).
The recommended method of adding v4l2_subdev support to an I2C driver is to embed the v4l2_subdev struct into the state struct that is created for each I2C device instance. Very simple devices have no state struct and in that case you can just create a v4l2_subdev directly.
A typical state struct would look like this (where 'chipname' is replaced by the name of the chip):
;
Initialize the v4l2_subdev struct as follows:
;
This function will fill in all the fields of v4l2_subdev ensure that the v4l2_subdev and i2c_client both point to one another.
You should also add a helper inline function to go from a v4l2_subdev pointer to a chipname_state struct:
static inline struct chipname_state *
Use this to go from the v4l2_subdev struct to the i2c_client struct:
struct i2c_client *client = ;
And this to go from an i2c_client to a v4l2_subdev struct:
struct v4l2_subdev *sd = ;
Make sure to call v4l2_device_unregister_subdev()(sd <v4l2_subdev>) when the remove() callback is called. This will unregister the sub-device from the bridge driver. It is safe to call this even if the sub-device was never registered.
You need to do this because when the bridge driver destroys the i2c adapter the remove() callbacks are called of the i2c devices on that adapter. After that the corresponding v4l2_subdev structures are invalid, so they have to be unregistered first. Calling v4l2_device_unregister_subdev()(sd <v4l2_subdev>) from the remove() callback ensures that this is always done correctly.
The bridge driver also has some helper functions it can use:
struct v4l2_subdev *sd = ;
This loads the given module (can be NULL if no module needs to be loaded) and calls i2c_new_client_device() with the given i2c_adapter and chip/address arguments. If all goes well, then it registers the subdev with the v4l2_device.
You can also use the last argument of v4l2_i2c_new_subdev() to pass an array of possible I2C addresses that it should probe. These probe addresses are only used if the previous argument is 0. A non-zero argument means that you know the exact i2c address so in that case no probing will take place.
Both functions return NULL if something went wrong.
Note that the chipid you pass to v4l2_i2c_new_subdev() is usually the same as the module name. It allows you to specify a chip variant, e.g. "saa7114" or "saa7115". In general though the i2c driver autodetects this. The use of chipid is something that needs to be looked at more closely at a later date. It differs between i2c drivers and as such can be confusing. To see which chip variants are supported you can look in the i2c driver code for the i2c_device_id table. This lists all the possibilities.
There are one more helper function:
v4l2_i2c_new_subdev_board() uses an i2c_board_info struct which is passed to the i2c driver and replaces the irq, platform_data and addr arguments.
If the subdev supports the s_config core ops, then that op is called with the irq and platform_data arguments after the subdev was setup.
The v4l2_i2c_new_subdev() function will call v4l2_i2c_new_subdev_board(), internally filling a i2c_board_info structure using the client_type and the addr to fill it.
Centrally managed subdev active state #
Traditionally V4L2 subdev drivers maintained internal state for the active device configuration. This is often implemented as e.g. an array of struct v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose rectangles.
In addition to the active configuration, each subdev file handle has a struct v4l2_subdev_state, managed by the V4L2 core, which contains the try configuration.
To simplify the subdev drivers the V4L2 subdev API now optionally supports a centrally managed active configuration represented by v4l2_subdev_state. One instance of state, which contains the active device configuration, is stored in the sub-device itself as part of the v4l2_subdev structure, while the core associates a try state to each open file handle, to store the try configuration related to that file handle.
Sub-device drivers can opt-in and use state to manage their active configuration by initializing the subdevice state with a call to v4l2_subdev_init_finalize() before registering the sub-device. They must also call v4l2_subdev_cleanup() to release all the allocated resources before unregistering the sub-device. The core automatically allocates and initializes a state for each open file handle to store the try configurations and frees it when closing the file handle.
V4L2 sub-device operations that use both the ACTIVE and TRY formats receive the correct state to operate on through the 'state' parameter. The state must be locked and unlocked by the caller by calling v4l2_subdev_lock_state() and v4l2_subdev_unlock_state(). The caller can do so by calling the subdev operation through the v4l2_subdev_call_state_active() macro.
Operations that do not receive a state parameter implicitly operate on the subdevice active state, which drivers can exclusively access by calling v4l2_subdev_lock_and_get_active_state(). The sub-device active state must equally be released by calling v4l2_subdev_unlock_state().
Drivers must never manually access the state stored in the v4l2_subdev or in the file handle without going through the designated helpers.
While the V4L2 core passes the correct try or active state to the subdevice operations, many existing device drivers pass a NULL state when calling operations with v4l2_subdev_call(). This legacy construct causes issues with subdevice drivers that let the V4L2 core manage the active state, as they expect to receive the appropriate state as a parameter. To help the conversion of subdevice drivers to a managed active state without having to convert all callers at the same time, an additional wrapper layer has been added to v4l2_subdev_call(), which handles the NULL case by getting and locking the callee's active state with v4l2_subdev_lock_and_get_active_state(), and unlocking the state after the call.
The whole subdev state is in reality split into three parts: the v4l2_subdev_state, subdev controls and subdev driver's internal state. In the future these parts should be combined into a single state. For the time being we need a way to handle the locking for these parts. This can be accomplished by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock' pointer and the same model is used with states. The driver can do the following before calling v4l2_subdev_init_finalize():
sd->ctrl_handler->lock = &priv->mutex;
sd->state_lock = &priv->mutex;
This shares the driver's private mutex between the controls and the states.
Streams, multiplexed media pads and internal routing #
A subdevice driver can implement support for multiplexed streams by setting the V4L2_SUBDEV_FL_STREAMS subdev flag and implementing support for centrally managed subdev active state, routing and stream based configuration.
V4L2 sub-device functions and data structures #
struct v4l2_decode_vbi_line #
used to decode_vbi_line
Definition
;
Members
is_second_field: Set to 0 for the first (odd) field; set to 1 for the second (even) field.p: Pointer to the sliced VBI data from the decoder. On exit, points to the start of the payload.line: Line number of the sliced VBI data (1-23)type: VBI service type (V4L2_SLICED_*). 0 if no service found
enum v4l2_subdev_io_pin_bits #
Subdevice external IO pin configuration bits
Constants
V4L2_SUBDEV_IO_PIN_DISABLE: disables a pin config. ENABLE assumed.V4L2_SUBDEV_IO_PIN_OUTPUT: set it if pin is an output.V4L2_SUBDEV_IO_PIN_INPUT: set it if pin is an input.V4L2_SUBDEV_IO_PIN_SET_VALUE: to set the output value viastruct v4l2_subdev_io_pin_config->value.V4L2_SUBDEV_IO_PIN_ACTIVE_LOW: pin active is bit 0. Otherwise, ACTIVE HIGH is assumed.
struct v4l2_subdev_io_pin_config #
Subdevice external IO pin configuration
Definition
;
Members
flags: bitmask with flags for this pin's config, whose bits are defined byenum v4l2_subdev_io_pin_bits.pin: Chip external IO pin to configurefunction: Internal signal pad/function to route to IO pinvalue: Initial value for pin - e.g. GPIO output valuestrength: Pin drive strength
struct v4l2_subdev_core_ops #
Define core ops callbacks for subdevs
Definition
;
Members
log_status: callback forVIDIOC_LOG_STATUS()ioctl handler code.s_io_pin_config: configure one or more chip I/O pins for chips that multiplex different internal signal pads out to IO pins. This function takes a pointer to an array of 'n' pin configuration entries, one for each pin being configured. This function could be called at times other than just subdevice initialization.init: initialize the sensor registers to some sort of reasonable default values. Do not use for new drivers and should be removed in existing drivers.load_fw: load firmware.reset: generic reset command. The argument selects which subsystems to reset. Passing 0 will always reset the whole chip. Do not use for new drivers without discussing this first on the linux-media mailinglist. There should be no reason normally to reset a device.s_gpio: set GPIO pins. Very simple right now, might need to be extended with a direction argument if needed.command: called by in-kernel drivers in order to call functions internal to subdev drivers driver that have a separate callback.ioctl: called at the end ofioctl()syscall handler at the V4L2 core. used to provide support for private ioctls used on the driver.compat_ioctl32: called when a 32 bits application uses a 64 bits Kernel, in order to fix data passed from/to userspace.g_register: callback forVIDIOC_DBG_G_REGISTER()ioctl handler code.s_register: callback forVIDIOC_DBG_S_REGISTER()ioctl handler code.s_power: puts subdevice in power saving mode (on == 0) or normal operation mode (on == 1). DEPRECATED. See Documentation/driver-api/media/camera-sensor.rst . pre_streamon and post_streamoff callbacks can be used for e.g. setting the bus to LP-11 mode before s_stream is called.interrupt_service_routine: Called by the bridge chip's interrupt service handler, when an interrupt status has be raised due to this subdev, so that this subdev can handle the details. It may schedule work to be performed later. It must not sleep. Called from an IRQ context.subscribe_event: used by the drivers to request the control framework that for it to be warned when the value of a control changes.unsubscribe_event: remove event subscription from the control framework.
struct v4l2_subdev_tuner_ops #
Callbacks used when v4l device was opened in radio mode.
Definition
;
Members
standby: puts the tuner in standby mode. It will be woken up automatically the next time it is used.s_radio: callback that switches the tuner to radio mode. drivers should explicitly call it when a tuner ops should operate on radio mode, before being able to handle it. Used on devices that have both AM/FM radio receiver and TV.s_frequency: callback forVIDIOC_S_FREQUENCY()ioctl handler code.g_frequency: callback forVIDIOC_G_FREQUENCY()ioctl handler code. freq->type must be filled in. Normally done byvideo_ioctl2()or the bridge driver.enum_freq_bands: callback forVIDIOC_ENUM_FREQ_BANDS()ioctl handler code.g_tuner: callback forVIDIOC_G_TUNER()ioctl handler code.s_tuner: callback forVIDIOC_S_TUNER()ioctl handler code. vt->type must be filled in. Normally done by video_ioctl2 or the bridge driver.g_modulator: callback forVIDIOC_G_MODULATOR()ioctl handler code.s_modulator: callback forVIDIOC_S_MODULATOR()ioctl handler code.s_type_addr: sets tuner type and its I2C addr.s_config: sets tda9887 specific stuff, like port1, port2 and qss
Description
struct v4l2_subdev_audio_ops #
Callbacks used for audio-related settings
Definition
;
Members
s_clock_freq: set the frequency (in Hz) of the audio clock output. Used to slave an audio processor to the video decoder, ensuring that audio and video remain synchronized. Usual values for the frequency are 48000, 44100 or 32000 Hz. If the frequency is not supported, then -EINVAL is returned.s_i2s_clock_freq: sets I2S speed in bps. This is used to provide a standard way to select I2S clock used by driving digital audio streams at some board designs. Usual values for the frequency are 1024000 and 2048000. If the frequency is not supported, then-EINVALis returned.s_routing: used to define the input and/or output pins of an audio chip, and any additional configuration data. Never attempt to use user-level input IDs (e.g. Composite, S-Video, Tuner) at this level. An i2c device shouldn't know about whether an input pin is connected to a Composite connector, become on another board or platform it might be connected to something else entirely. The calling driver is responsible for mapping a user-level input to the right pins on the i2c device.s_stream: used to notify the audio code that stream will start or has stopped.
struct v4l2_mbus_frame_desc_entry_csi2 #
Definition
;
Members
vc: CSI-2 virtual channeldt: CSI-2 data type ID
enum v4l2_mbus_frame_desc_flags #
media bus frame description flags
Constants
V4L2_MBUS_FRAME_DESC_FL_LEN_MAX: Indicates thatstruct v4l2_mbus_frame_desc_entry->length field specifies maximum data length.V4L2_MBUS_FRAME_DESC_FL_BLOB: Indicates that the format does not have line offsets, i.e. the receiver should use 1D DMA.
struct v4l2_mbus_frame_desc_entry #
media bus frame description structure
Definition
;
Members
flags: bitmask flags, as defined byenum v4l2_mbus_frame_desc_flags.stream: stream in routing configurationpixelcode: media bus pixel code, valid if flagsFRAME_DESC_FL_BLOBis not set.length: number of octets per frame, valid if flagsV4L2_MBUS_FRAME_DESC_FL_LEN_MAXis set.bus: Bus-specific frame descriptor parametersbus.csi2: CSI-2-specific bus configuration
enum v4l2_mbus_frame_desc_type #
media bus frame description type
Constants
V4L2_MBUS_FRAME_DESC_TYPE_UNDEFINED: Undefined frame desc type. Drivers should not use this, it is for backwards compatibility.V4L2_MBUS_FRAME_DESC_TYPE_PARALLEL: Parallel media bus.V4L2_MBUS_FRAME_DESC_TYPE_CSI2: CSI-2 media bus. Frame desc parameters must be set instruct v4l2_mbus_frame_desc_entry->csi2.
struct v4l2_mbus_frame_desc #
media bus data frame description
Definition
;
Members
type: type of the bus (enum v4l2_mbus_frame_desc_type)entry: frame descriptors arraynum_entries: number of entries in entry array
enum v4l2_subdev_pre_streamon_flags #
Flags for pre_streamon subdev core op
Constants
V4L2_SUBDEV_PRE_STREAMON_FL_MANUAL_LP: Set the transmitter to either LP-11 or LP-111 mode before call tos_stream().
struct v4l2_subdev_video_ops #
Callbacks used when v4l device was opened in video mode.
Definition
;
Members
s_routing: see s_routing in audio_ops, except this version is for video devices.s_crystal_freq: sets the frequency of the crystal used to generate the clocks in Hz. An extra flags field allows device specific configuration regarding clock frequency dividers, etc. If not used, then set flags to 0. If the frequency is not supported, then -EINVAL is returned.g_std: callback forVIDIOC_G_STD()ioctl handler code.s_std: callback forVIDIOC_S_STD()ioctl handler code.s_std_output: set v4l2_std_id for video OUTPUT devices. This is ignored by video input devices.g_std_output: get current standard for video OUTPUT devices. This is ignored by video input devices.querystd: callback forVIDIOC_QUERYSTD()ioctl handler code.g_tvnorms: getv4l2_std_idwith all standards supported by the video CAPTURE device. This is ignored by video output devices.g_tvnorms_output: get v4l2_std_id with all standards supported by the video OUTPUT device. This is ignored by video capture devices.g_input_status: get input status. Same as the status field in thestruct v4l2_inputs_stream: start (enabled == 1) or stop (enabled == 0) streaming on the sub-device. Failure on stop will remove any resources acquired in streaming start, while the error code is still returned by the driver. The caller shall track the subdev state, and shall not start or stop an already started or stopped subdev. Also see call_s_stream wrapper in v4l2-subdev.c.s_rx_buffer: set a host allocated memory buffer for the subdev. The subdev can adjust size to a lower value and must not write more data to the buffer starting at data than the original value of size.pre_streamon: May be called before streaming is actually started, to help initialising the bus. Current usage is to set a CSI-2 transmitter to LP-11 or LP-111 mode before streaming. Seeenum v4l2_subdev_pre_streamon_flags.post_streamoff: Called after streaming is stopped, but if and only if pre_streamon was called earlier.
Description
This callback is DEPRECATED. New drivers should instead implement
v4l2_subdev_pad_ops.enable_streams and
v4l2_subdev_pad_ops.disable_streams operations, and use
v4l2_subdev_s_stream_helper for the v4l2_subdev_video_ops.s_stream
operation to support legacy users.
Drivers should also not call the .s_stream() subdev operation directly,
but use the v4l2_subdev_enable_streams() and
v4l2_subdev_disable_streams() helpers.
pre_streamon shall return error if it cannot perform the operation as indicated by the flags argument. In particular, -EACCES indicates lack of support for the operation. The caller shall call post_streamoff for each successful call of pre_streamon.
struct v4l2_subdev_vbi_ops #
Callbacks used when v4l device was opened in video mode via the vbi device node.
Definition
;
Members
decode_vbi_line: video decoders that support sliced VBI need to implement this ioctl. Field p of thestruct v4l2_decode_vbi_lineis set to the start of the VBI data that was generated by the decoder. The driver then parses the sliced VBI data and sets the other fields in the struct accordingly. The pointer p is updated to point to the start of the payload which can be copied verbatim into the data field of thestruct v4l2_sliced_vbi_data. If no valid VBI data was found, then the type field is set to 0 on return.s_vbi_data: used to generate VBI signals on a video signal.struct v4l2_sliced_vbi_datais filled with the data packets that should be output. Note that if you set the line field to 0, then that VBI signal is disabled. If no valid VBI data was found, then the type field is set to 0 on return.g_vbi_data: used to obtain the sliced VBI packet from a readback register. Not all video decoders support this. If no data is available because the readback register contains invalid or erroneous data-EIOis returned. Note that you must fill in the 'id' member and the 'field' member (to determine whether CC data from the first or second field should be obtained).g_sliced_vbi_cap: callback forVIDIOC_G_SLICED_VBI_CAP()ioctl handler code.s_raw_fmt: setup the video encoder/decoder for raw VBI.g_sliced_fmt: retrieve the current sliced VBI settings.s_sliced_fmt: setup the sliced VBI settings.
struct v4l2_subdev_sensor_ops #
v4l2-subdev sensor operations
Definition
;
Members
g_skip_top_lines: number of lines at the top of the image to be skipped. This is needed for some sensors, which always corrupt several top lines of the output image, or which send their metadata in them.g_skip_frames: number of frames to skip at stream start. This is needed for buggy sensors that generate faulty frames when they are turned on.
enum v4l2_subdev_ir_mode #
describes the type of IR supported
Constants
V4L2_SUBDEV_IR_MODE_PULSE_WIDTH: IR uses struct ir_raw_event records
struct v4l2_subdev_ir_parameters #
Parameters for IR TX or TX
Definition
;
Members
bytes_per_data_element: bytes per data element of data in read or write call.mode: IR mode as defined byenum v4l2_subdev_ir_mode.enable: device is active if trueinterrupt_enable: IR interrupts are enabled if trueshutdown: if true: set hardware to low/no power, false: normal modemodulation: if true, it uses carrier, if false: basebandmax_pulse_width: maximum pulse width in ns, valid only for baseband signalcarrier_freq: carrier frequency in Hz, valid only for modulated signalduty_cycle: duty cycle percentage, valid only for modulated signalinvert_level: invert signal levelinvert_carrier_sense: Send 0/space as a carrier burst. used only in TX.noise_filter_min_width: min time of a valid pulse, in ns. Used only for RX.carrier_range_lower: Lower carrier range, in Hz, valid only for modulated signal. Used only for RX.carrier_range_upper: Upper carrier range, in Hz, valid only for modulated signal. Used only for RX.resolution: The receive resolution, in ns . Used only for RX.
struct v4l2_subdev_ir_ops #
operations for IR subdevices
Definition
;
Members
rx_read: Reads received codes or pulse width data. The semantics are similar to a non-blockingread()call.rx_g_parameters: Get the current operating parameters and state of the IR receiver.rx_s_parameters: Set the current operating parameters and state of the IR receiver. It is recommended to call [rt]x_g_parameters first to fill out the current state, and only change the fields that need to be changed. Upon return, the actual device operating parameters and state will be returned. Note that hardware limitations may prevent the actual settings from matching the requested settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz was requested. An exception is when the shutdown parameter is true. The last used operational parameters will be returned, but the actual state of the hardware be different to minimize power consumption and processing when shutdown is true.tx_write: Writes codes or pulse width data for transmission. The semantics are similar to a non-blockingwrite()call.tx_g_parameters: Get the current operating parameters and state of the IR transmitter.tx_s_parameters: Set the current operating parameters and state of the IR transmitter. It is recommended to call [rt]x_g_parameters first to fill out the current state, and only change the fields that need to be changed. Upon return, the actual device operating parameters and state will be returned. Note that hardware limitations may prevent the actual settings from matching the requested settings - e.g. an actual carrier setting of 35,904 Hz when 36,000 Hz was requested. An exception is when the shutdown parameter is true. The last used operational parameters will be returned, but the actual state of the hardware be different to minimize power consumption and processing when shutdown is true.
struct v4l2_subdev_pad_config #
Used for storing subdev pad information.
Definition
;
Members
format:struct v4l2_mbus_framefmtcrop:struct v4l2_rectto be used for cropcompose:struct v4l2_rectto be used for composeinterval: frame interval
struct v4l2_subdev_stream_configs #
A collection of stream configs.
Definition
;
Members
num_configs: number of entries in config.configs: an array ofstruct v4l2_subdev_stream_configs.
struct v4l2_subdev_krouting #
subdev routing table
Definition
;
Members
len_routes: length of routes array, in routesnum_routes: number of routesroutes:struct v4l2_subdev_route
Description
This structure contains the routing table for a subdev.
struct v4l2_subdev_state #
Used for storing subdev state information.
Definition
;
Members
_lock: default for 'lock'lock: mutex for the state. May be replaced by the user.sd: the sub-device which the state is related topads:struct v4l2_subdev_pad_configarrayrouting: routing table for the subdevstream_configs: stream configurations (only for V4L2_SUBDEV_FL_STREAMS)
Description
This structure only needs to be passed to the pad op if the 'which' field
of the main argument is set to V4L2_SUBDEV_FORMAT_TRY. For
V4L2_SUBDEV_FORMAT_ACTIVE it is safe to pass NULL.
struct v4l2_subdev_pad_ops #
v4l2-subdev pad level operations
Definition
;
Members
enum_mbus_code: callback forVIDIOC_SUBDEV_ENUM_MBUS_CODE()ioctl handler code.enum_frame_size: callback forVIDIOC_SUBDEV_ENUM_FRAME_SIZE()ioctl handler code.enum_frame_interval: callback forVIDIOC_SUBDEV_ENUM_FRAME_INTERVAL()ioctl handler code.get_fmt: callback forVIDIOC_SUBDEV_G_FMT()ioctl handler code.set_fmt: callback forVIDIOC_SUBDEV_S_FMT()ioctl handler code.get_selection: callback forVIDIOC_SUBDEV_G_SELECTION()ioctl handler code.set_selection: callback forVIDIOC_SUBDEV_S_SELECTION()ioctl handler code.get_frame_interval: callback forVIDIOC_SUBDEV_G_FRAME_INTERVAL()ioctl handler code.set_frame_interval: callback forVIDIOC_SUBDEV_S_FRAME_INTERVAL()ioctl handler code.get_edid: callback forVIDIOC_SUBDEV_G_EDID()ioctl handler code.set_edid: callback forVIDIOC_SUBDEV_S_EDID()ioctl handler code.s_dv_timings: Set custom dv timings in the sub device. This is used when sub device is capable of setting detailed timing information in the hardware to generate/detect the video signal.g_dv_timings: Get custom dv timings in the sub device.query_dv_timings: callback forVIDIOC_QUERY_DV_TIMINGS()ioctl handler code.dv_timings_cap: callback forVIDIOC_SUBDEV_DV_TIMINGS_CAP()ioctl handler code.enum_dv_timings: callback forVIDIOC_SUBDEV_ENUM_DV_TIMINGS()ioctl handler code.link_validate: used by the media controller code to check if the links that belongs to a pipeline can be used for stream.get_frame_desc: get the current low level media bus frame parameters.set_frame_desc: set the low level media bus frame parameters, fd array may be adjusted by the subdev driver to device capabilities.get_mbus_config: get the media bus configuration of a remote sub-device. The media bus configuration is usually retrieved from the firmware interface at sub-device probe time, immediately applied to the hardware and eventually adjusted by the driver. Remote sub-devices (usually video receivers) shall use this operation to query the transmitting end bus configuration in order to adjust their own one accordingly. Callers should make sure they get the most up-to-date as possible configuration from the remote end, likely calling this operation as close as possible to stream on time. The operation shall fail if the pad index it has been called on is not valid or in case of unrecoverable failures. The config argument has been memset to 0 just before calling the op.set_routing: Enable or disable data connection routes described in the subdevice routing table. Subdevs that implement this operation must set the V4L2_SUBDEV_FL_STREAMS flag.enable_streams: Enable the streams defined in streams_mask on the given source pad. Subdevs that implement this operation must use the active state management provided by the subdev core (enabled through a call tov4l2_subdev_init_finalize()at initialization time). Do not call directly, usev4l2_subdev_enable_streams()instead.disable_streams: Disable the streams defined in streams_mask on the given source pad. Subdevs that implement this operation must use the active state management provided by the subdev core (enabled through a call tov4l2_subdev_init_finalize()at initialization time). Do not call directly, usev4l2_subdev_disable_streams()instead.
Description
Drivers that support only a single stream without setting the V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask argument.
Drivers that support only a single stream without setting the V4L2_SUBDEV_CAP_STREAMS sub-device capability flag can ignore the mask argument.
struct v4l2_subdev_ops #
Subdev operations
Definition
;
Members
core: pointer tostruct v4l2_subdev_core_ops. Can beNULLtuner: pointer tostruct v4l2_subdev_tuner_ops. Can beNULLaudio: pointer tostruct v4l2_subdev_audio_ops. Can beNULLvideo: pointer tostruct v4l2_subdev_video_ops. Can beNULLvbi: pointer tostruct v4l2_subdev_vbi_ops. Can beNULLir: pointer tostruct v4l2_subdev_ir_ops. Can beNULLsensor: pointer tostruct v4l2_subdev_sensor_ops. Can beNULLpad: pointer tostruct v4l2_subdev_pad_ops. Can beNULL
struct v4l2_subdev_internal_ops #
V4L2 subdev internal ops
Definition
;
Members
init_state: initialize the subdev state to default valuesregistered: called when this subdev is registered. When called the v4l2_dev field is set to the correct v4l2_device.unregistered: called when this subdev is unregistered. When called the v4l2_dev field is still set to the correct v4l2_device.open: called when the subdev device node is opened by an application.close: called when the subdev device node is closed. Please note that it is possible for close to be called after unregistered!release: called when the last user of the subdev device is gone. This happens after the unregistered callback and when the last open filehandle to the v4l-subdevX device node was closed. If no device node was created for this sub-device, then the release callback is called right after the unregistered callback. The release callback is typically used to free the memory containing the v4l2_subdev structure. It is almost certainly required for any sub-device that sets the V4L2_SUBDEV_FL_HAS_DEVNODE flag.
Description
struct v4l2_subdev_platform_data #
regulators config struct
Definition
;
Members
regulators: Optional regulators used to power on/off the subdevicenum_regulators: Number of regululatorshost_priv: Per-subdevice data, specific for a certain video host device
struct v4l2_subdev #
describes a V4L2 sub-device
Definition
;
Members
entity: pointer tostruct media_entitylist: List of sub-devicesowner: The owner is the same as the driver'sstruct deviceowner.owner_v4l2_dev: true if thesd->ownermatches the owner of v4l2_dev->dev owner. Initialized byv4l2_device_register_subdev().flags: subdev flags. Can be:V4L2_SUBDEV_FL_IS_I2C- Set this flag if this subdev is a i2c device;V4L2_SUBDEV_FL_IS_SPI- Set this flag if this subdev is a spi device;V4L2_SUBDEV_FL_HAS_DEVNODE- Set this flag if this subdev needs a device node;V4L2_SUBDEV_FL_HAS_EVENTS- Set this flag if this subdev generates events.v4l2_dev: pointer to structv4l2_deviceops: pointer to structv4l2_subdev_opsinternal_ops: pointer to structv4l2_subdev_internal_ops. Never call these internal ops from within a driver!ctrl_handler: The control handler of this subdev. May be NULL.name: Name of the sub-device. Please notice that the name must be unique.grp_id: can be used to group similar subdevs. Value is driver-specificdev_priv: pointer to private datahost_priv: pointer to private data used by the device where the subdev is attached.devnode: subdev device nodedev: pointer to the physical device, if anyfwnode: The fwnode_handle of the subdev, usually the same as either dev->of_node->fwnode or dev->fwnode (whichever is non-NULL).async_list: Links this subdev to a global subdev_list or notifier->done_list list.async_subdev_endpoint_list: List entry in async_subdev_endpoint_entry ofstruct v4l2_async_subdev_endpoint.subdev_notifier: A sub-device notifier implicitly registered for the sub- device usingv4l2_async_register_subdev_sensor().asc_list: Async connection list, ofstruct v4l2_async_connection.subdev_entry.pdata: common part of subdevice platform datastate_lock: A pointer to a lock used for all the subdev's states, set by the driver. This is optional. If NULL, each state instance will get a lock of its own.privacy_led: Optional pointer to a LED classdev for the privacy LED for sensors.active_state: Active state for the subdev (NULL for subdevs tracking the state internally). Initialized by callingv4l2_subdev_init_finalize().enabled_pads: Bitmask of enabled pads used byv4l2_subdev_enable_streams()andv4l2_subdev_disable_streams()helper functions for fallback cases.s_stream_enabled: Tracks whether streaming has been enabled with s_stream. This is only forcall_s_stream()internal use.
Description
Each instance of a subdev driver should create this struct, either stand-alone or embedded in a larger struct.
This structure should be initialized by v4l2_subdev_init() or one of
its variants: v4l2_spi_subdev_init(), v4l2_i2c_subdev_init().
media_entity_to_v4l2_subdev() #
Returns a struct v4l2_subdev from the struct media_entity embedded in it.
Parameters
ent: pointer tostruct media_entity.
vdev_to_v4l2_subdev() #
Returns a struct v4l2_subdev from the struct video_device embedded on it.
Parameters
vdev: pointer tostruct video_device
struct v4l2_subdev_fh #
Used for storing subdev information per file handle
Definition
;
Members
vfh: pointer tostruct v4l2_fhowner: module pointer to the owner of this file handlestate: pointer tostruct v4l2_subdev_stateclient_caps: bitmask ofV4L2_SUBDEV_CLIENT_CAP_*
to_v4l2_subdev_fh() #
Returns a struct v4l2_subdev_fh from the struct v4l2_fh embedded on it.
Parameters
fh: pointer tostruct v4l2_fh
v4l2_set_subdevdata() #
void Sets V4L2 dev private device data
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevvoid *p: pointer to the private device data to be stored.
v4l2_get_subdevdata() #
void * Gets V4L2 dev private device data
Parameters
const struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
Description
Returns the pointer to the private device data to be stored.
v4l2_set_subdev_hostdata() #
void Sets V4L2 dev private host data
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevvoid *p: pointer to the private data to be stored.
v4l2_get_subdev_hostdata() #
void * Gets V4L2 dev private data
Parameters
const struct v4l2_subdev *sd: pointer tostruct v4l2_subdev
Description
Returns the pointer to the private host data to be stored.
v4l2_subdev_get_fwnode_pad_1_to_1() #
int Get pad number from a subdev fwnode endpoint, assuming 1:1 port:pad
Parameters
struct media_entity *entity: Pointer to the subdev entitystruct fwnode_endpoint *endpoint: Pointer to a parsed fwnode endpoint
Description
This function can be used as the .get_fwnode_pad operation for subdevices that map port numbers and pad indexes 1:1. If the endpoint is owned by the subdevice, the function returns the endpoint port number.
Returns the endpoint port number on success or a negative error code.
v4l2_subdev_link_validate_default() #
int validates a media link
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevstruct media_link *link: pointer tostruct media_linkstruct v4l2_subdev_format *source_fmt: pointer tostruct v4l2_subdev_formatstruct v4l2_subdev_format *sink_fmt: pointer tostruct v4l2_subdev_format
Description
This function ensures that width, height and the media bus pixel code are equal on both source and sink of the link.
v4l2_subdev_link_validate() #
int validates a media link
Parameters
struct media_link *link: pointer tostruct media_link
Description
This function calls the subdev's link_validate ops to validate
if a media link is valid for streaming. It also internally
calls v4l2_subdev_link_validate_default() to ensure that
width, height and the media bus pixel code are equal on both
source and sink of the link.
The function can be used as a drop-in media_entity_ops.link_validate
implementation for v4l2_subdev instances. It supports all links between
subdevs, as well as links between subdevs and video devices, provided that
the video devices also implement their media_entity_ops.link_validate
operation.
v4l2_subdev_has_pad_interdep() #
bool MC has_pad_interdep implementation for subdevs
Parameters
struct media_entity *entity: pointer tostruct media_entityunsigned int pad0: pad number for the first padunsigned int pad1: pad number for the second pad
Description
This function is an implementation of the media_entity_operations.has_pad_interdep operation for subdevs that implement the multiplexed streams API (as indicated by the V4L2_SUBDEV_FL_STREAMS subdev flag).
It considers two pads interdependent if there is an active route between pad0 and pad1.
__v4l2_subdev_state_alloc() #
struct v4l2_subdev_state * allocate v4l2_subdev_state
Parameters
struct v4l2_subdev *sd: pointer tostruct v4l2_subdevfor which the state is being allocated.const char *lock_name: name of the state lockstruct lock_class_key *key: lock_class_key for the lock
Description
Must call __v4l2_subdev_state_free() when state is no longer needed.
Not to be called directly by the drivers.
__v4l2_subdev_state_free() #
void free a v4l2_subdev_state
Parameters
struct v4l2_subdev_state *state: v4l2_subdev_state to be freed.
Description
Not to be called directly by the drivers.
v4l2_subdev_init_finalize() #
Finalizes the initialization of the subdevice
Parameters
sd: The subdev
Description
This function finalizes the initialization of the subdev, including allocation of the active state for the subdev.
This function must be called by the subdev drivers that use the centralized
active state, after the subdev struct has been initialized and
media_entity_pads_init() has been called, but before registering the
subdev.
The user must call v4l2_subdev_cleanup() when the subdev is being removed.
v4l2_subdev_cleanup() #
void Releases the resources allocated by the subdevice
Parameters
struct v4l2_subdev *sd: The subdevice
Description
Clean up a V4L2 async sub-device. Must be called for a sub-device as part of
its release if resources have been associated with it using
v4l2_async_subdev_endpoint_add() or v4l2_subdev_init_finalize().
v4l2_subdev_state_get_format() #
Get pointer to a stream format
Parameters
state: subdevice statepad: pad id...: stream id (optional argument)
Description
This returns a pointer to struct v4l2_mbus_framefmt for the given pad +
stream in the subdev state.
For stream-unaware drivers the format for the corresponding pad is returned. If the pad does not exist, NULL is returned.
v4l2_subdev_state_get_crop() #
Get pointer to a stream crop rectangle
Parameters
state: subdevice statepad: pad id...: stream id (optional argument)
Description
This returns a pointer to crop rectangle for the given pad + stream in the subdev state.
For stream-unaware drivers the crop rectangle for the corresponding pad is returned. If the pad does not exist, NULL is returned.
v4l2_subdev_state_get_compose() #
Get pointer to a stream compose rectangle
Parameters
state: subdevice statepad: pad id...: stream id (optional argument)
Description
This returns a pointer to compose rectangle for the given pad + stream in the subdev state.
For stream-unaware drivers the compose rectangle for the corresponding pad is returned. If the pad does not exist, NULL is returned.
v4l2_subdev_state_get_interval() #
Get pointer to a stream frame interval
Parameters
state: subdevice statepad: pad id...: stream id (optional argument)
Description
This returns a pointer to the frame interval for the given pad + stream in the subdev state.
For stream-unaware drivers the frame interval for the corresponding pad is returned. If the pad does not exist, NULL is returned.
v4l2_subdev_get_fmt() #
int Fill format based on state
Parameters
struct v4l2_subdev *sd: subdevicestruct v4l2_subdev_state *state: subdevice statestruct v4l2_subdev_format *format: pointer tostruct v4l2_subdev_format
Description
Fill format->format field based on the information in the format struct.
This function can be used by the subdev drivers which support active state to implement v4l2_subdev_pad_ops.get_fmt if the subdev driver does not need to do anything special in their get_fmt op.
Returns 0 on success, error value otherwise.
v4l2_subdev_get_frame_interval() #
int Fill frame interval based on state
Parameters
struct v4l2_subdev *sd: subdevicestruct v4l2_subdev_state *state: subdevice statestruct v4l2_subdev_frame_interval *fi: pointer tostruct v4l2_subdev_frame_interval
Description
Fill fi->interval field based on the information in the fi struct.
This function can be used by the subdev drivers which support active state to implement v4l2_subdev_pad_ops.get_frame_interval if the subdev driver does not need to do anything special in their get_frame_interval op.
Returns 0 on success, error value otherwise.
v4l2_subdev_set_routing() #
int Set given routing to subdev state
Parameters
struct v4l2_subdev *sd: The subdevicestruct v4l2_subdev_state *state: The subdevice stateconst struct v4l2_subdev_krouting *routing: Routing that will be copied to subdev state
Description
This will release old routing table (if any) from the state, allocate enough space for the given routing, and copy the routing.
This can be used from the subdev driver's set_routing op, after validating the routing.
for_each_active_route() #
iterate on all active routes of a routing table
Parameters
routing: The routing tableroute: The route iterator
v4l2_subdev_set_routing_with_fmt() #
int Set given routing and format to subdev state
Parameters
struct v4l2_subdev *sd: The subdevicestruct v4l2_subdev_state *state: The subdevice stateconst struct v4l2_subdev_krouting *routing: Routing that will be copied to subdev stateconst struct v4l2_mbus_framefmt *fmt: Format used to initialize all the streams
Description
This is the same as v4l2_subdev_set_routing, but additionally initializes all the streams using the given format.
v4l2_subdev_routing_find_opposite_end() #
int Find the opposite stream
Parameters
const struct v4l2_subdev_krouting *routing: routing used to find the opposite sideu32 pad: pad idu32 stream: stream idu32 *other_pad: pointer used to return the opposite padu32 *other_stream: pointer used to return the opposite stream
Description
This function uses the routing table to find the pad + stream which is opposite the given pad + stream.
other_pad and/or other_stream can be NULL if the caller does not need the value.
Returns 0 on success, or -EINVAL if no matching route is found.
v4l2_subdev_state_get_opposite_stream_format() #
struct v4l2_mbus_framefmt * Get pointer to opposite stream format
Parameters
struct v4l2_subdev_state *state: subdevice stateu32 pad: pad idu32 stream: stream id
Description
This returns a pointer to struct v4l2_mbus_framefmt for the pad + stream
that is opposite the given pad + stream in the subdev state.
If the state does not contain the given pad + stream, NULL is returned.
v4l2_subdev_state_xlate_streams() #
u64 Translate streams from one pad to another
Parameters
const struct v4l2_subdev_state *state: Subdevice stateu32 pad0: The first padu32 pad1: The second padu64 *streams: Streams bitmask on the first pad
Description
Streams on sink pads of a subdev are routed to source pads as expressed in the subdev state routing table. Stream numbers don't necessarily match on the sink and source side of a route. This function translates stream numbers on pad0, expressed as a bitmask in streams, to the corresponding streams on pad1 using the routing table from the state. It returns the stream mask on pad1, and updates streams with the streams that have been found in the routing table.
pad0 and pad1 must be a sink and a source, in any order.
Return
The bitmask of streams of pad1 that are routed to streams on pad0.
enum v4l2_subdev_routing_restriction #
Subdevice internal routing restrictions
Constants
V4L2_SUBDEV_ROUTING_NO_1_TO_N: an input stream shall not be routed to multiple output streams (stream duplication)V4L2_SUBDEV_ROUTING_NO_N_TO_1: multiple input streams shall not be routed to the same output stream (stream merging)V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX: all streams from a sink pad must be routed to a single source padV4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX: all streams on a source pad must originate from a single sink padV4L2_SUBDEV_ROUTING_NO_SINK_MULTIPLEXING: sink pads shall not contain multiplexed streamsV4L2_SUBDEV_ROUTING_NO_SOURCE_MULTIPLEXING: source pads shall not contain multiplexed streamsV4L2_SUBDEV_ROUTING_ONLY_1_TO_1: only non-overlapping 1-to-1 stream routing is allowed (a combination of V4L2_SUBDEV_ROUTING_NO_1_TO_N and V4L2_SUBDEV_ROUTING_NO_N_TO_1)V4L2_SUBDEV_ROUTING_NO_STREAM_MIX: all streams from a sink pad must be routed to a single source pad, and that source pad shall not get routes from any other sink pad (a combination of V4L2_SUBDEV_ROUTING_NO_SINK_STREAM_MIX and V4L2_SUBDEV_ROUTING_NO_SOURCE_STREAM_MIX)V4L2_SUBDEV_ROUTING_NO_MULTIPLEXING: no multiplexed streams allowed on either source or sink sides.
v4l2_subdev_routing_validate() #
int Verify that routes comply with driver constraints
Parameters
struct v4l2_subdev *sd: The subdeviceconst struct v4l2_subdev_krouting *routing: Routing to verifyenum v4l2_subdev_routing_restriction disallow: Restrictions on routes
Description
This verifies that the given routing complies with the disallow constraints.
Returns 0 on success, error value otherwise.
v4l2_subdev_enable_streams() #
int Enable streams on a pad
Parameters
struct v4l2_subdev *sd: The subdeviceu32 pad: The padu64 streams_mask: Bitmask of streams to enable
Description
This function enables streams on a source pad of a subdevice. The pad is identified by its index, while the streams are identified by the streams_mask bitmask. This allows enabling multiple streams on a pad at once.
Enabling a stream that is already enabled isn't allowed. If streams_mask contains an already enabled stream, this function returns -EALREADY without performing any operation.
Per-stream enable is only available for subdevs that implement the
.enable_streams() and .disable_streams() operations. For other subdevs, this
function implements a best-effort compatibility by calling the .s_stream()
operation, limited to subdevs that have a single source pad.
Drivers that are not stream-aware shall set streams_mask to BIT_ULL(0).
Return
- 0: Success
- -EALREADY: One of the streams in streams_mask is already enabled
- -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
- -EOPNOTSUPP: Falling back to the legacy .
s_stream()operation is impossible because the subdev has multiple source pads
v4l2_subdev_disable_streams() #
int Disable streams on a pad
Parameters
struct v4l2_subdev *sd: The subdeviceu32 pad: The padu64 streams_mask: Bitmask of streams to disable
Description
This function disables streams on a source pad of a subdevice. The pad is identified by its index, while the streams are identified by the streams_mask bitmask. This allows disabling multiple streams on a pad at once.
Disabling a streams that is not enabled isn't allowed. If streams_mask contains a disabled stream, this function returns -EALREADY without performing any operation.
Per-stream disable is only available for subdevs that implement the
.enable_streams() and .disable_streams() operations. For other subdevs, this
function implements a best-effort compatibility by calling the .s_stream()
operation, limited to subdevs that have a single source pad.
Drivers that are not stream-aware shall set streams_mask to BIT_ULL(0).
Return
- 0: Success
- -EALREADY: One of the streams in streams_mask is not enabled
- -EINVAL: The pad index is invalid, or doesn't correspond to a source pad
- -EOPNOTSUPP: Falling back to the legacy .
s_stream()operation is impossible because the subdev has multiple source pads
v4l2_subdev_s_stream_helper() #
int Helper to implement the subdev s_stream operation using enable_streams and disable_streams
Parameters
struct v4l2_subdev *sd: The subdeviceint enable: Enable or disable streaming
Description
Subdevice drivers that implement the streams-aware
v4l2_subdev_pad_ops.enable_streams and v4l2_subdev_pad_ops.disable_streams
operations can use this helper to implement the legacy
v4l2_subdev_video_ops.s_stream operation.
This helper can only be used by subdevs that have a single source pad.
Return
0 on success, or a negative error code otherwise.
v4l2_subdev_lock_state() #
void Locks the subdev state
Parameters
struct v4l2_subdev_state *state: The subdevice state
Description
Locks the given subdev state.
The state must be unlocked with v4l2_subdev_unlock_state() after use.
v4l2_subdev_unlock_state() #
void Unlocks the subdev state
Parameters
struct v4l2_subdev_state *state: The subdevice state
Description
Unlocks the given subdev state.
v4l2_subdev_lock_states() #
void Lock two sub-device states
Parameters
struct v4l2_subdev_state *state1: One subdevice statestruct v4l2_subdev_state *state2: The other subdevice state
Description
Locks the state of two sub-devices.
The states must be unlocked with v4l2_subdev_unlock_states() after use.
This differs from calling v4l2_subdev_lock_state() on both states so that if
the states share the same lock, the lock is acquired only once (so no
deadlock occurs). The caller is responsible for ensuring the locks will
always be acquired in the same order.
v4l2_subdev_unlock_states() #
void Unlock two sub-device states
Parameters
struct v4l2_subdev_state *state1: One subdevice statestruct v4l2_subdev_state *state2: The other subdevice state
Description
Unlocks the state of two sub-devices.
This differs from calling v4l2_subdev_unlock_state() on both states so that
if the states share the same lock, the lock is released only once.
v4l2_subdev_get_unlocked_active_state() #
struct v4l2_subdev_state * Checks that the active subdev state is unlocked and returns it
Parameters
struct v4l2_subdev *sd: The subdevice
Description
Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls
lockdep_assert_not_held() to issue a warning if the state is locked.
This function is to be used e.g. when getting the active state for the sole purpose of passing it forward, without accessing the state fields.
v4l2_subdev_get_locked_active_state() #
struct v4l2_subdev_state * Checks that the active subdev state is locked and returns it
Parameters
struct v4l2_subdev *sd: The subdevice
Description
Returns the active state for the subdevice, or NULL if the subdev does not
support active state. If the state is not NULL, calls lockdep_assert_held()
to issue a warning if the state is not locked.
This function is to be used when the caller knows that the active state is already locked.
v4l2_subdev_lock_and_get_active_state() #
struct v4l2_subdev_state * Locks and returns the active subdev state for the subdevice
Parameters
struct v4l2_subdev *sd: The subdevice
Description
Returns the locked active state for the subdevice, or NULL if the subdev does not support active state.
The state must be unlocked with v4l2_subdev_unlock_state() after use.
v4l2_subdev_init() #
void initializes the sub-device struct
Parameters
struct v4l2_subdev *sd: pointer to thestruct v4l2_subdevto be initializedconst struct v4l2_subdev_ops *ops: pointer tostruct v4l2_subdev_ops.
v4l2_subdev_call() #
call an operation of a v4l2_subdev.
Parameters
sd: pointer to thestruct v4l2_subdevo: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of callbacks functions.f: callback function to be called. The callback functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Example
err = v4l2_subdev_call(sd, video, s_std, norm);
v4l2_subdev_call_state_active() #
call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev its active state.
Parameters
sd: pointer to thestruct v4l2_subdevo: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of callbacks functions.f: callback function to be called. The callback functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
This is similar to v4l2_subdev_call(), except that this version can only be
used for ops that take a subdev state as a parameter. The macro will get the
active state, lock it before calling the op and unlock it after the call.
v4l2_subdev_call_state_try() #
call an operation of a v4l2_subdev which takes state as a parameter, passing the subdev a newly allocated try state.
Parameters
sd: pointer to thestruct v4l2_subdevo: name of the element atstruct v4l2_subdev_opsthat contains f. Each element there groups a set of callbacks functions.f: callback function to be called. The callback functions are defined in groups, according to each element atstruct v4l2_subdev_ops.args...: arguments for f.
Description
This is similar to v4l2_subdev_call_state_active(), except that as this
version allocates a new state, this is only usable for
V4L2_SUBDEV_FORMAT_TRY use cases.
Note
only legacy non-MC drivers may need this macro.
v4l2_subdev_has_op() #
Checks if a subdev defines a certain operation.
Parameters
sd: pointer to thestruct v4l2_subdevo: The group of callback functions instruct v4l2_subdev_opswhich f is a part of.f: callback function to be checked for its existence.
v4l2_subdev_notify_event() #
void Delivers event notification for subdevice
Parameters
struct v4l2_subdev *sd: The subdev for which to deliver the eventconst struct v4l2_event *ev: The event to deliver
Description
Will deliver the specified event to all userspace event listeners which are
subscribed to the v42l subdev event queue as well as to the bridge driver
using the notify callback. The notification type for the notify callback
will be V4L2_DEVICE_NOTIFY_EVENT.
v4l2_subdev_is_streaming() #
bool Returns if the subdevice is streaming
Parameters
struct v4l2_subdev *sd: The subdevice
Description
v4l2_subdev_is_streaming() tells if the subdevice is currently streaming.
"Streaming" here means whether .s_stream() or .enable_streams() has been
successfully called, and the streaming has not yet been disabled.
If the subdevice implements .enable_streams() this function must be called
while holding the active state lock.
Tuner functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
enum tuner_mode #
Mode of the tuner
Constants
T_RADIO: Tuner core will work in radio modeT_ANALOG_TV: Tuner core will work in analog TV mode
Description
Older boards only had a single tuner device, but some devices have a separate tuner for radio. In any case, the tuner-core needs to know if the tuner chip(s) will be used in radio mode or analog TV mode, as, on radio mode, frequencies are specified on a different range than on TV mode. This enum is used by the tuner core in order to work with the proper tuner range and eventually use a different tuner chip while in radio mode.
struct tuner_setup #
setup the tuner chipsets
Definition
;
Members
addr: I2C address used to control the tuner device/chipsettype: Type of the tuner, as defined at the TUNER_* macros. Each different tuner model should have an unique identifier.mode_mask: Mask with the allowed tuner modes: V4L2_TUNER_RADIO, V4L2_TUNER_ANALOG_TV and/or V4L2_TUNER_DIGITAL_TV, describing if the tuner should be used to support Radio, analog TV and/or digital TV.config: Used to send tuner-specific configuration for complex tuners that require extra parameters to be set. Only a very few tuners require it and its usage on newer tuners should be avoided.tuner_callback: Some tuners require to call back the bridge driver, in order to do some tasks like rising a GPIO at the bridge chipset, in order to do things like resetting the device.
Description
Older boards only had a single tuner device. Nowadays multiple tuner devices may be present on a single board. Using TUNER_SET_TYPE_ADDR to pass the tuner_setup structure it is possible to setup each tuner device in turn.
Since multiple devices may be present it is no longer sufficient to send a command to a single i2c device. Instead you should broadcast the command to all i2c devices.
By setting the mode_mask correctly you can select which commands are accepted by a specific tuner device. For example, set mode_mask to T_RADIO if the device is a radio-only tuner. That specific tuner will only accept commands when the tuner is in radio mode and ignore them when the tuner is set to TV mode.
enum param_type #
type of the tuner pameters
Constants
TUNER_PARAM_TYPE_RADIO: Tuner params are for FM and/or AM radioTUNER_PARAM_TYPE_PAL: Tuner params are for PAL color TV standardTUNER_PARAM_TYPE_SECAM: Tuner params are for SECAM color TV standardTUNER_PARAM_TYPE_NTSC: Tuner params are for NTSC color TV standardTUNER_PARAM_TYPE_DIGITAL: Tuner params are for digital TV
struct tuner_range #
define the frequencies supported by the tuner
Definition
;
Members
limit: Max frequency supported by that range, in 62.5 kHz (TV) or 62.5 Hz (Radio), as defined by V4L2_TUNER_CAP_LOW.config: Value of the band switch byte (BB) to setup this mode.cb: Value of the CB byte to setup this mode.
Description
Please notice that digital tuners like xc3028/xc4000/xc5000 don't use those ranges, as they're defined inside the driver. This is used by analog tuners that are compatible with the "Philips way" to setup the tuners. On those devices, the tuner set is done via 4 bytes:
#) divider byte1 (DB1) #) divider byte 2 (DB2) #) Control byte (CB) #) band switch byte (BB)
Some tuners also have an additional optional Auxiliary byte (AB).
struct tuner_params #
Parameters to be used to setup the tuner. Those are used by drivers/media/tuners/tuner-types.c in order to specify the tuner properties. Most of the parameters are for tuners based on tda9887 IF-PLL multi-standard analog TV/Radio demodulator, with is very common on legacy analog tuners.
Definition
;
Members
type: Type of the tuner parameters, as defined at enum param_type. If the tuner supports multiple standards, an array should be used, with one row per different standard.cb_first_if_lower_freq: Many Philips-based tuners have a comment in their datasheet like "For channel selection involving band switching, and to ensure smooth tuning to the desired channel without causing unnecessary charge pump action, it is recommended to consider the difference between wanted channel frequency and the current channel frequency. Unnecessary charge pump action will result in very low tuning voltage which may drive the oscillator to extreme conditions". Set cb_first_if_lower_freq to 1, if this check is required for this tuner. I tested this for PAL by first setting the TV frequency to 203 MHz and then switching to 96.6 MHz FM radio. The result was static unless the control byte was sent first.has_tda9887: Set to 1 if this tuner uses a tda9887port1_fm_high_sensitivity: Many Philips tuners use tda9887 PORT1 to select the FM radio sensitivity. If this setting is 1, then set PORT1 to 1 to get proper FM reception.port2_fm_high_sensitivity: Some Philips tuners use tda9887 PORT2 to select the FM radio sensitivity. If this setting is 1, then set PORT2 to 1 to get proper FM reception.fm_gain_normal: Some Philips tuners use tda9887 cGainNormal to select the FM radio sensitivity. If this setting is 1, e register will use cGainNormal instead of cGainLow.intercarrier_mode: Most tuners with a tda9887 use QSS mode. Some (cheaper) tuners use Intercarrier mode. If this setting is 1, then the tuner needs to be set to intercarrier mode.port1_active: This setting sets the default value for PORT1. 0 means inactive, 1 means active. Note: the actual bit value written to the tda9887 is inverted. So a 0 here means a 1 in the B6 bit.port2_active: This setting sets the default value for PORT2. 0 means inactive, 1 means active. Note: the actual bit value written to the tda9887 is inverted. So a 0 here means a 1 in the B7 bit.port1_invert_for_secam_lc: Sometimes PORT1 is inverted when the SECAM-L' standard is selected. Set this bit to 1 if this is needed.port2_invert_for_secam_lc: Sometimes PORT2 is inverted when the SECAM-L' standard is selected. Set this bit to 1 if this is needed.port1_set_for_fm_mono: Some cards require PORT1 to be 1 for mono Radio FM and 0 for stereo.default_pll_gating_18: Select 18% (or according to datasheet 0%) L standard PLL gating, vs the driver default of 36%.radio_if: IF to use in radio mode. Tuners with a separate radio IF filter seem to use 10.7, while those without use 33.3 for PAL/SECAM tuners and 41.3 for NTSC tuners. 0 = 10.7, 1 = 33.3, 2 = 41.3default_top_low: Default tda9887 TOP value in dB for the low band. Default is 0. Range: -16:+15default_top_mid: Default tda9887 TOP value in dB for the mid band. Default is 0. Range: -16:+15default_top_high: Default tda9887 TOP value in dB for the high band. Default is 0. Range: -16:+15default_top_secam_low: Default tda9887 TOP value in dB for SECAM-L/L' for the low band. Default is 0. Several tuners require a different TOP value for the SECAM-L/L' standards. Range: -16:+15default_top_secam_mid: Default tda9887 TOP value in dB for SECAM-L/L' for the mid band. Default is 0. Several tuners require a different TOP value for the SECAM-L/L' standards. Range: -16:+15default_top_secam_high: Default tda9887 TOP value in dB for SECAM-L/L' for the high band. Default is 0. Several tuners require a different TOP value for the SECAM-L/L' standards. Range: -16:+15iffreq: Intermediate frequency (IF) used by the tuner on digital mode.count: Size of the ranges array.ranges: Array with the frequency ranges supported by the tuner.
struct tunertype #
describes the known tuners.
Definition
;
Members
name: string with the tuner's name.count: size ofstruct tuner_paramsarray.params: pointer tostruct tuner_paramsarray.min: minimal tuner frequency, in 62.5 kHz step. should be multiplied to 16 to convert to MHz.max: minimal tuner frequency, in 62.5 kHz step. Should be multiplied to 16 to convert to MHz.stepsize: frequency step, in Hz.initdata: optional byte sequence to initialize the tuner.sleepdata: optional byte sequence to power down the tuner.
Hauppauge TV EEPROM functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
enum tveeprom_audio_processor #
Specifies the type of audio processor used on a Hauppauge device.
Constants
TVEEPROM_AUDPROC_NONE: No audio processor presentTVEEPROM_AUDPROC_INTERNAL: The audio processor is internal to the video processorTVEEPROM_AUDPROC_MSP: The audio processor is a MSPXXXX deviceTVEEPROM_AUDPROC_OTHER: The audio processor is another device
struct tveeprom #
Contains the fields parsed from Hauppauge eeproms
Definition
;
Members
has_radio: 1 if the device has radio; 0 otherwise.has_ir: If has_ir == 0, then it is unknown what the IR capabilities are. Otherwise: bit 0) 1 (= IR capabilities are known); bit 1) IR receiver present; bit 2) IR transmitter (blaster) present.has_MAC_address: 0: no MAC, 1: MAC present, 2: unknown.tuner_type: type of the tuner (TUNER_*, as defined at include/media/tuner.h).tuner_formats: Supported analog TV standards (V4L2_STD_*).tuner_hauppauge_model: Hauppauge's code for the device model number.tuner2_type: type of the second tuner (TUNER_*, as defined at include/media/tuner.h).tuner2_formats: Tuner 2 supported analog TV standards (V4L2_STD_*).tuner2_hauppauge_model: tuner 2 Hauppauge's code for the device model number.audio_processor: analog audio decoder, as defined by enum tveeprom_audio_processor.decoder_processor: Hauppauge's code for the decoder chipset. Unused by the drivers, as they probe the decoder based on the PCI or USB ID.model: Hauppauge's model numberrevision: Card revision numberserial_number: Card's serial numberrev_str: Card revision converted to numberMAC_address: MAC address for the network interface
tveeprom_hauppauge_analog() #
void Fill struct tveeprom using the contents of the eeprom previously filled at eeprom_data field.
Parameters
struct tveeprom *tvee: Struct to where the eeprom parsed data will be filled;unsigned char *eeprom_data: Array with the contents of the eeprom_data. It should contain 256 bytes filled with the contents of the eeprom read from the Hauppauge device.
tveeprom_read() #
int Reads the contents of the eeprom found at the Hauppauge devices.
Parameters
struct i2c_client *c: I2C client structunsigned char *eedata: Array where the eeprom content will be stored.int len: Size of eedata array. If the eeprom content will be latter be parsed bytveeprom_hauppauge_analog(), len should be, at least, 256.
V4L2 videobuf2 functions and data structures
Peios Kernel / Hardware and drivers / Driver development / Media devices
enum vb2_memory #
type of memory model used to make the buffers visible on userspace.
Constants
VB2_MEMORY_UNKNOWN: Buffer status is unknown or it is not used yet on userspace.VB2_MEMORY_MMAP: The buffers are allocated by the Kernel and it is memory mapped viammap()ioctl. This model is also used when the user is using the buffers viaread()orwrite()system calls.VB2_MEMORY_USERPTR: The buffers was allocated in userspace and it is memory mapped viammap()ioctl.VB2_MEMORY_DMABUF: The buffers are passed to userspace via DMA buffer.
struct vb2_mem_ops #
memory handling/memory allocator operations.
Definition
;
Members
alloc: allocate video memory and, optionally, allocator private data, returnERR_PTR()on failure or a pointer to allocator private, per-buffer data on success; the returned private structure will then be passed as buf_priv argument to other ops in this structure. The size argument to this function shall be page aligned.put: inform the allocator that the buffer will no longer be used; usually will result in the allocator freeing the buffer (if no other users of this buffer are present); the buf_priv argument is the allocator private per-buffer structure previously returned from the alloc callback.get_dmabuf: acquire userspace memory for a hardware operation; used for DMABUF memory types.get_userptr: acquire userspace memory for a hardware operation; used for USERPTR memory types; vaddr is the address passed to the videobuf2 layer when queuing a video buffer of USERPTR type; should return an allocator private per-buffer structure associated with the buffer on success,ERR_PTR()on failure; the returned private structure will then be passed as buf_priv argument to other ops in this structure.put_userptr: inform the allocator that a USERPTR buffer will no longer be used.prepare: called every time the buffer is passed from userspace to the driver, useful for cache synchronisation, optional.finish: called every time the buffer is passed back from the driver to the userspace, also optional.attach_dmabuf: attach a sharedstruct dma_buffor a hardware operation; used for DMABUF memory types; dev is the alloc device dbuf is the shared dma_buf; returnsERR_PTR()on failure; allocator private per-buffer structure on success; this needs to be used for further accesses to the buffer.detach_dmabuf: inform the exporter of the buffer that the current DMABUF buffer is no longer used; the buf_priv argument is the allocator private per-buffer structure previously returned from the attach_dmabuf callback.map_dmabuf: request for access to the dmabuf from allocator; the allocator of dmabuf is informed that this driver is going to use the dmabuf.unmap_dmabuf: releases access control to the dmabuf - allocator is notified that this driver is done using the dmabuf for now.vaddr: return a kernel virtual address to a given memory buffer associated with the passed private structure or NULL if no such mapping exists.cookie: return allocator specific cookie for a given memory buffer associated with the passed private structure or NULL if not available.num_users: return the current number of users of a memory buffer; return 1 if the videobuf2 layer (or actually the driver using it) is the only user.mmap: setup a userspace mapping for a given memory buffer under the provided virtual memory region.
Description
Those operations are used by the videobuf2 core to implement the memory handling/memory allocators for each type of supported streaming I/O method.
struct vb2_plane #
plane information.
Definition
;
Members
mem_priv: private data with this plane.dbuf: dma_buf - shared buffer object.dbuf_mapped: flag to show whether dbuf is mapped or notdbuf_duplicated: boolean to show whether dbuf is duplicated with a previous plane of the buffer.bytesused: number of bytes occupied by data in the plane (payload).length: size of this plane (NOT the payload) in bytes. The maximum valid size is MAX_UINT - PAGE_SIZE.min_length: minimum required size of this plane (NOT the payload) in bytes. length is always greater or equal to min_length, and like length, it is limited to MAX_UINT - PAGE_SIZE.m: Union with memtype-specific data.m.offset: when memory in the associated struct vb2_buffer isVB2_MEMORY_MMAP, equals the offset from the start of the device memory for this plane (or is a "cookie" that should be passed tommap()called on the video node).m.userptr: when memory isVB2_MEMORY_USERPTR, a userspace pointer pointing to this plane.m.fd: when memory isVB2_MEMORY_DMABUF, a userspace file descriptor associated with this plane.data_offset: offset in the plane to the start of data; usually 0, unless there is a header in front of the data.
Description
Should contain enough information to be able to cover all the fields
of struct v4l2_plane at videodev2.h.
enum vb2_io_modes #
queue access methods.
Constants
VB2_MMAP: driver supports MMAP with streaming API.VB2_USERPTR: driver supports USERPTR with streaming API.VB2_READ: driver supportsread()style access.VB2_WRITE: driver supportswrite()style access.VB2_DMABUF: driver supports DMABUF with streaming API.
enum vb2_buffer_state #
current video buffer state.
Constants
VB2_BUF_STATE_DEQUEUED: buffer under userspace control.VB2_BUF_STATE_IN_REQUEST: buffer is queued in media request.VB2_BUF_STATE_PREPARING: buffer is being prepared in videobuf2.VB2_BUF_STATE_QUEUED: buffer queued in videobuf2, but not in driver.VB2_BUF_STATE_ACTIVE: buffer queued in driver and possibly used in a hardware operation.VB2_BUF_STATE_DONE: buffer returned from driver to videobuf2, but not yet dequeued to userspace.VB2_BUF_STATE_ERROR: same as above, but the operation on the buffer has ended with an error, which will be reported to the userspace when it is dequeued.
struct vb2_buffer #
represents a video buffer.
Definition
;
Members
vb2_queue: pointer tostruct vb2_queuewith the queue to which this driver belongs.index: id number of the buffer.type: buffer type.memory: the method, in which the actual data is passed.num_planes: number of planes in the buffer on an internal driver queue.timestamp: frame timestamp in ns.request: the request this buffer is associated with.req_obj: used to bind this buffer to a request. This request object has a refcount.
struct vb2_ops #
driver-specific callbacks.
Definition
;
Members
queue_setup: called fromVIDIOC_REQBUFS()andVIDIOC_CREATE_BUFS()handlers before memory allocation. It can be called twice: if the original number of requested buffers could not be allocated, then it will be called a second time with the actually allocated number of buffers to verify if that is OK. The driver should return the required number of buffers in *num_buffers, the required number of planes per buffer in *num_planes, the size of each plane should be set in the sizes\[\] array and optional per-plane allocator specific device in the alloc_devs\[\] array. When called fromVIDIOC_REQBUFS(), *num_planes == 0, the driver has to use the currently configured format to determine the plane sizes and *num_buffers is the total number of buffers that are being allocated. When called fromVIDIOC_CREATE_BUFS(), *num_planes != 0 and it describes the requested number of planes and sizes\[\] contains the requested plane sizes. In this case *num_buffers are being allocated additionally to the buffers already allocated. If either *num_planes or the requested sizes are invalid callback must return-EINVAL.buf_out_validate: called when the output buffer is prepared or queued to a request; drivers can use this to validate userspace-provided information; this is required only for OUTPUT queues.buf_init: called once after allocating a buffer (in MMAP case) or after acquiring a new USERPTR buffer; drivers may perform additional buffer-related initialization; initialization failure (return != 0) will prevent queue setup from completing successfully; optional.buf_prepare: called every time the buffer is queued from userspace and from theVIDIOC_PREPARE_BUF()ioctl; drivers may perform any initialization required before each hardware operation in this callback; drivers can access/modify the buffer here as it is still synced for the CPU; drivers that supportVIDIOC_CREATE_BUFS()must also validate the buffer size; if an error is returned, the buffer will not be queued in driver; optional.buf_finish: called before every dequeue of the buffer back to userspace; the buffer is synced for the CPU, so drivers can access/modify the buffer contents; drivers may perform any operations required before userspace accesses the buffer; optional. The buffer state can be one of the following:DONEandERRORoccur while streaming is in progress, and thePREPAREDstate occurs when the queue has been canceled and all pending buffers are being returned to their defaultDEQUEUEDstate. Typically you only have to do something if the state isVB2_BUF_STATE_DONE, since in all other cases the buffer contents will be ignored anyway.buf_cleanup: called once before the buffer is freed; drivers may perform any additional cleanup; optional.prepare_streaming: called once to prepare for 'streaming' state; this is where validation can be done to verify everything is okay and streaming resources can be claimed. It is called when the VIDIOC_STREAMON ioctl is called. The actual streaming starts when start_streaming is called. Optional.start_streaming: called once to enter 'streaming' state; the driver may receive buffers with buf_queue callback before start_streaming is called; the driver gets the number of already queued buffers in count parameter; driver can return an error if hardware fails, in that case all buffers that have been already given by the buf_queue callback are to be returned by the driver by callingvb2_buffer_done()withVB2_BUF_STATE_QUEUED. If you need a minimum number of buffers before you can start streaming, then setvb2_queue->min_queued_buffers. If that is non-zero then start_streaming won't be called until at least that many buffers have been queued up by userspace.stop_streaming: called when 'streaming' state must be disabled; driver should stop any DMA transactions or wait until they finish and give back all buffers it got frombuf_queuecallback by callingvb2_buffer_done()with eitherVB2_BUF_STATE_DONEorVB2_BUF_STATE_ERROR; may usevb2_wait_for_all_buffers()functionunprepare_streaming: called as counterpart to prepare_streaming; any claimed streaming resources can be released here. It is called when the VIDIOC_STREAMOFF ioctls is called or when the streaming filehandle is closed. Optional.buf_queue: passes buffer vb to the driver; driver may start hardware operation on this buffer; driver should give the buffer back by callingvb2_buffer_done()function; it is always called after callingVIDIOC_STREAMON()ioctl; might be called before start_streaming callback if user pre-queued buffers before callingVIDIOC_STREAMON().buf_request_complete: a buffer that was never queued to the driver but is associated with a queued request was canceled. The driver will have to mark associated objects in the request as completed; required if requests are supported.
Description
These operations are not called from interrupt context except where mentioned specifically.
struct vb2_buf_ops #
driver-specific callbacks.
Definition
;
Members
verify_planes_array: Verify that a given user space structure contains enough planes for the buffer. This is called for each dequeued buffer.init_buffer: given avb2_bufferinitialize the extra data after struct vb2_buffer. For V4L2 this is astruct vb2_v4l2_buffer.fill_user_buffer: given avb2_bufferfill in the userspace structure. For V4L2 this is astruct v4l2_buffer.fill_vb2_buffer: given a userspace structure, fill in thevb2_buffer. If the userspace structure is invalid, then this op will return an error.copy_timestamp: copy the timestamp from a userspace structure to thestruct vb2_buffer.
struct vb2_queue #
a videobuf2 queue.
Definition
;
Members
type: private buffer type whose content is defined by the vb2-core caller. For example, for V4L2, it should match the types defined onenum v4l2_buf_type.io_modes: supported io methods (seeenum vb2_io_modes).dev: device to use for the default allocation context if the driver doesn't fill in the alloc_devs array.dma_attrs: DMA attributes to use for the DMA.bidirectional: when this flag is set the DMA direction for the buffers of this queue will be overridden withDMA_BIDIRECTIONALdirection. This is useful in cases where the hardware (firmware) writes to a buffer which is mapped as read (DMA_TO_DEVICE), or reads from buffer which is mapped for write (DMA_FROM_DEVICE) in order to satisfy some internal hardware restrictions or adds a padding needed by the processing algorithm. In case the DMA mapping is not bidirectional but the hardware (firmware) trying to access the buffer (in the opposite direction) this could lead to an IOMMU protection faults.fileio_read_once: report EOF after reading the first bufferfileio_write_immediately: queue buffer after eachwrite()callallow_zero_bytesused: allow bytesused == 0 to be passed to the driverquirk_poll_must_check_waiting_for_buffers: ReturnEPOLLERRat poll when QBUF has not been called. This is a vb1 idiom that has been adopted also by vb2.supports_requests: this queue supports the Request API.requires_requests: this queue requires the Request API. If this is set to 1, then supports_requests must be set to 1 as well.uses_qbuf: qbuf was used directly for this queue. Set to 1 the first time this is called. Set to 0 when the queue is canceled. If this is 1, then you cannot queue buffers from a request.uses_requests: requests are used for this queue. Set to 1 the first time a request is queued. Set to 0 when the queue is canceled. If this is 1, then you cannot queue buffers directly.allow_cache_hints: when set user-space can pass cache management hints in order to skip cache flush/invalidation on ->prepare()or/and ->finish().non_coherent_mem: when set queue will attempt to allocate buffers using non-coherent memory.lock: pointer to a mutex that protects thestruct vb2_queue. The driver must set this to a mutex to let the v4l2 core serialize the queuing ioctls. This lock is used when waiting for a new buffer to arrive: the lock is released, we wait for the new buffer, and then retaken.owner: The filehandle that 'owns' the buffers, i.e. the filehandle that called reqbufs, create_buffers or started fileio. This field is not used by the videobuf2 core API, but it allows drivers to easily associate an owner filehandle with the queue.ops: driver-specific callbacksmem_ops: memory allocator specific callbacksbuf_ops: callbacks to deliver buffer information. between user-space and kernel-space.drv_priv: driver private data.subsystem_flags: Flags specific to the subsystem (V4L2/DVB/etc.). Not used by the vb2 core.buf_struct_size: size of the driver-specific buffer structure; "0" indicates the driver doesn't want to use a custom buffer structure type. In that case a subsystem-specific struct will be used (in the case of V4L2 that issizeof(struct vb2_v4l2_buffer)). The first field of the driver-specific buffer structure must be the subsystem-specific struct (vb2_v4l2_buffer in the case of V4L2).timestamp_flags: Timestamp flags;V4L2_BUF_FLAG_TIMESTAMP_*andV4L2_BUF_FLAG_TSTAMP_SRC_*gfp_flags: additional gfp flags used when allocating the buffers. Typically this is 0, but it may be e.g.GFP_DMAor__GFP_DMA32to force the buffer allocation to a specific memory zone.min_queued_buffers: the minimum number of queued buffers needed before start_streaming can be called. Used when a DMA engine cannot be started unless at least this number of buffers have been queued into the driver. VIDIOC_REQBUFS will ensure at least min_queued_buffers + 1 buffers will be allocated. Note that VIDIOC_CREATE_BUFS will not modify the requested buffer count.min_reqbufs_allocation: the minimum number of buffers to be allocated when calling VIDIOC_REQBUFS. Note that VIDIOC_CREATE_BUFS will not modify the requested buffer count and does not use this field. Drivers can set this if there has to be a certain number of buffers available for the hardware to work effectively. This allows calling VIDIOC_REQBUFS with a buffer count of 1 and it will be automatically adjusted to a workable buffer count. If set, then min_reqbufs_allocation must be larger than min_queued_buffers + 1. If this field is > 3, then it is highly recommended that the driver implements the V4L2_CID_MIN_BUFFERS_FOR_CAPTURE/OUTPUT control.alloc_devs:struct devicememory type/allocator-specific per-plane device
vb2_queue_allows_cache_hints() #
bool Return true if the queue allows cache and memory consistency hints.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue
vb2_plane_vaddr() #
void * Return a kernel virtual address of a given plane.
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto which the plane in question belongs to.unsigned int plane_no: plane number for which the address is to be returned.
Description
This function returns a kernel virtual address of a given plane if such a mapping exist, NULL otherwise.
vb2_plane_cookie() #
void * Return allocator specific cookie for the given plane.
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto which the plane in question belongs to.unsigned int plane_no: plane number for which the cookie is to be returned.
Description
This function returns an allocator specific cookie for a given plane if available, NULL otherwise. The allocator should provide some simple static inline function, which would convert this cookie to the allocator specific type that can be used directly by the driver to access the buffer. This can be for example physical address, pointer to scatter list or IOMMU mapping.
vb2_buffer_done() #
void inform videobuf2 that an operation on a buffer is finished.
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto be used.enum vb2_buffer_state state: state of the buffer, as defined byenum vb2_buffer_state. EitherVB2_BUF_STATE_DONEif the operation finished successfully,VB2_BUF_STATE_ERRORif the operation finished with an error orVB2_BUF_STATE_QUEUED.
Description
This function should be called by the driver after a hardware operation on
a buffer is finished and the buffer may be returned to userspace. The driver
cannot use this buffer anymore until it is queued back to it by videobuf
by the means of vb2_ops->buf_queue callback. Only buffers previously queued
to the driver by vb2_ops->buf_queue can be passed to this function.
While streaming a buffer can only be returned in state DONE or ERROR.
The vb2_ops->start_streaming op can also return them in case the DMA engine
cannot be started for some reason. In that case the buffers should be
returned with state QUEUED to put them back into the queue.
vb2_discard_done() #
void discard all buffers marked as DONE.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This function is intended to be used with suspend/resume operations. It discards all 'done' buffers as they would be too old to be requested after resume.
Drivers must stop the hardware and synchronize with interrupt handlers and/or delayed works before calling this function to make sure no buffer will be touched by the driver and/or hardware.
vb2_wait_for_all_buffers() #
int wait until all buffers are given back to vb2.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This function will wait until all buffers that have been given to the driver
by vb2_ops->buf_queue are given back to vb2 with vb2_buffer_done().
It is intended to be called with all locks taken, for example from
vb2_ops->stop_streaming callback.
vb2_core_querybuf() #
void query video buffer information.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct vb2_buffer *vb: pointer to structvb2_buffer.void *pb: buffer struct passed from userspace.
Description
Videobuf2 core helper to implement VIDIOC_QUERYBUF() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
The passed buffer should have been verified.
This function fills the relevant information for the userspace.
Return
returns zero on success; an error code otherwise.
vb2_core_reqbufs() #
int Initiate streaming.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.enum vb2_memory memory: memory type, as defined byenum vb2_memory.unsigned int flags: auxiliary queue/buffer management flags. Currently, the only used flag isV4L2_MEMORY_FLAG_NON_COHERENT.unsigned int *count: requested buffer count.
Description
Videobuf2 core helper to implement VIDIOC_REQBUF() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
This function:
#) verifies streaming parameters passed from the userspace;
#) sets up the queue;
#) negotiates number of buffers and planes per buffer with the driver
to be used during streaming;
#) allocates internal buffer structures (struct vb2_buffer), according to
the agreed parameters;
#) for MMAP memory type, allocates actual video memory, using the
memory handling/allocation routines provided during queue initialization.
If req->count is 0, all the memory will be freed instead.
If the queue has been allocated previously by a previous vb2_core_reqbufs()
call and the queue is not busy, memory will be reallocated.
Return
returns zero on success; an error code otherwise.
vb2_core_create_bufs() #
int Allocate buffers and any required auxiliary structs
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.enum vb2_memory memory: memory type, as defined byenum vb2_memory.unsigned int flags: auxiliary queue/buffer management flags.unsigned int *count: requested buffer count.unsigned int requested_planes: number of planes requested.const unsigned int requested_sizes[]: array with the size of the planes.unsigned int *first_index: index of the first created buffer, all allocated buffers have indices in the range [first_index..first_index+count-1]
Description
Videobuf2 core helper to implement VIDIOC_CREATE_BUFS() operation. It is
called internally by VB2 by an API-specific handler, like
videobuf2-v4l2.h.
This function:
#) verifies parameter sanity;
#) calls the vb2_ops->queue_setup queue operation;
#) performs any necessary memory allocations.
Return
returns zero on success; an error code otherwise.
vb2_core_prepare_buf() #
int Pass ownership of a buffer from userspace to the kernel.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct vb2_buffer *vb: pointer to structvb2_buffer.void *pb: buffer structure passed from userspace tov4l2_ioctl_ops->vidioc_prepare_bufhandler in driver.
Description
Videobuf2 core helper to implement VIDIOC_PREPARE_BUF() operation. It is
called internally by VB2 by an API-specific handler, like
videobuf2-v4l2.h.
The passed buffer should have been verified.
This function calls vb2_ops->buf_prepare callback in the driver (if provided), in which driver-specific buffer initialization can be performed.
Return
returns zero on success; an error code otherwise.
vb2_core_remove_bufs() #
int Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.unsigned int start: first index of the range of buffers to remove.unsigned int count: number of buffers to remove.
Return
returns zero on success; an error code otherwise.
vb2_core_qbuf() #
int Queue a buffer from userspace
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct vb2_buffer *vb: pointer to structvb2_buffer.void *pb: buffer structure passed from userspace to v4l2_ioctl_ops->vidioc_qbuf handler in driverstruct media_request *req: pointer tostruct media_request, may be NULL.
Description
Videobuf2 core helper to implement VIDIOC_QBUF() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
This function:
-
#) If req is non-NULL, then the buffer will be bound to this
media request and it returns. The buffer will be prepared and queued to the driver (i.e. the next two steps) when the request itself is queued.
-
#) if necessary, calls
vb2_ops->buf_preparecallback in the driver(if provided), in which driver-specific buffer initialization can be performed;
-
#) if streaming is on, queues the buffer in driver by the means of
vb2_ops->buf_queuecallback for processing.
Return
returns zero on success; an error code otherwise.
vb2_core_dqbuf() #
int Dequeue a buffer to the userspace
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queueunsigned int *pindex: pointer to the buffer index. May be NULLvoid *pb: buffer structure passed from userspace to v4l2_ioctl_ops->vidioc_dqbuf handler in driver.bool nonblocking: if true, this call will not sleep waiting for a buffer if no buffers ready for dequeuing are present. Normally the driver would be passing (file->f_flags & O_NONBLOCK) here.
Description
Videobuf2 core helper to implement VIDIOC_DQBUF() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
This function:
-
#) calls buf_finish callback in the driver (if provided), in which
driver can perform any additional operations that may be required before returning the buffer to userspace, such as cache sync,
-
#) the buffer struct members are filled with relevant information for
the userspace.
Return
returns zero on success; an error code otherwise.
vb2_core_streamon() #
int Implements VB2 stream ON logic
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queueunsigned int type: type of the queue to be started. For V4L2, this is defined byenum v4l2_buf_typetype.
Description
Videobuf2 core helper to implement VIDIOC_STREAMON() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
Return
returns zero on success; an error code otherwise.
vb2_core_streamoff() #
int Implements VB2 stream OFF logic
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queueunsigned int type: type of the queue to be started. For V4L2, this is defined byenum v4l2_buf_typetype.
Description
Videobuf2 core helper to implement VIDIOC_STREAMOFF() operation. It is
called internally by VB2 by an API-specific handler, like
videobuf2-v4l2.h.
Return
returns zero on success; an error code otherwise.
vb2_core_expbuf() #
int Export a buffer as a file descriptor.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.int *fd: pointer to the file descriptor associated with DMABUF (set by driver).unsigned int type: buffer type.struct vb2_buffer *vb: pointer to structvb2_buffer.unsigned int plane: index of the plane to be exported, 0 for single plane queuesunsigned int flags: file flags for newly created file, as defined at include/uapi/asm-generic/fcntl.h. Currently, the only used flag isO_CLOEXEC. is supported, refer to manual of open syscall for more details.
Description
Videobuf2 core helper to implement VIDIOC_EXPBUF() operation. It is called
internally by VB2 by an API-specific handler, like videobuf2-v4l2.h.
Return
returns zero on success; an error code otherwise.
vb2_core_queue_init() #
int initialize a videobuf2 queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue. This structure should be allocated in driver
Description
The vb2_queue structure should be allocated by the driver. The driver is
responsible of clearing it's content and setting initial values for some
required entries before calling this function.
vb2_core_queue_release() #
void stop streaming, release the queue and free memory
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This function stops streaming and performs necessary clean ups, including
freeing video buffer memory. The driver is responsible for freeing
the struct vb2_queue itself.
vb2_queue_error() #
void signal a fatal error on the queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
Flag that a fatal unrecoverable error has occurred and wake up all processes
waiting on the queue. Polling will now set EPOLLERR and queuing and dequeuing
buffers will return -EIO.
The error flag will be cleared when canceling the queue, either from
vb2_streamoff() or vb2_queue_release(). Drivers should thus not call this
function before starting the stream, otherwise the error flag will remain set
until the queue is released when closing the device node.
vb2_mmap() #
int map video buffers into application address space.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct vm_area_struct *vma: pointer tostruct vm_area_structwith the vma passed to the mmap file operation handler in the driver.
Description
Should be called from mmap file operation handler of a driver. This function maps one plane of one of the available video buffers to userspace. To map whole video memory allocated on reqbufs, this function has to be called once per each plane per each buffer previously allocated.
When the userspace application calls mmap, it passes to it an offset returned
to it earlier by the means of v4l2_ioctl_ops->vidioc_querybuf handler.
That offset acts as a "cookie", which is then used to identify the plane
to be mapped.
This function finds a plane with a matching offset and a mapping is performed by the means of a provided memory operation.
The return values from this function are intended to be directly returned from the mmap handler in driver.
vb2_get_unmapped_area() #
unsigned long map video buffers into application address space.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.unsigned long addr: memory address.unsigned long len: buffer size.unsigned long pgoff: page offset.unsigned long flags: memory flags.
Description
This function is used in noMMU platforms to propose address mapping
for a given buffer. It's intended to be used as a handler for the
file_operations->get_unmapped_area operation.
This is called by the mmap() syscall routines will call this
to get a proposed address for the mapping, when !CONFIG_MMU.
vb2_core_poll() #
__poll_t implements poll syscall() logic.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct file *file:struct fileargument passed to the poll file operation handler.poll_table *wait:poll_tablewait argument passed to the poll file operation handler.
Description
This function implements poll file operation handler for a driver. For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will be informed that the file descriptor of a video device is available for reading. For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor will be reported as available for writing.
The return values from this function are intended to be directly returned from poll handler in driver.
vb2_read() #
size_t implements read() syscall logic.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.char __user *data: pointed to target userspace buffersize_t count: number of bytes to readloff_t *ppos: file handle position tracking pointerint nonblock: mode selector (1 means blocking calls, 0 means nonblocking)
vb2_write() #
size_t implements write() syscall logic.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.const char __user *data: pointed to target userspace buffersize_t count: number of bytes to writeloff_t *ppos: file handle position tracking pointerint nonblock: mode selector (1 means blocking calls, 0 means nonblocking)
vb2_thread_fnc() #
typedef int
callback function for use with vb2_thread.
Parameters
struct vb2_buffer *vb: pointer to structvb2_buffer.void *priv: pointer to a private data.
Description
This is called whenever a buffer is dequeued in the thread.
vb2_thread_start() #
int start a thread for the given queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.vb2_thread_fnc fnc:vb2_thread_fnccallback function.void *priv: priv pointer passed to the callback function.const char *thread_name: the name of the thread. This will be prefixed with "vb2-".
Description
This starts a thread that will queue and dequeue until an error occurs
or vb2_thread_stop() is called.
vb2_thread_stop() #
int stop the thread for the given queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_is_streaming() #
bool return streaming status of the queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_fileio_is_active() #
bool return true if fileio is active.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This returns true if read() or write() is used to stream the data
as opposed to stream I/O. This is almost never an important distinction,
except in rare cases. One such case is that using read() or write() to
stream a format using V4L2_FIELD_ALTERNATE is not allowed since there
is no way you can pass the field information of each buffer to/from
userspace. A driver that supports this field format should check for
this in the vb2_ops->queue_setup op and reject it if this function returns
true.
vb2_get_num_buffers() #
unsigned int get the number of buffer in a queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_is_busy() #
bool return busy status of the queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This function checks if queue has any buffers allocated.
vb2_get_drv_priv() #
void * return driver private data associated with the queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_set_plane_payload() #
void set bytesused for the plane plane_no.
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto which the plane in question belongs to.unsigned int plane_no: plane number for which payload should be set.unsigned long size: payload in bytes.
vb2_get_plane_payload() #
unsigned long get bytesused for the plane plane_no
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto which the plane in question belongs to.unsigned int plane_no: plane number for which payload should be set.
vb2_plane_size() #
unsigned long return plane size in bytes.
Parameters
struct vb2_buffer *vb: pointer tostruct vb2_bufferto which the plane in question belongs to.unsigned int plane_no: plane number for which size should be returned.
vb2_start_streaming_called() #
bool return streaming status of driver.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_clear_last_buffer_dequeued() #
void clear last buffer dequeued flag of queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
vb2_get_buffer() #
struct vb2_buffer * get a buffer from a queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.unsigned int index: buffer index
Description
This function obtains a buffer from a queue, by its index. Keep in mind that there is no refcounting involved in this operation, so the buffer lifetime should be taken into consideration.
vb2_buffer_in_use() #
bool return true if the buffer is in use and the queue cannot be freed (by the means of VIDIOC_REQBUFS(0)) call.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct vb2_buffer *vb: buffer for which plane size should be returned.
vb2_verify_memory_type() #
int Check whether the memory type and buffer type passed to a buffer operation are compatible with the queue.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.enum vb2_memory memory: memory model, as defined by enumvb2_memory.unsigned int type: private buffer type whose content is defined by the vb2-core caller. For example, for V4L2, it should match the types defined on enumv4l2_buf_type.
vb2_request_object_is_buffer() #
bool return true if the object is a buffer
Parameters
struct media_request_object *obj: the request object.
vb2_request_buffer_cnt() #
unsigned int return the number of buffers in the request
Parameters
struct media_request *req: the request.
struct vb2_v4l2_buffer #
video buffer information for v4l2.
Definition
;
Members
vb2_buf: embedded structvb2_buffer.flags: buffer informational flags.field: field order of the image in the buffer, as defined byenum v4l2_field.timecode: frame timecode.sequence: sequence count of this frame.request_fd: the request_fd associated with this bufferis_held: if true, then this capture buffer was heldplanes: plane information (userptr/fd, length, bytesused, data_offset).
Description
Should contain enough information to be able to cover all the fields
of struct v4l2_buffer at videodev2.h.
vb2_find_buffer() #
struct vb2_buffer * Find a buffer with given timestamp
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.u64 timestamp: the timestamp to find.
Description
Returns the buffer with the given timestamp, or NULL if not found.
vb2_reqbufs() #
int Wrapper for vb2_core_reqbufs() that also verifies the memory and type values.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct v4l2_requestbuffers *req:struct v4l2_requestbufferspassed from userspace tov4l2_ioctl_ops->vidioc_reqbufshandler in driver.
vb2_create_bufs() #
int Wrapper for vb2_core_create_bufs() that also verifies the memory and type values.
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct v4l2_create_buffers *create: creation parameters, passed from userspace tov4l2_ioctl_ops->vidioc_create_bufshandler in driver
vb2_prepare_buf() #
int Pass ownership of a buffer from userspace to the kernel
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct media_device *mdev: pointer tostruct media_device, may be NULL.struct v4l2_buffer *b: buffer structure passed from userspace tov4l2_ioctl_ops->vidioc_prepare_bufhandler in driver
Description
Should be called from v4l2_ioctl_ops->vidioc_prepare_buf ioctl handler
of a driver.
This function:
#) verifies the passed buffer,
#) calls vb2_ops->buf_prepare callback in the driver (if provided),
in which driver-specific buffer initialization can be performed.
#) if b->request_fd is non-zero and mdev->ops->req_queue is set,
then bind the prepared buffer to the request.
The return values from this function are intended to be directly returned
from v4l2_ioctl_ops->vidioc_prepare_buf handler in driver.
vb2_qbuf() #
int Queue a buffer from userspace
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct media_device *mdev: pointer tostruct media_device, may be NULL.struct v4l2_buffer *b: buffer structure passed from userspace tov4l2_ioctl_ops->vidioc_qbufhandler in driver
Description
Should be called from v4l2_ioctl_ops->vidioc_qbuf handler of a driver.
This function:
#) verifies the passed buffer;
#) if b->request_fd is non-zero and mdev->ops->req_queue is set,
then bind the buffer to the request.
#) if necessary, calls vb2_ops->buf_prepare callback in the driver
(if provided), in which driver-specific buffer initialization can
be performed;
#) if streaming is on, queues the buffer in driver by the means of
vb2_ops->buf_queue callback for processing.
The return values from this function are intended to be directly returned
from v4l2_ioctl_ops->vidioc_qbuf handler in driver.
vb2_expbuf() #
int Export a buffer as a file descriptor
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct v4l2_exportbuffer *eb: export buffer structure passed from userspace tov4l2_ioctl_ops->vidioc_expbufhandler in driver
Description
The return values from this function are intended to be directly returned
from v4l2_ioctl_ops->vidioc_expbuf handler in driver.
vb2_dqbuf() #
int Dequeue a buffer to the userspace
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct v4l2_buffer *b: buffer structure passed from userspace tov4l2_ioctl_ops->vidioc_dqbufhandler in driverbool nonblocking: if true, this call will not sleep waiting for a buffer if no buffers ready for dequeuing are present. Normally the driver would be passing (file->f_flags&O_NONBLOCK) here
Description
Should be called from v4l2_ioctl_ops->vidioc_dqbuf ioctl handler
of a driver.
This function:
#) verifies the passed buffer;
#) calls vb2_ops->buf_finish callback in the driver (if provided), in which
driver can perform any additional operations that may be required before
returning the buffer to userspace, such as cache sync;
#) the buffer struct members are filled with relevant information for
the userspace.
The return values from this function are intended to be directly returned
from v4l2_ioctl_ops->vidioc_dqbuf handler in driver.
vb2_streamon() #
int start streaming
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.enum v4l2_buf_type type: type argument passed from userspace to vidioc_streamon handler, as defined byenum v4l2_buf_type.
Description
Should be called from v4l2_ioctl_ops->vidioc_streamon handler of a driver.
This function:
- verifies current state
- passes any previously queued buffers to the driver and starts streaming
The return values from this function are intended to be directly returned
from v4l2_ioctl_ops->vidioc_streamon handler in the driver.
vb2_streamoff() #
int stop streaming
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.enum v4l2_buf_type type: type argument passed from userspace to vidioc_streamoff handler
Description
Should be called from vidioc_streamoff handler of a driver.
This function:
#) verifies current state, #) stop streaming and dequeues any queued buffers, including those previously passed to the driver (after waiting for the driver to finish).
This call can be used for pausing playback. The return values from this function are intended to be directly returned from vidioc_streamoff handler in the driver
vb2_queue_init() #
int initialize a videobuf2 queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
The vb2_queue structure should be allocated by the driver. The driver is responsible of clearing it's content and setting initial values for some required entries before calling this function. q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer to the struct vb2_queue description in include/media/videobuf2-core.h for more information.
vb2_queue_init_name() #
int initialize a videobuf2 queue with a name
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.const char *name: the queue name
Description
This function initializes the vb2_queue exactly like vb2_queue_init(),
and additionally sets the queue name. The queue name is used for logging
purpose, and should uniquely identify the queue within the context of the
device it belongs to. This is useful to attribute kernel log messages to the
right queue for m2m devices or other devices that handle multiple queues.
vb2_queue_release() #
void stop streaming, release the queue and free memory
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.
Description
This function stops streaming and performs necessary clean ups, including freeing video buffer memory. The driver is responsible for freeing the vb2_queue structure itself.
vb2_queue_change_type() #
int change the type of an inactive vb2_queue
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.unsigned int type: the type to change to (V4L2_BUF_TYPE_VIDEO_*)
Description
This function changes the type of the vb2_queue. This is only possible if the queue is not busy (i.e. no buffers have been allocated).
vb2_queue_change_type() can be used to support multiple buffer types using
the same queue. The driver can implement v4l2_ioctl_ops.vidioc_reqbufs and
v4l2_ioctl_ops.vidioc_create_bufs functions and call vb2_queue_change_type()
before calling vb2_ioctl_reqbufs() or vb2_ioctl_create_bufs(), and thus
"lock" the buffer type until the buffers have been released.
vb2_poll() #
__poll_t implements poll userspace operation
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct file *file: file argument passed to the poll file operation handlerpoll_table *wait: wait argument passed to the poll file operation handler
Description
This function implements poll file operation handler for a driver. For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will be informed that the file descriptor of a video device is available for reading. For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor will be reported as available for writing.
If the driver uses struct v4l2_fh, then vb2_poll() will also check for any
pending events.
The return values from this function are intended to be directly returned from poll handler in driver.
vb2_queue_is_busy() #
bool check if the queue is busy
Parameters
struct vb2_queue *q: pointer tostruct vb2_queuewith videobuf2 queue.struct file *file: file through which the vb2 queue access is performed
Description
The queue is considered busy if it has an owner and the owner is not the file.
Queue ownership is acquired and checked by some of the v4l2_ioctl_ops helpers below. Drivers can also use this function directly when they need to open-code ioctl handlers, for instance to add additional checks between the queue ownership test and the call to the corresponding vb2 operation.
vb2_video_unregister_device() #
void unregister the video device and release queue
Parameters
struct video_device *vdev: pointer tostruct video_device
Description
If the driver uses vb2_fop_release()/_vb2_fop_release(), then it should use
vb2_video_unregister_device() instead of video_unregister_device().
This function will call video_unregister_device() and then release the
vb2_queue if streaming is in progress. This will stop streaming and
this will simplify the unbind sequence since after this call all subdevs
will have stopped streaming as well.
struct vb2_vmarea_handler #
common vma refcount tracking handler.
Definition
;
Members
refcount: pointer torefcount_tentry in the buffer.put: callback to function that decreases buffer refcount.arg: argument for put callback.