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

.. _media_ioc_g_topology:

**************************
ioctl MEDIA_IOC_G_TOPOLOGY
**************************

Name
====

MEDIA_IOC_G_TOPOLOGY - Enumerate the graph topology and graph element properties

Synopsis
========

.. c:macro:: MEDIA_IOC_G_TOPOLOGY

``int ioctl(int fd, MEDIA_IOC_G_TOPOLOGY, struct media_v2_topology *argp)``

Arguments
=========

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

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

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

The typical usage of this ioctl is to call it twice. On the first call,
the structure defined at struct
:c:type:`media_v2_topology` should be zeroed. At
return, if no errors happen, this ioctl will return the
``topology_version`` and the total number of entities, interfaces, pads
and links.

Before the second call, the userspace should allocate arrays to store
the graph elements that are desired, putting the pointers to them at the
ptr_entities, ptr_interfaces, ptr_links and/or ptr_pads, keeping the
other values untouched.

If the ``topology_version`` remains the same, the ioctl should fill the
desired arrays with the media graph elements.

.. tabularcolumns:: |p{1.6cm}|p{3.4cm}|p{12.3cm}|

.. c:type:: media_v2_topology

.. flat-table:: struct media_v2_topology
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u64
       -  ``topology_version``
       -  Version of the media graph topology. When the graph is created,
	  this field starts with zero. Every time a graph element is added
	  or removed, this field is incremented.

    *  -  __u32
       -  ``num_entities``
       -  Number of entities in the graph

    *  -  __u32
       -  ``reserved1``
       -  Applications and drivers shall set this to 0.

    *  -  __u64
       -  ``ptr_entities``
       -  A pointer to a memory area where the entities array will be
	  stored, converted to a 64-bits integer. It can be zero. if zero,
	  the ioctl won't store the entities. It will just update
	  ``num_entities``

    *  -  __u32
       -  ``num_interfaces``
       -  Number of interfaces in the graph

    *  -  __u32
       -  ``reserved2``
       -  Applications and drivers shall set this to 0.

    *  -  __u64
       -  ``ptr_interfaces``
       -  A pointer to a memory area where the interfaces array will be
	  stored, converted to a 64-bits integer. It can be zero. if zero,
	  the ioctl won't store the interfaces. It will just update
	  ``num_interfaces``

    *  -  __u32
       -  ``num_pads``
       -  Total number of pads in the graph

    *  -  __u32
       -  ``reserved3``
       -  Applications and drivers shall set this to 0.

    *  -  __u64
       -  ``ptr_pads``
       -  A pointer to a memory area where the pads array will be stored,
	  converted to a 64-bits integer. It can be zero. if zero, the ioctl
	  won't store the pads. It will just update ``num_pads``

    *  -  __u32
       -  ``num_links``
       -  Total number of data and interface links in the graph

    *  -  __u32
       -  ``reserved4``
       -  Applications and drivers shall set this to 0.

    *  -  __u64
       -  ``ptr_links``
       -  A pointer to a memory area where the links array will be stored,
	  converted to a 64-bits integer. It can be zero. if zero, the ioctl
	  won't store the links. It will just update ``num_links``

.. tabularcolumns:: |p{1.6cm}|p{3.2cm}|p{12.5cm}|

.. c:type:: media_v2_entity

.. flat-table:: struct media_v2_entity
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u32
       -  ``id``
       -  Unique ID for the entity. Do not expect that the ID will
	  always be the same for each instance of the device. In other words,
	  do not hardcode entity IDs in an application.

    *  -  char
       -  ``name``\ [64]
       -  Entity name as an UTF-8 NULL-terminated string. This name must be unique
          within the media topology.

    *  -  __u32
       -  ``function``
       -  Entity main function, see :ref:`media-entity-functions` for details.

    *  -  __u32
       -  ``flags``
       -  Entity flags, see :ref:`media-entity-flag` for details.
	  Only valid if ``MEDIA_V2_ENTITY_HAS_FLAGS(media_version)``
	  returns true. The ``media_version`` is defined in struct
	  :c:type:`media_device_info` and can be retrieved using
	  :ref:`MEDIA_IOC_DEVICE_INFO`.

    *  -  __u32
       -  ``reserved``\ [5]
       -  Reserved for future extensions. Drivers and applications must set
	  this array to zero.

.. tabularcolumns:: |p{1.6cm}|p{3.2cm}|p{12.5cm}|

.. c:type:: media_v2_interface

.. flat-table:: struct media_v2_interface
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u32
       -  ``id``
       -  Unique ID for the interface. Do not expect that the ID will
	  always be the same for each instance of the device. In other words,
	  do not hardcode interface IDs in an application.

    *  -  __u32
       -  ``intf_type``
       -  Interface type, see :ref:`media-intf-type` for details.

    *  -  __u32
       -  ``flags``
       -  Interface flags. Currently unused.

    *  -  __u32
       -  ``reserved``\ [9]
       -  Reserved for future extensions. Drivers and applications must set
	  this array to zero.

    *  -  struct media_v2_intf_devnode
       -  ``devnode``
       -  Used only for device node interfaces. See
	  :c:type:`media_v2_intf_devnode` for details.

.. tabularcolumns:: |p{1.6cm}|p{3.2cm}|p{12.5cm}|

.. c:type:: media_v2_intf_devnode

.. flat-table:: struct media_v2_intf_devnode
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u32
       -  ``major``
       -  Device node major number.

    *  -  __u32
       -  ``minor``
       -  Device node minor number.

.. tabularcolumns:: |p{1.6cm}|p{3.2cm}|p{12.5cm}|

.. c:type:: media_v2_pad

.. flat-table:: struct media_v2_pad
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u32
       -  ``id``
       -  Unique ID for the pad. Do not expect that the ID will
	  always be the same for each instance of the device. In other words,
	  do not hardcode pad IDs in an application.

    *  -  __u32
       -  ``entity_id``
       -  Unique ID for the entity where this pad belongs.

    *  -  __u32
       -  ``flags``
       -  Pad flags, see :ref:`media-pad-flag` for more details.

    *  -  __u32
       -  ``index``
       -  Pad index, starts at 0. Only valid if ``MEDIA_V2_PAD_HAS_INDEX(media_version)``
	  returns true. The ``media_version`` is defined in struct
	  :c:type:`media_device_info` and can be retrieved using
	  :ref:`MEDIA_IOC_DEVICE_INFO`.

    *  -  __u32
       -  ``reserved``\ [4]
       -  Reserved for future extensions. Drivers and applications must set
	  this array to zero.

.. tabularcolumns:: |p{1.6cm}|p{3.2cm}|p{12.5cm}|

.. c:type:: media_v2_link

.. flat-table:: struct media_v2_link
    :header-rows:  0
    :stub-columns: 0
    :widths: 1 2 8

    *  -  __u32
       -  ``id``
       -  Unique ID for the link. Do not expect that the ID will
	  always be the same for each instance of the device. In other words,
	  do not hardcode link IDs in an application.

    *  -  __u32
       -  ``source_id``
       -  On pad to pad links: unique ID for the source pad.

	  On interface to entity links: unique ID for the interface.

    *  -  __u32
       -  ``sink_id``
       -  On pad to pad links: unique ID for the sink pad.

	  On interface to entity links: unique ID for the entity.

    *  -  __u32
       -  ``flags``
       -  Link flags, see :ref:`media-link-flag` for more details.

    *  -  __u32
       -  ``reserved``\ [6]
       -  Reserved for future extensions. Drivers and applications must set
	  this array to zero.

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.

ENOSPC
    This is returned when either one or more of the num_entities,
    num_interfaces, num_links or num_pads are non-zero and are
    smaller than the actual number of elements inside the graph. This
    may happen if the ``topology_version`` changed when compared to the
    last time this ioctl was called. Userspace should usually free the
    area for the pointers, zero the struct elements and call this ioctl
    again.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _media_ioc_request_alloc:

*****************************
ioctl MEDIA_IOC_REQUEST_ALLOC
*****************************

Name
====

MEDIA_IOC_REQUEST_ALLOC - Allocate a request

Synopsis
========

.. c:macro:: MEDIA_IOC_REQUEST_ALLOC

``int ioctl(int fd, MEDIA_IOC_REQUEST_ALLOC, int *argp)``

Arguments
=========

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

``argp``
    Pointer to an integer.

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

If the media device supports :ref:`requests <media-request-api>`, then
this ioctl can be used to allocate a request. If it is not supported, then
``errno`` is set to ``ENOTTY``. A request is accessed through a file descriptor
that is returned in ``*argp``.

If the request was successfully allocated, then the request file descriptor
can be passed to the :ref:`VIDIOC_QBUF <VIDIOC_QBUF>`,
:ref:`VIDIOC_G_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>`,
:ref:`VIDIOC_S_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>` and
:ref:`VIDIOC_TRY_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>` ioctls.

In addition, the request can be queued by calling
:ref:`MEDIA_REQUEST_IOC_QUEUE` and re-initialized by calling
:ref:`MEDIA_REQUEST_IOC_REINIT`.

Finally, the file descriptor can be :ref:`polled <request-func-poll>` to wait
for the request to complete.

The request will remain allocated until all the file descriptors associated
with it are closed by :c:func:`close()` and the driver no
longer uses the request internally. See also
:ref:`here <media-request-life-time>` for more information.

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.

ENOTTY
    The driver has no support for requests.

repo_name: angery/linux


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

.. _media_ioc_setup_link:

**************************
ioctl MEDIA_IOC_SETUP_LINK
**************************

Name
====

MEDIA_IOC_SETUP_LINK - Modify the properties of a link

Synopsis
========

.. c:macro:: MEDIA_IOC_SETUP_LINK

``int ioctl(int fd, MEDIA_IOC_SETUP_LINK, struct media_link_desc *argp)``

Arguments
=========

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

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

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

To change link properties applications fill a struct
:c:type:`media_link_desc` with link identification
information (source and sink pad) and the new requested link flags. They
then call the MEDIA_IOC_SETUP_LINK ioctl with a pointer to that
structure.

The only configurable property is the ``ENABLED`` link flag to
enable/disable a link. Links marked with the ``IMMUTABLE`` link flag can
not be enabled or disabled.

Link configuration has no side effect on other links. If an enabled link
at the sink pad prevents the link from being enabled, the driver returns
with an ``EBUSY`` error code.

Only links marked with the ``DYNAMIC`` link flag can be enabled/disabled
while streaming media data. Attempting to enable or disable a streaming
non-dynamic link will return an ``EBUSY`` error code.

If the specified link can't be found the driver returns with an ``EINVAL``
error code.

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
    The struct :c:type:`media_link_desc` references a
    non-existing link, or the link is immutable and an attempt to modify
    its configuration was made.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _media_request_ioc_queue:

*****************************
ioctl MEDIA_REQUEST_IOC_QUEUE
*****************************

Name
====

MEDIA_REQUEST_IOC_QUEUE - Queue a request

Synopsis
========

.. c:macro:: MEDIA_REQUEST_IOC_QUEUE

``int ioctl(int request_fd, MEDIA_REQUEST_IOC_QUEUE)``

Arguments
=========

``request_fd``
    File descriptor returned by :ref:`MEDIA_IOC_REQUEST_ALLOC`.

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

If the media device supports :ref:`requests <media-request-api>`, then
this request ioctl can be used to queue a previously allocated request.

If the request was successfully queued, then the file descriptor can be
:ref:`polled <request-func-poll>` to wait for the request to complete.

If the request was already queued before, then ``EBUSY`` is returned.
Other errors can be returned if the contents of the request contained
invalid or inconsistent data, see the next section for a list of
common error codes. On error both the request and driver state are unchanged.

