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

PXA-Camera Host Driver
======================

Author: Robert Jarzmik <robert.jarzmik@free.fr>

Constraints
-----------

a) Image size for YUV422P format
   All YUV422P images are enforced to have width x height % 16 = 0.
   This is due to DMA constraints, which transfers only planes of 8 byte
   multiples.

Global video workflow
---------------------

a) QCI stopped
   Initially, the QCI interface is stopped.
   When a buffer is queued, start_streaming is called and the QCI starts.

b) QCI started
   More buffers can be queued while the QCI is started without halting the
   capture.  The new buffers are "appended" at the tail of the DMA chain, and
   smoothly captured one frame after the other.

   Once a buffer is filled in the QCI interface, it is marked as "DONE" and
   removed from the active buffers list. It can be then requeud or dequeued by
   userland application.

   Once the last buffer is filled in, the QCI interface stops.

c) Capture global finite state machine schema

.. code-block:: none

	+----+                             +---+  +----+
	| DQ |                             | Q |  | DQ |
	|    v                             |   v  |    v
	+-----------+                     +------------------------+
	|   STOP    |                     | Wait for capture start |
	+-----------+         Q           +------------------------+
	+-> | QCI: stop | ------------------> | QCI: run               | <------------+
	|   | DMA: stop |                     | DMA: stop              |              |
	|   +-----------+             +-----> +------------------------+              |
	|                            /                            |                   |
	|                           /             +---+  +----+   |                   |
	|capture list empty        /              | Q |  | DQ |   | QCI Irq EOF       |
	|                         /               |   v  |    v   v                   |
	|   +--------------------+             +----------------------+               |
	|   | DMA hotlink missed |             |    Capture running   |               |
	|   +--------------------+             +----------------------+               |
	|   | QCI: run           |     +-----> | QCI: run             | <-+           |
	|   | DMA: stop          |    /        | DMA: run             |   |           |
	|   +--------------------+   /         +----------------------+   | Other     |
	|     ^                     /DMA still            |               | channels  |
	|     | capture list       /  running             | DMA Irq End   | not       |
	|     | not empty         /                       |               | finished  |
	|     |                  /                        v               | yet       |
	|   +----------------------+           +----------------------+   |           |
	|   |  Videobuf released   |           |  Channel completed   |   |           |
	|   +----------------------+           +----------------------+   |           |
	+-- | QCI: run             |           | QCI: run             | --+           |
	| DMA: run             |           | DMA: run             |               |
	+----------------------+           +----------------------+               |
		^                      /           |                           |
		|          no overrun /            | overrun                   |
		|                    /             v                           |
	+--------------------+         /   +----------------------+               |
	|  Frame completed   |        /    |     Frame overran    |               |
	+--------------------+ <-----+     +----------------------+ restart frame |
	| QCI: run           |             | QCI: stop            | --------------+
	| DMA: run           |             | DMA: stop            |
	+--------------------+             +----------------------+

	Legend: - each box is a FSM state
		- each arrow is the condition to transition to another state
		- an arrow with a comment is a mandatory transition (no condition)
		- arrow "Q" means : a buffer was enqueued
		- arrow "DQ" means : a buffer was dequeued
		- "QCI: stop" means the QCI interface is not enabled
		- "DMA: stop" means all 3 DMA channels are stopped
		- "DMA: run" means at least 1 DMA channel is still running

DMA usage
---------

a) DMA flow
     - first buffer queued for capture
       Once a first buffer is queued for capture, the QCI is started, but data
       transfer is not started. On "End Of Frame" interrupt, the irq handler
       starts the DMA chain.
     - capture of one videobuffer
       The DMA chain starts transferring data into videobuffer RAM pages.
       When all pages are transferred, the DMA irq is raised on "ENDINTR" status
     - finishing one videobuffer
       The DMA irq handler marks the videobuffer as "done", and removes it from
       the active running queue
       Meanwhile, the next videobuffer (if there is one), is transferred by DMA
     - finishing the last videobuffer
       On the DMA irq of the last videobuffer, the QCI is stopped.

b) DMA prepared buffer will have this structure

.. code-block:: none

     +------------+-----+---------------+-----------------+
     | desc-sg[0] | ... | desc-sg[last] | finisher/linker |
     +------------+-----+---------------+-----------------+

This structure is pointed by dma->sg_cpu.
The descriptors are used as follows:

- desc-sg[i]: i-th descriptor, transferring the i-th sg
  element to the video buffer scatter gather
- finisher: has ddadr=DADDR_STOP, dcmd=ENDIRQEN
- linker: has ddadr= desc-sg[0] of next video buffer, dcmd=0

For the next schema, let's assume d0=desc-sg[0] .. dN=desc-sg[N],
"f" stands for finisher and "l" for linker.
A typical running chain is :

.. code-block:: none

         Videobuffer 1         Videobuffer 2
     +---------+----+---+  +----+----+----+---+
     | d0 | .. | dN | l |  | d0 | .. | dN | f |
     +---------+----+-|-+  ^----+----+----+---+
                      |    |
                      +----+

After the chaining is finished, the chain looks like :

.. code-block:: none

         Videobuffer 1         Videobuffer 2         Videobuffer 3
     +---------+----+---+  +----+----+----+---+  +----+----+----+---+
     | d0 | .. | dN | l |  | d0 | .. | dN | l |  | d0 | .. | dN | f |
     +---------+----+-|-+  ^----+----+----+-|-+  ^----+----+----+---+
                      |    |                |    |
                      +----+                +----+
                                           new_link

c) DMA hot chaining timeslice issue

As DMA chaining is done while DMA _is_ running, the linking may be done
while the DMA jumps from one Videobuffer to another. On the schema, that
would be a problem if the following sequence is encountered :

- DMA chain is Videobuffer1 + Videobuffer2
- pxa_videobuf_queue() is called to queue Videobuffer3
- DMA controller finishes Videobuffer2, and DMA stops

.. code-block:: none

      =>
         Videobuffer 1         Videobuffer 2
     +---------+----+---+  +----+----+----+---+
     | d0 | .. | dN | l |  | d0 | .. | dN | f |
     +---------+----+-|-+  ^----+----+----+-^-+
                      |    |                |
                      +----+                +-- DMA DDADR loads DDADR_STOP

- pxa_dma_add_tail_buf() is called, the Videobuffer2 "finisher" is
  replaced by a "linker" to Videobuffer3 (creation of new_link)
- pxa_videobuf_queue() finishes
- the DMA irq handler is called, which terminates Videobuffer2
- Videobuffer3 capture is not scheduled on DMA chain (as it stopped !!!)

.. code-block:: none

         Videobuffer 1         Videobuffer 2         Videobuffer 3
     +---------+----+---+  +----+----+----+---+  +----+----+----+---+
     | d0 | .. | dN | l |  | d0 | .. | dN | l |  | d0 | .. | dN | f |
     +---------+----+-|-+  ^----+----+----+-|-+  ^----+----+----+---+
                      |    |                |    |
                      +----+                +----+
                                           new_link
                                          DMA DDADR still is DDADR_STOP

- pxa_camera_check_link_miss() is called
  This checks if the DMA is finished and a buffer is still on the
  pcdev->capture list. If that's the case, the capture will be restarted,
  and Videobuffer3 is scheduled on DMA chain.
- the DMA irq handler finishes

.. note::

     If DMA stops just after pxa_camera_check_link_miss() reads DDADR()
     value, we have the guarantee that the DMA irq handler will be called back
     when the DMA will finish the buffer, and pxa_camera_check_link_miss() will
     be called again, to reschedule Videobuffer3.


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

The Radiotrack radio driver
===========================

Author: Stephen M. Benoit <benoits@servicepro.com>

Date:  Dec 14, 1996

ACKNOWLEDGMENTS
----------------

