code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: CEC

.. _CEC_TRANSMIT:
.. _CEC_RECEIVE:

***********************************
ioctls CEC_RECEIVE and CEC_TRANSMIT
***********************************

Name
====

CEC_RECEIVE, CEC_TRANSMIT - Receive or transmit a CEC message

Synopsis
========

.. c:macro:: CEC_RECEIVE

``int ioctl(int fd, CEC_RECEIVE, struct cec_msg *argp)``

.. c:macro:: CEC_TRANSMIT

``int ioctl(int fd, CEC_TRANSMIT, struct cec_msg *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct cec_msg.

Description
===========

To receive a CEC message the application has to fill in the
``timeout`` field of struct :c:type:`cec_msg` and pass it to
:ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`.
If the file descriptor is in non-blocking mode and there are no received
messages pending, then it will return -1 and set errno to the ``EAGAIN``
error code. If the file descriptor is in blocking mode and ``timeout``
is non-zero and no message arrived within ``timeout`` milliseconds, then
it will return -1 and set errno to the ``ETIMEDOUT`` error code.

A received message can be:

1. a message received from another CEC device (the ``sequence`` field will
   be 0, ``tx_status`` will be 0 and ``rx_status`` will be non-zero).
2. the transmit result of an earlier non-blocking transmit (the ``sequence``
   field will be non-zero, ``tx_status`` will be non-zero and ``rx_status``
   will be 0).
3. the reply to an earlier non-blocking transmit (the ``sequence`` field will
   be non-zero, ``tx_status`` will be 0 and ``rx_status`` will be non-zero).

To send a CEC message the application has to fill in the struct
:c:type:`cec_msg` and pass it to :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>`.
The :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` is only available if
``CEC_CAP_TRANSMIT`` is set. If there is no more room in the transmit
queue, then it will return -1 and set errno to the ``EBUSY`` error code.
The transmit queue has enough room for 18 messages (about 1 second worth
of 2-byte messages). Note that the CEC kernel framework will also reply
to core messages (see :ref:`cec-core-processing`), so it is not a good
idea to fully fill up the transmit queue.

If the file descriptor is in non-blocking mode then the transmit will
return 0 and the result of the transmit will be available via
:ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>` once the transmit has finished.
If a non-blocking transmit also specified waiting for a reply, then
the reply will arrive in a later message. The ``sequence`` field can
be used to associate both transmit results and replies with the original
transmit.

Normally calling :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` when the physical
address is invalid (due to e.g. a disconnect) will return ``ENONET``.

However, the CEC specification allows sending messages from 'Unregistered' to
'TV' when the physical address is invalid since some TVs pull the hotplug detect
pin of the HDMI connector low when they go into standby, or when switching to
another input.

When the hotplug detect pin goes low the EDID disappears, and thus the
physical address, but the cable is still connected and CEC still works.
In order to detect/wake up the device it is allowed to send poll and 'Image/Text
View On' messages from initiator 0xf ('Unregistered') to destination 0 ('TV').

.. tabularcolumns:: |p{1.0cm}|p{3.5cm}|p{12.8cm}|

.. c:type:: cec_msg

.. cssclass:: longtable

.. flat-table:: struct cec_msg
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 1 16

    * - __u64
      - ``tx_ts``
      - Timestamp in ns of when the last byte of the message was transmitted.
	The timestamp has been taken from the ``CLOCK_MONOTONIC`` clock. To access
	the same clock from userspace use :c:func:`clock_gettime`.
    * - __u64
      - ``rx_ts``
      - Timestamp in ns of when the last byte of the message was received.
	The timestamp has been taken from the ``CLOCK_MONOTONIC`` clock. To access
	the same clock from userspace use :c:func:`clock_gettime`.
    * - __u32
      - ``len``
      - The length of the message. For :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` this is filled in
	by the application. The driver will fill this in for
	:ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`. For :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` it will be
	filled in by the driver with the length of the reply message if ``reply`` was set.
    * - __u32
      - ``timeout``
      - The timeout in milliseconds. This is the time the device will wait
	for a message to be received before timing out. If it is set to 0,
	then it will wait indefinitely when it is called by :ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`.
	If it is 0 and it is called by :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>`,
	then it will be replaced by 1000 if the ``reply`` is non-zero or
	ignored if ``reply`` is 0.
    * - __u32
      - ``sequence``
      - A non-zero sequence number is automatically assigned by the CEC framework
	for all transmitted messages. It is used by the CEC framework when it queues
	the transmit result for a non-blocking transmit. This allows the application
	to associate the received message with the original transmit.

	In addition, if a non-blocking transmit will wait for a reply (ii.e. ``timeout``
	was not 0), then the ``sequence`` field of the reply will be set to the sequence
	value of the original transmit. This allows the application to associate the
	received message with the original transmit.
    * - __u32
      - ``flags``
      - Flags. See :ref:`cec-msg-flags` for a list of available flags.
    * - __u8
      - ``msg[16]``
      - The message payload. For :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` this is filled in by the
	application. The driver will fill this in for :ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`.
	For :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` it will be filled in by the driver with
	the payload of the reply message if ``timeout`` was set.
    * - __u8
      - ``reply``
      - Wait until this message is replied. If ``reply`` is 0 and the
	``timeout`` is 0, then don't wait for a reply but return after
	transmitting the message. Ignored by :ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`.
	The case where ``reply`` is 0 (this is the opcode for the Feature Abort
	message) and ``timeout`` is non-zero is specifically allowed to make it
	possible to send a message and wait up to ``timeout`` milliseconds for a
	Feature Abort reply. In this case ``rx_status`` will either be set
	to :ref:`CEC_RX_STATUS_TIMEOUT <CEC-RX-STATUS-TIMEOUT>` or
	:ref:`CEC_RX_STATUS_FEATURE_ABORT <CEC-RX-STATUS-FEATURE-ABORT>`.

	If the transmitter message is ``CEC_MSG_INITIATE_ARC`` then the ``reply``
	values ``CEC_MSG_REPORT_ARC_INITIATED`` and ``CEC_MSG_REPORT_ARC_TERMINATED``
	are processed differently: either value will match both possible replies.
	The reason is that the ``CEC_MSG_INITIATE_ARC`` message is the only CEC
	message that has two possible replies other than Feature Abort. The
	``reply`` field will be updated with the actual reply so that it is
	synchronized with the contents of the received message.
    * - __u8
      - ``rx_status``
      - The status bits of the received message. See
	:ref:`cec-rx-status` for the possible status values.
    * - __u8
      - ``tx_status``
      - The status bits of the transmitted message. See
	:ref:`cec-tx-status` for the possible status values.
	When calling :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` in non-blocking mode,
	this field will be 0 if the transmit started, or non-0 if the transmit
	result is known immediately. The latter would be the case when attempting
	to transmit a Poll message to yourself. That results in a
	:ref:`CEC_TX_STATUS_NACK <CEC-TX-STATUS-NACK>` without ever actually
	transmitting the Poll message.
    * - __u8
      - ``tx_arb_lost_cnt``
      - A counter of the number of transmit attempts that resulted in the
	Arbitration Lost error. This is only set if the hardware supports
	this, otherwise it is always 0. This counter is only valid if the
	:ref:`CEC_TX_STATUS_ARB_LOST <CEC-TX-STATUS-ARB-LOST>` status bit is set.
    * - __u8
      - ``tx_nack_cnt``
      - A counter of the number of transmit attempts that resulted in the
	Not Acknowledged error. This is only set if the hardware supports
	this, otherwise it is always 0. This counter is only valid if the
	:ref:`CEC_TX_STATUS_NACK <CEC-TX-STATUS-NACK>` status bit is set.
    * - __u8
      - ``tx_low_drive_cnt``
      - A counter of the number of transmit attempts that resulted in the
	Arbitration Lost error. This is only set if the hardware supports
	this, otherwise it is always 0. This counter is only valid if the
	:ref:`CEC_TX_STATUS_LOW_DRIVE <CEC-TX-STATUS-LOW-DRIVE>` status bit is set.
    * - __u8
      - ``tx_error_cnt``
      - A counter of the number of transmit errors other than Arbitration
	Lost or Not Acknowledged. This is only set if the hardware
	supports this, otherwise it is always 0. This counter is only
	valid if the :ref:`CEC_TX_STATUS_ERROR <CEC-TX-STATUS-ERROR>` status bit is set.

.. tabularcolumns:: |p{6.2cm}|p{1.0cm}|p{10.1cm}|

.. _cec-msg-flags:

.. flat-table:: Flags for struct cec_msg
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 4

    * .. _`CEC-MSG-FL-REPLY-TO-FOLLOWERS`:

      - ``CEC_MSG_FL_REPLY_TO_FOLLOWERS``
      - 1
      - If a CEC transmit expects a reply, then by default that reply is only sent to
	the filehandle that called :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>`. If this
	flag is set, then the reply is also sent to all followers, if any. If the
	filehandle that called :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` is also a
	follower, then that filehandle will receive the reply twice: once as the
	result of the :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>`, and once via
	:ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>`.

    * .. _`CEC-MSG-FL-RAW`:

      - ``CEC_MSG_FL_RAW``
      - 2
      - Normally CEC messages are validated before transmitting them. If this
        flag is set when :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` is called,
	then no validation takes place and the message is transmitted as-is.
	This is useful when debugging CEC issues.
	This flag is only allowed if the process has the ``CAP_SYS_RAWIO``
	capability. If that is not set, then the ``EPERM`` error code is
	returned.

.. tabularcolumns:: |p{5.6cm}|p{0.9cm}|p{10.8cm}|

.. _cec-tx-status:

.. flat-table:: CEC Transmit Status
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 16

    * .. _`CEC-TX-STATUS-OK`:

      - ``CEC_TX_STATUS_OK``
      - 0x01
      - The message was transmitted successfully. This is mutually
	exclusive with :ref:`CEC_TX_STATUS_MAX_RETRIES <CEC-TX-STATUS-MAX-RETRIES>`.
	Other bits can still be set if earlier attempts met with failure before
	the transmit was eventually successful.
    * .. _`CEC-TX-STATUS-ARB-LOST`:

      - ``CEC_TX_STATUS_ARB_LOST``
      - 0x02
      - CEC line arbitration was lost, i.e. another transmit started at the
        same time with a higher priority. Optional status, not all hardware
	can detect this error condition.
    * .. _`CEC-TX-STATUS-NACK`:

      - ``CEC_TX_STATUS_NACK``
      - 0x04
      - Message was not acknowledged. Note that some hardware cannot tell apart
        a 'Not Acknowledged' status from other error conditions, i.e. the result
	of a transmit is just OK or FAIL. In that case this status will be
	returned when the transmit failed.
    * .. _`CEC-TX-STATUS-LOW-DRIVE`:

      - ``CEC_TX_STATUS_LOW_DRIVE``
      - 0x08
      - Low drive was detected on the CEC bus. This indicates that a
	follower detected an error on the bus and requests a
	retransmission. Optional status, not all hardware can detect this
	error condition.
    * .. _`CEC-TX-STATUS-ERROR`:

      - ``CEC_TX_STATUS_ERROR``
      - 0x10
      - Some error occurred. This is used for any errors that do not fit
	``CEC_TX_STATUS_ARB_LOST`` or ``CEC_TX_STATUS_LOW_DRIVE``, either because
	the hardware could not tell which error occurred, or because the hardware
	tested for other conditions besides those two. Optional status.
    * .. _`CEC-TX-STATUS-MAX-RETRIES`:

      - ``CEC_TX_STATUS_MAX_RETRIES``
      - 0x20
      - The transmit failed after one or more retries. This status bit is
	mutually exclusive with :ref:`CEC_TX_STATUS_OK <CEC-TX-STATUS-OK>`.
	Other bits can still be set to explain which failures were seen.
    * .. _`CEC-TX-STATUS-ABORTED`:

      - ``CEC_TX_STATUS_ABORTED``
      - 0x40
      - The transmit was aborted due to an HDMI disconnect, or the adapter
        was unconfigured, or a transmit was interrupted, or the driver
	returned an error when attempting to start a transmit.
    * .. _`CEC-TX-STATUS-TIMEOUT`:

      - ``CEC_TX_STATUS_TIMEOUT``
      - 0x80
      - The transmit timed out. This should not normally happen and this
	indicates a driver problem.

.. tabularcolumns:: |p{5.6cm}|p{0.9cm}|p{10.8cm}|

.. _cec-rx-status:

.. flat-table:: CEC Receive Status
    :header-rows:  0
    :stub-columns: 0
    :widths:       3 1 16

    * .. _`CEC-RX-STATUS-OK`:

      - ``CEC_RX_STATUS_OK``
      - 0x01
      - The message was received successfully.
    * .. _`CEC-RX-STATUS-TIMEOUT`:

      - ``CEC_RX_STATUS_TIMEOUT``
      - 0x02
      - The reply to an earlier transmitted message timed out.
    * .. _`CEC-RX-STATUS-FEATURE-ABORT`:

      - ``CEC_RX_STATUS_FEATURE_ABORT``
      - 0x04
      - The message was received successfully but the reply was
	``CEC_MSG_FEATURE_ABORT``. This status is only set if this message
	was the reply to an earlier transmitted message.
    * .. _`CEC-RX-STATUS-ABORTED`:

      - ``CEC_RX_STATUS_ABORTED``
      - 0x08
      - The wait for a reply to an earlier transmitted message was aborted
        because the HDMI cable was disconnected, the adapter was unconfigured
	or the :ref:`CEC_TRANSMIT <CEC_RECEIVE>` that waited for a
	reply was interrupted.

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

The :ref:`ioctl CEC_RECEIVE <CEC_RECEIVE>` can return the following
error codes:

EAGAIN
    No messages are in the receive queue, and the filehandle is in non-blocking mode.

ETIMEDOUT
    The ``timeout`` was reached while waiting for a message.

ERESTARTSYS
    The wait for a message was interrupted (e.g. by Ctrl-C).

The :ref:`ioctl CEC_TRANSMIT <CEC_TRANSMIT>` can return the following
error codes:

ENOTTY
    The ``CEC_CAP_TRANSMIT`` capability wasn't set, so this ioctl is not supported.

EPERM
    The CEC adapter is not configured, i.e. :ref:`ioctl CEC_ADAP_S_LOG_ADDRS <CEC_ADAP_S_LOG_ADDRS>`
    has never been called, or ``CEC_MSG_FL_RAW`` was used from a process that
    did not have the ``CAP_SYS_RAWIO`` capability.

ENONET
    The CEC adapter is not configured, i.e. :ref:`ioctl CEC_ADAP_S_LOG_ADDRS <CEC_ADAP_S_LOG_ADDRS>`
    was called, but the physical address is invalid so no logical address was claimed.
    An exception is made in this case for transmits from initiator 0xf ('Unregistered')
    to destination 0 ('TV'). In that case the transmit will proceed as usual.

EBUSY
    Another filehandle is in exclusive follower or initiator mode, or the filehandle
    is in mode ``CEC_MODE_NO_INITIATOR``. This is also returned if the transmit
    queue is full.

EINVAL
    The contents of struct :c:type:`cec_msg` is invalid.

ERESTARTSYS
    The wait for a successful transmit was interrupted (e.g. by Ctrl-C).


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _cec_pin_error_inj:

CEC Pin Framework Error Injection
=================================

The CEC Pin Framework is a core CEC framework for CEC hardware that only
has low-level support for the CEC bus. Most hardware today will have
high-level CEC support where the hardware deals with driving the CEC bus,
but some older devices aren't that fancy. However, this framework also
allows you to connect the CEC pin to a GPIO on e.g. a Raspberry Pi and
you have now made a CEC adapter.

What makes doing this so interesting is that since we have full control
over the bus it is easy to support error injection. This is ideal to
test how well CEC adapters can handle error conditions.

Currently only the cec-gpio driver (when the CEC line is directly
connected to a pull-up GPIO line) and the AllWinner A10/A20 drm driver
support this framework.

If ``CONFIG_CEC_PIN_ERROR_INJ`` is enabled, then error injection is available
through debugfs. Specifically, in ``/sys/kernel/debug/cec/cecX/`` there is
now an ``error-inj`` file.

.. note::

    The error injection commands are not a stable ABI and may change in the
    future.

With ``cat error-inj`` you can see both the possible commands and the current
error injection status::

	$ cat /sys/kernel/debug/cec/cec0/error-inj
	# Clear error injections:
	#   clear          clear all rx and tx error injections
	#   rx-clear       clear all rx error injections
	#   tx-clear       clear all tx error injections
	#   <op> clear     clear all rx and tx error injections for <op>
	#   <op> rx-clear  clear all rx error injections for <op>
	#   <op> tx-clear  clear all tx error injections for <op>
	#
	# RX error injection:
	#   <op>[,<mode>] rx-nack              NACK the message instead of sending an ACK
	#   <op>[,<mode>] rx-low-drive <bit>   force a low-drive condition at this bit position
	#   <op>[,<mode>] rx-add-byte          add a spurious byte to the received CEC message
	#   <op>[,<mode>] rx-remove-byte       remove the last byte from the received CEC message
	#    any[,<mode>] rx-arb-lost [<poll>] generate a POLL message to trigger an arbitration lost
	#
	# TX error injection settings:
	#   tx-ignore-nack-until-eom           ignore early NACKs until EOM
	#   tx-custom-low-usecs <usecs>        define the 'low' time for the custom pulse
	#   tx-custom-high-usecs <usecs>       define the 'high' time for the custom pulse
	#   tx-custom-pulse                    transmit the custom pulse once the bus is idle
	#
	# TX error injection:
	#   <op>[,<mode>] tx-no-eom            don't set the EOM bit
	#   <op>[,<mode>] tx-early-eom         set the EOM bit one byte too soon
	#   <op>[,<mode>] tx-add-bytes <num>   append <num> (1-255) spurious bytes to the message
	#   <op>[,<mode>] tx-remove-byte       drop the last byte from the message
	#   <op>[,<mode>] tx-short-bit <bit>   make this bit shorter than allowed
	#   <op>[,<mode>] tx-long-bit <bit>    make this bit longer than allowed
	#   <op>[,<mode>] tx-custom-bit <bit>  send the custom pulse instead of this bit
	#   <op>[,<mode>] tx-short-start       send a start pulse that's too short
	#   <op>[,<mode>] tx-long-start        send a start pulse that's too long
	#   <op>[,<mode>] tx-custom-start      send the custom pulse instead of the start pulse
	#   <op>[,<mode>] tx-last-bit <bit>    stop sending after this bit
	#   <op>[,<mode>] tx-low-drive <bit>   force a low-drive condition at this bit position
	#
	# <op>       CEC message opcode (0-255) or 'any'
	# <mode>     'once' (default), 'always', 'toggle' or 'off'
	# <bit>      CEC message bit (0-159)
	#            10 bits per 'byte': bits 0-7: data, bit 8: EOM, bit 9: ACK
	# <poll>     CEC poll message used to test arbitration lost (0x00-0xff, default 0x0f)
	# <usecs>    microseconds (0-10000000, default 1000)

	clear

You can write error injection commands to ``error-inj`` using
``echo 'cmd' >error-inj`` or ``cat cmd.txt >error-inj``. The ``cat error-inj``
output contains the current error commands. You can save the output to a file
and use it as an input to ``error-inj`` later.

Basic Syntax
------------

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.

The error injection commands fall in two main groups: those relating to
receiving CEC messages and those relating to transmitting CEC messages. In
addition, there are commands to clear existing error injection commands and
to create custom pulses on the CEC bus.

Most error injection commands can be executed for specific CEC opcodes or for
all opcodes (``any``). Each command also has a 'mode' which can be ``off``
(can be used to turn off an existing error injection command), ``once``
(the default) which will trigger the error injection only once for the next
received or transmitted message, ``always`` to always trigger the error
injection and ``toggle`` to toggle the error injection on or off for every
transmit or receive.

So '``any rx-nack``' will NACK the next received CEC message,
'``any,always rx-nack``' will NACK all received CEC messages and
'``0x82,toggle rx-nack``' will only NACK if an Active Source message was
received and do that only for every other received message.

After an error was injected with mode ``once`` the error injection command
is cleared automatically, so ``once`` is a one-time deal.

All combinations of ``<op>`` and error injection commands can co-exist. So
this is fine::

	0x9e tx-add-bytes 1
	0x9e tx-early-eom
	0x9f tx-add-bytes 2
	any rx-nack

All four error injection commands will be active simultaneously.

However, if the same ``<op>`` and command combination is specified,
but with different arguments::

	0x9e tx-add-bytes 1
	0x9e tx-add-bytes 2

Then the second will overwrite the first.

Clear Error Injections
----------------------

``clear``
    Clear all error injections.

``rx-clear``
    Clear all receive error injections

``tx-clear``
    Clear all transmit error injections

``<op> clear``
    Clear all error injections for the given opcode.

``<op> rx-clear``
    Clear all receive error injections for the given opcode.

``<op> tx-clear``
    Clear all transmit error injections for the given opcode.

Receive Messages
----------------

``<op>[,<mode>] rx-nack``
    NACK broadcast messages and messages directed to this CEC adapter.
    Every byte of the message will be NACKed in case the transmitter
    keeps transmitting after the first byte was NACKed.

``<op>[,<mode>] rx-low-drive <bit>``
    Force a Low Drive condition at this bit position. If <op> specifies
    a specific CEC opcode then the bit position must be at least 18,
    otherwise the opcode hasn't been received yet. This tests if the
    transmitter can handle the Low Drive condition correctly and reports
    the error correctly. Note that a Low Drive in the first 4 bits can also
    be interpreted as an Arbitration Lost condition by the transmitter.
    This is implementation dependent.

``<op>[,<mode>] rx-add-byte``
    Add a spurious 0x55 byte to the received CEC message, provided
    the message was 15 bytes long or less. This is useful to test
    the high-level protocol since spurious bytes should be ignored.

``<op>[,<mode>] rx-remove-byte``
    Remove the last byte from the received CEC message, provided it
    was at least 2 bytes long. This is useful to test the high-level
    protocol since messages that are too short should be ignored.

``<op>[,<mode>] rx-arb-lost <poll>``
    Generate a POLL message to trigger an Arbitration Lost condition.
    This command is only allowed for ``<op>`` values of ``next`` or ``all``.
    As soon as a start bit has been received the CEC adapter will switch
    to transmit mode and it will transmit a POLL message. By default this is
    0x0f, but it can also be specified explicitly via the ``<poll>`` argument.

    This command can be used to test the Arbitration Lost condition in
    the remote CEC transmitter. Arbitration happens when two CEC adapters
    start sending a message at the same time. In that case the initiator
    with the most leading zeroes wins and the other transmitter has to
    stop transmitting ('Arbitration Lost'). This is very hard to test,
    except by using this error injection command.

    This does not work if the remote CEC transmitter has logical address
    0 ('TV') since that will always win.

Transmit Messages
-----------------

``tx-ignore-nack-until-eom``
    This setting changes the behavior of transmitting CEC messages. Normally
    as soon as the receiver NACKs a byte the transmit will stop, but the
    specification also allows that the full message is transmitted and only
    at the end will the transmitter look at the ACK bit. This is not
    recommended behavior since there is no point in keeping the CEC bus busy
    for longer than is strictly needed. Especially given how slow the bus is.

    This setting can be used to test how well a receiver deals with
    transmitters that ignore NACKs until the very end of the message.

``<op>[,<mode>] tx-no-eom``
    Don't set the EOM bit. Normally the last byte of the message has the EOM
    (End-Of-Message) bit set. With this command the transmit will just stop
    without ever sending an EOM. This can be used to test how a receiver
    handles this case. Normally receivers have a time-out after which
    they will go back to the Idle state.

``<op>[,<mode>] tx-early-eom``
    Set the EOM bit one byte too soon. This obviously only works for messages
    of two bytes or more. The EOM bit will be set for the second-to-last byte
    and not for the final byte. The receiver should ignore the last byte in
    this case. Since the resulting message is likely to be too short for this
    same reason the whole message is typically ignored. The receiver should be
    in Idle state after the last byte was transmitted.

``<op>[,<mode>] tx-add-bytes <num>``
    Append ``<num>`` (1-255) spurious bytes to the message. The extra bytes
    have the value of the byte position in the message. So if you transmit a
    two byte message (e.g. a Get CEC Version message) and add 2 bytes, then
    the full message received by the remote CEC adapter is
    ``0x40 0x9f 0x02 0x03``.

    This command can be used to test buffer overflows in the receiver. E.g.
    what does it do when it receives more than the maximum message size of 16
    bytes.

``<op>[,<mode>] tx-remove-byte``
    Drop the last byte from the message, provided the message is at least
    two bytes long. The receiver should ignore messages that are too short.

``<op>[,<mode>] tx-short-bit <bit>``
    Make this bit period shorter than allowed. The bit position cannot be
    an Ack bit.  If <op> specifies a specific CEC opcode then the bit position
    must be at least 18, otherwise the opcode hasn't been received yet.
    Normally the period of a data bit is between 2.05 and 2.75 milliseconds.
    With this command the period of this bit is 1.8 milliseconds, this is
    done by reducing the time the CEC bus is high. This bit period is less
    than is allowed and the receiver should respond with a Low Drive
    condition.

    This command is ignored for 0 bits in bit positions 0 to 3. This is
    because the receiver also looks for an Arbitration Lost condition in
    those first four bits and it is undefined what will happen if it
    sees a too-short 0 bit.

``<op>[,<mode>] tx-long-bit <bit>``
    Make this bit period longer than is valid. The bit position cannot be
    an Ack bit.  If <op> specifies a specific CEC opcode then the bit position
    must be at least 18, otherwise the opcode hasn't been received yet.
    Normally the period of a data bit is between 2.05 and 2.75 milliseconds.
    With this command the period of this bit is 2.9 milliseconds, this is
    done by increasing the time the CEC bus is high.

    Even though this bit period is longer than is valid it is undefined what
    a receiver will do. It might just accept it, or it might time out and
    return to Idle state. Unfortunately the CEC specification is silent about
    this.

    This command is ignored for 0 bits in bit positions 0 to 3. This is
    because the receiver also looks for an Arbitration Lost condition in
    those first four bits and it is undefined what will happen if it
    sees a too-long 0 bit.

``<op>[,<mode>] tx-short-start``
    Make this start bit period shorter than allowed. Normally the period of
    a start bit is between 4.3 and 4.7 milliseconds. With this command the
    period of the start bit is 4.1 milliseconds, this is done by reducing
    the time the CEC bus is high. This start bit period is less than is
    allowed and the receiver should return to Idle state when this is detected.

``<op>[,<mode>] tx-long-start``
    Make this start bit period longer than is valid. Normally the period of
    a start bit is between 4.3 and 4.7 milliseconds. With this command the
    period of the start bit is 5 milliseconds, this is done by increasing
    the time the CEC bus is high. This start bit period is more than is
    valid and the receiver should return to Idle state when this is detected.

    Even though this start bit period is longer than is valid it is undefined
    what a receiver will do. It might just accept it, or it might time out and
    return to Idle state. Unfortunately the CEC specification is silent about
    this.

``<op>[,<mode>] tx-last-bit <bit>``
    Just stop transmitting after this bit.  If <op> specifies a specific CEC
    opcode then the bit position must be at least 18, otherwise the opcode
    hasn't been received yet. This command can be used to test how the receiver
    reacts when a message just suddenly stops. It should time out and go back
    to Idle state.

``<op>[,<mode>] tx-low-drive <bit>``
    Force a Low Drive condition at this bit position. If <op> specifies a
    specific CEC opcode then the bit position must be at least 18, otherwise
    the opcode hasn't been received yet. This can be used to test how the
    receiver handles Low Drive conditions. Note that if this happens at bit
    positions 0-3 the receiver can interpret this as an Arbitration Lost
    condition. This is implementation dependent.

Custom Pulses
-------------

``tx-custom-low-usecs <usecs>``
    This defines the duration in microseconds that the custom pulse pulls
    the CEC line low. The default is 1000 microseconds.

``tx-custom-high-usecs <usecs>``
    This defines the duration in microseconds that the custom pulse keeps the
    CEC line high (unless another CEC adapter pulls it low in that time).
    The default is 1000 microseconds. The total period of the custom pulse is
    ``tx-custom-low-usecs + tx-custom-high-usecs``.

``<op>[,<mode>] tx-custom-bit <bit>``
    Send the custom bit instead of a regular data bit. The bit position cannot
    be an Ack bit.  If <op> specifies a specific CEC opcode then the bit
    position must be at least 18, otherwise the opcode hasn't been received yet.

``<op>[,<mode>] tx-custom-start``
    Send the custom bit instead of a regular start bit.

``tx-custom-pulse``
    Transmit a single custom pulse as soon as the CEC bus is idle.

repo_name: angery/linux


code:
# -*- coding: utf-8; mode: python -*-

# SPDX-License-Identifier: GPL-2.0

project = 'Linux Media Subsystem Documentation'

# It is possible to run Sphinx in nickpick mode with:
nitpicky = True

# within nit-picking build, do not refer to any intersphinx object
intersphinx_mapping = {}

# In nickpick mode, it will complain about lots of missing references that
#
# 1) are just typedefs like: bool, __u32, etc;
# 2) It will complain for things like: enum, NULL;
# 3) It will complain for symbols that should be on different
#    books (but currently aren't ported to ReST)
#
# The list below has a list of such symbols to be ignored in nitpick mode
#
nitpick_ignore = [
    ("c:func", "clock_gettime"),
    ("c:func", "close"),
    ("c:func", "container_of"),
    ("c:func", "copy_from_user"),
    ("c:func", "copy_to_user"),
    ("c:func", "determine_valid_ioctls"),
    ("c:func", "ERR_PTR"),
    ("c:func", "i2c_new_client_device"),
    ("c:func", "ioctl"),
    ("c:func", "IS_ERR"),
    ("c:func", "KERNEL_VERSION"),
    ("c:func", "mmap"),
    ("c:func", "open"),
    ("c:func", "pci_name"),
    ("c:func", "poll"),
    ("c:func", "PTR_ERR"),
    ("c:func", "read"),
    ("c:func", "release"),
    ("c:func", "set"),
    ("c:func", "struct fd_set"),
    ("c:func", "struct pollfd"),
    ("c:func", "usb_make_path"),
    ("c:func", "wait_finish"),
    ("c:func", "wait_prepare"),
    ("c:func", "write"),

    ("c:type", "atomic_t"),
    ("c:type", "bool"),
    ("c:type", "boolean"),
    ("c:type", "buf_queue"),
    ("c:type", "device"),
    ("c:type", "device_driver"),
    ("c:type", "device_node"),
    ("c:type", "enum"),
    ("c:type", "fd"),
    ("c:type", "fd_set"),
    ("c:type", "file"),
    ("c:type", "i2c_adapter"),
    ("c:type", "i2c_board_info"),
    ("c:type", "i2c_client"),
    ("c:type", "int16_t"),
    ("c:type", "ktime_t"),
    ("c:type", "led_classdev_flash"),
    ("c:type", "list_head"),
    ("c:type", "lock_class_key"),
    ("c:type", "module"),
    ("c:type", "mutex"),
    ("c:type", "NULL"),
    ("c:type", "off_t"),
    ("c:type", "pci_dev"),
    ("c:type", "pdvbdev"),
    ("c:type", "poll_table"),
    ("c:type", "platform_device"),
    ("c:type", "pollfd"),
    ("c:type", "poll_table_struct"),
    ("c:type", "s32"),
    ("c:type", "s64"),
    ("c:type", "sd"),
    ("c:type", "size_t"),
    ("c:type", "spi_board_info"),
    ("c:type", "spi_device"),
    ("c:type", "spi_master"),
    ("c:type", "ssize_t"),
    ("c:type", "fb_fix_screeninfo"),
    ("c:type", "pollfd"),
    ("c:type", "timeval"),
    ("c:type", "video_capability"),
    ("c:type", "timeval"),
    ("c:type", "__u16"),
    ("c:type", "u16"),
    ("c:type", "__u32"),
    ("c:type", "u32"),
    ("c:type", "__u64"),
    ("c:type", "u64"),
    ("c:type", "u8"),
    ("c:type", "uint16_t"),
    ("c:type", "uint32_t"),
    ("c:type", "union"),
    ("c:type", "__user"),
    ("c:type", "usb_device"),
    ("c:type", "usb_interface"),
    ("c:type", "v4l2_std_id"),
    ("c:type", "video_system_t"),
    ("c:type", "vm_area_struct"),

    # Opaque structures

    ("c:type", "v4l2_m2m_dev"),
]


code:
# SPDX-License-Identifier: GPL-2.0

# Ignore header name
ignore define _UAPI_DVBDMX_H_

# Ignore limit constants
ignore define DMX_FILTER_SIZE

# dmx_pes_type_t enum symbols
replace enum dmx_ts_pes :c:type:`dmx_pes_type`
replace symbol DMX_PES_AUDIO0 :c:type:`dmx_pes_type`
replace symbol DMX_PES_VIDEO0 :c:type:`dmx_pes_type`
replace symbol DMX_PES_TELETEXT0 :c:type:`dmx_pes_type`
replace symbol DMX_PES_SUBTITLE0 :c:type:`dmx_pes_type`
replace symbol DMX_PES_PCR0 :c:type:`dmx_pes_type`
replace symbol DMX_PES_AUDIO1 :c:type:`dmx_pes_type`
replace symbol DMX_PES_VIDEO1 :c:type:`dmx_pes_type`
replace symbol DMX_PES_TELETEXT1 :c:type:`dmx_pes_type`
replace symbol DMX_PES_SUBTITLE1 :c:type:`dmx_pes_type`
replace symbol DMX_PES_PCR1 :c:type:`dmx_pes_type`
replace symbol DMX_PES_AUDIO2 :c:type:`dmx_pes_type`
replace symbol DMX_PES_VIDEO2 :c:type:`dmx_pes_type`
replace symbol DMX_PES_TELETEXT2 :c:type:`dmx_pes_type`
replace symbol DMX_PES_SUBTITLE2 :c:type:`dmx_pes_type`
replace symbol DMX_PES_PCR2 :c:type:`dmx_pes_type`
replace symbol DMX_PES_AUDIO3 :c:type:`dmx_pes_type`
replace symbol DMX_PES_VIDEO3 :c:type:`dmx_pes_type`
replace symbol DMX_PES_TELETEXT3 :c:type:`dmx_pes_type`
replace symbol DMX_PES_SUBTITLE3 :c:type:`dmx_pes_type`
replace symbol DMX_PES_PCR3 :c:type:`dmx_pes_type`
replace symbol DMX_PES_OTHER :c:type:`dmx_pes_type`

# Ignore obsolete symbols
ignore define DMX_PES_AUDIO
ignore define DMX_PES_VIDEO
ignore define DMX_PES_TELETEXT
ignore define DMX_PES_SUBTITLE
ignore define DMX_PES_PCR

# dmx_input_t symbols
replace enum dmx_input :c:type:`dmx_input`
replace symbol DMX_IN_FRONTEND :c:type:`dmx_input`
replace symbol DMX_IN_DVR :c:type:`dmx_input`

# Flags for struct dmx_sct_filter_params
replace define DMX_CHECK_CRC :c:type:`dmx_sct_filter_params`
replace define DMX_ONESHOT :c:type:`dmx_sct_filter_params`
replace define DMX_IMMEDIATE_START :c:type:`dmx_sct_filter_params`

# some typedefs should point to struct/enums
replace typedef dmx_filter_t :c:type:`dmx_filter`
replace typedef dmx_pes_type_t :c:type:`dmx_pes_type`
replace typedef dmx_input_t :c:type:`dmx_input`

replace symbol DMX_BUFFER_FLAG_HAD_CRC32_DISCARD :c:type:`dmx_buffer_flags`
replace	symbol DMX_BUFFER_FLAG_TEI :c:type:`dmx_buffer_flags`
replace	symbol DMX_BUFFER_PKT_COUNTER_MISMATCH :c:type:`dmx_buffer_flags`
replace	symbol DMX_BUFFER_FLAG_DISCONTINUITY_DETECTED :c:type:`dmx_buffer_flags`
replace	symbol DMX_BUFFER_FLAG_DISCONTINUITY_INDICATOR :c:type:`dmx_buffer_flags`

replace symbol DMX_OUT_DECODER :c:type:`dmx_output`
replace symbol DMX_OUT_TAP :c:type:`dmx_output`
replace symbol DMX_OUT_TS_TAP :c:type:`dmx_output`
replace symbol DMX_OUT_TSDEMUX_TAP :c:type:`dmx_output`

replace ioctl DMX_DQBUF dmx_qbuf


code:
.. SPDX-License-Identifier: GPL-2.0

.. include:: <isonum.txt>

ASPEED video driver
===================

ASPEED Video Engine found on AST2400/2500/2600 SoC supports high performance
video compressions with a wide range of video quality and compression ratio
options. The adopted compressing algorithm is a modified JPEG algorithm.

There are 2 types of compressions in this IP.

* JPEG JFIF standard mode: for single frame and management compression
* ASPEED proprietary mode: for multi-frame and differential compression.
  Support 2-pass (high quality) video compression scheme (Patent pending by
  ASPEED). Provide visually lossless video compression quality or to reduce
  the network average loading under intranet KVM applications.

VIDIOC_S_FMT can be used to choose which format you want. V4L2_PIX_FMT_JPEG
stands for JPEG JFIF standard mode; V4L2_PIX_FMT_AJPG stands for ASPEED
proprietary mode.

More details on the ASPEED video hardware operations can be found in
*chapter 6.2.16 KVM Video Driver* of SDK_User_Guide which available on
AspeedTech-BMC/openbmc/releases.

The ASPEED video driver implements the following driver-specific control:

``V4L2_CID_ASPEED_HQ_MODE``
---------------------------
    Enable/Disable ASPEED's High quality mode. This is a private control
    that can be used to enable high quality for aspeed proprietary mode.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - ``(0)``
      - ASPEED HQ mode is disabled.
    * - ``(1)``
      - ASPEED HQ mode is enabled.

``V4L2_CID_ASPEED_HQ_JPEG_QUALITY``
-----------------------------------
    Define the quality of ASPEED's High quality mode. This is a private control
    that can be used to decide compression quality if High quality mode enabled
    . Higher the value, better the quality and bigger the size.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - ``(1)``
      - minimum
    * - ``(12)``
      - maximum
    * - ``(1)``
      - step
    * - ``(1)``
      - default

**Copyright** |copy| 2022 ASPEED Technology Inc.


code:
.. SPDX-License-Identifier: GPL-2.0-only

.. include:: <isonum.txt>

MIPI CCS camera sensor driver
=============================

The MIPI CCS camera sensor driver is a generic driver for `MIPI CCS
<https://www.mipi.org/specifications/camera-command-set>`_ compliant
camera sensors. It exposes three sub-devices representing the pixel array,
the binner and the scaler.

As the capabilities of individual devices vary, the driver exposes
interfaces based on the capabilities that exist in hardware.

Pixel Array sub-device
----------------------

The pixel array sub-device represents the camera sensor's pixel matrix, as well
as analogue crop functionality present in many compliant devices. The analogue
crop is configured using the ``V4L2_SEL_TGT_CROP`` on the source pad (0) of the
entity. The size of the pixel matrix can be obtained by getting the
``V4L2_SEL_TGT_NATIVE_SIZE`` target.

Binner
------

The binner sub-device represents the binning functionality on the sensor. For
that purpose, selection target ``V4L2_SEL_TGT_COMPOSE`` is supported on the
sink pad (0).

Additionally, if a device has no scaler or digital crop functionality, the
source pad (1) expses another digital crop selection rectangle that can only
crop at the end of the lines and frames.

Scaler
------

The scaler sub-device represents the digital crop and scaling functionality of
the sensor. The V4L2 selection target ``V4L2_SEL_TGT_CROP`` is used to
configure the digital crop on the sink pad (0) when digital crop is supported.
Scaling is configured using selection target ``V4L2_SEL_TGT_COMPOSE`` on the
sink pad (0) as well.

Additionally, if the scaler sub-device exists, its source pad (1) exposes
another digital crop selection rectangle that can only crop at the end of the
lines and frames.

Digital and analogue crop
-------------------------

Digital crop functionality is referred to as cropping that effectively works by
dropping some data on the floor. Analogue crop, on the other hand, means that
the cropped information is never retrieved. In case of camera sensors, the
analogue data is never read from the pixel matrix that are outside the
configured selection rectangle that designates crop. The difference has an
effect in device timing and likely also in power consumption.

Private controls
----------------

The MIPI CCS driver implements a number of private controls under
``V4L2_CID_USER_BASE_CCS`` to control the MIPI CCS compliant camera sensors.

Analogue gain model
~~~~~~~~~~~~~~~~~~~

The CCS defines an analogue gain model where the gain can be calculated using
the following formula:

	gain = m0 * x + c0 / (m1 * x + c1)

Either m0 or c0 will be zero. The constants that are device specific, can be
obtained from the following controls:

	V4L2_CID_CCS_ANALOGUE_GAIN_M0
	V4L2_CID_CCS_ANALOGUE_GAIN_M1
	V4L2_CID_CCS_ANALOGUE_GAIN_C0
	V4L2_CID_CCS_ANALOGUE_GAIN_C1

The analogue gain (``x`` in the formula) is controlled through
``V4L2_CID_ANALOGUE_GAIN`` in this case.

Alternate analogue gain model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The CCS defines another analogue gain model called alternate analogue gain. In
this case, the formula to calculate actual gain consists of linear and
exponential parts:

	gain = linear * 2 ^ exponent

The ``linear`` and ``exponent`` factors can be set using the
``V4L2_CID_CCS_ANALOGUE_LINEAR_GAIN`` and
``V4L2_CID_CCS_ANALOGUE_EXPONENTIAL_GAIN`` controls, respectively

Shading correction
~~~~~~~~~~~~~~~~~~

The CCS standard supports lens shading correction. The feature can be controlled
using ``V4L2_CID_CCS_SHADING_CORRECTION``. Additionally, the luminance
correction level may be changed using
``V4L2_CID_CCS_LUMINANCE_CORRECTION_LEVEL``, where value 0 indicates no
correction and 128 indicates correcting the luminance in corners to 10 % less
than in the centre.

Shading correction needs to be enabled for luminance correction level to have an
effect.

**Copyright** |copy| 2020 Intel Corporation


code:
.. SPDX-License-Identifier: GPL-2.0

The cx2341x driver
==================

Non-compressed file format
--------------------------

The cx23416 can produce (and the cx23415 can also read) raw YUV output. The
format of a YUV frame is 16x16 linear tiled NV12 (V4L2_PIX_FMT_NV12_16L16).

The format is YUV 4:2:0 which uses 1 Y byte per pixel and 1 U and V byte per
four pixels.

The data is encoded as two macroblock planes, the first containing the Y
values, the second containing UV macroblocks.

The Y plane is divided into blocks of 16x16 pixels from left to right
and from top to bottom. Each block is transmitted in turn, line-by-line.

So the first 16 bytes are the first line of the top-left block, the
second 16 bytes are the second line of the top-left block, etc. After
transmitting this block the first line of the block on the right to the
first block is transmitted, etc.

The UV plane is divided into blocks of 16x8 UV values going from left
to right, top to bottom. Each block is transmitted in turn, line-by-line.

So the first 16 bytes are the first line of the top-left block and
contain 8 UV value pairs (16 bytes in total). The second 16 bytes are the
second line of 8 UV pairs of the top-left block, etc. After transmitting
this block the first line of the block on the right to the first block is
transmitted, etc.

The code below is given as an example on how to convert V4L2_PIX_FMT_NV12_16L16
to separate Y, U and V planes. This code assumes frames of 720x576 (PAL) pixels.

The width of a frame is always 720 pixels, regardless of the actual specified
width.

If the height is not a multiple of 32 lines, then the captured video is
missing macroblocks at the end and is unusable. So the height must be a
multiple of 32.

Raw format c example
~~~~~~~~~~~~~~~~~~~~

.. code-block:: c

	#include <stdio.h>
	#include <stdlib.h>
	#include <string.h>

	static unsigned char frame[576*720*3/2];
	static unsigned char framey[576*720];
	static unsigned char frameu[576*720 / 4];
	static unsigned char framev[576*720 / 4];

	static void de_macro_y(unsigned char* dst, unsigned char *src, int dstride, int w, int h)
	{
	unsigned int y, x, i;

	// descramble Y plane
	// dstride = 720 = w
	// The Y plane is divided into blocks of 16x16 pixels
	// Each block in transmitted in turn, line-by-line.
	for (y = 0; y < h; y += 16) {
		for (x = 0; x < w; x += 16) {
		for (i = 0; i < 16; i++) {
			memcpy(dst + x + (y + i) * dstride, src, 16);
			src += 16;
		}
		}
	}
	}

	static void de_macro_uv(unsigned char *dstu, unsigned char *dstv, unsigned char *src, int dstride, int w, int h)
	{
	unsigned int y, x, i;

	// descramble U/V plane
	// dstride = 720 / 2 = w
	// The U/V values are interlaced (UVUV...).
	// Again, the UV plane is divided into blocks of 16x16 UV values.
	// Each block in transmitted in turn, line-by-line.
	for (y = 0; y < h; y += 16) {
		for (x = 0; x < w; x += 8) {
		for (i = 0; i < 16; i++) {
			int idx = x + (y + i) * dstride;

			dstu[idx+0] = src[0];  dstv[idx+0] = src[1];
			dstu[idx+1] = src[2];  dstv[idx+1] = src[3];
			dstu[idx+2] = src[4];  dstv[idx+2] = src[5];
			dstu[idx+3] = src[6];  dstv[idx+3] = src[7];
			dstu[idx+4] = src[8];  dstv[idx+4] = src[9];
			dstu[idx+5] = src[10]; dstv[idx+5] = src[11];
			dstu[idx+6] = src[12]; dstv[idx+6] = src[13];
			dstu[idx+7] = src[14]; dstv[idx+7] = src[15];
			src += 16;
		}
		}
	}
	}

	/*************************************************************************/
	int main(int argc, char **argv)
	{
	FILE *fin;
	int i;

	if (argc == 1) fin = stdin;
	else fin = fopen(argv[1], "r");

	if (fin == NULL) {
		fprintf(stderr, "cannot open input\n");
		exit(-1);
	}
	while (fread(frame, sizeof(frame), 1, fin) == 1) {
		de_macro_y(framey, frame, 720, 720, 576);
		de_macro_uv(frameu, framev, frame + 720 * 576, 720 / 2, 720 / 2, 576 / 2);
		fwrite(framey, sizeof(framey), 1, stdout);
		fwrite(framev, sizeof(framev), 1, stdout);
		fwrite(frameu, sizeof(frameu), 1, stdout);
	}
	fclose(fin);
	return 0;
	}

Format of embedded V4L2_MPEG_STREAM_VBI_FMT_IVTV VBI data
---------------------------------------------------------

Author: Hans Verkuil <hverkuil@xs4all.nl>

This section describes the V4L2_MPEG_STREAM_VBI_FMT_IVTV format of the VBI data
embedded in an MPEG-2 program stream. This format is in part dictated by some
hardware limitations of the ivtv driver (the driver for the Conexant cx23415/6
chips), in particular a maximum size for the VBI data. Anything longer is cut
off when the MPEG stream is played back through the cx23415.

The advantage of this format is it is very compact and that all VBI data for
all lines can be stored while still fitting within the maximum allowed size.

The stream ID of the VBI data is 0xBD. The maximum size of the embedded data is
4 + 43 * 36, which is 4 bytes for a header and 2 * 18 VBI lines with a 1 byte
header and a 42 bytes payload each. Anything beyond this limit is cut off by
the cx23415/6 firmware. Besides the data for the VBI lines we also need 36 bits
for a bitmask determining which lines are captured and 4 bytes for a magic cookie,
signifying that this data package contains V4L2_MPEG_STREAM_VBI_FMT_IVTV VBI data.
If all lines are used, then there is no longer room for the bitmask. To solve this
two different magic numbers were introduced:

'itv0': After this magic number two unsigned longs follow. Bits 0-17 of the first
unsigned long denote which lines of the first field are captured. Bits 18-31 of
the first unsigned long and bits 0-3 of the second unsigned long are used for the
second field.

'ITV0': This magic number assumes all VBI lines are captured, i.e. it implicitly
implies that the bitmasks are 0xffffffff and 0xf.

After these magic cookies (and the 8 byte bitmask in case of cookie 'itv0') the
captured VBI lines start:

For each line the least significant 4 bits of the first byte contain the data type.
Possible values are shown in the table below. The payload is in the following 42
bytes.

Here is the list of possible data types:

.. code-block:: c

	#define IVTV_SLICED_TYPE_TELETEXT       0x1     // Teletext (uses lines 6-22 for PAL)
	#define IVTV_SLICED_TYPE_CC             0x4     // Closed Captions (line 21 NTSC)
	#define IVTV_SLICED_TYPE_WSS            0x5     // Wide Screen Signal (line 23 PAL)
	#define IVTV_SLICED_TYPE_VPS            0x7     // Video Programming System (PAL) (line 16)


code:
.. SPDX-License-Identifier: GPL-2.0

=========================
i.MX Video Capture Driver
=========================

Events
======

.. _imx_api_ipuX_csiY:

ipuX_csiY
---------

This subdev can generate the following event when enabling the second
IDMAC source pad:

- V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR

The user application can subscribe to this event from the ipuX_csiY
subdev node. This event is generated by the Frame Interval Monitor
(see below for more on the FIM).

Controls
========

.. _imx_api_FIM:

Frame Interval Monitor in ipuX_csiY
-----------------------------------

The adv718x decoders can occasionally send corrupt fields during
NTSC/PAL signal re-sync (too little or too many video lines). When
this happens, the IPU triggers a mechanism to re-establish vertical
sync by adding 1 dummy line every frame, which causes a rolling effect
from image to image, and can last a long time before a stable image is
recovered. Or sometimes the mechanism doesn't work at all, causing a
permanent split image (one frame contains lines from two consecutive
captured images).

From experiment it was found that during image rolling, the frame
intervals (elapsed time between two EOF's) drop below the nominal
value for the current standard, by about one frame time (60 usec),
and remain at that value until rolling stops.

While the reason for this observation isn't known (the IPU dummy
line mechanism should show an increase in the intervals by 1 line
time every frame, not a fixed value), we can use it to detect the
corrupt fields using a frame interval monitor. If the FIM detects a
bad frame interval, the ipuX_csiY subdev will send the event
V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR. Userland can register with
the FIM event notification on the ipuX_csiY subdev device node.
Userland can issue a streaming restart when this event is received
to correct the rolling/split image.

The ipuX_csiY subdev includes custom controls to tweak some dials for
FIM. If one of these controls is changed during streaming, the FIM will
be reset and will continue at the new settings.

- V4L2_CID_IMX_FIM_ENABLE

Enable/disable the FIM.

- V4L2_CID_IMX_FIM_NUM

How many frame interval measurements to average before comparing against
the nominal frame interval reported by the sensor. This can reduce noise
caused by interrupt latency.

- V4L2_CID_IMX_FIM_TOLERANCE_MIN

If the averaged intervals fall outside nominal by this amount, in
microseconds, the V4L2_EVENT_IMX_FRAME_INTERVAL_ERROR event is sent.

- V4L2_CID_IMX_FIM_TOLERANCE_MAX

If any intervals are higher than this value, those samples are
discarded and do not enter into the average. This can be used to
discard really high interval errors that might be due to interrupt
latency from high system load.

- V4L2_CID_IMX_FIM_NUM_SKIP

How many frames to skip after a FIM reset or stream restart before
FIM begins to average intervals.

- V4L2_CID_IMX_FIM_ICAP_CHANNEL / V4L2_CID_IMX_FIM_ICAP_EDGE

These controls will configure an input capture channel as the method
for measuring frame intervals. This is superior to the default method
of measuring frame intervals via EOF interrupt, since it is not subject
to uncertainty errors introduced by interrupt latency.

Input capture requires hardware support. A VSYNC signal must be routed
to one of the i.MX6 input capture channel pads.

V4L2_CID_IMX_FIM_ICAP_CHANNEL configures which i.MX6 input capture
channel to use. This must be 0 or 1.

V4L2_CID_IMX_FIM_ICAP_EDGE configures which signal edge will trigger
input capture events. By default the input capture method is disabled
with a value of IRQ_TYPE_NONE. Set this control to IRQ_TYPE_EDGE_RISING,
IRQ_TYPE_EDGE_FALLING, or IRQ_TYPE_EDGE_BOTH to enable input capture,
triggered on the given signal edge(s).

When input capture is disabled, frame intervals will be measured via
EOF interrupt.

File list
---------

drivers/staging/media/imx/
include/media/imx.h
include/linux/imx-media.h

Authors
-------

- Steve Longerbeam <steve_longerbeam@mentor.com>
- Philipp Zabel <kernel@pengutronix.de>
- Russell King <linux@armlinux.org.uk>

Copyright (C) 2012-2017 Mentor Graphics Inc.


code:
.. SPDX-License-Identifier: GPL-2.0

.. include:: <isonum.txt>

.. _v4l-drivers_uapi:

################################################
Video4Linux (V4L)  driver-specific documentation
################################################

**Copyright** |copy| 1999-2016 : 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 version 2 of the License.

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.

.. only:: html

   .. class:: toc-title

        Table of Contents

.. toctree::
	:maxdepth: 5
	:numbered:

	aspeed-video
	ccs
	cx2341x-uapi
	dw100
	imx-uapi
	max2175
	meye-uapi
	omap3isp-uapi
	st-vgxy61
	uvcvideo


code:
.. SPDX-License-Identifier: GPL-2.0

Maxim Integrated MAX2175 RF to bits tuner driver
================================================

The MAX2175 driver implements the following driver-specific controls:

``V4L2_CID_MAX2175_I2S_ENABLE``
-------------------------------
    Enable/Disable I2S output of the tuner. This is a private control
    that can be accessed only using the subdev interface.
    Refer to Documentation/driver-api/media/v4l2-controls.rst for more details.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - ``(0)``
      - I2S output is disabled.
    * - ``(1)``
      - I2S output is enabled.

``V4L2_CID_MAX2175_HSLS``
-------------------------
    The high-side/low-side (HSLS) control of the tuner for a given band.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - ``(0)``
      - The LO frequency position is below the desired frequency.
    * - ``(1)``
      - The LO frequency position is above the desired frequency.

``V4L2_CID_MAX2175_RX_MODE (menu)``
-----------------------------------
    The Rx mode controls a number of preset parameters of the tuner like
    sample clock (sck), sampling rate etc. These multiple settings are
    provided under one single label called Rx mode in the datasheet. The
    list below shows the supported modes with a brief description.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - ``"Europe modes"``
    * - ``"FM 1.2" (0)``
      - This configures FM band with a sample rate of 0.512 million
        samples/sec with a 10.24 MHz sck.
    * - ``"DAB 1.2" (1)``
      - This configures VHF band with a sample rate of 2.048 million
        samples/sec with a 32.768 MHz sck.

    * - ``"North America modes"``
    * - ``"FM 1.0" (0)``
      - This configures FM band with a sample rate of 0.7441875 million
        samples/sec with a 14.88375 MHz sck.
    * - ``"DAB 1.2" (1)``
      - This configures FM band with a sample rate of 0.372 million
        samples/sec with a 7.441875 MHz sck.


code:
.. SPDX-License-Identifier: GPL-2.0

.. include:: <isonum.txt>

Vaio Picturebook Motion Eye Camera Driver
=========================================

Copyright |copy| 2001-2004 Stelian Pop <stelian@popies.net>

Copyright |copy| 2001-2002 Alcôve <www.alcove.com>

Copyright |copy| 2000 Andrew Tridgell <tridge@samba.org>

Private API
-----------

The driver supports frame grabbing with the video4linux API,
so all video4linux tools (like xawtv) should work with this driver.

Besides the video4linux interface, the driver has a private interface
for accessing the Motion Eye extended parameters (camera sharpness,
agc, video framerate), the snapshot and the MJPEG capture facilities.

This interface consists of several ioctls (prototypes and structures
can be found in include/linux/meye.h):

MEYEIOC_G_PARAMS and MEYEIOC_S_PARAMS
	Get and set the extended parameters of the motion eye camera.
	The user should always query the current parameters with
	MEYEIOC_G_PARAMS, change what he likes and then issue the
	MEYEIOC_S_PARAMS call (checking for -EINVAL). The extended
	parameters are described by the meye_params structure.

MEYEIOC_QBUF_CAPT
	Queue a buffer for capture (the buffers must have been
	obtained with a VIDIOCGMBUF call and mmap'ed by the
	application). The argument to MEYEIOC_QBUF_CAPT is the
	buffer number to queue (or -1 to end capture). The first
	call to MEYEIOC_QBUF_CAPT starts the streaming capture.

MEYEIOC_SYNC
	Takes as an argument the buffer number you want to sync.
	This ioctl blocks until the buffer is filled and ready
	for the application to use. It returns the buffer size.

MEYEIOC_STILLCAPT and MEYEIOC_STILLJCAPT
	Takes a snapshot in an uncompressed or compressed jpeg format.
	This ioctl blocks until the snapshot is done and returns (for
	jpeg snapshot) the size of the image. The image data is
	available from the first mmap'ed buffer.

Look at the 'motioneye' application code for an actual example.


code:
.. SPDX-License-Identifier: GPL-2.0

.. include:: <isonum.txt>

OMAP 3 Image Signal Processor (ISP) driver
==========================================

Copyright |copy| 2010 Nokia Corporation

Copyright |copy| 2009 Texas Instruments, Inc.

Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com>,
Sakari Ailus <sakari.ailus@iki.fi>, David Cohen <dacohen@gmail.com>

Events
------

The OMAP 3 ISP driver does support the V4L2 event interface on CCDC and
statistics (AEWB, AF and histogram) subdevs.

The CCDC subdev produces V4L2_EVENT_FRAME_SYNC type event on HS_VS
interrupt which is used to signal frame start. Earlier version of this
driver used V4L2_EVENT_OMAP3ISP_HS_VS for this purpose. The event is
triggered exactly when the reception of the first line of the frame starts
in the CCDC module. The event can be subscribed on the CCDC subdev.

(When using parallel interface one must pay account to correct configuration
of the VS signal polarity. This is automatically correct when using the serial
receivers.)

Each of the statistics subdevs is able to produce events. An event is
generated whenever a statistics buffer can be dequeued by a user space
application using the VIDIOC_OMAP3ISP_STAT_REQ IOCTL. The events available
are:

- V4L2_EVENT_OMAP3ISP_AEWB
- V4L2_EVENT_OMAP3ISP_AF
- V4L2_EVENT_OMAP3ISP_HIST

The type of the event data is struct omap3isp_stat_event_status for these
ioctls. If there is an error calculating the statistics, there will be an
event as usual, but no related statistics buffer. In this case
omap3isp_stat_event_status.buf_err is set to non-zero.

Private IOCTLs
--------------

The OMAP 3 ISP driver supports standard V4L2 IOCTLs and controls where
possible and practical. Much of the functions provided by the ISP, however,
does not fall under the standard IOCTLs --- gamma tables and configuration of
statistics collection are examples of such.

In general, there is a private ioctl for configuring each of the blocks
containing hardware-dependent functions.

The following private IOCTLs are supported:

- VIDIOC_OMAP3ISP_CCDC_CFG
- VIDIOC_OMAP3ISP_PRV_CFG
- VIDIOC_OMAP3ISP_AEWB_CFG
- VIDIOC_OMAP3ISP_HIST_CFG
- VIDIOC_OMAP3ISP_AF_CFG
- VIDIOC_OMAP3ISP_STAT_REQ
- VIDIOC_OMAP3ISP_STAT_EN

The parameter structures used by these ioctls are described in
include/linux/omap3isp.h. The detailed functions of the ISP itself related to
a given ISP block is described in the Technical Reference Manuals (TRMs) ---
see the end of the document for those.

While it is possible to use the ISP driver without any use of these private
IOCTLs it is not possible to obtain optimal image quality this way. The AEWB,
AF and histogram modules cannot be used without configuring them using the
appropriate private IOCTLs.

CCDC and preview block IOCTLs
-----------------------------

The VIDIOC_OMAP3ISP_CCDC_CFG and VIDIOC_OMAP3ISP_PRV_CFG IOCTLs are used to
configure, enable and disable functions in the CCDC and preview blocks,
respectively. Both IOCTLs control several functions in the blocks they
control. VIDIOC_OMAP3ISP_CCDC_CFG IOCTL accepts a pointer to struct
omap3isp_ccdc_update_config as its argument. Similarly VIDIOC_OMAP3ISP_PRV_CFG
accepts a pointer to struct omap3isp_prev_update_config. The definition of
both structures is available in [#]_.

The update field in the structures tells whether to update the configuration
for the specific function and the flag tells whether to enable or disable the
function.

The update and flag bit masks accept the following values. Each separate
functions in the CCDC and preview blocks is associated with a flag (either
disable or enable; part of the flag field in the structure) and a pointer to
configuration data for the function.

Valid values for the update and flag fields are listed here for
VIDIOC_OMAP3ISP_CCDC_CFG. Values may be or'ed to configure more than one
function in the same IOCTL call.

- OMAP3ISP_CCDC_ALAW
- OMAP3ISP_CCDC_LPF
- OMAP3ISP_CCDC_BLCLAMP
- OMAP3ISP_CCDC_BCOMP
- OMAP3ISP_CCDC_FPC
- OMAP3ISP_CCDC_CULL
- OMAP3ISP_CCDC_CONFIG_LSC
- OMAP3ISP_CCDC_TBL_LSC

The corresponding values for the VIDIOC_OMAP3ISP_PRV_CFG are here:

- OMAP3ISP_PREV_LUMAENH
- OMAP3ISP_PREV_INVALAW
- OMAP3ISP_PREV_HRZ_MED
- OMAP3ISP_PREV_CFA
- OMAP3ISP_PREV_CHROMA_SUPP
- OMAP3ISP_PREV_WB
- OMAP3ISP_PREV_BLKADJ
- OMAP3ISP_PREV_RGB2RGB
- OMAP3ISP_PREV_COLOR_CONV
- OMAP3ISP_PREV_YC_LIMIT
- OMAP3ISP_PREV_DEFECT_COR
- OMAP3ISP_PREV_GAMMABYPASS
- OMAP3ISP_PREV_DRK_FRM_CAPTURE
- OMAP3ISP_PREV_DRK_FRM_SUBTRACT
- OMAP3ISP_PREV_LENS_SHADING
- OMAP3ISP_PREV_NF
- OMAP3ISP_PREV_GAMMA

The associated configuration pointer for the function may not be NULL when
enabling the function. When disabling a function the configuration pointer is
ignored.

Statistic blocks IOCTLs
-----------------------

The statistics subdevs do offer more dynamic configuration options than the
other subdevs. They can be enabled, disable and reconfigured when the pipeline
is in streaming state.

The statistics blocks always get the input image data from the CCDC (as the
histogram memory read isn't implemented). The statistics are dequeueable by
the user from the statistics subdev nodes using private IOCTLs.

The private IOCTLs offered by the AEWB, AF and histogram subdevs are heavily
reflected by the register level interface offered by the ISP hardware. There
are aspects that are purely related to the driver implementation and these are
discussed next.

VIDIOC_OMAP3ISP_STAT_EN
-----------------------

This private IOCTL enables/disables a statistic module. If this request is
done before streaming, it will take effect as soon as the pipeline starts to
stream.  If the pipeline is already streaming, it will take effect as soon as
the CCDC becomes idle.

VIDIOC_OMAP3ISP_AEWB_CFG, VIDIOC_OMAP3ISP_HIST_CFG and VIDIOC_OMAP3ISP_AF_CFG
-----------------------------------------------------------------------------

Those IOCTLs are used to configure the modules. They require user applications
to have an in-depth knowledge of the hardware. Most of the fields explanation
can be found on OMAP's TRMs. The two following fields common to all the above
configure private IOCTLs require explanation for better understanding as they
are not part of the TRM.

omap3isp_[h3a_af/h3a_aewb/hist]\_config.buf_size:

The modules handle their buffers internally. The necessary buffer size for the
module's data output depends on the requested configuration. Although the
driver supports reconfiguration while streaming, it does not support a
reconfiguration which requires bigger buffer size than what is already
internally allocated if the module is enabled. It will return -EBUSY on this
case. In order to avoid such condition, either disable/reconfigure/enable the
module or request the necessary buffer size during the first configuration
while the module is disabled.

The internal buffer size allocation considers the requested configuration's
minimum buffer size and the value set on buf_size field. If buf_size field is
out of [minimum, maximum] buffer size range, it's clamped to fit in there.
The driver then selects the biggest value. The corrected buf_size value is
written back to user application.

omap3isp_[h3a_af/h3a_aewb/hist]\_config.config_counter:

As the configuration doesn't take effect synchronously to the request, the
driver must provide a way to track this information to provide more accurate
data. After a configuration is requested, the config_counter returned to user
space application will be an unique value associated to that request. When
user application receives an event for buffer availability or when a new
buffer is requested, this config_counter is used to match a buffer data and a
configuration.

VIDIOC_OMAP3ISP_STAT_REQ
------------------------

Send to user space the oldest data available in the internal buffer queue and
discards such buffer afterwards. The field omap3isp_stat_data.frame_number
matches with the video buffer's field_count.

References
----------

.. [#] include/linux/omap3isp.h


code:
.. SPDX-License-Identifier: GPL-2.0

ST VGXY61 camera sensor driver
==============================

The ST VGXY61 driver implements the following controls:

``V4L2_CID_HDR_SENSOR_MODE``
-------------------------------
    Change the sensor HDR mode. A HDR picture is obtained by merging two
    captures of the same scene using two different exposure periods.

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths:       1 4

    * - HDR linearize
      - The merger outputs a long exposure capture as long as it is not
        saturated.
    * - HDR substraction
      - This involves subtracting the short exposure frame from the long
        exposure frame.
    * - No HDR
      - This mode is used for standard dynamic range (SDR) exposures.


code:
.. SPDX-License-Identifier: GPL-2.0

The Linux USB Video Class (UVC) driver
======================================

This file documents some driver-specific aspects of the UVC driver, such as
driver-specific ioctls and implementation notes.

Questions and remarks can be sent to the Linux UVC development mailing list at
linux-media@vger.kernel.org.

Extension Unit (XU) support
---------------------------

Introduction
~~~~~~~~~~~~

The UVC specification allows for vendor-specific extensions through extension
units (XUs). The Linux UVC driver supports extension unit controls (XU controls)
through two separate mechanisms:

  - through mappings of XU controls to V4L2 controls
  - through a driver-specific ioctl interface

The first one allows generic V4L2 applications to use XU controls by mapping
certain XU controls onto V4L2 controls, which then show up during ordinary
control enumeration.

The second mechanism requires uvcvideo-specific knowledge for the application to
access XU controls but exposes the entire UVC XU concept to user space for
maximum flexibility.

Both mechanisms complement each other and are described in more detail below.

Control mappings
~~~~~~~~~~~~~~~~

The UVC driver provides an API for user space applications to define so-called
control mappings at runtime. These allow for individual XU controls or byte
ranges thereof to be mapped to new V4L2 controls. Such controls appear and
function exactly like normal V4L2 controls (i.e. the stock controls, such as
brightness, contrast, etc.). However, reading or writing of such a V4L2 controls
triggers a read or write of the associated XU control.

The ioctl used to create these control mappings is called UVCIOC_CTRL_MAP.
Previous driver versions (before 0.2.0) required another ioctl to be used
beforehand (UVCIOC_CTRL_ADD) to pass XU control information to the UVC driver.
This is no longer necessary as newer uvcvideo versions query the information
directly from the device.

For details on the UVCIOC_CTRL_MAP ioctl please refer to the section titled
"IOCTL reference" below.

3. Driver specific XU control interface

For applications that need to access XU controls directly, e.g. for testing
purposes, firmware upload, or accessing binary controls, a second mechanism to
access XU controls is provided in the form of a driver-specific ioctl, namely
UVCIOC_CTRL_QUERY.

A call to this ioctl allows applications to send queries to the UVC driver that
directly map to the low-level UVC control requests.

In order to make such a request the UVC unit ID of the control's extension unit
and the control selector need to be known. This information either needs to be
hardcoded in the application or queried using other ways such as by parsing the
UVC descriptor or, if available, using the media controller API to enumerate a
device's entities.

Unless the control size is already known it is necessary to first make a
UVC_GET_LEN requests in order to be able to allocate a sufficiently large buffer
and set the buffer size to the correct value. Similarly, to find out whether
UVC_GET_CUR or UVC_SET_CUR are valid requests for a given control, a
UVC_GET_INFO request should be made. The bits 0 (GET supported) and 1 (SET
supported) of the resulting byte indicate which requests are valid.

With the addition of the UVCIOC_CTRL_QUERY ioctl the UVCIOC_CTRL_GET and
UVCIOC_CTRL_SET ioctls have become obsolete since their functionality is a
subset of the former ioctl. For the time being they are still supported but
application developers are encouraged to use UVCIOC_CTRL_QUERY instead.

For details on the UVCIOC_CTRL_QUERY ioctl please refer to the section titled
"IOCTL reference" below.

Security
~~~~~~~~

The API doesn't currently provide a fine-grained access control facility. The
UVCIOC_CTRL_ADD and UVCIOC_CTRL_MAP ioctls require super user permissions.

Suggestions on how to improve this are welcome.

Debugging
~~~~~~~~~

In order to debug problems related to XU controls or controls in general it is
recommended to enable the UVC_TRACE_CONTROL bit in the module parameter 'trace'.
This causes extra output to be written into the system log.

IOCTL reference
~~~~~~~~~~~~~~~

UVCIOC_CTRL_MAP - Map a UVC control to a V4L2 control
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Argument: struct uvc_xu_control_mapping

**Description**:

	This ioctl creates a mapping between a UVC control or part of a UVC
	control and a V4L2 control. Once mappings are defined, userspace
	applications can access vendor-defined UVC control through the V4L2
	control API.

	To create a mapping, applications fill the uvc_xu_control_mapping
	structure with information about an existing UVC control defined with
	UVCIOC_CTRL_ADD and a new V4L2 control.

	A UVC control can be mapped to several V4L2 controls. For instance,
	a UVC pan/tilt control could be mapped to separate pan and tilt V4L2
	controls. The UVC control is divided into non overlapping fields using
	the 'size' and 'offset' fields and are then independently mapped to
	V4L2 control.

	For signed integer V4L2 controls the data_type field should be set to
	UVC_CTRL_DATA_TYPE_SIGNED. Other values are currently ignored.

**Return value**:

	On success 0 is returned. On error -1 is returned and errno is set
	appropriately.

	ENOMEM
		Not enough memory to perform the operation.
	EPERM
		Insufficient privileges (super user privileges are required).
	EINVAL
		No such UVC control.
	EOVERFLOW
		The requested offset and size would overflow the UVC control.
	EEXIST
		Mapping already exists.

**Data types**:

.. code-block:: none

	* struct uvc_xu_control_mapping

	__u32	id		V4L2 control identifier
	__u8	name[32]	V4L2 control name
	__u8	entity[16]	UVC extension unit GUID
	__u8	selector	UVC control selector
	__u8	size		V4L2 control size (in bits)
	__u8	offset		V4L2 control offset (in bits)
	enum v4l2_ctrl_type
		v4l2_type	V4L2 control type
	enum uvc_control_data_type
		data_type	UVC control data type
	struct uvc_menu_info
		*menu_info	Array of menu entries (for menu controls only)
	__u32	menu_count	Number of menu entries (for menu controls only)

	* struct uvc_menu_info

	__u32	value		Menu entry value used by the device
	__u8	name[32]	Menu entry name

	* enum uvc_control_data_type

	UVC_CTRL_DATA_TYPE_RAW		Raw control (byte array)
	UVC_CTRL_DATA_TYPE_SIGNED	Signed integer
	UVC_CTRL_DATA_TYPE_UNSIGNED	Unsigned integer
	UVC_CTRL_DATA_TYPE_BOOLEAN	Boolean
	UVC_CTRL_DATA_TYPE_ENUM		Enumeration
	UVC_CTRL_DATA_TYPE_BITMASK	Bitmask

UVCIOC_CTRL_QUERY - Query a UVC XU control
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Argument: struct uvc_xu_control_query

**Description**:

	This ioctl queries a UVC XU control identified by its extension unit ID
	and control selector.

	There are a number of different queries available that closely
	correspond to the low-level control requests described in the UVC
	specification. These requests are:

	UVC_GET_CUR
		Obtain the current value of the control.
	UVC_GET_MIN
		Obtain the minimum value of the control.
	UVC_GET_MAX
		Obtain the maximum value of the control.
	UVC_GET_DEF
		Obtain the default value of the control.
	UVC_GET_RES
		Query the resolution of the control, i.e. the step size of the
		allowed control values.
	UVC_GET_LEN
		Query the size of the control in bytes.
	UVC_GET_INFO
		Query the control information bitmap, which indicates whether
		get/set requests are supported.
	UVC_SET_CUR
		Update the value of the control.

	Applications must set the 'size' field to the correct length for the
	control. Exceptions are the UVC_GET_LEN and UVC_GET_INFO queries, for
	which the size must be set to 2 and 1, respectively. The 'data' field
	must point to a valid writable buffer big enough to hold the indicated
	number of data bytes.

	Data is copied directly from the device without any driver-side
	processing. Applications are responsible for data buffer formatting,
	including little-endian/big-endian conversion. This is particularly
	important for the result of the UVC_GET_LEN requests, which is always
	returned as a little-endian 16-bit integer by the device.

**Return value**:

	On success 0 is returned. On error -1 is returned and errno is set
	appropriately.

	ENOENT
		The device does not support the given control or the specified
		extension unit could not be found.
	ENOBUFS
		The specified buffer size is incorrect (too big or too small).
	EINVAL
		An invalid request code was passed.
	EBADRQC
		The given request is not supported by the given control.
	EFAULT
		The data pointer references an inaccessible memory area.

**Data types**:

.. code-block:: none

	* struct uvc_xu_control_query

	__u8	unit		Extension unit ID
	__u8	selector	Control selector
	__u8	query		Request code to send to the device
	__u16	size		Control data size (in bytes)
	__u8	*data		Control value


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _ca_fclose:

=====================
Digital TV CA close()
=====================

Name
----

Digital TV CA close()

Synopsis
--------

.. c:function:: int close(int fd)

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

Description
-----------

This system call closes a previously opened CA device.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _ca_fopen:

====================
Digital TV CA open()
====================

Name
----

Digital TV CA open()

Synopsis
--------

.. c:function:: int open(const char *name, int flags)

Arguments
---------

``name``
  Name of specific Digital TV CA device.

``flags``
  A bit-wise OR of the following flags:

.. tabularcolumns:: |p{2.5cm}|p{15.0cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 16

    -  - ``O_RDONLY``
       - read-only access

    -  - ``O_RDWR``
       - read/write access

    -  - ``O_NONBLOCK``
       - open in non-blocking mode
         (blocking mode is the default)

Description
-----------

This system call opens a named ca device (e.g. ``/dev/dvb/adapter?/ca?``)
for subsequent use.

When an ``open()`` call has succeeded, the device will be ready for use. The
significance of blocking or non-blocking mode is described in the
documentation for functions where there is a difference. It does not
affect the semantics of the ``open()`` call itself. A device opened in
blocking mode can later be put into non-blocking mode (and vice versa)
using the ``F_SETFL`` command of the ``fcntl`` system call. This is a
standard system call, documented in the Linux manual page for fcntl.
Only one user can open the CA Device in ``O_RDWR`` mode. All other
attempts to open the device in this mode will fail, and an error code
will be returned.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_GET_CAP:

==========
CA_GET_CAP
==========

Name
----

CA_GET_CAP

Synopsis
--------

.. c:macro:: CA_GET_CAP

``int ioctl(fd, CA_GET_CAP, struct ca_caps *caps)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``caps``
  Pointer to struct :c:type:`ca_caps`.

Description
-----------

Queries the Kernel for information about the available CA and descrambler
slots, and their types.

Return Value
------------

On success 0 is returned and :c:type:`ca_caps` is filled.

On error, -1 is returned and the ``errno`` variable is set
appropriately.

The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_GET_DESCR_INFO:

=================
CA_GET_DESCR_INFO
=================

Name
----

CA_GET_DESCR_INFO

Synopsis
--------

.. c:macro:: CA_GET_DESCR_INFO

``int ioctl(fd, CA_GET_DESCR_INFO, struct ca_descr_info *desc)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``desc``
  Pointer to struct :c:type:`ca_descr_info`.

Description
-----------

Returns information about all descrambler slots.

Return Value
------------

On success 0 is returned, and :c:type:`ca_descr_info` is filled.

On error -1 is returned, and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_GET_MSG:

==========
CA_GET_MSG
==========

Name
----

CA_GET_MSG

Synopsis
--------

.. c:macro:: CA_GET_MSG

``int ioctl(fd, CA_GET_MSG, struct ca_msg *msg)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``msg``
  Pointer to struct :c:type:`ca_msg`.

Description
-----------

Receives a message via a CI CA module.

.. note::

   Please notice that, on most drivers, this is done by reading from
   the /dev/adapter?/ca? device node.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_GET_SLOT_INFO:

================
CA_GET_SLOT_INFO
================

Name
----

CA_GET_SLOT_INFO

Synopsis
--------

.. c:macro:: CA_GET_SLOT_INFO

``int ioctl(fd, CA_GET_SLOT_INFO, struct ca_slot_info *info)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``info``
  Pointer to struct :c:type:`ca_slot_info`.

Description
-----------

Returns information about a CA slot identified by
:c:type:`ca_slot_info`.slot_num.

Return Value
------------

On success 0 is returned, and :c:type:`ca_slot_info` is filled.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

.. tabularcolumns:: |p{2.5cm}|p{15.0cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 16

    -  -  ``ENODEV``
       -  the slot is not available.

The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_RESET:

========
CA_RESET
========

Name
----

CA_RESET

Synopsis
--------

.. c:macro:: CA_RESET

``int ioctl(fd, CA_RESET)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

Description
-----------

Puts the Conditional Access hardware on its initial state. It should
be called before start using the CA hardware.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_SEND_MSG:

===========
CA_SEND_MSG
===========

Name
----

CA_SEND_MSG

Synopsis
--------

.. c:macro:: CA_SEND_MSG

``int ioctl(fd, CA_SEND_MSG, struct ca_msg *msg)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``msg``
  Pointer to struct :c:type:`ca_msg`.

Description
-----------

Sends a message via a CI CA module.

.. note::

   Please notice that, on most drivers, this is done by writing
   to the /dev/adapter?/ca? device node.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.ca

.. _CA_SET_DESCR:

============
CA_SET_DESCR
============

Name
----

CA_SET_DESCR

Synopsis
--------

.. c:macro:: CA_SET_DESCR

``int ioctl(fd, CA_SET_DESCR, struct ca_descr *desc)``

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

``msg``
  Pointer to struct :c:type:`ca_descr`.

Description
-----------

CA_SET_DESCR is used for feeding descrambler CA slots with descrambling
keys (referred as control words).

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _dvb_ca:

####################
Digital TV CA Device
####################

The Digital TV CA device controls the conditional access hardware. It
can be accessed through ``/dev/dvb/adapter?/ca?``. Data types and ioctl
definitions can be accessed by including ``linux/dvb/ca.h`` in your
application.

.. note::

   There are three ioctls at this API that aren't documented:
   :ref:`CA_GET_MSG`, :ref:`CA_SEND_MSG` and :ref:`CA_SET_DESCR`.
   Documentation for them are welcome.

.. toctree::
    :maxdepth: 1

    ca_data_types
    ca_function_calls
    ca_high_level


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _ca_data_types:

*************
CA Data Types
*************

.. kernel-doc:: include/uapi/linux/dvb/ca.h


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _ca_function_calls:

*****************
CA Function Calls
*****************

.. toctree::
    :maxdepth: 1

    ca-fopen
    ca-fclose
    ca-reset
    ca-get-cap
    ca-get-slot-info
    ca-get-descr-info
    ca-get-msg
    ca-send-msg
    ca-set-descr


code:
.. SPDX-License-Identifier: GPL-2.0

The High level CI API
=====================

.. note::

   This documentation is outdated.

This document describes the high level CI API as in accordance to the
Linux DVB API.

With the High Level CI approach any new card with almost any random
architecture can be implemented with this style, the definitions
inside the switch statement can be easily adapted for any card, thereby
eliminating the need for any additional ioctls.

The disadvantage is that the driver/hardware has to manage the rest. For
the application programmer it would be as simple as sending/receiving an
array to/from the CI ioctls as defined in the Linux DVB API. No changes
have been made in the API to accommodate this feature.

Why the need for another CI interface?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is one of the most commonly asked question. Well a nice question.
Strictly speaking this is not a new interface.

The CI interface is defined in the DVB API in ca.h as:

.. code-block:: c

	typedef struct ca_slot_info {
		int num;               /* slot number */

		int type;              /* CA interface this slot supports */
	#define CA_CI            1     /* CI high level interface */
	#define CA_CI_LINK       2     /* CI link layer level interface */
	#define CA_CI_PHYS       4     /* CI physical layer level interface */
	#define CA_DESCR         8     /* built-in descrambler */
	#define CA_SC          128     /* simple smart card interface */

		unsigned int flags;
	#define CA_CI_MODULE_PRESENT 1 /* module (or card) inserted */
	#define CA_CI_MODULE_READY   2
	} ca_slot_info_t;

This CI interface follows the CI high level interface, which is not
implemented by most applications. Hence this area is revisited.

This CI interface is quite different in the case that it tries to
accommodate all other CI based devices, that fall into the other categories.

This means that this CI interface handles the EN50221 style tags in the
Application layer only and no session management is taken care of by the
application. The driver/hardware will take care of all that.

This interface is purely an EN50221 interface exchanging APDU's. This
means that no session management, link layer or a transport layer do
exist in this case in the application to driver communication. It is
as simple as that. The driver/hardware has to take care of that.

With this High Level CI interface, the interface can be defined with the
regular ioctls.

All these ioctls are also valid for the High level CI interface

#define CA_RESET          _IO('o', 128)
#define CA_GET_CAP        _IOR('o', 129, ca_caps_t)
#define CA_GET_SLOT_INFO  _IOR('o', 130, ca_slot_info_t)
#define CA_GET_DESCR_INFO _IOR('o', 131, ca_descr_info_t)
#define CA_GET_MSG        _IOR('o', 132, ca_msg_t)
#define CA_SEND_MSG       _IOW('o', 133, ca_msg_t)
#define CA_SET_DESCR      _IOW('o', 134, ca_descr_t)

On querying the device, the device yields information thus:

.. code-block:: none

	CA_GET_SLOT_INFO
	----------------------------
	Command = [info]
	APP: Number=[1]
	APP: Type=[1]
	APP: flags=[1]
	APP: CI High level interface
	APP: CA/CI Module Present

	CA_GET_CAP
	----------------------------
	Command = [caps]
	APP: Slots=[1]
	APP: Type=[1]
	APP: Descrambler keys=[16]
	APP: Type=[1]

	CA_SEND_MSG
	----------------------------
	Descriptors(Program Level)=[ 09 06 06 04 05 50 ff f1]
	Found CA descriptor @ program level

	(20) ES type=[2] ES pid=[201]  ES length =[0 (0x0)]
	(25) ES type=[4] ES pid=[301]  ES length =[0 (0x0)]
	ca_message length is 25 (0x19) bytes
	EN50221 CA MSG=[ 9f 80 32 19 03 01 2d d1 f0 08 01 09 06 06 04 05 50 ff f1 02 e0 c9 00 00 04 e1 2d 00 00]

Not all ioctl's are implemented in the driver from the API, the other
features of the hardware that cannot be implemented by the API are achieved
using the CA_GET_MSG and CA_SEND_MSG ioctls. An EN50221 style wrapper is
used to exchange the data to maintain compatibility with other hardware.

.. code-block:: c

	/* a message to/from a CI-CAM */
	typedef struct ca_msg {
		unsigned int index;
		unsigned int type;
		unsigned int length;
		unsigned char msg[256];
	} ca_msg_t;

The flow of data can be described thus,

.. code-block:: none

	App (User)
	-----
	parse
	  |
	  |
	  v
	en50221 APDU (package)
   --------------------------------------
   |	  |				| High Level CI driver
   |	  |				|
   |	  v				|
   |	en50221 APDU (unpackage)	|
   |	  |				|
   |	  |				|
   |	  v				|
   |	sanity checks			|
   |	  |				|
   |	  |				|
   |	  v				|
   |	do (H/W dep)			|
   --------------------------------------
	  |    Hardware
	  |
	  v

The High Level CI interface uses the EN50221 DVB standard, following a
standard ensures futureproofness.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later

.. _dvb_demux:

#######################
Digital TV Demux Device
#######################

The Digital TV demux device controls the MPEG-TS filters for the
digital TV. If the driver and hardware supports, those filters are
implemented at the hardware. Otherwise, the Kernel provides a software
emulation.

It can be accessed through ``/dev/adapter?/demux?``. Data types and
ioctl definitions can be accessed by including ``linux/dvb/dmx.h`` in
your application.

.. toctree::
    :maxdepth: 1

    dmx_types
    dmx_fcalls


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.dmx

.. _DMX_ADD_PID:

===========
DMX_ADD_PID
===========

Name
----

DMX_ADD_PID

Synopsis
--------

.. c:macro:: DMX_ADD_PID

``int ioctl(fd, DMX_ADD_PID, __u16 *pid)``

Arguments
---------

``fd``
    File descriptor returned by :c:func:`open()`.

``pid``
   PID number to be filtered.

Description
-----------

This ioctl call allows to add multiple PIDs to a transport stream filter
previously set up with :ref:`DMX_SET_PES_FILTER` and output equal to
:c:type:`DMX_OUT_TSDEMUX_TAP <dmx_output>`.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

Generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.dmx

.. _DMX_EXPBUF:

****************
ioctl DMX_EXPBUF
****************

Name
====

DMX_EXPBUF - Export a buffer as a DMABUF file descriptor.

.. warning:: this API is still experimental

Synopsis
========

.. c:macro:: DMX_EXPBUF

``int ioctl(int fd, DMX_EXPBUF, struct dmx_exportbuffer *argp)``

Arguments
=========

``fd``
    File descriptor returned by :c:func:`open()`.

``argp``
    Pointer to struct :c:type:`dmx_exportbuffer`.

Description
===========

This ioctl is an extension to the memory mapping I/O method.
It can be used to export a buffer as a DMABUF file at any time after
buffers have been allocated with the :ref:`DMX_REQBUFS` ioctl.

To export a buffer, applications fill struct :c:type:`dmx_exportbuffer`.
Applications must set the ``index`` field. Valid index numbers
range from zero to the number of buffers allocated with :ref:`DMX_REQBUFS`
(struct :c:type:`dmx_requestbuffers` ``count``) minus one.
Additional flags may be posted in the ``flags`` field. Refer to a manual
for open() for details. Currently only O_CLOEXEC, O_RDONLY, O_WRONLY,
and O_RDWR are supported.
All other fields must be set to zero. In the
case of multi-planar API, every plane is exported separately using
multiple :ref:`DMX_EXPBUF` calls.

After calling :ref:`DMX_EXPBUF` the ``fd`` field will be set by a
driver, on success. This is a DMABUF file descriptor. The application may
pass it to other DMABUF-aware devices. It is recommended to close a DMABUF
file when it is no longer used to allow the associated memory to be reclaimed.

Examples
========

.. code-block:: c

    int buffer_export(int v4lfd, enum dmx_buf_type bt, int index, int *dmafd)
    {
	struct dmx_exportbuffer expbuf;

	memset(&expbuf, 0, sizeof(expbuf));
	expbuf.type = bt;
	expbuf.index = index;
	if (ioctl(v4lfd, DMX_EXPBUF, &expbuf) == -1) {
	    perror("DMX_EXPBUF");
	    return -1;
	}

	*dmafd = expbuf.fd;

	return 0;
    }

Return Value
============

On success 0 is returned, on error -1 and the ``errno`` variable is set
appropriately. The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.

EINVAL
    A queue is not in MMAP mode or DMABUF exporting is not supported or
    ``flags`` or ``index`` fields are invalid.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.dmx

.. _dmx_fclose:

========================
Digital TV demux close()
========================

Name
----

Digital TV demux close()

Synopsis
--------

.. c:function:: int close(int fd)

Arguments
---------

``fd``
  File descriptor returned by a previous call to
  :c:func:`open()`.

Description
-----------

This system call deactivates and deallocates a filter that was
previously allocated via the :c:func:`open()` call.

Return Value
------------

On success 0 is returned.

On error, -1 is returned and the ``errno`` variable is set
appropriately.

The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.dmx

.. _dmx_fopen:

=======================
Digital TV demux open()
=======================

Name
----

Digital TV demux open()

Synopsis
--------

.. c:function:: int open(const char *deviceName, int flags)

Arguments
---------

``name``
  Name of specific Digital TV demux device.

``flags``
  A bit-wise OR of the following flags:

.. tabularcolumns:: |p{2.5cm}|p{15.0cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 16

    -
       - ``O_RDONLY``
       - read-only access

    -
       - ``O_RDWR``
       - read/write access

    -
       - ``O_NONBLOCK``
       - open in non-blocking mode
         (blocking mode is the default)

Description
-----------

This system call, used with a device name of ``/dev/dvb/adapter?/demux?``,
allocates a new filter and returns a handle which can be used for
subsequent control of that filter. This call has to be made for each
filter to be used, i.e. every returned file descriptor is a reference to
a single filter. ``/dev/dvb/adapter?/dvr?`` is a logical device to be used
for retrieving Transport Streams for digital video recording. When
reading from this device a transport stream containing the packets from
all PES filters set in the corresponding demux device
(``/dev/dvb/adapter?/demux?``) having the output set to ``DMX_OUT_TS_TAP``.
A recorded Transport Stream is replayed by writing to this device.

The significance of blocking or non-blocking mode is described in the
documentation for functions where there is a difference. It does not
affect the semantics of the ``open()`` call itself. A device opened
in blocking mode can later be put into non-blocking mode (and vice versa)
using the ``F_SETFL`` command of the fcntl system call.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

.. tabularcolumns:: |p{2.5cm}|p{15.0cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 16

    -  -  ``EMFILE``
       -  "Too many open files", i.e. no more filters available.

The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.


code:
.. SPDX-License-Identifier: GFDL-1.1-no-invariants-or-later
.. c:namespace:: DTV.dmx

.. _dmx_fread:

=======================
Digital TV demux read()
=======================

Name
----

Digital TV demux read()

Synopsis
--------

.. c:function:: size_t read(int fd, void *buf, size_t count)

Arguments
---------

``fd``
  File descriptor returned by a previous call to :c:func:`open()`.

 ``buf``
   Buffer to be filled

``count``
   Max number of bytes to read

Description
-----------

This system call returns filtered data, which might be section or Packetized
Elementary Stream (PES) data. The filtered data is transferred from
the driver's internal circular buffer to ``buf``. The maximum amount of data
to be transferred is implied by count.

.. note::

   if a section filter created with
   :c:type:`DMX_CHECK_CRC <dmx_sct_filter_params>` flag set,
   data that fails on CRC check will be silently ignored.

Return Value
------------

On success 0 is returned.

On error -1 is returned, and the ``errno`` variable is set
appropriately.

.. tabularcolumns:: |p{2.5cm}|p{15.0cm}|

.. flat-table::
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 16

    -  -  ``EWOULDBLOCK``
       -  No data to return and ``O_NONBLOCK`` was specified.

    -  -  ``EOVERFLOW``
       -  The filtered data was not read from the buffer in due time,
	  resulting in non-read data being lost. The buffer is flushed.

    -  -  ``ETIMEDOUT``
       -  The section was not loaded within the stated timeout period.
          See ioctl :ref:`DMX_SET_FILTER` for how to set a timeout.

    -  -  ``EFAULT``
       -  The driver failed to write to the callers buffer due to an
          invalid \*buf pointer.

The generic error codes are described at the
:ref:`Generic Error Codes <gen-errors>` chapter.