Once a request is queued, then the driver is required to gracefully handle
errors that occur when the request is applied to the hardware. The
exception is the ``EIO`` error which signals a fatal error that requires
the application to stop streaming to reset the hardware state.

It is not allowed to mix queuing requests with queuing buffers directly
(without a request). ``EBUSY`` will be returned if the first buffer was
queued directly and you next try to queue a request, or vice versa.

A request must contain at least one buffer, otherwise this ioctl will
return an ``ENOENT`` error.

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.

EBUSY
    The request was already queued or the application queued the first
    buffer directly, but later attempted to use a request. It is not permitted
    to mix the two APIs.
ENOENT
    The request did not contain any buffers. All requests are required
    to have at least one buffer. This can also be returned if some required
    configuration is missing in the request.
ENOMEM
    Out of memory when allocating internal data structures for this
    request.
EINVAL
    The request has invalid data.
EIO
    The hardware is in a bad state. To recover, the application needs to
    stop streaming to reset the hardware state and then try to restart
    streaming.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _media_request_ioc_reinit:

******************************
ioctl MEDIA_REQUEST_IOC_REINIT
******************************

Name
====

MEDIA_REQUEST_IOC_REINIT - Re-initialize a request

Synopsis
========

.. c:macro:: MEDIA_REQUEST_IOC_REINIT

``int ioctl(int request_fd, MEDIA_REQUEST_IOC_REINIT)``

Arguments
=========

``request_fd``
    File descriptor returned by :ref:`MEDIA_IOC_REQUEST_ALLOC`.

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

If the media device supports :ref:`requests <media-request-api>`, then
this request ioctl can be used to re-initialize a previously allocated
request.

Re-initializing a request will clear any existing data from the request.
This avoids having to :c:func:`close()` a completed
request and allocate a new request. Instead the completed request can just
be re-initialized and it is ready to be used again.

A request can only be re-initialized if it either has not been queued
yet, or if it was queued and completed. Otherwise it will set ``errno``
to ``EBUSY``. No other error codes can be returned.

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

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

EBUSY
    The request is queued but not yet completed.


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

.. _media-controller-types:

Types and flags used to represent the media graph elements
==========================================================

..  tabularcolumns:: |p{8.2cm}|p{9.3cm}|

.. _media-entity-functions:
.. _MEDIA-ENT-F-UNKNOWN:
.. _MEDIA-ENT-F-V4L2-SUBDEV-UNKNOWN:
.. _MEDIA-ENT-F-IO-V4L:
.. _MEDIA-ENT-F-IO-VBI:
.. _MEDIA-ENT-F-IO-SWRADIO:
.. _MEDIA-ENT-F-IO-DTV:
.. _MEDIA-ENT-F-DTV-DEMOD:
.. _MEDIA-ENT-F-TS-DEMUX:
.. _MEDIA-ENT-F-DTV-CA:
.. _MEDIA-ENT-F-DTV-NET-DECAP:
.. _MEDIA-ENT-F-CONN-RF:
.. _MEDIA-ENT-F-CONN-SVIDEO:
.. _MEDIA-ENT-F-CONN-COMPOSITE:
.. _MEDIA-ENT-F-CAM-SENSOR:
.. _MEDIA-ENT-F-FLASH:
.. _MEDIA-ENT-F-LENS:
.. _MEDIA-ENT-F-ATV-DECODER:
.. _MEDIA-ENT-F-TUNER:
.. _MEDIA-ENT-F-IF-VID-DECODER:
.. _MEDIA-ENT-F-IF-AUD-DECODER:
.. _MEDIA-ENT-F-AUDIO-CAPTURE:
.. _MEDIA-ENT-F-AUDIO-PLAYBACK:
.. _MEDIA-ENT-F-AUDIO-MIXER:
.. _MEDIA-ENT-F-PROC-VIDEO-COMPOSER:
.. _MEDIA-ENT-F-PROC-VIDEO-PIXEL-FORMATTER:
.. _MEDIA-ENT-F-PROC-VIDEO-PIXEL-ENC-CONV:
.. _MEDIA-ENT-F-PROC-VIDEO-LUT:
.. _MEDIA-ENT-F-PROC-VIDEO-SCALER:
.. _MEDIA-ENT-F-PROC-VIDEO-STATISTICS:
.. _MEDIA-ENT-F-PROC-VIDEO-ENCODER:
.. _MEDIA-ENT-F-PROC-VIDEO-DECODER:
.. _MEDIA-ENT-F-PROC-VIDEO-ISP:
.. _MEDIA-ENT-F-VID-MUX:
.. _MEDIA-ENT-F-VID-IF-BRIDGE:
.. _MEDIA-ENT-F-DV-DECODER:
.. _MEDIA-ENT-F-DV-ENCODER:

.. cssclass:: longtable

.. flat-table:: Media entity functions
    :header-rows:  0
    :stub-columns: 0

    *  -  ``MEDIA_ENT_F_UNKNOWN`` and
	  ``MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN``
       -  Unknown entity. That generally indicates that a driver didn't
	  initialize properly the entity, which is a Kernel bug

    *  -  ``MEDIA_ENT_F_IO_V4L``
       -  Data streaming input and/or output entity.

    *  -  ``MEDIA_ENT_F_IO_VBI``
       -  V4L VBI streaming input or output entity

    *  -  ``MEDIA_ENT_F_IO_SWRADIO``
       -  V4L Software Digital Radio (SDR) streaming input or output entity

    *  -  ``MEDIA_ENT_F_IO_DTV``
       -  DVB Digital TV streaming input or output entity

    *  -  ``MEDIA_ENT_F_DTV_DEMOD``
       -  Digital TV demodulator entity.

    *  -  ``MEDIA_ENT_F_TS_DEMUX``
       -  MPEG Transport stream demux entity. Could be implemented on
	  hardware or in Kernelspace by the Linux DVB subsystem.

    *  -  ``MEDIA_ENT_F_DTV_CA``
       -  Digital TV Conditional Access module (CAM) entity

    *  -  ``MEDIA_ENT_F_DTV_NET_DECAP``
       -  Digital TV network ULE/MLE desencapsulation entity. Could be
	  implemented on hardware or in Kernelspace

    *  -  ``MEDIA_ENT_F_CONN_RF``
       -  Connector for a Radio Frequency (RF) signal.

    *  -  ``MEDIA_ENT_F_CONN_SVIDEO``
       -  Connector for a S-Video signal.

    *  -  ``MEDIA_ENT_F_CONN_COMPOSITE``
       -  Connector for a RGB composite signal.

    *  -  ``MEDIA_ENT_F_CAM_SENSOR``
       -  Camera video sensor entity.

    *  -  ``MEDIA_ENT_F_FLASH``
       -  Flash controller entity.

    *  -  ``MEDIA_ENT_F_LENS``
       -  Lens controller entity.

    *  -  ``MEDIA_ENT_F_ATV_DECODER``
       -  Analog video decoder, the basic function of the video decoder is
	  to accept analogue video from a wide variety of sources such as
	  broadcast, DVD players, cameras and video cassette recorders, in
	  either NTSC, PAL, SECAM or HD format, separating the stream into
	  its component parts, luminance and chrominance, and output it in
	  some digital video standard, with appropriate timing signals.

    *  -  ``MEDIA_ENT_F_TUNER``
       -  Digital TV, analog TV, radio and/or software radio tuner, with
	  consists on a PLL tuning stage that converts radio frequency (RF)
	  signal into an Intermediate Frequency (IF). Modern tuners have
	  internally IF-PLL decoders for audio and video, but older models
	  have those stages implemented on separate entities.

    *  -  ``MEDIA_ENT_F_IF_VID_DECODER``
       -  IF-PLL video decoder. It receives the IF from a PLL and decodes
	  the analog TV video signal. This is commonly found on some very
	  old analog tuners, like Philips MK3 designs. They all contain a
	  tda9887 (or some software compatible similar chip, like tda9885).
	  Those devices use a different I2C address than the tuner PLL.

    *  -  ``MEDIA_ENT_F_IF_AUD_DECODER``
       -  IF-PLL sound decoder. It receives the IF from a PLL and decodes
	  the analog TV audio signal. This is commonly found on some very
	  old analog hardware, like Micronas msp3400, Philips tda9840,
	  tda985x, etc. Those devices use a different I2C address than the
	  tuner PLL and should be controlled together with the IF-PLL video
	  decoder.

    *  -  ``MEDIA_ENT_F_AUDIO_CAPTURE``
       -  Audio Capture Function Entity.

    *  -  ``MEDIA_ENT_F_AUDIO_PLAYBACK``
       -  Audio Playback Function Entity.

    *  -  ``MEDIA_ENT_F_AUDIO_MIXER``
       -  Audio Mixer Function Entity.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_COMPOSER``
       -  Video composer (blender). An entity capable of video
	  composing must have at least two sink pads and one source
	  pad, and composes input video frames onto output video
	  frames. Composition can be performed using alpha blending,
	  color keying, raster operations (ROP), stitching or any other
	  means.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_PIXEL_FORMATTER``
       -  Video pixel formatter. An entity capable of pixel formatting
	  must have at least one sink pad and one source pad. Read
	  pixel formatters read pixels from memory and perform a subset
	  of unpacking, cropping, color keying, alpha multiplication
	  and pixel encoding conversion. Write pixel formatters perform
	  a subset of dithering, pixel encoding conversion and packing
	  and write pixels to memory.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_PIXEL_ENC_CONV``
       -  Video pixel encoding converter. An entity capable of pixel
	  encoding conversion must have at least one sink pad and one
	  source pad, and convert the encoding of pixels received on
	  its sink pad(s) to a different encoding output on its source
	  pad(s). Pixel encoding conversion includes but isn't limited
	  to RGB to/from HSV, RGB to/from YUV and CFA (Bayer) to RGB
	  conversions.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_LUT``
       -  Video look-up table. An entity capable of video lookup table
	  processing must have one sink pad and one source pad. It uses
	  the values of the pixels received on its sink pad to look up
	  entries in internal tables and output them on its source pad.
	  The lookup processing can be performed on all components
	  separately or combine them for multi-dimensional table
	  lookups.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_SCALER``
       -  Video scaler. An entity capable of video scaling must have
	  at least one sink pad and one source pad, and scale the
	  video frame(s) received on its sink pad(s) to a different
	  resolution output on its source pad(s). The range of
	  supported scaling ratios is entity-specific and can differ
	  between the horizontal and vertical directions (in particular
	  scaling can be supported in one direction only). Binning and
	  sub-sampling (occasionally also referred to as skipping) are
	  considered as scaling.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_STATISTICS``
       -  Video statistics computation (histogram, 3A, etc.). An entity
	  capable of statistics computation must have one sink pad and
	  one source pad. It computes statistics over the frames
	  received on its sink pad and outputs the statistics data on
	  its source pad.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_ENCODER``
       -  Video (MPEG, HEVC, VPx, etc.) encoder. An entity capable of
          compressing video frames. Must have one sink pad and at least
	  one source pad.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_DECODER``
       -  Video (MPEG, HEVC, VPx, etc.) decoder. An entity capable of
          decompressing a compressed video stream into uncompressed video
	  frames. Must have one sink pad and at least one source pad.

    *  -  ``MEDIA_ENT_F_PROC_VIDEO_ISP``
       -  An Image Signal Processor (ISP) device. ISPs generally are one of a
	  kind devices that have their specific control interfaces using a
	  combination of custom V4L2 controls and IOCTLs, and parameters
	  supplied in a metadata buffer.

    *  -  ``MEDIA_ENT_F_VID_MUX``
       - Video multiplexer. An entity capable of multiplexing must have at
         least two sink pads and one source pad, and must pass the video
         frame(s) received from the active sink pad to the source pad.

    *  -  ``MEDIA_ENT_F_VID_IF_BRIDGE``
       - Video interface bridge. A video interface bridge entity must have at
         least one sink pad and at least one source pad. It receives video
         frames on its sink pad from an input video bus of one type (HDMI, eDP,
         MIPI CSI-2, etc.), and outputs them on its source pad to an output
         video bus of another type (eDP, MIPI CSI-2, parallel, etc.).

    *  -  ``MEDIA_ENT_F_DV_DECODER``
       -  Digital video decoder. The basic function of the video decoder is
	  to accept digital video from a wide variety of sources
	  and output it in some digital video standard, with appropriate
	  timing signals.

    *  -  ``MEDIA_ENT_F_DV_ENCODER``
       -  Digital video encoder. The basic function of the video encoder is
	  to accept digital video from some digital video standard with
	  appropriate timing signals (usually a parallel video bus with sync
	  signals) and output this to a digital video output connector such
	  as HDMI or DisplayPort.