This document was made based on 'C' code for Linux from Gideon le Grange
(legrang@active.co.za or legrang@cs.sun.ac.za) in 1994, and elaborations from
Frans Brinkman (brinkman@esd.nl) in 1996.  The results reported here are from
experiments that the author performed on his own setup, so your mileage may
vary... I make no guarantees, claims or warranties to the suitability or
validity of this information.  No other documentation on the AIMS
Lab (http://www.aimslab.com/) RadioTrack card was made available to the
author.  This document is offered in the hopes that it might help users who
want to use the RadioTrack card in an environment other than MS Windows.

WHY THIS DOCUMENT?
------------------

I have a RadioTrack card from back when I ran an MS-Windows platform.  After
converting to Linux, I found Gideon le Grange's command-line software for
running the card, and found that it was good!  Frans Brinkman made a
comfortable X-windows interface, and added a scanning feature.  For hack
value, I wanted to see if the tuner could be tuned beyond the usual FM radio
broadcast band, so I could pick up the audio carriers from North American
broadcast TV channels, situated just below and above the 87.0-109.0 MHz range.
I did not get much success, but I learned about programming ioports under
Linux and gained some insights about the hardware design used for the card.

So, without further delay, here are the details.

PHYSICAL DESCRIPTION
--------------------

The RadioTrack card is an ISA 8-bit FM radio card.  The radio frequency (RF)
input is simply an antenna lead, and the output is a power audio signal
available through a miniature phone plug.  Its RF frequencies of operation are
more or less limited from 87.0 to 109.0 MHz (the commercial FM broadcast
band).  Although the registers can be programmed to request frequencies beyond
these limits, experiments did not give promising results.  The variable
frequency oscillator (VFO) that demodulates the intermediate frequency (IF)
signal probably has a small range of useful frequencies, and wraps around or
gets clipped beyond the limits mentioned above.

CONTROLLING THE CARD WITH IOPORT
--------------------------------

The RadioTrack (base) ioport is configurable for 0x30c or 0x20c.  Only one
ioport seems to be involved.  The ioport decoding circuitry must be pretty
simple, as individual ioport bits are directly matched to specific functions
(or blocks) of the radio card.  This way, many functions can be changed in
parallel with one write to the ioport.  The only feedback available through
the ioports appears to be the "Stereo Detect" bit.

The bits of the ioport are arranged as follows:

.. code-block:: none

	MSb                                                         LSb
	+------+------+------+--------+--------+-------+---------+--------+
	| VolA | VolB | ???? | Stereo | Radio  | TuneA | TuneB   | Tune   |
	|  (+) |  (-) |      | Detect | Audio  | (bit) | (latch) | Update |
	|      |      |      | Enable | Enable |       |         | Enable |
	+------+------+------+--------+--------+-------+---------+--------+

====  ====  =================================
VolA  VolB  Description
====  ====  =================================
0	 0  audio mute
0	 1  volume +    (some delay required)
1	 0  volume -    (some delay required)
1	 1  stay at present volume
====  ====  =================================

====================	===========
Stereo Detect Enable	Description
====================	===========
0			No Detect
1			Detect
====================	===========

Results available by reading ioport >60 msec after last port write.

  0xff ==> no stereo detected,  0xfd ==> stereo detected.

=============================	=============================
Radio to Audio (path) Enable	Description
=============================	=============================
0				Disable path (silence)
1				Enable path  (audio produced)
=============================	=============================

=====  =====  ==================
TuneA  TuneB  Description
=====  =====  ==================
0	0     "zero" bit phase 1
0	1     "zero" bit phase 2
1	0     "one" bit phase 1
1	1     "one" bit phase 2
=====  =====  ==================

24-bit code, where bits = (freq*40) + 10486188.
The Most Significant 11 bits must be 1010 xxxx 0x0 to be valid.
The bits are shifted in LSb first.

==================	===========================
Tune Update Enable	Description
==================	===========================
0			Tuner held constant
1			Tuner updating in progress
==================	===========================

PROGRAMMING EXAMPLES
--------------------

.. code-block:: none

	Default:        BASE <-- 0xc8  (current volume, no stereo detect,
					radio enable, tuner adjust disable)

	Card Off:	BASE <-- 0x00  (audio mute, no stereo detect,
					radio disable, tuner adjust disable)

	Card On:	BASE <-- 0x00  (see "Card Off", clears any unfinished business)
			BASE <-- 0xc8  (see "Default")

	Volume Down:    BASE <-- 0x48  (volume down, no stereo detect,
					radio enable, tuner adjust disable)
			wait 10 msec
			BASE <-- 0xc8  (see "Default")

	Volume Up:      BASE <-- 0x88  (volume up, no stereo detect,
					radio enable, tuner adjust disable)
			wait 10 msec
			BASE <-- 0xc8  (see "Default")

	Check Stereo:   BASE <-- 0xd8  (current volume, stereo detect,
					radio enable, tuner adjust disable)
			wait 100 msec
			x <-- BASE     (read ioport)
			BASE <-- 0xc8  (see "Default")

			x=0xff ==> "not stereo", x=0xfd ==> "stereo detected"

	Set Frequency:  code = (freq*40) + 10486188
			foreach of the 24 bits in code,
			(from Least to Most Significant):
			to write a "zero" bit,
			BASE <-- 0x01  (audio mute, no stereo detect, radio
					disable, "zero" bit phase 1, tuner adjust)
			BASE <-- 0x03  (audio mute, no stereo detect, radio
					disable, "zero" bit phase 2, tuner adjust)
			to write a "one" bit,
			BASE <-- 0x05  (audio mute, no stereo detect, radio
					disable, "one" bit phase 1, tuner adjust)
			BASE <-- 0x07  (audio mute, no stereo detect, radio
					disable, "one" bit phase 2, tuner adjust)

repo_name: angery/linux


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

The Rockchip Image Signal Processor Driver (rkisp1)
===================================================

Versions and their differences
------------------------------

The rkisp1 block underwent some changes between SoC implementations.
The vendor designates them as:

- V10: used at least in rk3288 and rk3399
- V11: declared in the original vendor code, but not used
- V12: used at least in rk3326 and px30
- V13: used at least in rk1808
- V20: used in rk3568 and beyond

Right now the kernel supports rkisp1 implementations based
on V10 and V12 variants. V11 does not seem to be actually used
and V13 will need some more additions but isn't researched yet,
especially as it seems to be limited to the rk1808 which hasn't
reached much market spread.

V20 on the other hand will probably be used in future SoCs and
has seen really big changes in the vendor kernel, so will need
quite a bit of research.

Changes from V10 to V12
-----------------------

- V12 supports a new CSI-host implementation but can still
  also use the same implementation from V10
- The module for lens shading correction got changed
  from 12bit to 13bit width
- The AWB and AEC modules got replaced to support finer
  grained data collection

Changes from V12 to V13
-----------------------

The list for V13 is incomplete and needs further investigation.

- V13 does not support the old CSI-host implementation anymore


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

The saa7134 driver
==================

Author Gerd Hoffmann

Card Variations:
----------------

Cards can use either of these two crystals (xtal):

- 32.11 MHz -> .audio_clock=0x187de7
- 24.576MHz -> .audio_clock=0x200000 (xtal * .audio_clock = 51539600)

Some details about 30/34/35:

- saa7130 - low-price chip, doesn't have mute, that is why all those
  cards should have .mute field defined in their tuner structure.

- saa7134 - usual chip

- saa7133/35 - saa7135 is probably a marketing decision, since all those
  chips identifies itself as 33 on pci.

LifeView GPIOs
--------------

This section was authored by: Peter Missel <peter.missel@onlinehome.de>

- LifeView FlyTV Platinum FM (LR214WF)

    - GP27    MDT2005 PB4 pin 10
    - GP26    MDT2005 PB3 pin 9
    - GP25    MDT2005 PB2 pin 8
    - GP23    MDT2005 PB1 pin 7
    - GP22    MDT2005 PB0 pin 6
    - GP21    MDT2005 PB5 pin 11
    - GP20    MDT2005 PB6 pin 12
    - GP19    MDT2005 PB7 pin 13
    - nc      MDT2005 PA3 pin 2
    - Remote  MDT2005 PA2 pin 1
    - GP18    MDT2005 PA1 pin 18
    - nc      MDT2005 PA0 pin 17 strap low
    - GP17    Strap "GP7"=High
    - GP16    Strap "GP6"=High

	- 0=Radio 1=TV
	- Drives SA630D ENCH1 and HEF4052 A1 pinsto do FM radio through
	  SIF input

    - GP15    nc
    - GP14    nc
    - GP13    nc
    - GP12    Strap "GP5" = High
    - GP11    Strap "GP4" = High
    - GP10    Strap "GP3" = High
    - GP09    Strap "GP2" = Low
    - GP08    Strap "GP1" = Low
    - GP07.00 nc

Credits
-------

andrew.stevens@philips.com + werner.leeb@philips.com for providing
saa7134 hardware specs and sample board.


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

Cropping and Scaling algorithm, used in the sh_mobile_ceu_camera driver
=======================================================================

Author: Guennadi Liakhovetski <g.liakhovetski@gmx.de>

Terminology
-----------

sensor scales: horizontal and vertical scales, configured by the sensor driver
host scales: -"- host driver
combined scales: sensor_scale * host_scale

Generic scaling / cropping scheme
---------------------------------

.. code-block:: none

	-1--
	|
	-2-- -\
	|      --\
	|         --\
	+-5-- .      -- -3-- -\
	|      `...            -\
	|          `... -4-- .   - -7..
	|                     `.
	|                       `. .6--
	|
	|                        . .6'-
	|                      .´
	|           ... -4'- .´
	|       ...´             - -7'.
	+-5'- .´               -/
	|            -- -3'- -/
	|         --/
	|      --/
	-2'- -/
	|
	|
	-1'-

In the above chart minuses and slashes represent "real" data amounts, points and
accents represent "useful" data, basically, CEU scaled and cropped output,
mapped back onto the client's source plane.

Such a configuration can be produced by user requests:

S_CROP(left / top = (5) - (1), width / height = (5') - (5))
S_FMT(width / height = (6') - (6))

Here:

(1) to (1') - whole max width or height
(1) to (2)  - sensor cropped left or top
(2) to (2') - sensor cropped width or height
(3) to (3') - sensor scale
(3) to (4)  - CEU cropped left or top
(4) to (4') - CEU cropped width or height
(5) to (5') - reverse sensor scale applied to CEU cropped width or height
(2) to (5)  - reverse sensor scale applied to CEU cropped left or top
(6) to (6') - CEU scale - user window

S_FMT
-----

Do not touch input rectangle - it is already optimal.

1. Calculate current sensor scales:

	scale_s = ((2') - (2)) / ((3') - (3))

2. Calculate "effective" input crop (sensor subwindow) - CEU crop scaled back at
current sensor scales onto input window - this is user S_CROP:

	width_u = (5') - (5) = ((4') - (4)) * scale_s

3. Calculate new combined scales from "effective" input window to requested user
window:

	scale_comb = width_u / ((6') - (6))

4. Calculate sensor output window by applying combined scales to real input
window:

	width_s_out = ((7') - (7)) = ((2') - (2)) / scale_comb

5. Apply iterative sensor S_FMT for sensor output window.

	subdev->video_ops->s_fmt(.width = width_s_out)

6. Retrieve sensor output window (g_fmt)

7. Calculate new sensor scales:

	scale_s_new = ((3')_new - (3)_new) / ((2') - (2))

8. Calculate new CEU crop - apply sensor scales to previously calculated
"effective" crop:

	width_ceu = (4')_new - (4)_new = width_u / scale_s_new
	left_ceu = (4)_new - (3)_new = ((5) - (2)) / scale_s_new

9. Use CEU cropping to crop to the new window:

	ceu_crop(.width = width_ceu, .left = left_ceu)

10. Use CEU scaling to scale to the requested user window:

	scale_ceu = width_ceu / width

S_CROP
------

The :ref:`V4L2 crop API <crop-scale>` says:

"...specification does not define an origin or units. However by convention
drivers should horizontally count unscaled samples relative to 0H."

We choose to follow the advise and interpret cropping units as client input
pixels.

Cropping is performed in the following 6 steps:

1. Request exactly user rectangle from the sensor.

2. If smaller - iterate until a larger one is obtained. Result: sensor cropped
   to 2 : 2', target crop 5 : 5', current output format 6' - 6.

3. In the previous step the sensor has tried to preserve its output frame as
   good as possible, but it could have changed. Retrieve it again.

4. Sensor scaled to 3 : 3'. Sensor's scale is (2' - 2) / (3' - 3). Calculate
   intermediate window: 4' - 4 = (5' - 5) * (3' - 3) / (2' - 2)

5. Calculate and apply host scale = (6' - 6) / (4' - 4)

6. Calculate and apply host crop: 6 - 7 = (5 - 2) * (6' - 6) / (5' - 5)


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

Tuner drivers
=============

Simple tuner Programming
------------------------

There are some flavors of Tuner programming APIs.
These differ mainly by the bandswitch byte.

- L= LG_API       (VHF_LO=0x01, VHF_HI=0x02, UHF=0x08, radio=0x04)
- P= PHILIPS_API  (VHF_LO=0xA0, VHF_HI=0x90, UHF=0x30, radio=0x04)
- T= TEMIC_API    (VHF_LO=0x02, VHF_HI=0x04, UHF=0x01)
- A= ALPS_API     (VHF_LO=0x14, VHF_HI=0x12, UHF=0x11)
- M= PHILIPS_MK3  (VHF_LO=0x01, VHF_HI=0x02, UHF=0x04, radio=0x19)

Tuner Manufacturers
-------------------

- Samsung Tuner identification: (e.g. TCPM9091PD27)

.. code-block:: none

 TCP [ABCJLMNQ] 90[89][125] [DP] [ACD] 27 [ABCD]
 [ABCJLMNQ]:
   A= BG+DK
   B= BG
   C= I+DK
   J= NTSC-Japan
   L= Secam LL
   M= BG+I+DK
   N= NTSC
   Q= BG+I+DK+LL
 [89]: ?
 [125]:
   2: No FM
   5: With FM
 [DP]:
   D= NTSC
   P= PAL
 [ACD]:
   A= F-connector
   C= Phono connector
   D= Din Jack
 [ABCD]:
   3-wire/I2C tuning, 2-band/3-band

These Tuners are PHILIPS_API compatible.

Philips Tuner identification: (e.g. FM1216MF)

.. code-block:: none

  F[IRMQ]12[1345]6{MF|ME|MP}
  F[IRMQ]:
   FI12x6: Tuner Series
   FR12x6: Tuner + Radio IF
   FM12x6: Tuner + FM
   FQ12x6: special
   FMR12x6: special
   TD15xx: Digital Tuner ATSC
  12[1345]6:
   1216: PAL BG
   1236: NTSC
   1246: PAL I
   1256: Pal DK
  {MF|ME|MP}
   MF: BG LL w/ Secam (Multi France)
   ME: BG DK I LL   (Multi Europe)
   MP: BG DK I      (Multi PAL)
   MR: BG DK M (?)
   MG: BG DKI M (?)
  MK2 series PHILIPS_API, most tuners are compatible to this one !
  MK3 series introduced in 2002 w/ PHILIPS_MK3_API

Temic Tuner identification: (.e.g 4006FH5)

.. code-block:: none

   4[01][0136][269]F[HYNR]5
    40x2: Tuner (5V/33V), TEMIC_API.
    40x6: Tuner 5V
    41xx: Tuner compact
    40x9: Tuner+FM compact
   [0136]
    xx0x: PAL BG
    xx1x: Pal DK, Secam LL
    xx3x: NTSC
    xx6x: PAL I
   F[HYNR]5
    FH5: Pal BG
    FY5: others
    FN5: multistandard
    FR5: w/ FM radio
   3X xxxx: order number with specific connector
  Note: Only 40x2 series has TEMIC_API, all newer tuners have PHILIPS_API.

LG Innotek Tuner:

- TPI8NSR11 : NTSC J/M    (TPI8NSR01 w/FM)  (P,210/497)
- TPI8PSB11 : PAL B/G     (TPI8PSB01 w/FM)  (P,170/450)
- TAPC-I701 : PAL I       (TAPC-I001 w/FM)  (P,170/450)
- TPI8PSB12 : PAL D/K+B/G (TPI8PSB02 w/FM)  (P,170/450)
- TAPC-H701P: NTSC_JP     (TAPC-H001P w/FM) (L,170/450)
- TAPC-G701P: PAL B/G     (TAPC-G001P w/FM) (L,170/450)
- TAPC-W701P: PAL I       (TAPC-W001P w/FM) (L,170/450)
- TAPC-Q703P: PAL D/K     (TAPC-Q001P w/FM) (L,170/450)
- TAPC-Q704P: PAL D/K+I   (L,170/450)
- TAPC-G702P: PAL D/K+B/G (L,170/450)

- TADC-H002F: NTSC (L,175/410?; 2-B, C-W+11, W+12-69)
- TADC-M201D: PAL D/K+B/G+I (L,143/425)  (sound control at I2C address 0xc8)
- TADC-T003F: NTSC Taiwan  (L,175/410?; 2-B, C-W+11, W+12-69)

Suffix:
  - P= Standard phono female socket
  - D= IEC female socket
  - F= F-connector

Other Tuners:

- TCL2002MB-1 : PAL BG + DK       =TUNER_LG_PAL_NEW_TAPC
- TCL2002MB-1F: PAL BG + DK w/FM  =PHILIPS_PAL
- TCL2002MI-2 : PAL I		= ??

ALPS Tuners:

- Most are LG_API compatible
- TSCH6 has ALPS_API (TSCH5 ?)
- TSBE1 has extra API 05,02,08 Control_byte=0xCB Source:[#f1]_

.. [#f1] conexant100029b-PCI-Decoder-ApplicationNote.pdf


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

================================
vidtv: Virtual Digital TV driver
================================

Author: Daniel W. S. Almeida <dwlsalmeida@gmail.com>, June 2020.

Background
----------

Vidtv is a virtual DVB driver that aims to serve as a reference for driver
writers by serving as a template. It also validates the existing media DVB
APIs, thus helping userspace application writers.

Currently, it consists of:

- A fake tuner driver, which will report a bad signal quality if the chosen
  frequency is too far away from a table of valid frequencies for a
  particular delivery system.

- A fake demod driver, which will constantly poll the fake signal quality
  returned by the tuner, simulating a device that can lose/reacquire a lock
  on the signal depending on the CNR levels.

- A fake bridge driver, which is the module responsible for modprobing the
  fake tuner and demod modules and implementing the demux logic. This module
  takes parameters at initialization that will dictate how the simulation
  behaves.

- Code reponsible for encoding a valid MPEG Transport Stream, which is then
  passed to the bridge driver. This fake stream contains some hardcoded content.
  For now, we have a single, audio-only channel containing a single MPEG
  Elementary Stream, which in turn contains a SMPTE 302m encoded sine-wave.
  Note that this particular encoder was chosen because it is the easiest
  way to encode PCM audio data in a MPEG Transport Stream.

Building vidtv
--------------
vidtv is a test driver and thus is **not** enabled by default when
compiling the kernel.

In order to enable compilation of vidtv:

- Enable **DVB_TEST_DRIVERS**, then
- Enable **DVB_VIDTV**

When compiled as a module, expect the following .ko files:

- dvb_vidtv_tuner.ko

- dvb_vidtv_demod.ko

- dvb_vidtv_bridge.ko

Running vidtv
-------------
When compiled as a module, run::

	modprobe vidtv

That's it! The bridge driver will initialize the tuner and demod drivers as
part of its own initialization.

By default, it will accept the following frequencies:

	- 474 MHz for DVB-T/T2/C;
	- 11,362 GHz for DVB-S/S2.

For satellite systems, the driver simulates an universal extended
LNBf, with frequencies at Ku-Band, ranging from 10.7 GHz to 12.75 GHz.

You can optionally define some command-line arguments to vidtv.

Command-line arguments to vidtv
-------------------------------
Below is a list of all arguments that can be supplied to vidtv:

drop_tslock_prob_on_low_snr
	Probability of losing the TS lock if the signal quality is bad.
	This probability be used by the fake demodulator driver to
	eventually return a status of 0 when the signal quality is not
	good.

recover_tslock_prob_on_good_snr:
	Probability recovering the TS lock when the signal improves. This
	probability be used by the fake demodulator driver to eventually
	return a status of 0x1f when/if the signal quality improves.

mock_power_up_delay_msec
	Simulate a power up delay.  Default: 0.

mock_tune_delay_msec
	Simulate a tune delay.  Default 0.

vidtv_valid_dvb_t_freqs
	Valid DVB-T frequencies to simulate, in Hz.

vidtv_valid_dvb_c_freqs
	Valid DVB-C frequencies to simulate, in Hz.

vidtv_valid_dvb_s_freqs
	Valid DVB-S/S2 frequencies to simulate at Ku-Band, in kHz.

max_frequency_shift_hz,
	Maximum shift in HZ allowed when tuning in a channel.

si_period_msec
	How often to send SI packets.  Default: 40ms.

pcr_period_msec
	How often to send PCR packets.  Default: 40ms.

mux_rate_kbytes_sec
	Attempt to maintain this bit rate by inserting TS null packets, if
	necessary.  Default: 4096.

pcr_pid,
	PCR PID for all channels.  Default: 0x200.

mux_buf_sz_pkts,
	Size for the mux buffer in multiples of 188 bytes.

vidtv internal structure
------------------------
The kernel modules are split in the following way:

vidtv_tuner.[ch]
	Implements a fake tuner DVB driver.

vidtv_demod.[ch]
	Implements a fake demodulator DVB driver.

vidtv_bridge.[ch]
	Implements a bridge driver.

The MPEG related code is split in the following way:

vidtv_ts.[ch]
	Code to work with MPEG TS packets, such as TS headers, adaptation
	fields, PCR packets and NULL packets.

vidtv_psi.[ch]
	This is the PSI generator.  PSI packets contain general information
	about a MPEG Transport Stream.  A PSI generator is needed so
	userspace apps can retrieve information about the Transport Stream
	and eventually tune into a (dummy) channel.

	Because the generator is implemented in a separate file, it can be
	reused elsewhere in the media subsystem.

	Currently vidtv supports working with 5 PSI tables: PAT, PMT,
	SDT, NIT and EIT.

	The specification for PAT and PMT can be found in *ISO 13818-1:
	Systems*, while the specification for the SDT, NIT, EIT can be found in *ETSI
	EN 300 468: Specification for Service Information (SI) in DVB
	systems*.

	It isn't strictly necessary, but using a real TS file helps when
	debugging PSI tables. Vidtv currently tries to replicate the PSI
	structure found in this file: `TS1Globo.ts
	<https://tsduck.io/streams/brazil-isdb-tb/TS1globo.ts>`_.

	A good way to visualize the structure of streams is by using
	`DVBInspector <https://sourceforge.net/projects/dvbinspector/>`_.

vidtv_pes.[ch]
	Implements the PES logic to convert encoder data into MPEG TS
	packets. These can then be fed into a TS multiplexer and eventually
	into userspace.

vidtv_encoder.h
	An interface for vidtv encoders. New encoders can be added to this
	driver by implementing the calls in this file.

vidtv_s302m.[ch]
	Implements a S302M encoder to make it possible to insert PCM audio
	data in the generated MPEG Transport Stream. The relevant
	specification is available online as *SMPTE 302M-2007: Television -
	Mapping of AES3 Data into MPEG-2 Transport Stream*.

	The resulting MPEG Elementary Stream is conveyed in a private
	stream with a S302M registration descriptor attached.

	This shall enable passing an audio signal into userspace so it can
	be decoded and played by media software. The corresponding decoder
	in ffmpeg is located in 'libavcodec/s302m.c' and is experimental.

vidtv_channel.[ch]
	Implements a 'channel' abstraction.

	When vidtv boots, it will create some hardcoded channels:

	#. Their services will be concatenated to populate the SDT.

	#. Their programs will be concatenated to populate the PAT

	#. Their events will be concatenated to populate the EIT

	#. For each program in the PAT, a PMT section will be created

	#. The PMT section for a channel will be assigned its streams.

	#. Every stream will have its corresponding encoder polled in a
	   loop to produce TS packets.
	   These packets may be interleaved by the muxer and then delivered
	   to the bridge.

vidtv_mux.[ch]
	Implements a MPEG TS mux, loosely based on the ffmpeg
	implementation in "libavcodec/mpegtsenc.c"

	The muxer runs a loop which is responsible for:

	#. Keeping track of the amount of time elapsed since the last
	   iteration.

	#. Polling encoders in order to fetch 'elapsed_time' worth of data.

	#. Inserting PSI and/or PCR packets, if needed.

	#. Padding the resulting stream with NULL packets if
	   necessary in order to maintain the chosen bit rate.

	#. Delivering the resulting TS packets to the bridge
	   driver so it can pass them to the demux.

Testing vidtv with v4l-utils
----------------------------

Using the tools in v4l-utils is a great way to test and inspect the output of
vidtv. It is hosted here: `v4l-utils Documentation
<https://linuxtv.org/wiki/index.php/V4l-utils>`_.

From its webpage::

	The v4l-utils are a series of packages for handling media devices.

	It is hosted at http://git.linuxtv.org/v4l-utils.git, and packaged
	on most distributions.

	It provides a series of libraries and utilities to be used to
	control several aspect of the media boards.

Start by installing v4l-utils and then modprobing vidtv::

	modprobe dvb_vidtv_bridge

If the driver is OK, it should load and its probing code will run. This will
pull in the tuner and demod drivers.

Using dvb-fe-tool
~~~~~~~~~~~~~~~~~

The first step to check whether the demod loaded successfully is to run::

	$ dvb-fe-tool
	Device Dummy demod for DVB-T/T2/C/S/S2 (/dev/dvb/adapter0/frontend0) capabilities:
	    CAN_FEC_1_2
	    CAN_FEC_2_3
	    CAN_FEC_3_4
	    CAN_FEC_4_5
	    CAN_FEC_5_6
	    CAN_FEC_6_7
	    CAN_FEC_7_8
	    CAN_FEC_8_9
	    CAN_FEC_AUTO
	    CAN_GUARD_INTERVAL_AUTO
	    CAN_HIERARCHY_AUTO
	    CAN_INVERSION_AUTO
	    CAN_QAM_16
	    CAN_QAM_32
	    CAN_QAM_64
	    CAN_QAM_128
	    CAN_QAM_256
	    CAN_QAM_AUTO
	    CAN_QPSK
	    CAN_TRANSMISSION_MODE_AUTO
	DVB API Version 5.11, Current v5 delivery system: DVBC/ANNEX_A
	Supported delivery systems:
	    DVBT
	    DVBT2
	    [DVBC/ANNEX_A]
	    DVBS
	    DVBS2
	Frequency range for the current standard:
	From:            51.0 MHz
	To:              2.15 GHz
	Step:            62.5 kHz
	Tolerance:       29.5 MHz
	Symbol rate ranges for the current standard:
	From:            1.00 MBauds
	To:              45.0 MBauds

This should return what is currently set up at the demod struct, i.e.::

	static const struct dvb_frontend_ops vidtv_demod_ops = {
		.delsys = {
			SYS_DVBT,
			SYS_DVBT2,
			SYS_DVBC_ANNEX_A,
			SYS_DVBS,
			SYS_DVBS2,
		},

		.info = {
			.name                   = "Dummy demod for DVB-T/T2/C/S/S2",
			.frequency_min_hz       = 51 * MHz,
			.frequency_max_hz       = 2150 * MHz,
			.frequency_stepsize_hz  = 62500,
			.frequency_tolerance_hz = 29500 * kHz,
			.symbol_rate_min        = 1000000,
			.symbol_rate_max        = 45000000,

			.caps = FE_CAN_FEC_1_2 |
				FE_CAN_FEC_2_3 |
				FE_CAN_FEC_3_4 |
				FE_CAN_FEC_4_5 |
				FE_CAN_FEC_5_6 |
				FE_CAN_FEC_6_7 |
				FE_CAN_FEC_7_8 |
				FE_CAN_FEC_8_9 |
				FE_CAN_QAM_16 |
				FE_CAN_QAM_64 |
				FE_CAN_QAM_32 |
				FE_CAN_QAM_128 |
				FE_CAN_QAM_256 |
				FE_CAN_QAM_AUTO |
				FE_CAN_QPSK |
				FE_CAN_FEC_AUTO |
				FE_CAN_INVERSION_AUTO |
				FE_CAN_TRANSMISSION_MODE_AUTO |
				FE_CAN_GUARD_INTERVAL_AUTO |
				FE_CAN_HIERARCHY_AUTO,
		}

		....

For more information on dvb-fe-tools check its online documentation here:
`dvb-fe-tool Documentation
<https://www.linuxtv.org/wiki/index.php/Dvb-fe-tool>`_.

Using dvb-scan
~~~~~~~~~~~~~~

In order to tune into a channel and read the PSI tables, we can use dvb-scan.

For this, one should provide a configuration file known as a 'scan file',
here's an example::

	[Channel]
	FREQUENCY = 474000000
	MODULATION = QAM/AUTO
	SYMBOL_RATE = 6940000
	INNER_FEC = AUTO
	DELIVERY_SYSTEM = DVBC/ANNEX_A

.. note::
	The parameters depend on the video standard you're testing.

.. note::
	Vidtv is a fake driver and does not validate much of the information
	in the scan file. Just specifying 'FREQUENCY' and 'DELIVERY_SYSTEM'
	should be enough for DVB-T/DVB-T2. For DVB-S/DVB-C however, you
	should also provide 'SYMBOL_RATE'.

You can browse scan tables online here: `dvb-scan-tables
<https://git.linuxtv.org/dtv-scan-tables.git>`_.

Assuming this channel is named 'channel.conf', you can then run::

	$ dvbv5-scan channel.conf
	dvbv5-scan ~/vidtv.conf
	ERROR    command BANDWIDTH_HZ (5) not found during retrieve
	Cannot calc frequency shift. Either bandwidth/symbol-rate is unavailable (yet).
	Scanning frequency #1 330000000
	    (0x00) Signal= -68.00dBm
	Scanning frequency #2 474000000
	Lock   (0x1f) Signal= -34.45dBm C/N= 33.74dB UCB= 0
	Service Beethoven, provider LinuxTV.org: digital television

For more information on dvb-scan, check its documentation online here:
`dvb-scan Documentation <https://www.linuxtv.org/wiki/index.php/Dvbscan>`_.

Using dvb-zap
~~~~~~~~~~~~~

dvbv5-zap is a command line tool that can be used to record MPEG-TS to disk. The
typical use is to tune into a channel and put it into record mode. The example
below - which is taken from the documentation - illustrates that\ [1]_::

	$ dvbv5-zap -c dvb_channel.conf "beethoven" -o music.ts -P -t 10
	using demux 'dvb0.demux0'
	reading channels from file 'dvb_channel.conf'
	tuning to 474000000 Hz
	pass all PID's to TS
	dvb_set_pesfilter 8192
	dvb_dev_set_bufsize: buffer set to 6160384
	Lock   (0x1f) Quality= Good Signal= -34.66dBm C/N= 33.41dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
	Lock   (0x1f) Quality= Good Signal= -34.57dBm C/N= 33.46dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
	Record to file 'music.ts' started
	received 24587768 bytes (2401 Kbytes/sec)
	Lock   (0x1f) Quality= Good Signal= -34.42dBm C/N= 33.89dB UCB= 0 postBER= 0 preBER= 2.44x10^-3 PER= 0

.. [1] In this example, it records 10 seconds with all program ID's stored
       at the music.ts file.

The channel can be watched by playing the contents of the stream with some
player that  recognizes the MPEG-TS format, such as ``mplayer`` or ``vlc``.

By playing the contents of the stream one can visually inspect the workings of
vidtv, e.g., to play a recorded TS file with::

	$ mplayer music.ts

or, alternatively, running this command on one terminal::

	$ dvbv5-zap -c dvb_channel.conf "beethoven" -P -r &

And, on a second terminal, playing the contents from DVR interface with::

	$ mplayer /dev/dvb/adapter0/dvr0

For more information on dvb-zap check its online documentation here:
`dvb-zap Documentation
<https://www.linuxtv.org/wiki/index.php/Dvbv5-zap>`_.
See also: `zap <https://www.linuxtv.org/wiki/index.php/Zap>`_.

What can still be improved in vidtv
-----------------------------------

Add *debugfs* integration
~~~~~~~~~~~~~~~~~~~~~~~~~

Although frontend drivers provide DVBv5 statistics via the .read_status
call, a nice addition would be to make additional statistics available to
userspace via debugfs, which is a simple-to-use, RAM-based filesystem
specifically designed for debug purposes.

The logic for this would be implemented on a separate file so as not to
pollute the frontend driver.  These statistics are driver-specific and can
be useful during tests.

The Siano driver is one example of a driver using
debugfs to convey driver-specific statistics to userspace and it can be
used as a reference.

This should be further enabled and disabled via a Kconfig
option for convenience.

Add a way to test video
~~~~~~~~~~~~~~~~~~~~~~~

Currently, vidtv can only encode PCM audio. It would be great to implement
a barebones version of MPEG-2 video encoding so we can also test video. The
first place to look into is *ISO 13818-2: Information technology — Generic
coding of moving pictures and associated audio information — Part 2: Video*,
which covers the encoding of compressed video in MPEG Transport Streams.

This might optionally use the Video4Linux2 Test Pattern Generator, v4l2-tpg,
which resides at::

	drivers/media/common/v4l2-tpg/

Add white noise simulation
~~~~~~~~~~~~~~~~~~~~~~~~~~

The vidtv tuner already has code to identify whether the chosen frequency
is too far away from a table of valid frequencies. For now, this means that
the demodulator can eventually lose the lock on the signal, since the tuner will
report a bad signal quality.

A nice addition is to simulate some noise when the signal quality is bad by:

- Randomly dropping some TS packets. This will trigger a continuity error if the
  continuity counter is updated but the packet is not passed on to the demux.

- Updating the error statistics accordingly (e.g. BER, etc).

- Simulating some noise in the encoded data.

Functions and structs used within vidtv
---------------------------------------

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_bridge.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_channel.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_demod.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_encoder.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_mux.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_pes.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_psi.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_s302m.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_ts.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_tuner.h

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_common.c

.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_tuner.c


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

The Virtual Media Controller Driver (vimc)
==========================================

Source code documentation
-------------------------

vimc-streamer
~~~~~~~~~~~~~

.. kernel-doc:: drivers/media/test-drivers/vimc/vimc-streamer.h
   :internal:

.. kernel-doc:: drivers/media/test-drivers/vimc/vimc-streamer.c


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

The Zoran driver
================

unified zoran driver (zr360x7, zoran, buz, dc10(+), dc30(+), lml33)

website: http://mjpeg.sourceforge.net/driver-zoran/

Frequently Asked Questions
--------------------------

What cards are supported
------------------------

Iomega Buz, Linux Media Labs LML33/LML33R10, Pinnacle/Miro
DC10/DC10+/DC30/DC30+ and related boards (available under various names).

Iomega Buz
~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36060 MJPEG codec
* Philips saa7111 TV decoder
* Philips saa7185 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, saa7111, saa7185, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 7

AverMedia 6 Eyes AVS6EYES
~~~~~~~~~~~~~~~~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36060 MJPEG codec
* Samsung ks0127 TV decoder
* Conexant bt866  TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, ks0127, bt866, zr36060, zr36067

Inputs/outputs:
	Six physical inputs. 1-6 are composite,
	1-2, 3-4, 5-6 doubles as S-video,
	1-3 triples as component.
	One composite output.

Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 8

.. note::

   Not autodetected, card=8 is necessary.

Linux Media Labs LML33
~~~~~~~~~~~~~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36060 MJPEG codec
* Brooktree bt819 TV decoder
* Brooktree bt856 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, bt819, bt856, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 5

Linux Media Labs LML33R10
~~~~~~~~~~~~~~~~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36060 MJPEG codec
* Philips saa7114 TV decoder
* Analog Devices adv7170 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, saa7114, adv7170, zr36060, zr36067

Inputs/outputs: Composite and S-video

Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)

Card number: 6

Pinnacle/Miro DC10(new)
~~~~~~~~~~~~~~~~~~~~~~~

* Zoran zr36057 PCI controller
* Zoran zr36060 MJPEG codec
* Philips saa7110a TV decoder
* Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, saa7110, adv7175, zr36060, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 1

Pinnacle/Miro DC10+
~~~~~~~~~~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36060 MJPEG codec
* Philips saa7110a TV decoder
* Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, saa7110, adv7175, zr36060, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 2

Pinnacle/Miro DC10(old)
~~~~~~~~~~~~~~~~~~~~~~~

* Zoran zr36057 PCI controller
* Zoran zr36050 MJPEG codec
* Zoran zr36016 Video Front End or Fuji md0211 Video Front End (clone?)
* Micronas vpx3220a TV decoder
* mse3000 TV encoder or Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, vpx3220, mse3000/adv7175, zr36050, zr36016, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 0

Pinnacle/Miro DC30
~~~~~~~~~~~~~~~~~~

* Zoran zr36057 PCI controller
* Zoran zr36050 MJPEG codec
* Zoran zr36016 Video Front End
* Micronas vpx3225d/vpx3220a/vpx3216b TV decoder
* Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36016, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 3

Pinnacle/Miro DC30+
~~~~~~~~~~~~~~~~~~~

* Zoran zr36067 PCI controller
* Zoran zr36050 MJPEG codec
* Zoran zr36016 Video Front End
* Micronas vpx3225d/vpx3220a/vpx3216b TV decoder
* Analog Devices adv7176 TV encoder

Drivers to use: videodev, i2c-core, i2c-algo-bit,
videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36015, zr36067

Inputs/outputs: Composite, S-video and Internal

Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)

Card number: 4

.. note::

   #) No module for the mse3000 is available yet
   #) No module for the vpx3224 is available yet

1.1 What the TV decoder can do an what not
------------------------------------------

The best know TV standards are NTSC/PAL/SECAM. but for decoding a frame that
information is not enough. There are several formats of the TV standards.
And not every TV decoder is able to handle every format. Also the every
combination is supported by the driver. There are currently 11 different
tv broadcast formats all aver the world.

The CCIR defines parameters needed for broadcasting the signal.
The CCIR has defined different standards: A,B,D,E,F,G,D,H,I,K,K1,L,M,N,...
The CCIR says not much about the colorsystem used !!!
And talking about a colorsystem says not to much about how it is broadcast.

The CCIR standards A,E,F are not used any more.

When you speak about NTSC, you usually mean the standard: CCIR - M using
the NTSC colorsystem which is used in the USA, Japan, Mexico, Canada
and a few others.

When you talk about PAL, you usually mean: CCIR - B/G using the PAL
colorsystem which is used in many Countries.

When you talk about SECAM, you mean: CCIR - L using the SECAM Colorsystem
which is used in France, and a few others.

There the other version of SECAM, CCIR - D/K is used in Bulgaria, China,
Slovakai, Hungary, Korea (Rep.), Poland, Rumania and a others.

The CCIR - H uses the PAL colorsystem (sometimes SECAM) and is used in
Egypt, Libya, Sri Lanka, Syrain Arab. Rep.

The CCIR - I uses the PAL colorsystem, and is used in Great Britain, Hong Kong,
Ireland, Nigeria, South Africa.

The CCIR - N uses the PAL colorsystem and PAL frame size but the NTSC framerate,
and is used in Argentinia, Uruguay, an a few others

We do not talk about how the audio is broadcast !

A rather good sites about the TV standards are:
http://www.sony.jp/support/
http://info.electronicwerkstatt.de/bereiche/fernsehtechnik/frequenzen_und_normen/Fernsehnormen/
and http://www.cabl.com/restaurant/channel.html

Other weird things around: NTSC 4.43 is a modificated NTSC, which is mainly
used in PAL VCR's that are able to play back NTSC. PAL 60 seems to be the same
as NTSC 4.43 . The Datasheets also talk about NTSC 44, It seems as if it would
be the same as NTSC 4.43.
NTSC Combs seems to be a decoder mode where the decoder uses a comb filter
to split coma and luma instead of a Delay line.

But I did not defiantly find out what NTSC Comb is.

Philips saa7111 TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1997, is used in the BUZ and
- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC N, NTSC 4.43 and SECAM

Philips saa7110a TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1995, is used in the Pinnacle/Miro DC10(new), DC10+ and
- can handle: PAL B/G, NTSC M and SECAM

Philips saa7114 TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 2000, is used in the LML33R10 and
- can handle: PAL B/G/D/H/I/N, PAL N, PAL M, NTSC M, NTSC 4.43 and SECAM

Brooktree bt819 TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1996, and is used in the LML33 and
- can handle: PAL B/D/G/H/I, NTSC M

Micronas vpx3220a TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1996, is used in the DC30 and DC30+ and
- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC 44, PAL 60, SECAM,NTSC Comb

Samsung ks0127 TV decoder
~~~~~~~~~~~~~~~~~~~~~~~~~

- is used in the AVS6EYES card and
- can handle: NTSC-M/N/44, PAL-M/N/B/G/H/I/D/K/L and SECAM

What the TV encoder can do an what not
--------------------------------------

The TV encoder is doing the "same" as the decoder, but in the other direction.
You feed them digital data and the generate a Composite or SVHS signal.
For information about the colorsystems and TV norm take a look in the
TV decoder section.

Philips saa7185 TV Encoder
~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1996, is used in the BUZ
- can generate: PAL B/G, NTSC M

Brooktree bt856 TV Encoder
~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1994, is used in the LML33
- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL-N (Argentina)

Analog Devices adv7170 TV Encoder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 2000, is used in the LML300R10
- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL 60

Analog Devices adv7175 TV Encoder
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1996, is used in the DC10, DC10+, DC10 old, DC30, DC30+
- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M

ITT mse3000 TV encoder
~~~~~~~~~~~~~~~~~~~~~~

- was introduced in 1991, is used in the DC10 old
- can generate: PAL , NTSC , SECAM

Conexant bt866 TV encoder
~~~~~~~~~~~~~~~~~~~~~~~~~

- is used in AVS6EYES, and
- can generate: NTSC/PAL, PAL-M, PAL-N

The adv717x, should be able to produce PAL N. But you find nothing PAL N
specific in the registers. Seem that you have to reuse a other standard
to generate PAL N, maybe it would work if you use the PAL M settings.

How do I get this damn thing to work
------------------------------------

Load zr36067.o. If it can't autodetect your card, use the card=X insmod
option with X being the card number as given in the previous section.
To have more than one card, use card=X1[,X2[,X3,[X4[..]]]]

To automate this, add the following to your /etc/modprobe.d/zoran.conf:

options zr36067 card=X1[,X2[,X3[,X4[..]]]]
alias char-major-81-0 zr36067

One thing to keep in mind is that this doesn't load zr36067.o itself yet. It
just automates loading. If you start using xawtv, the device won't load on
some systems, since you're trying to load modules as a user, which is not
allowed ("permission denied"). A quick workaround is to add 'Load "v4l"' to
XF86Config-4 when you use X by default, or to run 'v4l-conf -c <device>' in
one of your startup scripts (normally rc.local) if you don't use X. Both
make sure that the modules are loaded on startup, under the root account.

What mainboard should I use (or why doesn't my card work)
---------------------------------------------------------

<insert lousy disclaimer here>. In short: good=SiS/Intel, bad=VIA.

Experience tells us that people with a Buz, on average, have more problems
than users with a DC10+/LML33. Also, it tells us that people owning a VIA-
based mainboard (ktXXX, MVP3) have more problems than users with a mainboard
based on a different chipset. Here's some notes from Andrew Stevens:

Here's my experience of using LML33 and Buz on various motherboards:

- VIA MVP3
	- Forget it. Pointless. Doesn't work.
- Intel 430FX (Pentium 200)
	- LML33 perfect, Buz tolerable (3 or 4 frames dropped per movie)
- Intel 440BX (early stepping)
	- LML33 tolerable. Buz starting to get annoying (6-10 frames/hour)
- Intel 440BX (late stepping)
	- Buz tolerable, LML3 almost perfect (occasional single frame drops)
- SiS735
	- LML33 perfect, Buz tolerable.
- VIA KT133(*)
	- LML33 starting to get annoying, Buz poor enough that I have up.

- Both 440BX boards were dual CPU versions.

Bernhard Praschinger later added:

- AMD 751
	- Buz perfect-tolerable
- AMD 760
	- Buz perfect-tolerable

In general, people on the user mailinglist won't give you much of a chance
if you have a VIA-based motherboard. They may be cheap, but sometimes, you'd
rather want to spend some more money on better boards. In general, VIA
mainboard's IDE/PCI performance will also suck badly compared to others.
You'll noticed the DC10+/DC30+ aren't mentioned anywhere in the overview.
Basically, you can assume that if the Buz works, the LML33 will work too. If
the LML33 works, the DC10+/DC30+ will work too. They're most tolerant to
different mainboard chipsets from all of the supported cards.

If you experience timeouts during capture, buy a better mainboard or lower
the quality/buffersize during capture (see 'Concerning buffer sizes, quality,
output size etc.'). If it hangs, there's little we can do as of now. Check
your IRQs and make sure the card has its own interrupts.

Programming interface
---------------------

This driver conforms to video4linux2. Support for V4L1 and for the custom
zoran ioctls has been removed in kernel 2.6.38.

For programming example, please, look at lavrec.c and lavplay.c code in
the MJPEG-tools (http://mjpeg.sf.net/).

Additional notes for software developers:

   The driver returns maxwidth and maxheight parameters according to
   the current TV standard (norm). Therefore, the software which
   communicates with the driver and "asks" for these parameters should
   first set the correct norm. Well, it seems logically correct: TV
   standard is "more constant" for current country than geometry
   settings of a variety of TV capture cards which may work in ITU or
   square pixel format.

Applications
------------

Applications known to work with this driver:

TV viewing:

* xawtv
* kwintv
* probably any TV application that supports video4linux or video4linux2.

MJPEG capture/playback:

* mjpegtools/lavtools (or Linux Video Studio)
* gstreamer
* mplayer

General raw capture:

* xawtv
* gstreamer
* probably any application that supports video4linux or video4linux2

Video editing:

* Cinelerra
* MainActor
* mjpegtools (or Linux Video Studio)

Concerning buffer sizes, quality, output size etc.
--------------------------------------------------

The zr36060 can do 1:2 JPEG compression. This is really the theoretical
maximum that the chipset can reach. The driver can, however, limit compression
to a maximum (size) of 1:4. The reason for this is that some cards (e.g. Buz)
can't handle 1:2 compression without stopping capture after only a few minutes.
With 1:4, it'll mostly work. If you have a Buz, use 'low_bitrate=1' to go into
1:4 max. compression mode.

100% JPEG quality is thus 1:2 compression in practice. So for a full PAL frame
(size 720x576). The JPEG fields are stored in YUY2 format, so the size of the
fields are 720x288x16/2 bits/field (2 fields/frame) = 207360 bytes/field x 2 =
414720 bytes/frame (add some more bytes for headers and DHT (huffman)/DQT
(quantization) tables, and you'll get to something like 512kB per frame for
1:2 compression. For 1:4 compression, you'd have frames of half this size.

Some additional explanation by Martin Samuelsson, which also explains the
importance of buffer sizes:
--
> Hmm, I do not think it is really that way. With the current (downloaded
> at 18:00 Monday) driver I get that output sizes for 10 sec:
> -q 50 -b 128 : 24.283.332 Bytes
> -q 50 -b 256 : 48.442.368
> -q 25 -b 128 : 24.655.992
> -q 25 -b 256 : 25.859.820

I woke up, and can't go to sleep again. I'll kill some time explaining why
this doesn't look strange to me.

Let's do some math using a width of 704 pixels. I'm not sure whether the Buz
actually use that number or not, but that's not too important right now.

704x288 pixels, one field, is 202752 pixels. Divided by 64 pixels per block;
3168 blocks per field. Each pixel consist of two bytes; 128 bytes per block;
1024 bits per block. 100% in the new driver mean 1:2 compression; the maximum
output becomes 512 bits per block. Actually 510, but 512 is simpler to use
for calculations.

Let's say that we specify d1q50. We thus want 256 bits per block; times 3168
becomes 811008 bits; 101376 bytes per field. We're talking raw bits and bytes
here, so we don't need to do any fancy corrections for bits-per-pixel or such
things. 101376 bytes per field.

d1 video contains two fields per frame. Those sum up to 202752 bytes per
frame, and one of those frames goes into each buffer.

But wait a second! -b128 gives 128kB buffers! It's not possible to cram
202752 bytes of JPEG data into 128kB!

This is what the driver notice and automatically compensate for in your
examples. Let's do some math using this information:

128kB is 131072 bytes. In this buffer, we want to store two fields, which
leaves 65536 bytes for each field. Using 3168 blocks per field, we get
20.68686868... available bytes per block; 165 bits. We can't allow the
request for 256 bits per block when there's only 165 bits available! The -q50
option is silently overridden, and the -b128 option takes precedence, leaving
us with the equivalence of -q32.

This gives us a data rate of 165 bits per block, which, times 3168, sums up
to 65340 bytes per field, out of the allowed 65536. The current driver has
another level of rate limiting; it won't accept -q values that fill more than
6/8 of the specified buffers. (I'm not sure why. "Playing it safe" seem to be
a safe bet. Personally, I think I would have lowered requested-bits-per-block
by one, or something like that.) We can't use 165 bits per block, but have to
lower it again, to 6/8 of the available buffer space: We end up with 124 bits
per block, the equivalence of -q24. With 128kB buffers, you can't use greater
than -q24 at -d1. (And PAL, and 704 pixels width...)

The third example is limited to -q24 through the same process. The second
example, using very similar calculations, is limited to -q48. The only
example that actually grab at the specified -q value is the last one, which
is clearly visible, looking at the file size.
--

Conclusion: the quality of the resulting movie depends on buffer size, quality,
whether or not you use 'low_bitrate=1' as insmod option for the zr36060.c
module to do 1:4 instead of 1:2 compression, etc.

If you experience timeouts, lowering the quality/buffersize or using
'low_bitrate=1 as insmod option for zr36060.o might actually help, as is
proven by the Buz.

It hangs/crashes/fails/whatevers! Help!
---------------------------------------

Make sure that the card has its own interrupts (see /proc/interrupts), check
the output of dmesg at high verbosity (load zr36067.o with debug=2,
load all other modules with debug=1). Check that your mainboard is favorable
(see question 2) and if not, test the card in another computer. Also see the
notes given in question 3 and try lowering quality/buffersize/capturesize
if recording fails after a period of time.

If all this doesn't help, give a clear description of the problem including
detailed hardware information (memory+brand, mainboard+chipset+brand, which
MJPEG card, processor, other PCI cards that might be of interest), give the
system PnP information (/proc/interrupts, /proc/dma, /proc/devices), and give
the kernel version, driver version, glibc version, gcc version and any other
information that might possibly be of interest. Also provide the dmesg output
at high verbosity. See 'Contacting' on how to contact the developers.

Maintainers/Contacting
----------------------

Previous maintainers/developers of this driver are
- Laurent Pinchart <laurent.pinchart@skynet.be>
- Ronald Bultje rbultje@ronald.bitfreak.net
- Serguei Miridonov <mirsev@cicese.mx>
- Wolfgang Scherr <scherr@net4you.net>
- Dave Perks <dperks@ibm.net>
- Rainer Johanni <Rainer@Johanni.de>

Driver's License
----------------

    This driver is distributed under the terms of the General Public License.

    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; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

See http://www.gnu.org/ for more information.


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

Digital TV Conditional Access kABI
----------------------------------

.. kernel-doc:: include/media/dvb_ca_en50221.h


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

Digital TV Common functions
---------------------------

Math functions
~~~~~~~~~~~~~~

Provide some commonly-used math functions, usually required in order to
estimate signal strength and signal to noise measurements in dB.

.. kernel-doc:: include/media/dvb_math.h

DVB devices
~~~~~~~~~~~

Those functions are responsible for handling the DVB device nodes.

.. kernel-doc:: include/media/dvbdev.h

Digital TV Ring buffer
~~~~~~~~~~~~~~~~~~~~~~

Those routines implement ring buffers used to handle digital TV data and
copy it from/to userspace.

.. note::

  1) For performance reasons read and write routines don't check buffer sizes
     and/or number of bytes free/available. This has to be done before these
     routines are called. For example:

   .. code-block:: c

        /* write @buflen: bytes */
        free = dvb_ringbuffer_free(rbuf);
        if (free >= buflen)
                count = dvb_ringbuffer_write(rbuf, buffer, buflen);
        else
                /* do something */

        /* read min. 1000, max. @bufsize: bytes */
        avail = dvb_ringbuffer_avail(rbuf);
        if (avail >= 1000)
                count = dvb_ringbuffer_read(rbuf, buffer, min(avail, bufsize));
        else
                /* do something */

  2) If there is exactly one reader and one writer, there is no need
     to lock read or write operations.
     Two or more readers must be locked against each other.
     Flushing the buffer counts as a read operation.
     Resetting the buffer counts as a read and write operation.
     Two or more writers must be locked against each other.

.. kernel-doc:: include/media/dvb_ringbuffer.h

Digital TV VB2 handler
~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/dvb_vb2.h


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

Digital TV (DVB) devices
------------------------

Digital TV devices are implemented by several different drivers:

- A bridge driver that is responsible to talk with the bus where the other
  devices are connected (PCI, USB, SPI), bind to the other drivers and
  implement the digital demux logic (either in software or in hardware);

- Frontend drivers that are usually implemented as two separate drivers:

  - A tuner driver that implements the logic which commands the part of
    the hardware responsible for tuning into a digital TV transponder or
    physical channel. The output of a tuner is usually a baseband or
    Intermediate Frequency (IF) signal;

  - A demodulator driver (a.k.a "demod") that implements the logic which
    commands the digital TV decoding hardware. The output of a demod is
    a digital stream, with multiple audio, video and data channels typically
    multiplexed using MPEG Transport Stream [#f1]_.

On most hardware, the frontend drivers talk with the bridge driver using an
I2C bus.

.. [#f1] Some standards use TCP/IP for multiplexing data, like DVB-H (an
   abandoned standard, not used anymore) and ATSC version 3.0 current
   proposals. Currently, the DVB subsystem doesn't implement those standards.

.. toctree::
    :maxdepth: 1

    dtv-common
    dtv-frontend
    dtv-demux
    dtv-ca
    dtv-net


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

Digital TV Demux kABI
---------------------

Digital TV Demux
~~~~~~~~~~~~~~~~

The Kernel Digital TV Demux kABI defines a driver-internal interface for
registering low-level, hardware specific driver to a hardware independent
demux layer. It is only of interest for Digital TV device driver writers.
The header file for this kABI is named ``demux.h`` and located in
``include/media``.

The demux kABI should be implemented for each demux in the system. It is
used to select the TS source of a demux and to manage the demux resources.
When the demux client allocates a resource via the demux kABI, it receives
a pointer to the kABI of that resource.

Each demux receives its TS input from a DVB front-end or from memory, as
set via this demux kABI. In a system with more than one front-end, the kABI
can be used to select one of the DVB front-ends as a TS source for a demux,
unless this is fixed in the HW platform.

The demux kABI only controls front-ends regarding to their connections with
demuxes; the kABI used to set the other front-end parameters, such as
tuning, are devined via the Digital TV Frontend kABI.

The functions that implement the abstract interface demux should be defined
static or module private and registered to the Demux core for external
access. It is not necessary to implement every function in the struct
:c:type:`dmx_demux`. For example, a demux interface might support Section filtering,
but not PES filtering. The kABI client is expected to check the value of any
function pointer before calling the function: the value of ``NULL`` means
that the function is not available.

Whenever the functions of the demux API modify shared data, the
possibilities of lost update and race condition problems should be
addressed, e.g. by protecting parts of code with mutexes.

Note that functions called from a bottom half context must not sleep.
Even a simple memory allocation without using ``GFP_ATOMIC`` can result in a
kernel thread being put to sleep if swapping is needed. For example, the
Linux Kernel calls the functions of a network device interface from a
bottom half context. Thus, if a demux kABI function is called from network
device code, the function must not sleep.

Demux Callback API
~~~~~~~~~~~~~~~~~~

This kernel-space API comprises the callback functions that deliver filtered
data to the demux client. Unlike the other DVB kABIs, these functions are
provided by the client and called from the demux code.

The function pointers of this abstract interface are not packed into a
structure as in the other demux APIs, because the callback functions are
registered and used independent of each other. As an example, it is possible
for the API client to provide several callback functions for receiving TS
packets and no callbacks for PES packets or sections.

The functions that implement the callback API need not be re-entrant: when
a demux driver calls one of these functions, the driver is not allowed to
call the function again before the original call returns. If a callback is
triggered by a hardware interrupt, it is recommended to use the Linux
bottom half mechanism or start a tasklet instead of making the callback
function call directly from a hardware interrupt.

This mechanism is implemented by :c:func:`dmx_ts_cb()` and :c:func:`dmx_section_cb()`
callbacks.

Digital TV Demux device registration functions and data structures
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/dmxdev.h

High-level Digital TV demux interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/dvb_demux.h

Driver-internal low-level hardware specific driver demux interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/demux.h


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

Digital TV Frontend kABI
------------------------

Digital TV Frontend
~~~~~~~~~~~~~~~~~~~

The Digital TV Frontend kABI defines a driver-internal interface for
registering low-level, hardware specific driver to a hardware independent
frontend layer. It is only of interest for Digital TV device driver writers.
The header file for this API is named ``dvb_frontend.h`` and located in
``include/media/``.

Demodulator driver
^^^^^^^^^^^^^^^^^^

The demodulator driver is responsible for talking with the decoding part of the
hardware. Such driver should implement :c:type:`dvb_frontend_ops`, which
tells what type of digital TV standards are supported, and points to a
series of functions that allow the DVB core to command the hardware via
the code under ``include/media/dvb_frontend.c``.

A typical example of such struct in a driver ``foo`` is::

	static struct dvb_frontend_ops foo_ops = {
		.delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
		.info = {
			.name	= "foo DVB-T/T2/C driver",
			.caps = FE_CAN_FEC_1_2 |
				FE_CAN_FEC_2_3 |
				FE_CAN_FEC_3_4 |
				FE_CAN_FEC_5_6 |
				FE_CAN_FEC_7_8 |
				FE_CAN_FEC_AUTO |
				FE_CAN_QPSK |
				FE_CAN_QAM_16 |
				FE_CAN_QAM_32 |
				FE_CAN_QAM_64 |
				FE_CAN_QAM_128 |
				FE_CAN_QAM_256 |
				FE_CAN_QAM_AUTO |
				FE_CAN_TRANSMISSION_MODE_AUTO |
				FE_CAN_GUARD_INTERVAL_AUTO |
				FE_CAN_HIERARCHY_AUTO |
				FE_CAN_MUTE_TS |
				FE_CAN_2G_MODULATION,
			.frequency_min = 42000000, /* Hz */
			.frequency_max = 1002000000, /* Hz */
			.symbol_rate_min = 870000,
			.symbol_rate_max = 11700000
		},
		.init = foo_init,
		.sleep = foo_sleep,
		.release = foo_release,
		.set_frontend = foo_set_frontend,
		.get_frontend = foo_get_frontend,
		.read_status = foo_get_status_and_stats,
		.tune = foo_tune,
		.i2c_gate_ctrl = foo_i2c_gate_ctrl,
		.get_frontend_algo = foo_get_algo,
	};

A typical example of such struct in a driver ``bar`` meant to be used on
Satellite TV reception is::

	static const struct dvb_frontend_ops bar_ops = {
		.delsys = { SYS_DVBS, SYS_DVBS2 },
		.info = {
			.name		= "Bar DVB-S/S2 demodulator",
			.frequency_min	= 500000, /* KHz */
			.frequency_max	= 2500000, /* KHz */
			.frequency_stepsize	= 0,
			.symbol_rate_min = 1000000,
			.symbol_rate_max = 45000000,
			.symbol_rate_tolerance = 500,
			.caps = FE_CAN_INVERSION_AUTO |
				FE_CAN_FEC_AUTO |
				FE_CAN_QPSK,
		},
		.init = bar_init,
		.sleep = bar_sleep,
		.release = bar_release,
		.set_frontend = bar_set_frontend,
		.get_frontend = bar_get_frontend,
		.read_status = bar_get_status_and_stats,
		.i2c_gate_ctrl = bar_i2c_gate_ctrl,
		.get_frontend_algo = bar_get_algo,
		.tune = bar_tune,

		/* Satellite-specific */
		.diseqc_send_master_cmd = bar_send_diseqc_msg,
		.diseqc_send_burst = bar_send_burst,
		.set_tone = bar_set_tone,
		.set_voltage = bar_set_voltage,
	};

.. note::

   #) For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the
      frequencies are specified in kHz, while, for terrestrial and cable
      standards, they're specified in Hz. Due to that, if the same frontend
      supports both types, you'll need to have two separate
      :c:type:`dvb_frontend_ops` structures, one for each standard.
   #) The ``.i2c_gate_ctrl`` field is present only when the hardware has
      allows controlling an I2C gate (either directly of via some GPIO pin),
      in order to remove the tuner from the I2C bus after a channel is
      tuned.
   #) All new drivers should implement the
      :ref:`DVBv5 statistics <dvbv5_stats>` via ``.read_status``.
      Yet, there are a number of callbacks meant to get statistics for
      signal strength, S/N and UCB. Those are there to provide backward
      compatibility with legacy applications that don't support the DVBv5
      API. Implementing those callbacks are optional. Those callbacks may be
      removed in the future, after we have all existing drivers supporting
      DVBv5 stats.
   #) Other callbacks are required for satellite TV standards, in order to
      control LNBf and DiSEqC: ``.diseqc_send_master_cmd``,
      ``.diseqc_send_burst``, ``.set_tone``, ``.set_voltage``.

.. |delta|   unicode:: U+00394

The ``include/media/dvb_frontend.c`` has a kernel thread which is
responsible for tuning the device. It supports multiple algorithms to
detect a channel, as defined at enum :c:func:`dvbfe_algo`.

The algorithm to be used is obtained via ``.get_frontend_algo``. If the driver
doesn't fill its field at struct dvb_frontend_ops, it will default to
``DVBFE_ALGO_SW``, meaning that the dvb-core will do a zigzag when tuning,
e. g. it will try first to use the specified center frequency ``f``,
then, it will do ``f`` + |delta|, ``f`` - |delta|, ``f`` + 2 x |delta|,
``f`` - 2 x |delta| and so on.

If the hardware has internally a some sort of zigzag algorithm, you should
define a ``.get_frontend_algo`` function that would return ``DVBFE_ALGO_HW``.

.. note::

   The core frontend support also supports
   a third type (``DVBFE_ALGO_CUSTOM``), in order to allow the driver to
   define its own hardware-assisted algorithm. Very few hardware need to
   use it nowadays. Using ``DVBFE_ALGO_CUSTOM`` require to provide other
   function callbacks at struct dvb_frontend_ops.

Attaching frontend driver to the bridge driver
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Before using the Digital TV frontend core, the bridge driver should attach
the frontend demod, tuner and SEC devices and call
:c:func:`dvb_register_frontend()`,
in order to register the new frontend at the subsystem. At device
detach/removal, the bridge driver should call
:c:func:`dvb_unregister_frontend()` to
remove the frontend from the core and then :c:func:`dvb_frontend_detach()`
to free the memory allocated by the frontend drivers.

The drivers should also call :c:func:`dvb_frontend_suspend()` as part of
their handler for the :c:type:`device_driver`.\ ``suspend()``, and
:c:func:`dvb_frontend_resume()` as
part of their handler for :c:type:`device_driver`.\ ``resume()``.

A few other optional functions are provided to handle some special cases.

.. _dvbv5_stats:

Digital TV Frontend statistics
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Introduction
^^^^^^^^^^^^

Digital TV frontends provide a range of
:ref:`statistics <frontend-stat-properties>` meant to help tuning the device
and measuring the quality of service.

For each statistics measurement, the driver should set the type of scale used,
or ``FE_SCALE_NOT_AVAILABLE`` if the statistics is not available on a given
time. Drivers should also provide the number of statistics for each type.
that's usually 1 for most video standards [#f2]_.

Drivers should initialize each statistic counters with length and
scale at its init code. For example, if the frontend provides signal
strength, it should have, on its init code::

	struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;

	c->strength.len = 1;
	c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;

And, when the statistics got updated, set the scale::

	c->strength.stat[0].scale = FE_SCALE_DECIBEL;
	c->strength.stat[0].uvalue = strength;

.. [#f2] For ISDB-T, it may provide both a global statistics and a per-layer
   set of statistics. On such cases, len should be equal to 4. The first
   value corresponds to the global stat; the other ones to each layer, e. g.:

   - c->cnr.stat[0] for global S/N carrier ratio,
   - c->cnr.stat[1] for Layer A S/N carrier ratio,
   - c->cnr.stat[2] for layer B S/N carrier ratio,
   - c->cnr.stat[3] for layer C S/N carrier ratio.

.. note:: Please prefer to use ``FE_SCALE_DECIBEL`` instead of
   ``FE_SCALE_RELATIVE`` for signal strength and CNR measurements.

Groups of statistics
^^^^^^^^^^^^^^^^^^^^

There are several groups of statistics currently supported:

Signal strength (:ref:`DTV-STAT-SIGNAL-STRENGTH`)
  - Measures the signal strength level at the analog part of the tuner or
    demod.

  - Typically obtained from the gain applied to the tuner and/or frontend
    in order to detect the carrier. When no carrier is detected, the gain is
    at the maximum value (so, strength is on its minimal).

  - As the gain is visible through the set of registers that adjust the gain,
    typically, this statistics is always available [#f3]_.

  - Drivers should try to make it available all the times, as these statistics
    can be used when adjusting an antenna position and to check for troubles
    at the cabling.

  .. [#f3] On a few devices, the gain keeps floating if there is no carrier.
     On such devices, strength report should check first if carrier is
     detected at the tuner (``FE_HAS_CARRIER``, see :c:type:`fe_status`),
     and otherwise return the lowest possible value.

Carrier Signal to Noise ratio (:ref:`DTV-STAT-CNR`)
  - Signal to Noise ratio for the main carrier.

  - Signal to Noise measurement depends on the device. On some hardware, it is
    available when the main carrier is detected. On those hardware, CNR
    measurement usually comes from the tuner (e. g. after ``FE_HAS_CARRIER``,
    see :c:type:`fe_status`).

    On other devices, it requires inner FEC decoding,
    as the frontend measures it indirectly from other parameters (e. g. after
    ``FE_HAS_VITERBI``, see :c:type:`fe_status`).

    Having it available after inner FEC is more common.

Bit counts post-FEC (:ref:`DTV-STAT-POST-ERROR-BIT-COUNT` and :ref:`DTV-STAT-POST-TOTAL-BIT-COUNT`)
  - Those counters measure the number of bits and bit errors after
    the forward error correction (FEC) on the inner coding block
    (after Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock
    (e. g. after ``FE_HAS_SYNC`` or after ``FE_HAS_LOCK``,
    see :c:type:`fe_status`).

Bit counts pre-FEC (:ref:`DTV-STAT-PRE-ERROR-BIT-COUNT` and :ref:`DTV-STAT-PRE-TOTAL-BIT-COUNT`)
  - Those counters measure the number of bits and bit errors before
    the forward error correction (FEC) on the inner coding block
    (before Viterbi, LDPC or other inner code).

  - Not all frontends provide this kind of statistics.

  - Due to its nature, those statistics depend on inner coding lock (e. g.
    after ``FE_HAS_VITERBI``, see :c:type:`fe_status`).

Block counts (:ref:`DTV-STAT-ERROR-BLOCK-COUNT` and :ref:`DTV-STAT-TOTAL-BLOCK-COUNT`)
  - Those counters measure the number of blocks and block errors after
    the forward error correction (FEC) on the inner coding block
    (before Viterbi, LDPC or other inner code).

  - Due to its nature, those statistics depend on full coding lock
    (e. g. after ``FE_HAS_SYNC`` or after
    ``FE_HAS_LOCK``, see :c:type:`fe_status`).

.. note:: All counters should be monotonically increased as they're
   collected from the hardware.

A typical example of the logic that handle status and statistics is::

	static int foo_get_status_and_stats(struct dvb_frontend *fe)
	{
		struct foo_state *state = fe->demodulator_priv;
		struct dtv_frontend_properties *c = &fe->dtv_property_cache;

		int rc;
		enum fe_status *status;

		/* Both status and strength are always available */
		rc = foo_read_status(fe, &status);
		if (rc < 0)
			return rc;

		rc = foo_read_strength(fe);
		if (rc < 0)
			return rc;

		/* Check if CNR is available */
		if (!(fe->status & FE_HAS_CARRIER))
			return 0;

		rc = foo_read_cnr(fe);
		if (rc < 0)
			return rc;

		/* Check if pre-BER stats are available */
		if (!(fe->status & FE_HAS_VITERBI))
			return 0;

		rc = foo_get_pre_ber(fe);
		if (rc < 0)
			return rc;

		/* Check if post-BER stats are available */
		if (!(fe->status & FE_HAS_SYNC))
			return 0;

		rc = foo_get_post_ber(fe);
		if (rc < 0)
			return rc;
	}

	static const struct dvb_frontend_ops ops = {
		/* ... */
		.read_status = foo_get_status_and_stats,
	};

Statistics collection
^^^^^^^^^^^^^^^^^^^^^

On almost all frontend hardware, the bit and byte counts are stored by
the hardware after a certain amount of time or after the total bit/block
counter reaches a certain value (usually programmable), for example, on
every 1000 ms or after receiving 1,000,000 bits.

So, if you read the registers too soon, you'll end by reading the same
value as in the previous reading, causing the monotonic value to be
incremented too often.

Drivers should take the responsibility to avoid too often reads. That
can be done using two approaches:

if the driver have a bit that indicates when a collected data is ready
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Driver should check such bit before making the statistics available.

An example of such behavior can be found at this code snippet (adapted
from mb86a20s driver's logic)::

	static int foo_get_pre_ber(struct dvb_frontend *fe)
	{
		struct foo_state *state = fe->demodulator_priv;
		struct dtv_frontend_properties *c = &fe->dtv_property_cache;
		int rc, bit_error;

		/* Check if the BER measures are already available */
		rc = foo_read_u8(state, 0x54);
		if (rc < 0)
			return rc;

		if (!rc)
			return 0;

		/* Read Bit Error Count */
		bit_error = foo_read_u32(state, 0x55);
		if (bit_error < 0)
			return bit_error;

		/* Read Total Bit Count */
		rc = foo_read_u32(state, 0x51);
		if (rc < 0)
			return rc;

		c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
		c->pre_bit_error.stat[0].uvalue += bit_error;
		c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
		c->pre_bit_count.stat[0].uvalue += rc;

		return 0;
	}

If the driver doesn't provide a statistics available check bit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

A few devices, however, may not provide a way to check if the stats are
available (or the way to check it is unknown). They may not even provide
a way to directly read the total number of bits or blocks.

On those devices, the driver need to ensure that it won't be reading from
the register too often and/or estimate the total number of bits/blocks.

On such drivers, a typical routine to get statistics would be like
(adapted from dib8000 driver's logic)::

	struct foo_state {
		/* ... */

		unsigned long per_jiffies_stats;
	}

	static int foo_get_pre_ber(struct dvb_frontend *fe)
	{
		struct foo_state *state = fe->demodulator_priv;
		struct dtv_frontend_properties *c = &fe->dtv_property_cache;
		int rc, bit_error;
		u64 bits;

		/* Check if time for stats was elapsed */
		if (!time_after(jiffies, state->per_jiffies_stats))
			return 0;

		/* Next stat should be collected in 1000 ms */
		state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);

		/* Read Bit Error Count */
		bit_error = foo_read_u32(state, 0x55);
		if (bit_error < 0)
			return bit_error;

		/*
		 * On this particular frontend, there's no register that
		 * would provide the number of bits per 1000ms sample. So,
		 * some function would calculate it based on DTV properties
		 */
		bits = get_number_of_bits_per_1000ms(fe);

		c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
		c->pre_bit_error.stat[0].uvalue += bit_error;
		c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
		c->pre_bit_count.stat[0].uvalue += bits;

		return 0;
	}

Please notice that, on both cases, we're getting the statistics using the
:c:type:`dvb_frontend_ops` ``.read_status`` callback. The rationale is that
the frontend core will automatically call this function periodically
(usually, 3 times per second, when the frontend is locked).

That warrants that we won't miss to collect a counter and increment the
monotonic stats at the right time.

Digital TV Frontend functions and types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. kernel-doc:: include/media/dvb_frontend.h


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

Digital TV Network kABI
-----------------------

.. kernel-doc:: include/media/dvb_net.h


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

.. include:: <isonum.txt>

===================================
Media subsystem kernel internal API
===================================

This section contains usage information about media subsystem and
its supported drivers.

Please see:

Documentation/admin-guide/media/index.rst

  - for usage information about media subsystem and supported drivers;

Documentation/userspace-api/media/index.rst

  - for the userspace APIs used on media devices.

.. only:: html

   .. class:: toc-title

        Table of Contents

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

    maintainer-entry-profile

    v4l2-core
    dtv-core
    rc-core
    mc-core
    cec-core
    tx-rx
    camera-sensor

    drivers/index

**Copyright** |copy| 2009-2020 : LinuxTV Developers

::

  This documentation is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option) any
  later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  more details.

  For more details see the file COPYING in the source distribution of Linux.


code:
Media Subsystem Profile
=======================

Overview
--------

The media subsystem covers support for a variety of devices: stream
capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC
and media pipeline control.

It covers, mainly, the contents of those directories:

  - drivers/media
  - drivers/staging/media
  - Documentation/admin-guide/media
  - Documentation/driver-api/media
  - Documentation/userspace-api/media
  - Documentation/devicetree/bindings/media/\ [1]_
  - include/media

.. [1] Device tree bindings are maintained by the
       OPEN FIRMWARE AND FLATTENED DEVICE TREE BINDINGS maintainers
       (see the MAINTAINERS file). So, changes there must be reviewed
       by them before being merged via the media subsystem's development
       tree.

Both media userspace and Kernel APIs are documented and the documentation
must be kept in sync with the API changes. It means that all patches that
add new features to the subsystem must also bring changes to the
corresponding API files.

Due to the size and wide scope of the media subsystem, media's
maintainership model is to have sub-maintainers that have a broad
knowledge of a specific aspect of the subsystem. It is the sub-maintainers'
task to review the patches, providing feedback to users if the patches are
following the subsystem rules and are properly using the media kernel and
userspace APIs.

Patches for the media subsystem must be sent to the media mailing list
at linux-media@vger.kernel.org as plain text only e-mail. Emails with
HTML will be automatically rejected by the mail server. It could be wise
to also copy the sub-maintainer(s).

Media's workflow is heavily based on Patchwork, meaning that, once a patch
is submitted, the e-mail will first be accepted by the mailing list
server, and, after a while, it should appear at:

   - https://patchwork.linuxtv.org/project/linux-media/list/

If it doesn't automatically appear there after a few minutes, then
probably something went wrong on your submission. Please check if the
email is in plain text\ [2]_ only and if your emailer is not mangling
whitespaces before complaining or submitting them again.

You can check if the mailing list server accepted your patch, by looking at:

   - https://lore.kernel.org/linux-media/

.. [2] If your email contains HTML, the mailing list server will simply
       drop it, without any further notice.

Media maintainers
+++++++++++++++++

At the media subsystem, we have a group of senior developers that
are responsible for doing the code reviews at the drivers (also known as
sub-maintainers), and another senior developer responsible for the
subsystem as a whole. For core changes, whenever possible, multiple
media maintainers do the review.

The media maintainers that work on specific areas of the subsystem are:

- Remote Controllers (infrared):
    Sean Young <sean@mess.org>

- HDMI CEC:
    Hans Verkuil <hverkuil@xs4all.nl>

- Media controller drivers:
    Laurent Pinchart <laurent.pinchart@ideasonboard.com>

- ISP, v4l2-async, v4l2-fwnode, v4l2-flash-led-class and Sensor drivers:
    Sakari Ailus <sakari.ailus@linux.intel.com>

- V4L2 drivers and core V4L2 frameworks:
    Hans Verkuil <hverkuil@xs4all.nl>

The subsystem maintainer is:
  Mauro Carvalho Chehab <mchehab@kernel.org>

Media maintainers may delegate a patch to other media maintainers as needed.
On such case, checkpatch's ``delegate`` field indicates who's currently
responsible for reviewing a patch.

Submit Checklist Addendum
-------------------------

Patches that change the Open Firmware/Device Tree bindings must be
reviewed by the Device Tree maintainers. So, DT maintainers should be
Cc:ed when those are submitted via devicetree@vger.kernel.org mailing
list.

There is a set of compliance tools at https://git.linuxtv.org/v4l-utils.git/
that should be used in order to check if the drivers are properly
implementing the media APIs:

====================	=======================================================
Type			Tool
====================	=======================================================
V4L2 drivers\ [3]_	``v4l2-compliance``
V4L2 virtual drivers	``contrib/test/test-media``
CEC drivers		``cec-compliance``
====================	=======================================================

.. [3] The ``v4l2-compliance`` also covers the media controller usage inside
       V4L2 drivers.

Other compilance tools are under development to check other parts of the
subsystem.

Those tests need to pass before the patches go upstream.

Also, please notice that we build the Kernel with::

	make CF=-D__CHECK_ENDIAN__ CONFIG_DEBUG_SECTION_MISMATCH=y C=1 W=1 CHECK=check_script

Where the check script is::

	#!/bin/bash
	/devel/smatch/smatch -p=kernel $@ >&2
	/devel/sparse/sparse $@ >&2

Be sure to not introduce new warnings on your patches without a
very good reason.

Style Cleanup Patches
+++++++++++++++++++++

Style cleanups are welcome when they come together with other changes
at the files where the style changes will affect.

We may accept pure standalone style cleanups, but they should ideally
be one patch for the whole subsystem (if the cleanup is low volume),
or at least be grouped per directory. So, for example, if you're doing a
big cleanup change set at drivers under drivers/media, please send a single
patch for all drivers under drivers/media/pci, another one for
drivers/media/usb and so on.

Coding Style Addendum
+++++++++++++++++++++

Media development uses ``checkpatch.pl`` on strict mode to verify the code
style, e.g.::

	$ ./scripts/checkpatch.pl --strict --max-line-length=80

In principle, patches should follow the coding style rules, but exceptions
are allowed if there are good reasons. On such case, maintainers and reviewers
may question about the rationale for not addressing the ``checkpatch.pl``.

Please notice that the goal here is to improve code readability. On
a few cases, ``checkpatch.pl`` may actually point to something that would
look worse. So, you should use good sense.

Note that addressing one ``checkpatch.pl`` issue (of any kind) alone may lead
to having longer lines than 80 characters per line. While this is not
strictly prohibited, efforts should be made towards staying within 80
characters per line. This could include using re-factoring code that leads
to less indentation, shorter variable or function names and last but not
least, simply wrapping the lines.

In particular, we accept lines with more than 80 columns:

    - on strings, as they shouldn't be broken due to line length limits;
    - when a function or variable name need to have a big identifier name,
      which keeps hard to honor the 80 columns limit;
    - on arithmetic expressions, when breaking lines makes them harder to
      read;
    - when they avoid a line to end with an open parenthesis or an open
      bracket.

Key Cycle Dates
---------------

New submissions can be sent at any time, but if they intend to hit the
next merge window they should be sent before -rc5, and ideally stabilized
in the linux-media branch by -rc6.

Review Cadence
--------------

Provided that your patch is at https://patchwork.linuxtv.org, it should
be sooner or later handled, so you don't need to re-submit a patch.

Except for bug fixes, we don't usually add new patches to the development
tree between -rc6 and the next -rc1.

Please notice that the media subsystem is a high traffic one, so it
could take a while for us to be able to review your patches. Feel free
to ping if you don't get a feedback in a couple of weeks or to ask
other developers to publicly add Reviewed-by and, more importantly,
``Tested-by:`` tags.

Please note that we expect a detailed description for ``Tested-by:``,
identifying what boards were used at the test and what it was tested.