..  tabularcolumns:: |p{5.5cm}|p{12.0cm}|

.. _media-entity-flag:
.. _MEDIA-ENT-FL-DEFAULT:
.. _MEDIA-ENT-FL-CONNECTOR:

.. flat-table:: Media entity flags
    :header-rows:  0
    :stub-columns: 0

    *  -  ``MEDIA_ENT_FL_DEFAULT``
       -  Default entity for its type. Used to discover the default audio,
	  VBI and video devices, the default camera sensor, etc.

    *  -  ``MEDIA_ENT_FL_CONNECTOR``
       -  The entity represents a connector.

..  tabularcolumns:: |p{6.5cm}|p{6.0cm}|p{4.8cm}|

.. _media-intf-type:
.. _MEDIA-INTF-T-DVB-FE:
.. _MEDIA-INTF-T-DVB-DEMUX:
.. _MEDIA-INTF-T-DVB-DVR:
.. _MEDIA-INTF-T-DVB-CA:
.. _MEDIA-INTF-T-DVB-NET:
.. _MEDIA-INTF-T-V4L-VIDEO:
.. _MEDIA-INTF-T-V4L-VBI:
.. _MEDIA-INTF-T-V4L-RADIO:
.. _MEDIA-INTF-T-V4L-SUBDEV:
.. _MEDIA-INTF-T-V4L-SWRADIO:
.. _MEDIA-INTF-T-V4L-TOUCH:
.. _MEDIA-INTF-T-ALSA-PCM-CAPTURE:
.. _MEDIA-INTF-T-ALSA-PCM-PLAYBACK:
.. _MEDIA-INTF-T-ALSA-CONTROL:
.. _MEDIA-INTF-T-ALSA-COMPRESS:
.. _MEDIA-INTF-T-ALSA-RAWMIDI:
.. _MEDIA-INTF-T-ALSA-HWDEP:
.. _MEDIA-INTF-T-ALSA-SEQUENCER:
.. _MEDIA-INTF-T-ALSA-TIMER:

.. flat-table:: Media interface types
    :header-rows:  0
    :stub-columns: 0

    *  -  ``MEDIA_INTF_T_DVB_FE``
       -  Device node interface for the Digital TV frontend
       -  typically, /dev/dvb/adapter?/frontend?

    *  -  ``MEDIA_INTF_T_DVB_DEMUX``
       -  Device node interface for the Digital TV demux
       -  typically, /dev/dvb/adapter?/demux?

    *  -  ``MEDIA_INTF_T_DVB_DVR``
       -  Device node interface for the Digital TV DVR
       -  typically, /dev/dvb/adapter?/dvr?

    *  -  ``MEDIA_INTF_T_DVB_CA``
       -  Device node interface for the Digital TV Conditional Access
       -  typically, /dev/dvb/adapter?/ca?

    *  -  ``MEDIA_INTF_T_DVB_NET``
       -  Device node interface for the Digital TV network control
       -  typically, /dev/dvb/adapter?/net?

    *  -  ``MEDIA_INTF_T_V4L_VIDEO``
       -  Device node interface for video (V4L)
       -  typically, /dev/video?

    *  -  ``MEDIA_INTF_T_V4L_VBI``
       -  Device node interface for VBI (V4L)
       -  typically, /dev/vbi?

    *  -  ``MEDIA_INTF_T_V4L_RADIO``
       -  Device node interface for radio (V4L)
       -  typically, /dev/radio?

    *  -  ``MEDIA_INTF_T_V4L_SUBDEV``
       -  Device node interface for a V4L subdevice
       -  typically, /dev/v4l-subdev?

    *  -  ``MEDIA_INTF_T_V4L_SWRADIO``
       -  Device node interface for Software Defined Radio (V4L)
       -  typically, /dev/swradio?

    *  -  ``MEDIA_INTF_T_V4L_TOUCH``
       -  Device node interface for Touch device (V4L)
       -  typically, /dev/v4l-touch?

    *  -  ``MEDIA_INTF_T_ALSA_PCM_CAPTURE``
       -  Device node interface for ALSA PCM Capture
       -  typically, /dev/snd/pcmC?D?c

    *  -  ``MEDIA_INTF_T_ALSA_PCM_PLAYBACK``
       -  Device node interface for ALSA PCM Playback
       -  typically, /dev/snd/pcmC?D?p

    *  -  ``MEDIA_INTF_T_ALSA_CONTROL``
       -  Device node interface for ALSA Control
       -  typically, /dev/snd/controlC?

    *  -  ``MEDIA_INTF_T_ALSA_COMPRESS``
       -  Device node interface for ALSA Compress
       -  typically, /dev/snd/compr?

    *  -  ``MEDIA_INTF_T_ALSA_RAWMIDI``
       -  Device node interface for ALSA Raw MIDI
       -  typically, /dev/snd/midi?

    *  -  ``MEDIA_INTF_T_ALSA_HWDEP``
       -  Device node interface for ALSA Hardware Dependent
       -  typically, /dev/snd/hwC?D?

    *  -  ``MEDIA_INTF_T_ALSA_SEQUENCER``
       -  Device node interface for ALSA Sequencer
       -  typically, /dev/snd/seq

    *  -  ``MEDIA_INTF_T_ALSA_TIMER``
       -  Device node interface for ALSA Timer
       -  typically, /dev/snd/timer

.. tabularcolumns:: |p{5.5cm}|p{12.0cm}|

.. _media-pad-flag:
.. _MEDIA-PAD-FL-SINK:
.. _MEDIA-PAD-FL-SOURCE:
.. _MEDIA-PAD-FL-MUST-CONNECT:

.. flat-table:: Media pad flags
    :header-rows:  0
    :stub-columns: 0

    *  -  ``MEDIA_PAD_FL_SINK``
       -  Input pad, relative to the entity. Input pads sink data and are
	  targets of links.

    *  -  ``MEDIA_PAD_FL_SOURCE``
       -  Output pad, relative to the entity. Output pads source data and
	  are origins of links.

    *  -  ``MEDIA_PAD_FL_MUST_CONNECT``
       -  If this flag is set and the pad is linked to any other pad, then
	  at least one of those links must be enabled for the entity to be
	  able to stream. There could be temporary reasons (e.g. device
	  configuration dependent) for the pad to need enabled links even
	  when this flag isn't set; the absence of the flag doesn't imply
	  there is none.

One and only one of ``MEDIA_PAD_FL_SINK`` and ``MEDIA_PAD_FL_SOURCE``
must be set for every pad.

.. tabularcolumns:: |p{5.5cm}|p{12.0cm}|

.. _media-link-flag:
.. _MEDIA-LNK-FL-ENABLED:
.. _MEDIA-LNK-FL-IMMUTABLE:
.. _MEDIA-LNK-FL-DYNAMIC:
.. _MEDIA-LNK-FL-LINK-TYPE:

.. flat-table:: Media link flags
    :header-rows:  0
    :stub-columns: 0

    *  -  ``MEDIA_LNK_FL_ENABLED``
       -  The link is enabled and can be used to transfer media data. When
	  two or more links target a sink pad, only one of them can be
	  enabled at a time.

    *  -  ``MEDIA_LNK_FL_IMMUTABLE``
       -  The link enabled state can't be modified at runtime. An immutable
	  link is always enabled.

    *  -  ``MEDIA_LNK_FL_DYNAMIC``
       -  The link enabled state can be modified during streaming. This flag
	  is set by drivers and is read-only for applications.

    *  -  ``MEDIA_LNK_FL_LINK_TYPE``
       -  This is a bitmask that defines the type of the link. The following
	  link types are currently supported:

	  .. _MEDIA-LNK-FL-DATA-LINK:

	  ``MEDIA_LNK_FL_DATA_LINK`` for links that represent a data connection
	  between two pads.

	  .. _MEDIA-LNK-FL-INTERFACE-LINK:

	  ``MEDIA_LNK_FL_INTERFACE_LINK`` for links that associate an entity to its
	  interface.

	  .. _MEDIA-LNK-FL-ANCILLARY-LINK:

	  ``MEDIA_LNK_FL_ANCILLARY_LINK`` for links that represent a physical
	  relationship between two entities. The link may or may not be
	  immutable, so applications must not assume either case.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _media-request-api:

Request API
===========

The Request API has been designed to allow V4L2 to deal with requirements of
modern devices (stateless codecs, complex camera pipelines, ...) and APIs
(Android Codec v2). One such requirement is the ability for devices belonging to
the same pipeline to reconfigure and collaborate closely on a per-frame basis.
Another is support of stateless codecs, which require controls to be applied
to specific frames (aka 'per-frame controls') in order to be used efficiently.

While the initial use-case was V4L2, it can be extended to other subsystems
as well, as long as they use the media controller.

Supporting these features without the Request API is not always possible and if
it is, it is terribly inefficient: user-space would have to flush all activity
on the media pipeline, reconfigure it for the next frame, queue the buffers to
be processed with that configuration, and wait until they are all available for
dequeuing before considering the next frame. This defeats the purpose of having
buffer queues since in practice only one buffer would be queued at a time.

The Request API allows a specific configuration of the pipeline (media
controller topology + configuration for each media entity) to be associated with
specific buffers. This allows user-space to schedule several tasks ("requests")
with different configurations in advance, knowing that the configuration will be
applied when needed to get the expected result. Configuration values at the time
of request completion are also available for reading.

General Usage
-------------

The Request API extends the Media Controller API and cooperates with
subsystem-specific APIs to support request usage. At the Media Controller
level, requests are allocated from the supporting Media Controller device
node. Their life cycle is then managed through the request file descriptors in
an opaque way. Configuration data, buffer handles and processing results
stored in requests are accessed through subsystem-specific APIs extended for
request support, such as V4L2 APIs that take an explicit ``request_fd``
parameter.

Request Allocation
------------------

User-space allocates requests using :ref:`MEDIA_IOC_REQUEST_ALLOC`
for the media device node. This returns a file descriptor representing the
request. Typically, several such requests will be allocated.

Request Preparation
-------------------

Standard V4L2 ioctls can then receive a request file descriptor to express the
fact that the ioctl is part of said request, and is not to be applied
immediately. See :ref:`MEDIA_IOC_REQUEST_ALLOC` for a list of ioctls that
support this. Configurations set with a ``request_fd`` parameter are stored
instead of being immediately applied, and buffers queued to a request do not
enter the regular buffer queue until the request itself is queued.

Request Submission
------------------

Once the configuration and buffers of the request are specified, it can be
queued by calling :ref:`MEDIA_REQUEST_IOC_QUEUE` on the request file descriptor.
A request must contain at least one buffer, otherwise ``ENOENT`` is returned.
A queued request cannot be modified anymore.

.. caution::
   For :ref:`memory-to-memory devices <mem2mem>` you can use requests only for
   output buffers, not for capture buffers. Attempting to add a capture buffer
   to a request will result in an ``EBADR`` error.

If the request contains configurations for multiple entities, individual drivers
may synchronize so the requested pipeline's topology is applied before the
buffers are processed. Media controller drivers do a best effort implementation
since perfect atomicity may not be possible due to hardware limitations.

.. caution::

   It is not allowed to mix queuing requests with directly queuing buffers:
   whichever method is used first locks this in place until
   :ref:`VIDIOC_STREAMOFF <VIDIOC_STREAMON>` is called or the device is
   :ref:`closed <func-close>`. Attempts to directly queue a buffer when earlier
   a buffer was queued via a request or vice versa will result in an ``EBUSY``
   error.

Controls can still be set without a request and are applied immediately,
regardless of whether a request is in use or not.

.. caution::

   Setting the same control through a request and also directly can lead to
   undefined behavior!

User-space can :c:func:`poll()` a request file descriptor in
order to wait until the request completes. A request is considered complete
once all its associated buffers are available for dequeuing and all the
associated controls have been updated with the values at the time of completion.
Note that user-space does not need to wait for the request to complete to
dequeue its buffers: buffers that are available halfway through a request can
be dequeued independently of the request's state.

A completed request contains the state of the device after the request was
executed. User-space can query that state by calling
:ref:`ioctl VIDIOC_G_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>` with the request file
descriptor. Calling :ref:`ioctl VIDIOC_G_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>` for a
request that has been queued but not yet completed will return ``EBUSY``
since the control values might be changed at any time by the driver while the
request is in flight.

.. _media-request-life-time:

Recycling and Destruction
-------------------------

Finally, a completed request can either be discarded or be reused. Calling
:c:func:`close()` on a request file descriptor will make
that file descriptor unusable and the request will be freed once it is no
longer in use by the kernel. That is, if the request is queued and then the
file descriptor is closed, then it won't be freed until the driver completed
the request.

The :ref:`MEDIA_REQUEST_IOC_REINIT` will clear a request's state and make it
available again. No state is retained by this operation: the request is as
if it had just been allocated.

Example for a Codec Device
--------------------------

For use-cases such as :ref:`codecs <mem2mem>`, the request API can be used
to associate specific controls to
be applied by the driver for the OUTPUT buffer, allowing user-space
to queue many such buffers in advance. It can also take advantage of requests'
ability to capture the state of controls when the request completes to read back
information that may be subject to change.

Put into code, after obtaining a request, user-space can assign controls and one
OUTPUT buffer to it:

.. code-block:: c

	struct v4l2_buffer buf;
	struct v4l2_ext_controls ctrls;
	int req_fd;
	...
	if (ioctl(media_fd, MEDIA_IOC_REQUEST_ALLOC, &req_fd))
		return errno;
	...
	ctrls.which = V4L2_CTRL_WHICH_REQUEST_VAL;
	ctrls.request_fd = req_fd;
	if (ioctl(codec_fd, VIDIOC_S_EXT_CTRLS, &ctrls))
		return errno;
	...
	buf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
	buf.flags |= V4L2_BUF_FLAG_REQUEST_FD;
	buf.request_fd = req_fd;
	if (ioctl(codec_fd, VIDIOC_QBUF, &buf))
		return errno;

Note that it is not allowed to use the Request API for CAPTURE buffers
since there are no per-frame settings to report there.

Once the request is fully prepared, it can be queued to the driver:

.. code-block:: c

	if (ioctl(req_fd, MEDIA_REQUEST_IOC_QUEUE))
		return errno;

User-space can then either wait for the request to complete by calling poll() on
its file descriptor, or start dequeuing CAPTURE buffers. Most likely, it will
want to get CAPTURE buffers as soon as possible and this can be done using a
regular :ref:`VIDIOC_DQBUF <VIDIOC_QBUF>`:

.. code-block:: c

	struct v4l2_buffer buf;

	memset(&buf, 0, sizeof(buf));
	buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	if (ioctl(codec_fd, VIDIOC_DQBUF, &buf))
		return errno;

Note that this example assumes for simplicity that for every OUTPUT buffer
there will be one CAPTURE buffer, but this does not have to be the case.

We can then, after ensuring that the request is completed via polling the
request file descriptor, query control values at the time of its completion via
a call to :ref:`VIDIOC_G_EXT_CTRLS <VIDIOC_G_EXT_CTRLS>`.
This is particularly useful for volatile controls for which we want to
query values as soon as the capture buffer is produced.

.. code-block:: c

	struct pollfd pfd = { .events = POLLPRI, .fd = req_fd };
	poll(&pfd, 1, -1);
	...
	ctrls.which = V4L2_CTRL_WHICH_REQUEST_VAL;
	ctrls.request_fd = req_fd;
	if (ioctl(codec_fd, VIDIOC_G_EXT_CTRLS, &ctrls))
		return errno;

Once we don't need the request anymore, we can either recycle it for reuse with
:ref:`MEDIA_REQUEST_IOC_REINIT`...

.. code-block:: c

	if (ioctl(req_fd, MEDIA_REQUEST_IOC_REINIT))
		return errno;

... or close its file descriptor to completely dispose of it.

.. code-block:: c

	close(req_fd);

Example for a Simple Capture Device
-----------------------------------

With a simple capture device, requests can be used to specify controls to apply
for a given CAPTURE buffer.

.. code-block:: c

	struct v4l2_buffer buf;
	struct v4l2_ext_controls ctrls;
	int req_fd;
	...
	if (ioctl(media_fd, MEDIA_IOC_REQUEST_ALLOC, &req_fd))
		return errno;
	...
	ctrls.which = V4L2_CTRL_WHICH_REQUEST_VAL;
	ctrls.request_fd = req_fd;
	if (ioctl(camera_fd, VIDIOC_S_EXT_CTRLS, &ctrls))
		return errno;
	...
	buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	buf.flags |= V4L2_BUF_FLAG_REQUEST_FD;
	buf.request_fd = req_fd;
	if (ioctl(camera_fd, VIDIOC_QBUF, &buf))
		return errno;

Once the request is fully prepared, it can be queued to the driver:

.. code-block:: c

	if (ioctl(req_fd, MEDIA_REQUEST_IOC_QUEUE))
		return errno;

User-space can then dequeue buffers, wait for the request completion, query
controls and recycle the request as in the M2M example above.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC.request

.. _request-func-close:

***************
request close()
***************

Name
====

request-close - Close a request file descriptor

Synopsis
========

.. code-block:: c

    #include <unistd.h>

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

Arguments
=========

``fd``
    File descriptor returned by :ref:`MEDIA_IOC_REQUEST_ALLOC`.

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

Closes the request file descriptor. Resources associated with the request
are freed once all file descriptors associated with the request are closed
and the driver has completed the request.
See :ref:`here <media-request-life-time>` for more information.

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

:c:func:`close()` returns 0 on success. On error, -1 is
returned, and ``errno`` is set appropriately. Possible error codes are:

EBADF
    ``fd`` is not a valid open file descriptor.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _request-func-ioctl:

***************
request ioctl()
***************

Name
====

request-ioctl - Control a request file descriptor

Synopsis
========

.. code-block:: c

    #include <sys/ioctl.h>

``int ioctl(int fd, int cmd, void *argp)``

Arguments
=========

``fd``
    File descriptor returned by :ref:`MEDIA_IOC_REQUEST_ALLOC`.

``cmd``
    The request ioctl command code as defined in the media.h header file, for
    example :ref:`MEDIA_REQUEST_IOC_QUEUE`.

``argp``
    Pointer to a request-specific structure.

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

The :ref:`ioctl() <request-func-ioctl>` function manipulates request
parameters. The argument ``fd`` must be an open file descriptor.

The ioctl ``cmd`` code specifies the request function to be called. It
has encoded in it whether the argument is an input, output or read/write
parameter, and the size of the argument ``argp`` in bytes.

Macros and structures definitions specifying request ioctl commands and
their parameters are located in the media.h header file. All request ioctl
commands, their respective function and parameters are specified in
:ref:`media-user-func`.

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.

Command-specific error codes are listed in the individual command
descriptions.

When an ioctl that takes an output or read/write parameter fails, the
parameter remains unmodified.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: MC

.. _request-func-poll:

**************
request poll()
**************

Name
====

request-poll - Wait for some event on a file descriptor

Synopsis
========

.. code-block:: c

    #include <sys/poll.h>

.. c:function:: int poll( struct pollfd *ufds, unsigned int nfds, int timeout )

Arguments
=========

``ufds``
   List of file descriptor events to be watched

``nfds``
   Number of file descriptor events at the \*ufds array

``timeout``
   Timeout to wait for events

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

With the :c:func:`poll()` function applications can wait
for a request to complete.

On success :c:func:`poll()` returns the number of file
descriptors that have been selected (that is, file descriptors for which the
``revents`` field of the respective struct :c:type:`pollfd`
is non-zero). Request file descriptor set the ``POLLPRI`` flag in ``revents``
when the request was completed.  When the function times out it returns
a value of zero, on failure it returns -1 and the ``errno`` variable is
set appropriately.

Attempting to poll for a request that is not yet queued will
set the ``POLLERR`` flag in ``revents``.

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

On success, :c:func:`poll()` returns the number of
structures which have non-zero ``revents`` fields, or zero if the call
timed out. On error -1 is returned, and the ``errno`` variable is set
appropriately:

``EBADF``
    One or more of the ``ufds`` members specify an invalid file
    descriptor.

``EFAULT``
    ``ufds`` references an inaccessible memory area.

``EINTR``
    The call was interrupted by a signal.

``EINVAL``
    The ``nfds`` value exceeds the ``RLIMIT_NOFILE`` value. Use
    ``getrlimit()`` to obtain this value.


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

# Ignore header name
ignore define _DVBNET_H_

# Ignore old ioctls/structs
ignore ioctl __NET_ADD_IF_OLD
ignore ioctl __NET_GET_IF_OLD
ignore struct __dvb_net_if_old

# Macros used at struct dvb_net_if
replace define DVB_NET_FEEDTYPE_MPE :c:type:`dvb_net_if`
replace define DVB_NET_FEEDTYPE_ULE :c:type:`dvb_net_if`


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

file: uapi/v4l/keytable.c
=========================

.. code-block:: c

    /* keytable.c - This program allows checking/replacing keys at IR

       Copyright (C) 2006-2009 Mauro Carvalho Chehab <mchehab@kernel.org>

       This program 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.
     */

    #include <ctype.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <linux/input.h>
    #include <sys/ioctl.h>

    #include "parse.h"

    void prtcode (int *codes)
    {
	    struct parse_key *p;

	    for (p=keynames;p->name!=NULL;p++) {
		    if (p->value == (unsigned)codes[1]) {
			    printf("scancode 0x%04x = %s (0x%02x)\\n", codes[0], p->name, codes[1]);
			    return;
		    }
	    }

	    if (isprint (codes[1]))
		    printf("scancode %d = '%c' (0x%02x)\\n", codes[0], codes[1], codes[1]);
	    else
		    printf("scancode %d = 0x%02x\\n", codes[0], codes[1]);
    }

    int parse_code(char *string)
    {
	    struct parse_key *p;

	    for (p=keynames;p->name!=NULL;p++) {
		    if (!strcasecmp(p->name, string)) {
			    return p->value;
		    }
	    }
	    return -1;
    }

    int main (int argc, char *argv[])
    {
	    int fd;
	    unsigned int i, j;
	    int codes[2];

	    if (argc<2 || argc>4) {
		    printf ("usage: %s <device> to get table; or\\n"
			    "       %s <device> <scancode> <keycode>\\n"
			    "       %s <device> <keycode_file>n",*argv,*argv,*argv);
		    return -1;
	    }

	    if ((fd = open(argv[1], O_RDONLY)) < 0) {
		    perror("Couldn't open input device");
		    return(-1);
	    }

	    if (argc==4) {
		    int value;

		    value=parse_code(argv[3]);

		    if (value==-1) {
			    value = strtol(argv[3], NULL, 0);
			    if (errno)
				    perror("value");
		    }

		    codes [0] = (unsigned) strtol(argv[2], NULL, 0);
		    codes [1] = (unsigned) value;

		    if(ioctl(fd, EVIOCSKEYCODE, codes))
			    perror ("EVIOCSKEYCODE");

		    if(ioctl(fd, EVIOCGKEYCODE, codes)==0)
			    prtcode(codes);
		    return 0;
	    }

	    if (argc==3) {
		    FILE *fin;
		    int value;
		    char *scancode, *keycode, s[2048];

		    fin=fopen(argv[2],"r");
		    if (fin==NULL) {
			    perror ("opening keycode file");
			    return -1;
		    }

		    /* Clears old table */
		    for (j = 0; j < 256; j++) {
			    for (i = 0; i < 256; i++) {
				    codes[0] = (j << 8) | i;
				    codes[1] = KEY_RESERVED;
				    ioctl(fd, EVIOCSKEYCODE, codes);
			    }
		    }

		    while (fgets(s,sizeof(s),fin)) {
			    scancode=strtok(s,"\\n\\t =:");
			    if (!scancode) {
				    perror ("parsing input file scancode");
				    return -1;
			    }
			    if (!strcasecmp(scancode, "scancode")) {
				    scancode = strtok(NULL,"\\n\\t =:");
				    if (!scancode) {
					    perror ("parsing input file scancode");
					    return -1;
				    }
			    }

			    keycode=strtok(NULL,"\\n\\t =:(");
			    if (!keycode) {
				    perror ("parsing input file keycode");
				    return -1;
			    }

			    // printf ("parsing %s=%s:", scancode, keycode);
			    value=parse_code(keycode);
			    // printf ("\\tvalue=%d\\n",value);

			    if (value==-1) {
				    value = strtol(keycode, NULL, 0);
				    if (errno)
					    perror("value");
			    }

			    codes [0] = (unsigned) strtol(scancode, NULL, 0);
			    codes [1] = (unsigned) value;

			    // printf("\\t%04x=%04x\\n",codes[0], codes[1]);
			    if(ioctl(fd, EVIOCSKEYCODE, codes)) {
				    fprintf(stderr, "Setting scancode 0x%04x with 0x%04x via ",codes[0], codes[1]);
				    perror ("EVIOCSKEYCODE");
			    }

			    if(ioctl(fd, EVIOCGKEYCODE, codes)==0)
				    prtcode(codes);
		    }
		    return 0;
	    }

	    /* Get scancode table */
	    for (j = 0; j < 256; j++) {
		    for (i = 0; i < 256; i++) {
			    codes[0] = (j << 8) | i;
			    if (!ioctl(fd, EVIOCGKEYCODE, codes) && codes[1] != KEY_RESERVED)
				    prtcode(codes);
		    }
	    }
	    return 0;
    }


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

.. _lirc_dev_intro:

************
Introduction
************

LIRC stands for Linux Infrared Remote Control. The LIRC device interface is
a bi-directional interface for transporting raw IR and decoded scancodes
data between userspace and kernelspace. Fundamentally, it is just a chardev
(/dev/lircX, for X = 0, 1, 2, ...), with a number of standard struct
file_operations defined on it. With respect to transporting raw IR and
decoded scancodes to and fro, the essential fops are read, write and ioctl.

It is also possible to attach a BPF program to a LIRC device for decoding
raw IR into scancodes.

Example dmesg output upon a driver registering w/LIRC:

.. code-block:: none

    $ dmesg |grep lirc_dev
    rc rc0: lirc_dev: driver mceusb registered at minor = 0, raw IR receiver, raw IR transmitter

What you should see for a chardev:

.. code-block:: none

    $ ls -l /dev/lirc*
    crw-rw---- 1 root root 248, 0 Jul 2 22:20 /dev/lirc0

Note that the package `v4l-utils <https://git.linuxtv.org/v4l-utils.git/>`_
contains tools for working with LIRC devices:

 - ir-ctl: can receive raw IR and transmit IR, as well as query LIRC
   device features.

 - ir-keytable: can load keymaps; allows you to set IR kernel protocols; load
   BPF IR decoders and test IR decoding. Some BPF IR decoders are also
   provided.

.. _lirc_modes:

**********
LIRC modes
**********

LIRC supports some modes of receiving and sending IR codes, as shown
on the following table.

.. _lirc-mode-scancode:
.. _lirc-scancode-flag-toggle:
.. _lirc-scancode-flag-repeat:

``LIRC_MODE_SCANCODE``

    This mode is for both sending and receiving IR.

    For transmitting (aka sending), create a struct lirc_scancode with
    the desired scancode set in the ``scancode`` member, :c:type:`rc_proto`
    set to the :ref:`IR protocol <Remote_controllers_Protocols>`, and all other
    members set to 0. Write this struct to the lirc device.

    For receiving, you read struct lirc_scancode from the LIRC device.
    The ``scancode`` field is set to the received scancode and the
    :ref:`IR protocol <Remote_controllers_Protocols>` is set in
    :c:type:`rc_proto`. If the scancode maps to a valid key code, this is set
    in the ``keycode`` field, else it is set to ``KEY_RESERVED``.

    The ``flags`` can have ``LIRC_SCANCODE_FLAG_TOGGLE`` set if the toggle
    bit is set in protocols that support it (e.g. rc-5 and rc-6), or
    ``LIRC_SCANCODE_FLAG_REPEAT`` for when a repeat is received for protocols
    that support it (e.g. nec).

    In the Sanyo and NEC protocol, if you hold a button on remote, rather than
    repeating the entire scancode, the remote sends a shorter message with
    no scancode, which just means button is held, a "repeat". When this is
    received, the ``LIRC_SCANCODE_FLAG_REPEAT`` is set and the scancode and
    keycode is repeated.

    With nec, there is no way to distinguish "button hold" from "repeatedly
    pressing the same button". The rc-5 and rc-6 protocols have a toggle bit.
    When a button is released and pressed again, the toggle bit is inverted.
    If the toggle bit is set, the ``LIRC_SCANCODE_FLAG_TOGGLE`` is set.

    The ``timestamp`` field is filled with the time nanoseconds
    (in ``CLOCK_MONOTONIC``) when the scancode was decoded.

.. _lirc-mode-mode2:

``LIRC_MODE_MODE2``

    The driver returns a sequence of pulse and space codes to userspace,
    as a series of u32 values.

    This mode is used only for IR receive.

    The upper 8 bits determine the packet type, and the lower 24 bits
    the payload. Use ``LIRC_VALUE()`` macro to get the payload, and
    the macro ``LIRC_MODE2()`` will give you the type, which
    is one of:

    ``LIRC_MODE2_PULSE``

        Signifies the presence of IR in microseconds, also known as *flash*.

    ``LIRC_MODE2_SPACE``

        Signifies absence of IR in microseconds, also known as *gap*.

    ``LIRC_MODE2_FREQUENCY``

        If measurement of the carrier frequency was enabled with
        :ref:`lirc_set_measure_carrier_mode` then this packet gives you
        the carrier frequency in Hertz.

    ``LIRC_MODE2_TIMEOUT``

        When the timeout set with :ref:`lirc_set_rec_timeout` expires due
        to no IR being detected, this packet will be sent, with the number
        of microseconds with no IR.

    ``LIRC_MODE2_OVERFLOW``

        Signifies that the IR receiver encounter an overflow, and some IR
        is missing. The IR data after this should be correct again. The
        actual value is not important, but this is set to 0xffffff by the
        kernel for compatibility with lircd.

.. _lirc-mode-pulse:

``LIRC_MODE_PULSE``

    In pulse mode, a sequence of pulse/space integer values are written to the
    lirc device using :ref:`lirc-write`.

    The values are alternating pulse and space lengths, in microseconds. The
    first and last entry must be a pulse, so there must be an odd number
    of entries.

    This mode is used only for IR send.

*************************************
Data types used by LIRC_MODE_SCANCODE
*************************************

.. kernel-doc:: include/uapi/linux/lirc.h
    :identifiers: lirc_scancode rc_proto

********************
BPF based IR decoder
********************

The kernel has support for decoding the most common
:ref:`IR protocols <Remote_controllers_Protocols>`, but there
are many protocols which are not supported. To support these, it is possible
to load an BPF program which does the decoding. This can only be done on
LIRC devices which support reading raw IR.

First, using the `bpf(2)`_ syscall with the ``BPF_LOAD_PROG`` argument,
program must be loaded of type ``BPF_PROG_TYPE_LIRC_MODE2``. Once attached
to the LIRC device, this program will be called for each pulse, space or
timeout event on the LIRC device. The context for the BPF program is a
pointer to a unsigned int, which is a :ref:`LIRC_MODE_MODE2 <lirc-mode-mode2>`
value. When the program has decoded the scancode, it can be submitted using
the BPF functions ``bpf_rc_keydown()`` or ``bpf_rc_repeat()``. Mouse or pointer
movements can be reported using ``bpf_rc_pointer_rel()``.

Once you have the file descriptor for the ``BPF_PROG_TYPE_LIRC_MODE2`` BPF
program, it can be attached to the LIRC device using the `bpf(2)`_ syscall.
The target must be the file descriptor for the LIRC device, and the
attach type must be ``BPF_LIRC_MODE2``. No more than 64 BPF programs can be
attached to a single LIRC device at a time.

.. _bpf(2): http://man7.org/linux/man-pages/man2/bpf.2.html


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

.. _lirc_dev:

LIRC Device Interface
=====================

.. toctree::
    :maxdepth: 1

    lirc-dev-intro
    lirc-func
    lirc-header


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

.. _lirc_func:

LIRC Function Reference
=======================

.. toctree::
    :maxdepth: 1

    lirc-read
    lirc-write
    lirc-get-features
    lirc-get-send-mode
    lirc-get-rec-mode
    lirc-get-rec-resolution
    lirc-set-send-duty-cycle
    lirc-get-timeout
    lirc-set-rec-timeout
    lirc-set-rec-carrier
    lirc-set-rec-carrier-range
    lirc-set-send-carrier
    lirc-set-transmitter-mask
    lirc-set-measure-carrier-mode
    lirc-set-wideband-receiver


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_get_features:

***********************
ioctl LIRC_GET_FEATURES
***********************

Name
====

LIRC_GET_FEATURES - Get the underlying hardware device's features

Synopsis
========

.. c:macro:: LIRC_GET_FEATURES

``int ioctl(int fd, LIRC_GET_FEATURES, __u32 *features)``

Arguments
=========

``fd``
    File descriptor returned by open().

``features``
    Bitmask with the LIRC features.

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

Get the underlying hardware device's features. If a driver does not
announce support of certain features, calling of the corresponding ioctls
is undefined.

LIRC features
=============

.. _LIRC-CAN-REC-RAW:

``LIRC_CAN_REC_RAW``

    Unused. Kept just to avoid breaking uAPI.

.. _LIRC-CAN-REC-PULSE:

``LIRC_CAN_REC_PULSE``

    Unused. Kept just to avoid breaking uAPI.
    :ref:`LIRC_MODE_PULSE <lirc-mode-pulse>` can only be used for transmitting.

.. _LIRC-CAN-REC-MODE2:

``LIRC_CAN_REC_MODE2``

    This is raw IR driver for receiving. This means that
    :ref:`LIRC_MODE_MODE2 <lirc-mode-MODE2>` is used. This also implies
    that :ref:`LIRC_MODE_SCANCODE <lirc-mode-SCANCODE>` is also supported,
    as long as the kernel is recent enough. Use the
    :ref:`lirc_set_rec_mode` to switch modes.

.. _LIRC-CAN-REC-LIRCCODE:

``LIRC_CAN_REC_LIRCCODE``

    Unused. Kept just to avoid breaking uAPI.

.. _LIRC-CAN-REC-SCANCODE:

``LIRC_CAN_REC_SCANCODE``

    This is a scancode driver for receiving. This means that
    :ref:`LIRC_MODE_SCANCODE <lirc-mode-SCANCODE>` is used.

.. _LIRC-CAN-SET-SEND-CARRIER:

``LIRC_CAN_SET_SEND_CARRIER``

    The driver supports changing the modulation frequency via
    :ref:`ioctl LIRC_SET_SEND_CARRIER <LIRC_SET_SEND_CARRIER>`.

.. _LIRC-CAN-SET-SEND-DUTY-CYCLE:

``LIRC_CAN_SET_SEND_DUTY_CYCLE``

    The driver supports changing the duty cycle using
    :ref:`ioctl LIRC_SET_SEND_DUTY_CYCLE <LIRC_SET_SEND_DUTY_CYCLE>`.

.. _LIRC-CAN-SET-TRANSMITTER-MASK:

``LIRC_CAN_SET_TRANSMITTER_MASK``

    The driver supports changing the active transmitter(s) using
    :ref:`ioctl LIRC_SET_TRANSMITTER_MASK <LIRC_SET_TRANSMITTER_MASK>`.

.. _LIRC-CAN-SET-REC-CARRIER:

``LIRC_CAN_SET_REC_CARRIER``

    The driver supports setting the receive carrier frequency using
    :ref:`ioctl LIRC_SET_REC_CARRIER <LIRC_SET_REC_CARRIER>`.

.. _LIRC-CAN-SET-REC-CARRIER-RANGE:

``LIRC_CAN_SET_REC_CARRIER_RANGE``

    The driver supports
    :ref:`ioctl LIRC_SET_REC_CARRIER_RANGE <LIRC_SET_REC_CARRIER_RANGE>`.

.. _LIRC-CAN-GET-REC-RESOLUTION:

``LIRC_CAN_GET_REC_RESOLUTION``

    The driver supports
    :ref:`ioctl LIRC_GET_REC_RESOLUTION <LIRC_GET_REC_RESOLUTION>`.

.. _LIRC-CAN-SET-REC-TIMEOUT:

``LIRC_CAN_SET_REC_TIMEOUT``

    The driver supports
    :ref:`ioctl LIRC_SET_REC_TIMEOUT <LIRC_SET_REC_TIMEOUT>`.

.. _LIRC-CAN-MEASURE-CARRIER:

``LIRC_CAN_MEASURE_CARRIER``

    The driver supports measuring of the modulation frequency using
    :ref:`ioctl LIRC_SET_MEASURE_CARRIER_MODE <LIRC_SET_MEASURE_CARRIER_MODE>`.

.. _LIRC-CAN-USE-WIDEBAND-RECEIVER:

``LIRC_CAN_USE_WIDEBAND_RECEIVER``

    The driver supports learning mode using
    :ref:`ioctl LIRC_SET_WIDEBAND_RECEIVER <LIRC_SET_WIDEBAND_RECEIVER>`.

.. _LIRC-CAN-SEND-RAW:

``LIRC_CAN_SEND_RAW``

    Unused. Kept just to avoid breaking uAPI.

.. _LIRC-CAN-SEND-PULSE:

``LIRC_CAN_SEND_PULSE``

    The driver supports sending (also called as IR blasting or IR TX) using
    :ref:`LIRC_MODE_PULSE <lirc-mode-pulse>`. This implies that
    :ref:`LIRC_MODE_SCANCODE <lirc-mode-SCANCODE>` is also supported for
    transmit, as long as the kernel is recent enough. Use the
    :ref:`lirc_set_send_mode` to switch modes.

.. _LIRC-CAN-SEND-MODE2:

``LIRC_CAN_SEND_MODE2``

    Unused. Kept just to avoid breaking uAPI.
    :ref:`LIRC_MODE_MODE2 <lirc-mode-mode2>` can only be used for receiving.

.. _LIRC-CAN-SEND-LIRCCODE:

``LIRC_CAN_SEND_LIRCCODE``

    Unused. Kept just to avoid breaking uAPI.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_get_rec_mode:
.. _lirc_set_rec_mode:

**********************************************
ioctls LIRC_GET_REC_MODE and LIRC_SET_REC_MODE
**********************************************

Name
====

LIRC_GET_REC_MODE/LIRC_SET_REC_MODE - Get/set current receive mode.

Synopsis
========

.. c:macro:: LIRC_GET_REC_MODE

``int ioctl(int fd, LIRC_GET_REC_MODE, __u32 *mode)``

.. c:macro:: LIRC_SET_REC_MODE

``int ioctl(int fd, LIRC_SET_REC_MODE, __u32 *mode)``

Arguments
=========

``fd``
    File descriptor returned by open().

``mode``
    Mode used for receive.

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

Get and set the current receive mode. Only
:ref:`LIRC_MODE_MODE2 <lirc-mode-mode2>` and
:ref:`LIRC_MODE_SCANCODE <lirc-mode-scancode>` are supported.
Use :ref:`lirc_get_features` to find out which modes the driver supports.

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

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

.. flat-table::
    :header-rows:  0
    :stub-columns: 0

    -  .. row 1

       -  ``ENODEV``

       -  Device not available.

    -  .. row 2

       -  ``ENOTTY``

       -  Device does not support receiving.

    -  .. row 3

       -  ``EINVAL``

       -  Invalid mode or invalid mode for this device.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_get_rec_resolution:

*****************************
ioctl LIRC_GET_REC_RESOLUTION
*****************************

Name
====

LIRC_GET_REC_RESOLUTION - Obtain the value of receive resolution, in microseconds.

Synopsis
========

.. c:macro:: LIRC_GET_REC_RESOLUTION

``int ioctl(int fd, LIRC_GET_REC_RESOLUTION, __u32 *microseconds)``

Arguments
=========

``fd``
    File descriptor returned by open().

``microseconds``
    Resolution, in microseconds.

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

Some receivers have maximum resolution which is defined by internal
sample rate or data format limitations. E.g. it's common that
signals can only be reported in 50 microsecond steps.

This ioctl returns the integer value with such resolution, with can be
used by userspace applications like lircd to automatically adjust the
tolerance value.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_get_send_mode:
.. _lirc_set_send_mode:

************************************************
ioctls LIRC_GET_SEND_MODE and LIRC_SET_SEND_MODE
************************************************

Name
====

LIRC_GET_SEND_MODE/LIRC_SET_SEND_MODE - Get/set current transmit mode.

Synopsis
========

.. c:macro:: LIRC_GET_SEND_MODE

``int ioctl(int fd, LIRC_GET_SEND_MODE, __u32 *mode)``

.. c:macro:: LIRC_SET_SEND_MODE

``int ioctl(int fd, LIRC_SET_SEND_MODE, __u32 *mode)``

Arguments
=========

``fd``
    File descriptor returned by open().

``mode``
    The mode used for transmitting.

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

Get/set current transmit mode.

Only :ref:`LIRC_MODE_PULSE <lirc-mode-pulse>` and
:ref:`LIRC_MODE_SCANCODE <lirc-mode-scancode>` are supported by for IR send,
depending on the driver. Use :ref:`lirc_get_features` to find out which
modes the driver supports.

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

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

.. flat-table::
    :header-rows:  0
    :stub-columns: 0

    -  .. row 1

       -  ``ENODEV``

       -  Device not available.

    -  .. row 2

       -  ``ENOTTY``

       -  Device does not support transmitting.

    -  .. row 3

       -  ``EINVAL``

       -  Invalid mode or invalid mode for this device.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_get_min_timeout:
.. _lirc_get_max_timeout:

****************************************************
ioctls LIRC_GET_MIN_TIMEOUT and LIRC_GET_MAX_TIMEOUT
****************************************************

Name
====

LIRC_GET_MIN_TIMEOUT / LIRC_GET_MAX_TIMEOUT - Obtain the possible timeout
range for IR receive.

Synopsis
========

.. c:macro:: LIRC_GET_MIN_TIMEOUT

``int ioctl(int fd, LIRC_GET_MIN_TIMEOUT, __u32 *timeout)``

.. c:macro:: LIRC_GET_MAX_TIMEOUT

``int ioctl(int fd, LIRC_GET_MAX_TIMEOUT, __u32 *timeout)``

Arguments
=========

``fd``
    File descriptor returned by open().

``timeout``
    Timeout, in microseconds.

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

Some devices have internal timers that can be used to detect when
there's no IR activity for a long time. This can help lircd in
detecting that a IR signal is finished and can speed up the decoding
process. Returns an integer value with the minimum/maximum timeout
that can be set.

.. note::

   Some devices have a fixed timeout, in that case
   both ioctls will return the same value even though the timeout
   cannot be changed via :ref:`LIRC_SET_REC_TIMEOUT`.

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.


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

.. _lirc_header:

****************
LIRC Header File
****************

.. kernel-include:: $BUILDDIR/lirc.h.rst


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc-read:

***********
LIRC read()
***********

Name
====

lirc-read - Read from a LIRC device

Synopsis
========

.. code-block:: c

    #include <unistd.h>

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

Arguments
=========

``fd``
    File descriptor returned by ``open()``.

``buf``
   Buffer to be filled

``count``
   Max number of bytes to read

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

:c:func:`read()` attempts to read up to ``count`` bytes from file
descriptor ``fd`` into the buffer starting at ``buf``.  If ``count`` is zero,
:c:func:`read()` returns zero and has no other results. If ``count``
is greater than ``SSIZE_MAX``, the result is unspecified.

The exact format of the data depends on what :ref:`lirc_modes` a driver
uses. Use :ref:`lirc_get_features` to get the supported mode, and use
:ref:`lirc_set_rec_mode` set the current active mode.

The mode :ref:`LIRC_MODE_MODE2 <lirc-mode-mode2>` is for raw IR,
in which packets containing an unsigned int value describing an IR signal are
read from the chardev.

Alternatively, :ref:`LIRC_MODE_SCANCODE <lirc-mode-scancode>` can be available,
in this mode scancodes which are either decoded by software decoders, or
by hardware decoders. The :c:type:`rc_proto` member is set to the
:ref:`IR protocol <Remote_controllers_Protocols>`
used for transmission, and ``scancode`` to the decoded scancode,
and the ``keycode`` set to the keycode or ``KEY_RESERVED``.

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

On success, the number of bytes read is returned. It is not an error if
this number is smaller than the number of bytes requested, or the amount
of data required for one frame.  On error, -1 is returned, and the ``errno``
variable is set appropriately.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_measure_carrier_mode:

***********************************
ioctl LIRC_SET_MEASURE_CARRIER_MODE
***********************************

Name
====

LIRC_SET_MEASURE_CARRIER_MODE - enable or disable measure mode

Synopsis
========

.. c:macro:: LIRC_SET_MEASURE_CARRIER_MODE

``int ioctl(int fd, LIRC_SET_MEASURE_CARRIER_MODE, __u32 *enable)``

Arguments
=========

``fd``
    File descriptor returned by open().

``enable``
    enable = 1 means enable measure mode, enable = 0 means disable measure
    mode.

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

.. _lirc-mode2-frequency:

Enable or disable measure mode. If enabled, from the next key
press on, the driver will send ``LIRC_MODE2_FREQUENCY`` packets. By
default this should be turned off.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_rec_carrier_range:

********************************
ioctl LIRC_SET_REC_CARRIER_RANGE
********************************

Name
====

LIRC_SET_REC_CARRIER_RANGE - Set lower bound of the carrier used to modulate
IR receive.

Synopsis
========

.. c:macro:: LIRC_SET_REC_CARRIER_RANGE

``int ioctl(int fd, LIRC_SET_REC_CARRIER_RANGE, __u32 *frequency)``

Arguments
=========

``fd``
    File descriptor returned by open().

``frequency``
    Frequency of the carrier that modulates PWM data, in Hz.

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

This ioctl sets the upper range of carrier frequency that will be recognized
by the IR receiver.

.. note::

   To set a range use :ref:`LIRC_SET_REC_CARRIER_RANGE
   <LIRC_SET_REC_CARRIER_RANGE>` with the lower bound first and later call
   :ref:`LIRC_SET_REC_CARRIER <LIRC_SET_REC_CARRIER>` with the upper bound.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_rec_carrier:

**************************
ioctl LIRC_SET_REC_CARRIER
**************************

Name
====

LIRC_SET_REC_CARRIER - Set carrier used to modulate IR receive.

Synopsis
========

.. c:macro:: LIRC_SET_REC_CARRIER

``int ioctl(int fd, LIRC_SET_REC_CARRIER, __u32 *frequency)``

Arguments
=========

``fd``
    File descriptor returned by open().

``frequency``
    Frequency of the carrier that modulates PWM data, in Hz.

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

Set receive carrier used to modulate IR PWM pulses and spaces.

.. note::

   If called together with :ref:`LIRC_SET_REC_CARRIER_RANGE`, this ioctl
   sets the upper bound frequency that will be recognized by the device.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_rec_timeout:
.. _lirc_get_rec_timeout:

***************************************************
ioctl LIRC_GET_REC_TIMEOUT and LIRC_SET_REC_TIMEOUT
***************************************************

Name
====

LIRC_GET_REC_TIMEOUT/LIRC_SET_REC_TIMEOUT - Get/set the integer value for IR inactivity timeout.

Synopsis
========

.. c:macro:: LIRC_GET_REC_TIMEOUT

``int ioctl(int fd, LIRC_GET_REC_TIMEOUT, __u32 *timeout)``

.. c:macro:: LIRC_SET_REC_TIMEOUT

``int ioctl(int fd, LIRC_SET_REC_TIMEOUT, __u32 *timeout)``

Arguments
=========

``fd``
    File descriptor returned by open().

``timeout``
    Timeout, in microseconds.

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

Get and set the integer value for IR inactivity timeout.

If supported by the hardware, setting it to 0  disables all hardware timeouts
and data should be reported as soon as possible. If the exact value
cannot be set, then the next possible value _greater_ than the
given value should be set.

.. note::

   The range of supported timeout is given by :ref:`LIRC_GET_MIN_TIMEOUT`.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_send_carrier:

***************************
ioctl LIRC_SET_SEND_CARRIER
***************************

Name
====

LIRC_SET_SEND_CARRIER - Set send carrier used to modulate IR TX.

Synopsis
========

.. c:macro:: LIRC_SET_SEND_CARRIER

``int ioctl(int fd, LIRC_SET_SEND_CARRIER, __u32 *frequency)``

Arguments
=========

``fd``
    File descriptor returned by open().

``frequency``
    Frequency of the carrier to be modulated, in Hz.

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

Set send carrier used to modulate IR PWM pulses and spaces.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_send_duty_cycle:

******************************
ioctl LIRC_SET_SEND_DUTY_CYCLE
******************************

Name
====

LIRC_SET_SEND_DUTY_CYCLE - Set the duty cycle of the carrier signal for
IR transmit.

Synopsis
========

.. c:macro:: LIRC_SET_SEND_DUTY_CYCLE

``int ioctl(int fd, LIRC_SET_SEND_DUTY_CYCLE, __u32 *duty_cycle)``

Arguments
=========

``fd``
    File descriptor returned by open().

``duty_cycle``
    Duty cicle, describing the pulse width in percent (from 1 to 99) of
    the total cycle. Values 0 and 100 are reserved.

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

Get/set the duty cycle of the carrier signal for IR transmit.

Currently, no special meaning is defined for 0 or 100, but this
could be used to switch off carrier generation in the future, so
these values should be reserved.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_transmitter_mask:

*******************************
ioctl LIRC_SET_TRANSMITTER_MASK
*******************************

Name
====

LIRC_SET_TRANSMITTER_MASK - Enables send codes on a given set of transmitters

Synopsis
========

.. c:macro:: LIRC_SET_TRANSMITTER_MASK

``int ioctl(int fd, LIRC_SET_TRANSMITTER_MASK, __u32 *mask)``

Arguments
=========

``fd``
    File descriptor returned by open().

``mask``
    Mask with channels to enable tx. Channel 0 is the least significant bit.

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

Some IR TX devices have multiple output channels, in such case,
:ref:`LIRC_CAN_SET_TRANSMITTER_MASK <LIRC-CAN-SET-TRANSMITTER-MASK>` is
returned via :ref:`LIRC_GET_FEATURES` and this ioctl sets what channels will
send IR codes.

This ioctl enables the given set of transmitters. The first transmitter is
encoded by the least significant bit and so on.

When an invalid bit mask is given, i.e. a bit is set, even though the device
does not have so many transitters, then this ioctl returns the number of
available transitters and does nothing otherwise.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc_set_wideband_receiver:

********************************
ioctl LIRC_SET_WIDEBAND_RECEIVER
********************************

Name
====

LIRC_SET_WIDEBAND_RECEIVER - enable wide band receiver.

Synopsis
========

.. c:macro:: LIRC_SET_WIDEBAND_RECEIVER

``int ioctl(int fd, LIRC_SET_WIDEBAND_RECEIVER, __u32 *enable)``

Arguments
=========

``fd``
    File descriptor returned by open().

``enable``
    enable = 1 means enable wideband receiver, enable = 0 means disable
    wideband receiver.

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

Some receivers are equipped with special wide band receiver which is
intended to be used to learn output of existing remote. This ioctl
allows enabling or disabling it.

This might be useful of receivers that have otherwise narrow band receiver
that prevents them to be used with some remotes. Wide band receiver might
also be more precise. On the other hand its disadvantage it usually
reduced range of reception.

.. note::

    Wide band receiver might be implictly enabled if you enable
    carrier reports. In that case it will be disabled as soon as you disable
    carrier reports. Trying to disable wide band receiver while carrier
    reports are active will do nothing.

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.


code:
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.1-no-invariants-or-later
.. c:namespace:: RC

.. _lirc-write:

************
LIRC write()
************

Name
====

lirc-write - Write to a LIRC device

Synopsis
========

.. code-block:: c

    #include <unistd.h>

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

Arguments
=========

``fd``
    File descriptor returned by ``open()``.

``buf``
    Buffer with data to be written

``count``
    Number of bytes at the buffer

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

:c:func:`write()` writes up to ``count`` bytes to the device
referenced by the file descriptor ``fd`` from the buffer starting at
``buf``.

The exact format of the data depends on what mode a driver is in, use
:ref:`lirc_get_features` to get the supported modes and use
:ref:`lirc_set_send_mode` set the mode.

When in :ref:`LIRC_MODE_PULSE <lirc-mode-PULSE>` mode, the data written to
the chardev is a pulse/space sequence of integer values. Pulses and spaces
are only marked implicitly by their position. The data must start and end
with a pulse, therefore, the data must always include an uneven number of
samples. The write function blocks until the data has been transmitted
by the hardware. If more data is provided than the hardware can send, the
driver returns ``EINVAL``.

When in :ref:`LIRC_MODE_SCANCODE <lirc-mode-scancode>` mode, one
``struct lirc_scancode`` must be written to the chardev at a time, else
``EINVAL`` is returned. Set the desired scancode in the ``scancode`` member,
and the :ref:`IR protocol <Remote_controllers_Protocols>` in the
:c:type:`rc_proto`: member. All other members must be
set to 0, else ``EINVAL`` is returned. If there is no protocol encoder
for the protocol or the scancode is not valid for the specified protocol,
``EINVAL`` is returned. The write function blocks until the scancode
is transmitted by the hardware.

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

On success, the number of bytes written is returned. It is not an error if
this number is smaller than the number of bytes requested, or the amount
of data required for one frame.  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: GPL-2.0 OR GFDL-1.1-no-invariants-or-later

.. _Remote_controllers_Intro:

************
Introduction
************

Currently, most analog and digital devices have a Infrared input for
remote controllers. Each manufacturer has their own type of control. It
is not rare for the same manufacturer to ship different types of
controls, depending on the device.

A Remote Controller interface is mapped as a normal evdev/input
interface, just like a keyboard or a mouse. So, it uses all ioctls
already defined for any other input devices.

However, remove controllers are more flexible than a normal input
device, as the IR receiver (and/or transmitter) can be used in
conjunction with a wide variety of different IR remotes.

In order to allow flexibility, the Remote Controller subsystem allows
controlling the RC-specific attributes via
:ref:`the sysfs class nodes <remote_controllers_sysfs_nodes>`.


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

.. _Remote_controllers_Protocols:

*****************************************
Remote Controller Protocols and Scancodes
*****************************************

IR is encoded as a series of pulses and spaces, using a protocol. These
protocols can encode e.g. an address (which device should respond) and a
command: what it should do. The values for these are not always consistent
across different devices for a given protocol.

Therefore out the output of the IR decoder is a scancode; a single u32
value. Using keymap tables this can be mapped to linux key codes.

Other things can be encoded too. Some IR protocols encode a toggle bit; this
is to distinguish whether the same button is being held down, or has been
released and pressed again. If has been released and pressed again, the
toggle bit will invert from one IR message to the next.

Some remotes have a pointer-type device which can used to control the
mouse; some air conditioning systems can have their target temperature
target set in IR.

The following are the protocols the kernel knows about and also lists
how scancodes are encoded for each protocol.

rc-5 (RC_PROTO_RC5)
-------------------

This IR protocol uses manchester encoding to encode 14 bits. There is a
detailed description here https://www.sbprojects.net/knowledge/ir/rc5.php.

The scancode encoding is *not* consistent with the lirc daemon (lircd) rc5
protocol, or the manchester BPF decoder.

.. flat-table:: rc5 bits scancode mapping
   :widths:       1 1 2

   * - rc-5 bit

     - scancode bit

     - description

   * - 1

     - none

     - Start bit, always set

   * - 1

     - 6 (inverted)

     - 2nd start bit in rc5,  re-used as 6th command bit

   * - 1

     - none

     - Toggle bit

   * - 5

     - 8 to 13

     - Address

   * - 6

     - 0 to 5

     - Command

There is a variant of rc5 called either rc5x or extended rc5
where there the second stop bit is the 6th commmand bit, but inverted.
This is done so it the scancodes and encoding is compatible with existing
schemes. This bit is stored in bit 6 of the scancode, inverted. This is
done to keep it compatible with plain rc-5 where there are two start bits.

rc-5-sz (RC_PROTO_RC5_SZ)
-------------------------
This is much like rc-5 but one bit longer. The scancode is encoded
differently.

.. flat-table:: rc-5-sz bits scancode mapping
   :widths:       1 1 2

   * - rc-5-sz bits

     - scancode bit

     - description

   * - 1

     - none

     - Start bit, always set

   * - 1

     - 13

     - Address bit

   * - 1

     - none

     - Toggle bit

   * - 6

     - 6 to 11

     - Address

   * - 6

     - 0 to 5

     - Command

rc-5x-20 (RC_PROTO_RC5X_20)
---------------------------

This rc-5 extended to encoded 20 bits. The is a 3555 microseconds space
after the 8th bit.

.. flat-table:: rc-5x-20 bits scancode mapping
   :widths:       1 1 2

   * - rc-5-sz bits

     - scancode bit

     - description

   * - 1

     - none

     - Start bit, always set

   * - 1

     - 14

     - Address bit

   * - 1

     - none

     - Toggle bit

   * - 5

     - 16 to 20

     - Address

   * - 6

     - 8 to 13

     - Address

   * - 6

     - 0 to 5

     - Command

jvc (RC_PROTO_JVC)
------------------

The jvc protocol is much like nec, without the inverted values. It is
described here https://www.sbprojects.net/knowledge/ir/jvc.php.

The scancode is a 16 bits value, where the address is the lower 8 bits
and the command the higher 8 bits; this is reversed from IR order.

sony-12 (RC_PROTO_SONY12)
-------------------------

The sony protocol is a pulse-width encoding. There are three variants,
which just differ in number of bits and scancode encoding.

.. flat-table:: sony-12 bits scancode mapping
   :widths:       1 1 2

   * - sony-12 bits

     - scancode bit

     - description

   * - 5

     - 16 to 20

     - device

   * - 7

     - 0 to 6

     - function

sony-15 (RC_PROTO_SONY15)
-------------------------

The sony protocol is a pulse-width encoding. There are three variants,
which just differ in number of bits and scancode encoding.

.. flat-table:: sony-12 bits scancode mapping
   :widths:       1 1 2

   * - sony-12 bits

     - scancode bit

     - description

   * - 8

     - 16 to 23

     - device

   * - 7

     - 0 to 6

     - function

sony-20 (RC_PROTO_SONY20)
-------------------------

The sony protocol is a pulse-width encoding. There are three variants,
which just differ in number of bits and scancode encoding.

.. flat-table:: sony-20 bits scancode mapping
   :widths:       1 1 2

   * - sony-20 bits

     - scancode bit

     - description

   * - 5

     - 16 to 20

     - device

   * - 7

     - 0 to 7

     - device

   * - 8

     - 8 to 15

     - extended bits

nec (RC_PROTO_NEC)
------------------

The nec protocol encodes an 8 bit address and an 8 bit command. It is
described here https://www.sbprojects.net/knowledge/ir/nec.php. Note
that the protocol sends least significant bit first.

As a check, the nec protocol sends the address and command twice; the
second time it is inverted. This is done for verification.

A plain nec IR message has 16 bits; the high 8 bits are the address
and the low 8 bits are the command.

nec-x (RC_PROTO_NECX)
---------------------

Extended nec has a 16 bit address and a 8 bit command. This is encoded
as a 24 bit value as you would expect, with the lower 8 bits the command
and the upper 16 bits the address.

nec-32 (RC_PROTO_NEC32)
-----------------------

nec-32 does not send an inverted address or an inverted command; the
entire message, all 32 bits, are used.

For this to be decoded correctly, the second 8 bits must not be the
inverted value of the first, and also the last 8 bits must not be the
inverted value of the third 8 bit value.

The scancode has a somewhat unusual encoding.

.. flat-table:: nec-32 bits scancode mapping

   * - nec-32 bits

     - scancode bit

   * - First 8 bits

     - 16 to 23

   * - Second 8 bits

     - 24 to 31

   * - Third 8 bits

     - 0 to 7

   * - Fourth 8 bits

     - 8 to 15

sanyo (RC_PROTO_SANYO)
----------------------

The sanyo protocol is like the nec protocol, but with 13 bits address
rather than 8 bits. Both the address and the command are followed by
their inverted versions, but these are not present in the scancodes.

Bis 8 to 20 of the scancode is the 13 bits address, and the lower 8
bits are the command.

mcir2-kbd (RC_PROTO_MCIR2_KBD)
------------------------------

This protocol is generated by the Microsoft MCE keyboard for keyboard
events. Refer to the ir-mce_kbd-decoder.c to see how it is encoded.

mcir2-mse (RC_PROTO_MCIR2_MSE)
------------------------------

This protocol is generated by the Microsoft MCE keyboard for pointer
events. Refer to the ir-mce_kbd-decoder.c to see how it is encoded.

rc-6-0 (RC_PROTO_RC6_0)
-----------------------

This is the rc-6 in mode 0. rc-6 is described here
https://www.sbprojects.net/knowledge/ir/rc6.php.
The scancode is the exact 16 bits as in the protocol. There is also a
toggle bit.

rc-6-6a-20 (RC_PROTO_RC6_6A_20)
-------------------------------

This is the rc-6 in mode 6a, 20 bits. rc-6 is described here
https://www.sbprojects.net/knowledge/ir/rc6.php.
The scancode is the exact 20 bits
as in the protocol. There is also a toggle bit.

rc-6-6a-24 (RC_PROTO_RC6_6A_24)
-------------------------------

This is the rc-6 in mode 6a, 24 bits. rc-6 is described here
https://www.sbprojects.net/knowledge/ir/rc6.php.
The scancode is the exact 24 bits
as in the protocol. There is also a toggle bit.

rc-6-6a-32 (RC_PROTO_RC6_6A_32)
-------------------------------

This is the rc-6 in mode 6a, 32 bits. rc-6 is described here
https://www.sbprojects.net/knowledge/ir/rc6.php.
The upper 16 bits are the vendor,
and the lower 16 bits are the vendor-specific bits. This protocol is
for the non-Microsoft MCE variant (vendor != 0x800f).

rc-6-mce (RC_PROTO_RC6_MCE)
---------------------------

This is the rc-6 in mode 6a, 32 bits. The upper 16 bits are the vendor,
and the lower 16 bits are the vendor-specific bits. This protocol is
for the Microsoft MCE variant (vendor = 0x800f). The toggle bit in the
protocol itself is ignored, and the 16th bit should be takes as the toggle
bit.

sharp (RC_PROTO_SHARP)
----------------------

This is a protocol used by Sharp VCRs, is described here
https://www.sbprojects.net/knowledge/ir/sharp.php. There is a very long
(40ms) space between the normal and inverted values, and some IR receivers
cannot decode this.

There is a 5 bit address and a 8 bit command. In the scancode the address is
in bits 8 to 12, and the command in bits 0 to 7.

xmp (RC_PROTO_XMP)
------------------

This protocol has several versions and only version 1 is supported. Refer
to the decoder (ir-xmp-decoder.c) to see how it is encoded.

cec (RC_PROTO_CEC)
------------------

This is not an IR protocol, this is a protocol over CEC. The CEC
infrastructure uses rc-core for handling CEC commands, so that they
can easily be remapped.

imon (RC_PROTO_IMON)
--------------------

This protocol is used by Antec Veris/SoundGraph iMON remotes.

The protocol
describes both button presses and pointer movements. The protocol encodes
31 bits, and the scancode is simply the 31 bits with the top bit always 0.

rc-mm-12 (RC_PROTO_RCMM12)
--------------------------

The rc-mm protocol is described here
https://www.sbprojects.net/knowledge/ir/rcmm.php. The scancode is simply
the 12 bits.

rc-mm-24 (RC_PROTO_RCMM24)
--------------------------

The rc-mm protocol is described here
https://www.sbprojects.net/knowledge/ir/rcmm.php. The scancode is simply
the 24 bits.

rc-mm-32 (RC_PROTO_RCMM32)
--------------------------

The rc-mm protocol is described here
https://www.sbprojects.net/knowledge/ir/rcmm.php. The scancode is simply
the 32 bits.

xbox-dvd (RC_PROTO_XBOX_DVD)
----------------------------

This protocol is used by XBox DVD Remote, which was made for the original
XBox. There is no in-kernel decoder or encoder for this protocol. The usb
device decodes the protocol. There is a BPF decoder available in v4l-utils.


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

.. _remote_controllers_sysfs_nodes:

*******************************
Remote Controller's sysfs nodes
*******************************

As defined at ``Documentation/ABI/testing/sysfs-class-rc``, those are
the sysfs nodes that control the Remote Controllers:

.. _sys_class_rc:

/sys/class/rc/
==============

The ``/sys/class/rc/`` class sub-directory belongs to the Remote
Controller core and provides a sysfs interface for configuring infrared
remote controller receivers.

.. _sys_class_rc_rcN:

/sys/class/rc/rcN/
==================

A ``/sys/class/rc/rcN`` directory is created for each remote control
receiver device where N is the number of the receiver.

.. _sys_class_rc_rcN_protocols:

/sys/class/rc/rcN/protocols
===========================

Reading this file returns a list of available protocols, something like::

	rc5 [rc6] nec jvc [sony]

Enabled protocols are shown in [] brackets.

Writing "+proto" will add a protocol to the list of enabled protocols.

Writing "-proto" will remove a protocol from the list of enabled
protocols.

Writing "proto" will enable only "proto".

Writing "none" will disable all protocols.

Write fails with ``EINVAL`` if an invalid protocol combination or unknown
protocol name is used.

.. _sys_class_rc_rcN_filter:

/sys/class/rc/rcN/filter
========================

Sets the scancode filter expected value.

Use in combination with ``/sys/class/rc/rcN/filter_mask`` to set the
expected value of the bits set in the filter mask. If the hardware
supports it then scancodes which do not match the filter will be
ignored. Otherwise the write will fail with an error.

This value may be reset to 0 if the current protocol is altered.

.. _sys_class_rc_rcN_filter_mask:

/sys/class/rc/rcN/filter_mask
=============================

Sets the scancode filter mask of bits to compare. Use in combination
with ``/sys/class/rc/rcN/filter`` to set the bits of the scancode which
should be compared against the expected value. A value of 0 disables the
filter to allow all valid scancodes to be processed.

If the hardware supports it then scancodes which do not match the filter
will be ignored. Otherwise the write will fail with an error.

This value may be reset to 0 if the current protocol is altered.

.. _sys_class_rc_rcN_wakeup_protocols:

/sys/class/rc/rcN/wakeup_protocols
==================================

Reading this file returns a list of available protocols to use for the
wakeup filter, something like::

	rc-5 nec nec-x rc-6-0 rc-6-6a-24 [rc-6-6a-32] rc-6-mce

Note that protocol variants are listed, so ``nec``, ``sony``, ``rc-5``, ``rc-6``
have their different bit length encodings listed if available.

Note that all protocol variants are listed.

The enabled wakeup protocol is shown in [] brackets.

Only one protocol can be selected at a time.

Writing "proto" will use "proto" for wakeup events.

Writing "none" will disable wakeup.

Write fails with ``EINVAL`` if an invalid protocol combination or unknown
protocol name is used, or if wakeup is not supported by the hardware.

.. _sys_class_rc_rcN_wakeup_filter:

/sys/class/rc/rcN/wakeup_filter
===============================

Sets the scancode wakeup filter expected value. Use in combination with
``/sys/class/rc/rcN/wakeup_filter_mask`` to set the expected value of
the bits set in the wakeup filter mask to trigger a system wake event.

If the hardware supports it and wakeup_filter_mask is not 0 then
scancodes which match the filter will wake the system from e.g. suspend
to RAM or power off. Otherwise the write will fail with an error.

This value may be reset to 0 if the wakeup protocol is altered.

.. _sys_class_rc_rcN_wakeup_filter_mask:

/sys/class/rc/rcN/wakeup_filter_mask
====================================

Sets the scancode wakeup filter mask of bits to compare. Use in
combination with ``/sys/class/rc/rcN/wakeup_filter`` to set the bits of
the scancode which should be compared against the expected value to
trigger a system wake event.

If the hardware supports it and wakeup_filter_mask is not 0 then
scancodes which match the filter will wake the system from e.g. suspend
to RAM or power off. Otherwise the write will fail with an error.

This value may be reset to 0 if the wakeup protocol is altered.


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

.. _Remote_controllers_table_change:

*******************************************
Changing default Remote Controller mappings
*******************************************

The event interface provides two ioctls to be used against the
/dev/input/event device, to allow changing the default keymapping.

This program demonstrates how to replace the keymap tables.

.. toctree::
    :maxdepth: 1

    keytable.c