diff --git a/Documentation/devicetree/bindings/media/apple,t8010-ave.yaml b/Documentation/devicetree/bindings/media/apple,t8010-ave.yaml new file mode 100644 index 00000000000000..d757c242902c8d --- /dev/null +++ b/Documentation/devicetree/bindings/media/apple,t8010-ave.yaml @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/media/apple,t8010-ave.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple A10 video encoder (AVE2) + +maintainers: + - Paul Scalise + +description: + The A10's H.264 and HEVC video encoder. Apple's firmware runs on a 32-bit + ARM CPU of the block's own and drives the encoder core. The host loads the + firmware, talks to it through a mailbox in the CPU's control block, and + maps its memory through the block's DART. + +properties: + compatible: + const: apple,t8010-ave + + reg: + items: + - description: the CPU's control block, with the host side of the + mailbox + - description: the translation unit in front of the DART + - description: the PMGR page with the encoder pipes' power states, + which the firmware gets mapped through the DART + + reg-names: + items: + - const: cpu + - const: smmu + - const: pmgr + + interrupts: + maxItems: 1 + + power-domains: + maxItems: 5 + + power-domain-names: + items: + - const: sys + - const: pipe4 + - const: pipe5 + - const: me0 + - const: me1 + + iommus: + maxItems: 1 + + firmware-name: + maxItems: 1 + +required: + - compatible + - reg + - reg-names + - interrupts + - power-domains + - power-domain-names + - iommus + - firmware-name + +additionalProperties: false + +examples: + - | + #include + #include + + soc { + #address-cells = <2>; + #size-cells = <2>; + + video-encoder@207c80000 { + compatible = "apple,t8010-ave"; + reg = <0x2 0x07c80000 0x0 0x80000>, + <0x2 0x07c20000 0x0 0x4000>, + <0x2 0x0e088000 0x0 0x4000>; + reg-names = "cpu", "smmu", "pmgr"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_venc_sys>, <&ps_venc_pipe4>, <&ps_venc_pipe5>, + <&ps_venc_me0>, <&ps_venc_me1>; + power-domain-names = "sys", "pipe4", "pipe5", "me0", "me1"; + iommus = <&dart_ave 0>; + firmware-name = "apple/ave-t8010.bin"; + }; + }; diff --git a/arch/arm64/boot/dts/apple/t8010.dtsi b/arch/arm64/boot/dts/apple/t8010.dtsi index e5385fef47d793..82a98acd6de49e 100644 --- a/arch/arm64/boot/dts/apple/t8010.dtsi +++ b/arch/arm64/boot/dts/apple/t8010.dtsi @@ -521,6 +521,38 @@ iommus = <&dart_jpeg1 0>; }; + dart_ave: iommu@207c30000 { + compatible = "apple,t8010-dart", "apple,s5l8960x-dart"; + reg = <0x2 0x07c30000 0x0 0x4000>; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_venc_sys>; + }; + + /* + * The video encoder: Apple's firmware on a 32-bit ARM CPU of its + * own drives the encoder core, which the AP never touches. "cpu" + * is the CPU's control block, with the AP's side of the mailbox at + * +0x40000, "smmu" the unit in front of dart-ave, and "pmgr" the + * PMGR page with the pipes' power states, which the firmware gets + * mapped through the DART. + */ + ave: video-encoder@207c80000 { + compatible = "apple,t8010-ave"; + reg = <0x2 0x07c80000 0x0 0x80000>, + <0x2 0x07c20000 0x0 0x4000>, + <0x2 0x0e088000 0x0 0x4000>; + reg-names = "cpu", "smmu", "pmgr"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_venc_sys>, <&ps_venc_pipe4>, <&ps_venc_pipe5>, + <&ps_venc_me0>, <&ps_venc_me1>; + power-domain-names = "sys", "pipe4", "pipe5", "me0", "me1"; + iommus = <&dart_ave 0>; + firmware-name = "apple/ave-t8010.bin"; + }; + sio: dma-controller@20ae00000 { compatible = "apple,t8010-sio"; reg = <0x2 0x0ae00000 0x0 0x10000>, diff --git a/arch/arm64/configs/orchard_apple16k_defconfig b/arch/arm64/configs/orchard_apple16k_defconfig index 2f837f32d90622..3c63ca03d53831 100644 --- a/arch/arm64/configs/orchard_apple16k_defconfig +++ b/arch/arm64/configs/orchard_apple16k_defconfig @@ -319,6 +319,7 @@ CONFIG_MEDIA_TEST_SUPPORT=y CONFIG_VIDEO_APPLE_T8010_ISP=m CONFIG_VIDEO_APPLE_VXD=m CONFIG_VIDEO_APPLE_JPEG=m +CONFIG_VIDEO_APPLE_AVE=m CONFIG_DRM=y CONFIG_DRM_APPLE_ADBE=y CONFIG_DRM_ADP=y diff --git a/drivers/media/platform/apple/Kconfig b/drivers/media/platform/apple/Kconfig index 0c7787cb34af70..2ea2459ada0b3f 100644 --- a/drivers/media/platform/apple/Kconfig +++ b/drivers/media/platform/apple/Kconfig @@ -5,3 +5,4 @@ comment "Apple media platform drivers" source "drivers/media/platform/apple/isp/Kconfig" source "drivers/media/platform/apple/vxd/Kconfig" source "drivers/media/platform/apple/jpeg/Kconfig" +source "drivers/media/platform/apple/ave/Kconfig" diff --git a/drivers/media/platform/apple/Makefile b/drivers/media/platform/apple/Makefile index 648c39e36951f2..a3b8c6824990dc 100644 --- a/drivers/media/platform/apple/Makefile +++ b/drivers/media/platform/apple/Makefile @@ -2,3 +2,4 @@ obj-y += isp/ obj-y += vxd/ obj-y += jpeg/ +obj-y += ave/ diff --git a/drivers/media/platform/apple/ave/Kconfig b/drivers/media/platform/apple/ave/Kconfig new file mode 100644 index 00000000000000..b33109b2e4c65c --- /dev/null +++ b/drivers/media/platform/apple/ave/Kconfig @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0-only +config VIDEO_APPLE_AVE + tristate "Apple T8010 video encoder (AVE2)" + depends on VIDEO_DEV && IOMMU_API + depends on ARCH_APPLE || COMPILE_TEST + select VIDEOBUF2_DMA_CONTIG + select V4L2_MEM2MEM_DEV + help + V4L2 stateful H.264 and HEVC encoder for the Apple A10's video + encoder, whose firmware (apple/ave-t8010.bin) runs on a CPU of its + own. + + To compile this driver as a module, choose M here: the module will be + called apple-ave. diff --git a/drivers/media/platform/apple/ave/Makefile b/drivers/media/platform/apple/ave/Makefile new file mode 100644 index 00000000000000..0d0363d8b14085 --- /dev/null +++ b/drivers/media/platform/apple/ave/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0-only +obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave.o +apple-ave-y := ave_drv.o ave_hw.o ave_v4l2.o diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h new file mode 100644 index 00000000000000..30af025550f9dc --- /dev/null +++ b/drivers/media/platform/apple/ave/ave.h @@ -0,0 +1,151 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Apple T8010 video encoder (AVE2): a V4L2 stateful encoder, H.264 and HEVC + * from NV12. + */ +#ifndef AVE_H +#define AVE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AVE_MIN_W 192 /* the firmware's H.264 limits */ +#define AVE_MIN_H 96 +#define AVE_MIN_W_HEVC 160 /* and HEVC's (iOS's checks) */ +#define AVE_MIN_H_HEVC 64 +#define AVE_MAX_W 4096 /* iOS: H.264 and HEVC 4K30, 1080p60 */ +#define AVE_MAX_H 2304 +#define AVE_STRIDE_ALIGN 64 /* source lines */ +#define AVE_MAX_STRIDE 8192 +#define AVE_TIMEOUT_MS 2000 /* one picture */ +#define AVE_MAX_B 2 /* B pictures between two anchors */ +#define AVE_MAX_INFLIGHT 2 /* pictures the firmware has at once */ + +/* what a picture is coded as */ +enum ave_pic_type { + AVE_PIC_IDR, + AVE_PIC_P, + AVE_PIC_B, /* not a reference */ +}; + +struct ave_hw; + +struct ave_dev { + struct device *dev; + struct v4l2_device v4l2; + struct video_device vdev; + struct v4l2_m2m_dev *m2m; + struct mutex lock; /* the video device's ioctls */ + struct ave_hw *hw; /* ave_hw.c's state */ + spinlock_t irq_lock; /* running */ + struct ave_ctx *running; /* the context whose pictures are encoding */ + struct mutex run_lock; /* posting pictures and completing them */ + struct delayed_work watchdog; +}; + +/* what a stream is encoded with: latched from the formats and controls when it starts */ +struct ave_params { + u32 codec; /* V4L2_PIX_FMT_H264 or _HEVC */ + u32 width, height; /* the source frame */ + u32 stride; /* its bytes per line (both planes) */ + bool src_ten; /* P010 (10-bit) rather than NV12; HEVC only */ + struct v4l2_rect crop; /* what is coded as visible */ + u32 fps_num, fps_den; /* frames per second: num / den */ + u32 rc_mode; /* V4L2_MPEG_VIDEO_BITRATE_MODE_* */ + u32 bitrate; /* bits per second (VBR, CBR) */ + u32 bitrate_peak; /* VBR peak */ + u32 qp_i, qp_p, qp_b; /* constant QP (CQ) */ + u32 qp_min, qp_max; + bool aq; /* adaptive quantization: a QP per 16x16 (not with CQ) */ + u32 gop; /* frames from IDR to IDR (0: only the first) */ + u32 bframes; /* B pictures between anchors (0..AVE_MAX_B) */ + u32 slice_mbs; /* at most this many macroblocks a slice (0: one slice) */ + u32 profile, level; /* V4L2 enums of the codec */ + u32 tier; /* HEVC: V4L2_MPEG_VIDEO_HEVC_TIER_* */ + bool cabac; /* H.264 entropy coding */ + bool headers_separate; /* SPS/PPS (VPS) in a buffer of their own */ + bool headers_every_idr; /* SPS/PPS (VPS) before every IDR picture */ + /* colorimetry for the VUI */ + u8 colorspace, xfer_func, ycbcr_enc, quantization; +}; + +struct ave_ctx { + struct v4l2_fh fh; + struct ave_dev *ave; + struct v4l2_ctrl_handler ctrls; + struct v4l2_ctrl *ctrl_bitrate; + struct v4l2_ctrl *ctrl_min_out; /* MIN_BUFFERS_FOR_OUTPUT: 1 + B pictures */ + struct v4l2_pix_format_mplane src_fmt; /* OUTPUT: raw NV12 */ + struct v4l2_pix_format_mplane dst_fmt; /* CAPTURE: H.264 / HEVC */ + struct v4l2_rect crop; /* the visible part of the source */ + u32 fps_num, fps_den; /* S_PARM: frames per second num / den */ + struct ave_params params; + void *session; /* ave_hw.c's per-stream state, NULL when stopped */ + u32 out_seq, cap_seq; + u32 frame_num; /* pictures posted since the stream started */ + bool force_idr; /* FORCE_KEY_FRAME, or the source restarted */ + bool headers_sent; /* the separate header buffer went out */ + bool cur_headers; /* the job in flight writes only the headers */ + /* + * Coding order. Source frames are taken in groups: the group's last + * frame (its anchor, I or P) is coded first, then the frames before + * it as B pictures, @held in display order. @disp numbers the frames + * in display order from the last IDR picture. + */ + spinlock_t sched_lock; /* the fields below: job_ready() reads them */ + struct vb2_v4l2_buffer *held[AVE_MAX_B]; + unsigned int n_held, next_held; + u32 disp; /* of the next frame not in a group yet */ + u32 held_disp; /* of held[0] */ + /* + * Pictures in flight: their source frames in @flight, in coding order + * (they stay queued until done, so draining works as for one); their + * capture buffers are the first @posted of that queue. The mem2mem + * job is held until the oldest is done. + */ + struct vb2_v4l2_buffer *flight[AVE_MAX_INFLIGHT]; + unsigned int posted; + u32 drain_seq; /* the sequence of the last frame before ENC_CMD_STOP */ + bool job_held; + wait_queue_head_t idle; /* posted went to 0 */ +}; + +static inline struct ave_ctx *ave_fh_to_ctx(struct v4l2_fh *fh) +{ + return container_of(fh, struct ave_ctx, fh); +} + +/* + * The hardware side (ave_hw.c). ave_hw_encode() starts one picture into the + * capture buffer and returns; the firmware may have up to + * ave_hw_max_inflight() of them, finishes them in order, and each answer + * ends the oldest with ave_frame_done(). The session calls sleep; they are + * serialised by the mem2mem core (one job at a time), run_lock and ave->lock. + */ +int ave_hw_init(struct ave_dev *ave, struct platform_device *pdev); +void ave_hw_remove(struct ave_dev *ave); +void ave_hw_suspend(struct ave_dev *ave); +int ave_hw_session_start(struct ave_ctx *ctx); +void ave_hw_session_stop(struct ave_ctx *ctx); +int ave_hw_headers(struct ave_ctx *ctx, struct vb2_v4l2_buffer *dst, u32 *bytes); +int ave_hw_encode(struct ave_ctx *ctx, struct vb2_v4l2_buffer *src, + struct vb2_v4l2_buffer *dst, enum ave_pic_type type, u32 disp); +unsigned int ave_hw_max_inflight(const struct ave_ctx *ctx); +int ave_hw_set_bitrate(struct ave_ctx *ctx, u32 bitrate); +void ave_hw_timeout(struct ave_dev *ave); + +/* a picture is done: its bytes in the capture buffer (ok false: failed) */ +void ave_frame_done(struct ave_dev *ave, u32 bytes, enum ave_pic_type type, bool ok); + +int ave_v4l2_register(struct ave_dev *ave); +void ave_v4l2_unregister(struct ave_dev *ave); + +#endif diff --git a/drivers/media/platform/apple/ave/ave_drv.c b/drivers/media/platform/apple/ave/ave_drv.c new file mode 100644 index 00000000000000..965dcdfdeada0c --- /dev/null +++ b/drivers/media/platform/apple/ave/ave_drv.c @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T8010 (A10) video encoder, AVE2, as a V4L2 stateful H.264 and HEVC + * encoder. + * + * The encoder core is driven by Apple's firmware on a 32-bit ARM CPU of its + * own (iOS's AppleAVE2 kext carries it; "apple/ave-t8010.bin" here). The AP + * boots the CPU, talks to it over rings in shared memory (the protocol of the + * H9 camera ISP's firmware) and hands it, per stream, the encoding parameters + * and the SPS/PPS and slice header bits, which iOS's kext and user-space + * encoder build; per picture, the frame, the references and the output + * buffer. ave_hw.c does that, ave_v4l2.c the V4L2 side. + */ + +#include +#include +#include +#include + +#include "ave.h" + +static int ave_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct ave_dev *ave; + int ret; + + ave = devm_kzalloc(dev, sizeof(*ave), GFP_KERNEL); + if (!ave) + return -ENOMEM; + ave->dev = dev; + platform_set_drvdata(pdev, ave); + mutex_init(&ave->lock); + + ret = ave_hw_init(ave, pdev); + if (ret) + return ret; + ret = ave_v4l2_register(ave); + if (ret) { + ave_hw_remove(ave); + return ret; + } + return 0; +} + +static void ave_remove(struct platform_device *pdev) +{ + struct ave_dev *ave = platform_get_drvdata(pdev); + + ave_v4l2_unregister(ave); + ave_hw_remove(ave); +} + +static int ave_suspend(struct device *dev) +{ + struct ave_dev *ave = dev_get_drvdata(dev); + + /* no new picture, the one running done, then the encoder off */ + v4l2_m2m_suspend(ave->m2m); + cancel_delayed_work_sync(&ave->watchdog); + ave_hw_suspend(ave); + return 0; +} + +static int ave_resume(struct device *dev) +{ + struct ave_dev *ave = dev_get_drvdata(dev); + + v4l2_m2m_resume(ave->m2m); + return 0; +} + +static DEFINE_SIMPLE_DEV_PM_OPS(ave_pm_ops, ave_suspend, ave_resume); + +static const struct of_device_id ave_of_match[] = { + { .compatible = "apple,t8010-ave" }, + {} +}; +MODULE_DEVICE_TABLE(of, ave_of_match); + +static struct platform_driver ave_driver = { + .driver = { + .name = "apple-ave", + .of_match_table = ave_of_match, + .pm = pm_sleep_ptr(&ave_pm_ops), + }, + .probe = ave_probe, + .remove = ave_remove, +}; +module_platform_driver(ave_driver); + +MODULE_DESCRIPTION("Apple T8010 video encoder (AVE2), V4L2 stateful H.264/HEVC"); +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_FIRMWARE("apple/ave-t8010.bin"); diff --git a/drivers/media/platform/apple/ave/ave_hw.c b/drivers/media/platform/apple/ave/ave_hw.c new file mode 100644 index 00000000000000..80b1e4d9394dc0 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave_hw.c @@ -0,0 +1,3656 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T8010 video encoder: the firmware and the stream. + * + * Booting: the firmware image goes at the start of a DMA window (its base is + * the CPU's address 0; every address exchanged with the CPU is relative to + * it), followed by the shared memory the IPC lives in, the firmware's extra + * heap and the stream's internal buffers. The CPU starts after a handshake + * on the mailbox's scratch registers, publishes its channel table, and from + * then on the AP posts commands on the IO ring and gets the answers on + * IO_T2H; TERMINAL carries the firmware's log. + * + * A stream: CONFIG (the first after a boot) or START, then AVC_INIT with the + * parameters (the video parameters, rate-control settings, the SPS and PPS + * with their bits), then one AVC_ENCODE per picture with its slice header + * (fields and bits from slice_type on) and its buffers: the source planes, + * the reconstructed picture, the reference, the output. The firmware writes + * Annex B slices into the output and their sizes into the slot's coded-data + * header. The QP comes from here (slice_qp_delta): constant, or a simple + * per-picture rate control for VBR and CBR. + * + * HEVC is the same protocol with its own commands: HEVC_INIT carries the + * VPS, SPS and PPS (fields and bits, written here) and the reference picture + * sets, HEVC_ENCODE the slice struct (fields only) and the picture's buffers. + * Unlike H.264, the firmware writes each HEVC slice header itself, after the + * slice is coded, into a buffer of its own; the slice data goes to the + * output. The header is put in front of the data here. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ave.h" + +/* CPU control ("cpu") */ +#define CPU_BASE 0x08 /* the firmware's DART address: the CPU's address 0 */ +#define CPU_WINDOW 0x28 +#define CPU_RUN 0x44 +#define CPU_RUN_GO 0x10 +#define CPU_STATUS 0x81c /* 0 before the CPU may start */ +/* the AP's side of the mailbox: in the CPU control block */ +#define MBOX_OFFSET 0x40000 /* 0x2_07cc_0000: the page the CPU also sees */ +#define MB_DOORBELL 0x0c /* 1 << a channel's src */ +#define MB_STATUS 0x10 /* bit n: src n has news; written back to clear */ +#define MB_SCRATCH(n) (0x18 + 4 * (n)) +#define MB_IDLE 0x38 /* iOS: 1 while powered down, 0 before commands */ + +#define MAGIC_HOST 0x08042006 + +/* the DMA window */ +#define FW_SIZE 0x200000 +#define SHARED_SIZE 0x400000 /* the IPC, boot args, commands, shared mallocs */ +/* the firmware's extra heap, at most (rhea: 12 MB) */ +#define HEAP_SIZE 0x1000000 +#define WIN_FIXED (FW_SIZE + SHARED_SIZE + HEAP_SIZE) +#define WIN_CPU_MAX 0x70800000 /* what the CPU reaches of DRAM */ +#define SLOT_SIZE 0x40 +#define MAX_CHANS 32 +#define MAX_SMALLOC 32 +#define SHARED_ORDER 6 /* 64-byte granules */ + +enum { RING_H2T = 0, RING_T2H = 1, RING_REPORT = 2 }; + +/* commands and answers */ +#define CMD_CONFIG 0x1 +#define CMD_START 0x2 +#define CMD_AVC_INIT 0x4 +#define CMD_HEVC_INIT 0x5 +#define CMD_AVC_ENCODE 0x6 +#define CMD_HEVC_ENCODE 0x7 +#define CMD_STOP 0x9 +#define CMD_POWERDOWN 0xb +#define ANS_TIMEOUT 0xe00 +#define ANS_CONFIG 0xe01 +#define ANS_START 0xe02 +#define ANS_INIT 0xe04 +#define ANS_ENCODE 0xe05 +#define ANS_FLUSH 0xe06 +#define ANS_STOP 0xe07 +#define ANS_COMPLETE 0xe08 +#define ANS_SLICE 0xe09 +#define STATUS_OK 0xee0000 +#define PLANE_CONFIG 10 +#define PLANE_START 11 +#define PLANE_STOP 13 +#define PLANE_POWERDOWN 16 +#define CLIENT_POWERDOWN 1 /* POWERDOWN is no client's */ +#define CODEC_AVC 0 +#define CODEC_HEVC 1 +#define HDR_SIZE 0x18 + +#define CONFIG_SIZE 0x34 +#define AVC_INIT_SIZE 0x3b0c +#define AVC_ENCODE_SIZE 0x1588 +#define HEVC_INIT_SIZE 0x1f588 +#define HEVC_ENCODE_SIZE 0x6098 + +/* AVC_INIT: VideoParams at +0x18 */ +#define VP 0x18 +#define VP_WIDTH (VP + 0x000) +#define VP_HEIGHT (VP + 0x004) +#define VP_BFRAMES (VP + 0x018) +#define VP_LOW_DELAY (VP + 0x020) +#define VP_RECON(i) (VP + 0x024 + 8 * (i)) /* {UV, Y} */ +#define VP_LOWRES(i) (VP + 0x134 + 4 * (i)) +#define VP_LOWRES_RESULT(i) (VP + 0x1bc + 4 * (i)) /* [2][8] */ +#define VP_CODED(i) (VP + 0x23c + 4 * (i)) +#define VP_CODED_SIZE(i) (VP + 0x250 + 4 * (i)) +#define VP_CODED_HDR(i) (VP + 0x270 + 4 * (i)) +#define VP_CODED_HDR_SIZE(i) (VP + 0x284 + 4 * (i)) +#define VP_SLICE_HDR(s, n) (VP + 0x298 + 4 * (256 * (s) + (n))) +#define VP_SLICE_HDR_SIZE(s, n) (VP + 0x1698 + 4 * (256 * (s) + (n))) +#define VP_COLOCATED(i) (VP + 0x2a98 + 4 * (i)) +#define VP_SRC_NBR_INFO (VP + 0x2ae4) +#define VP_SRC_NBR_PIXELS (VP + 0x2ae8) +#define VP_SRC_NBR_DATA (VP + 0x2aec) +#define VP_ENTROPY(i) (VP + 0x2af0 + 4 * (i)) /* [4][2] */ +#define VP_ENTROPY_SIZE(i) (VP + 0x2b30 + 4 * (i)) +#define VP_PARAM_SETS (VP + 0x2b70) +#define VP_PARAM_SETS_SIZE (VP + 0x2b74) +#define VP_VERBOSE (VP + 0x2b78) +/* u16: 0 +-192 x +-96, 1 +-128 x +-64, 2 +-64 x +-32 */ +#define VP_SEARCH_RANGE (VP + 0x2b80) +/* u8: ME1 searches too (the firmware starts it per picture) */ +#define VP_DUAL_ME (VP + 0x2b8a) +/* 2: 8x8 with 4x4 and 16x16 (1 would be 8x8 only) */ +#define VP_TRANSFORM_8X8 (VP + 0x2b8c) +#define VP_VISIBLE (VP + 0x2ba0) /* x, y, width, height */ +#define VP_SAO_ENB (VP + 0x2bb0) /* HEVC: sao_enb_config (fw default 0xffff) */ +#define VP_SAO_RDD_LUMA (VP + 0x2bb4) /* sao_rdd_off_offset_luma, _chroma */ +#define VP_SAO_RDD_CHROMA (VP + 0x2bb8) +#define VP_SAO_EO_BO (VP + 0x2bbc) /* sao_eo_bo_offset_config (-1: the fw's) */ +#define VP_PIX_PCK (VP + 0x2b88) /* u8: the source DMA's packing (P010: 1) */ +#define VP_INPUT_BITDEPTH (VP + 0x2bc0) /* exactly 8 or 10 */ +#define VP_MAX_NUM_REF (VP + 0x2bcc) +#define VP_PPS_ID(i) (VP + 0x2c20 + 4 * (i)) /* HEVC: the PPS ids (9) */ +#define VP_NUM_PPS (VP + 0x2c44) /* HEVC: how many */ +/* RateControllerSettings at +0x2c88 */ +#define RC 0x2c88 +#define RC_BITRATE (RC + 0x00) +#define RC_IDR_PERIOD (RC + 0x04) +#define RC_GOP (RC + 0x08) +#define RC_REORDER (RC + 0x0c) /* u8 bAllowFrameReordering: B pictures */ +#define RC_AVG_FPS (RC + 0x14) +#define RC_EXPECTED_FPS (RC + 0x18) +#define RC_FLAG (RC + 0x1c) /* 0 off: the QP from slice_qp_delta */ +#define RC_QPMOD (RC + 0x20) /* u8 bEnableQPMod: a QP per macroblock / 16x16 */ +/* u8: by variance thresholds (see ave_video_params()) */ +#define RC_QPMOD_THRESH (RC + 0x23) +#define RC_REALTIME (RC + 0x34) +#define RC_SOFT_MIN_QP (RC + 0x38) +#define RC_SOFT_MAX_QP (RC + 0x3c) +/* ME full-pel, sub-pel, low-res; MD inter, intra; intra offset */ +#define RC_LAMBDA(i) (RC + 0x48 + 4 * (i)) +#define RC_TABLES (RC + 0x70) /* 0x5b4 bytes: per-QP lambdas, thresholds, costs */ +#define RC_INIT_QP_I (RC + 0x64) +#define RC_INIT_QP_P (RC + 0x68) +#define RC_INIT_QP_B (RC + 0x6c) +/* the SPS struct at +0x32c0, the PPS struct at +0x396c */ +#define SPS 0x32c0 +#define SPS_PROFILE (SPS + 0x04) +#define SPS_CONSTRAINT(n) (SPS + 0x08 + 4 * (n)) +#define SPS_LEVEL (SPS + 0x20) +#define SPS_ID (SPS + 0x24) +#define SPS_CHROMA_FORMAT (SPS + 0x28) +#define SPS_SCALING_LISTS (SPS + 0x5a) /* u16: 6 x 16 (4x4), then 6 x 64 (8x8), zigzag */ +#define SPS_N_SCALING (6 * 16 + 6 * 64) +#define SPS_LOG2_MAX_FRAME_NUM (SPS + 0x41c) /* minus 4 */ +#define SPS_POC_TYPE (SPS + 0x420) +#define SPS_LOG2_MAX_POC (SPS + 0x424) /* minus 4 */ +#define SPS_MAX_NUM_REF (SPS + 0x42c) +#define SPS_WIDTH_MBS (SPS + 0x434) /* minus 1 */ +#define SPS_HEIGHT_MBS (SPS + 0x438) /* minus 1 */ +#define SPS_FRAME_MBS_ONLY (SPS + 0x43c) +#define SPS_DIRECT_8X8 (SPS + 0x440) +#define SPS_VUI (SPS + 0x444) /* u8 */ +#define SPS_VIDEO_SIGNAL (SPS + 0x447) /* u8 */ +#define SPS_VIDEO_FORMAT (SPS + 0x448) +#define SPS_FULL_RANGE (SPS + 0x44c) +#define SPS_COLOUR_DESC (SPS + 0x450) /* u8 */ +#define SPS_PRIMARIES (SPS + 0x454) +#define SPS_TRANSFER (SPS + 0x458) +#define SPS_MATRIX (SPS + 0x45c) +#define SPS_TIMING (SPS + 0x46c) /* u8 */ +#define SPS_RESTRICTION (SPS + 0x470) /* u8 */ +#define SPS_CROP (SPS + 0x490) /* u8, then left, right, top, bottom */ +#define SPS_BITS (SPS + 0x4a8) +#define SPS_BYTES (SPS + 0x4ac) /* up to 0x200 */ +#define PPS 0x396c +#define PPS_ID (PPS + 0x04) +#define PPS_SPS_ID (PPS + 0x08) +#define PPS_CABAC (PPS + 0x0c) +#define PPS_INIT_QP (PPS + 0x2c) /* minus 26 */ +#define PPS_DEBLOCKING_CTRL (PPS + 0x54) /* u8 */ +#define PPS_TRANSFORM_8X8 (PPS + 0x57) /* u8 */ +#define PPS_BITS (PPS + 0x80) +#define PPS_BYTES (PPS + 0x84) /* up to 0x100 */ +#define INIT_KEY 0x3af0 + +/* AVC_ENCODE: the slice header at +0x18, PicMgmtParams at +0x9a0 */ +#define SH 0x18 +#define SH_NAL_REF_IDC (SH + 0x04) +#define SH_NAL_TYPE (SH + 0x08) +#define SH_SLICE_TYPE (SH + 0x10) +#define SH_PPS_ID (SH + 0x14) +#define SH_FRAME_NUM (SH + 0x1c) +#define SH_IDR (SH + 0x22) /* u8 */ +#define SH_IDR_PIC_ID (SH + 0x24) +#define SH_POC_LSB (SH + 0x28) /* pic_order_cnt_lsb (POC type 0) */ +#define SH_DIRECT_SPATIAL (SH + 0x3c) /* u8 direct_spatial_mv_pred_flag */ +#define SH_OVERRIDE (SH + 0x40) +#define SH_NUM_REF_L0 (SH + 0x44) /* num_ref_idx_l0_active_minus1, -1: no list */ +#define SH_NUM_REF_L1 (SH + 0x48) +#define SH_CABAC_INIT (SH + 0x4c) +#define SH_QP_DELTA (SH + 0x50) +#define SH_DEBLOCK (SH + 0x5c) +#define SH_DIRECT_COLZERO (SH + 0x74) /* u16: spatial direct, 0x100: L1[0] short-term */ +#define SH_SLICE_MAP (SH + 0x472) /* u8 [256]: the slice of each macroblock row */ +/* 0: the map decides; the fw: slices = MBs / this */ +#define SH_MBS_PER_SLICE (SH + 0x574) +#define SH_BITS (SH + 0x57c) +#define SH_BYTES (SH + 0x580) /* up to 0x400 */ +#define PM 0x9a0 +#define PM_SIZE_WORD (PM + 0x000) +#define PM_LAMBDA_TABLE (PM + 0x0a8) /* the motion lambda per QP (52) */ +#define PM_REF_Y(i) (PM + 0x724 + 4 * (i)) /* [0] and [1]: iOS writes both */ +#define PM_REF_UV(i) (PM + 0x744 + 4 * (i)) +#define PM_REF_LOWRES(i) (PM + 0x764 + 4 * (i)) +#define PM_REF_Y_L1 (PM + 0x774) +#define PM_REF_UV_L1 (PM + 0x794) +#define PM_REF_LOWRES_L1 (PM + 0x7b4) +/* sRef.Colocated_L1: the reference's motion (TMVP) */ +#define PM_REF_COLOCATED (PM + 0x7c4) +#define PM_POC_L0(i) (PM + 0x7d4 + 4 * (i)) /* the references' POCs */ +#define PM_POC_L1 (PM + 0x7e4) +#define PM_REF_Y_LSB(i) (PM + 0x734 + 4 * (i)) /* 10-bit: the 2-bit planes */ +#define PM_REF_UV_LSB(i) (PM + 0x754 + 4 * (i)) +#define PM_REF_Y_LSB_L1 (PM + 0x784) +#define PM_REF_UV_LSB_L1 (PM + 0x7a4) +#define PM_RECON_Y (PM + 0x7f4) +#define PM_RECON_Y_LSB (PM + 0x7f8) +#define PM_RECON_UV (PM + 0x7fc) +#define PM_RECON_UV_LSB (PM + 0x800) +#define PM_RECON_COLOCATED (PM + 0x804) +#define PM_INPUT_Y (PM + 0x808) +#define PM_INPUT_Y_STRIDE (PM + 0x80c) +#define PM_INPUT_UV (PM + 0x810) +#define PM_INPUT_UV_STRIDE (PM + 0x814) +/* +0x860: a stride for Apple's compressed input formats only (iOS leaves it 0 for NV12) */ +#define PM_SRC_NBR_INFO (PM + 0x874) /* AVE_SetExtraBuff: the line buffers */ +#define PM_SRC_NBR_PIXELS (PM + 0x878) +#define PM_SRC_NBR_DATA (PM + 0x87c) +#define PM_ENTROPY(i, j) (PM + 0x884 + 8 * (i) + 4 * (j)) /* the CAVLC buffers */ +/* u8: 1 = the size at 0x8d4, 0 = INIT's apsCodedSize */ +#define PM_OUT_SIZE_OVERRIDE (PM + 0x8c4) +#define PM_OUT_SLOT (PM + 0x8c8) +#define PM_OUT_ADDR (PM + 0x8cc) +#define PM_OUT_CDH (PM + 0x8d0) /* the slot's coded-data header */ +#define PM_OUT_SIZE (PM + 0x8d4) +#define PM_RECON_LOWRES (PM + 0x8d8) +#define PM_LOWRES_RESULT(i) (PM + 0x8dc + 4 * (i)) /* the low-res ME's results (8) */ +/* the average macroblock variance for the QP modulation; -1: the firmware's (iOS) */ +#define PM_AVG_VARIANCE (PM + 0x65c) +#define PM_FRAME_NUM (PM + 0x920) /* in display order (echoed in the CDH) */ +#define PM_FRAME_TYPE (PM + 0x924) /* 0 I, 1 P, 2 B, 3 IDR */ +/* + * HEVC mode decision (the firmware reads PicMgmt + 4, so + * these are its +0x6fc..): 0 every candidate, 1 iOS's real-time setting + * (iOS up to 285600 CTB/s: 4K30 included; fewer mode-decision candidates, + * MD register 0x77f305b8 = 0xfcfe7f), 2 and 3 fast modes with much smaller + * candidate sets (iOS above that). +0x708 goes with the mode (3, 2, 0) into + * MD register 0x77f3093c bits 2-3. Mode 1 is 1.3x faster than 0, with + * 0.1 dB more and 7 % fewer bytes on the test pattern. iOS also sets + * +0x704 (mode != 3) and +0x705 (1): they cost 0.6 to 1.5 dB here (they + * feed the firmware's rate control and perceptual tuning), so they stay 0. + */ +#define PM_MD_MODE (PM + 0x700) +#define PM_MD_EARLY (PM + 0x708) +#define HEVC_MD_MODE 1 /* iOS's real-time setting */ +#define HEVC_MD_EARLY 3 /* +0x708 with mode 1 */ +#define PICMGMT_SIZE 0xbd8 + +/* the coded-data header: slice records */ +#define CDH_SIZE 0x22000 +#define CDH_CLEAR 0x218f8 +#define CDH_SLICE(n) (0xb8 + 0x218 * (n)) /* the slices' records, in picture order */ +#define MAX_SLICES 32 /* iOS's limit */ +#define CDH_SLICE_DROP 0x20c /* u8 */ +#define CDH_SLICE_HDR_ADDR 0x210 /* HEVC: where the firmware wrote the slice header */ +#define CDH_SLICE_HDR_SIZE 0x214 /* HEVC: its bytes, start code included */ + +/* + * HEVC_INIT: the header, VideoParams and RateControllerSettings as in + * AVC_INIT, then the VPS, SPS, PPS and RPS structs. Field names from the + * firmware's parameter dumps, and the order of the bits from the headers that + * iOS and the firmware write. + */ +#define HVPS 0x32c0 /* 0x11820 bytes */ +#define HVPS_LEN 0x11820 +#define HSPS 0x14ae0 /* 0x1edc */ +#define HSPS_LEN 0x1edc +#define HPPS 0x169bc /* 0x259c */ +#define HPPS_LEN 0x259c +#define HRPS 0x18f58 /* 0x6614 */ +#define HEVC_INIT_KEY 0x1f56c +/* profile_tier_level(), 0x220 bytes, at VPS + 0x18 and SPS + 0x10 */ +#define PTL_TIER 0x04 /* u8; +0x00 general_profile_space */ +#define PTL_PROFILE 0x08 +#define PTL_COMPAT(j) (0x0c + (j)) /* u8 general_profile_compatibility_flag[32] */ +#define PTL_PROGRESSIVE 0x2c /* u8: then interlaced, non_packed, frame_only */ +#define PTL_FRAME_ONLY 0x2f +#define PTL_LEVEL 0x3c +#define VPS_ID (HVPS + 0x04) +#define VPS_BASE_LAYER (HVPS + 0x08) /* u8 internal, u8 available */ +/* u8; +0x0c max_layers_minus1, +0x10 max_sub_layers_minus1 */ +#define VPS_TEMPORAL_NESTING (HVPS + 0x14) +#define VPS_PTL (HVPS + 0x18) +#define VPS_ORDERING_INFO (HVPS + 0x238) /* u8 */ +/* minus1, [8]; +0x25c num_reorder, +0x27c latency */ +#define VPS_MAX_DEC_PIC_BUF (HVPS + 0x23c) +#define VPS_BITS (HVPS + 0x11718) +#define VPS_BYTES (HVPS + 0x1171c) /* up to 0x100 */ +#define VPS_EPB (HVPS + 0x1181c) /* emulation prevention bytes in them */ +#define HSPS_TEMPORAL_NESTING (HSPS + 0x0c) /* u8; +0x04 vps id, +0x08 max_sub_layers_minus1 */ +#define HSPS_PTL (HSPS + 0x10) +#define HSPS_ID (HSPS + 0x230) +#define HSPS_CHROMA_FORMAT (HSPS + 0x234) +#define HSPS_WIDTH (HSPS + 0x23c) /* pic_width_in_luma_samples */ +#define HSPS_HEIGHT (HSPS + 0x240) +#define HSPS_WIDTH_CTBS (HSPS + 0x244) /* the fw codes slice_segment_address from these */ +#define HSPS_HEIGHT_CTBS (HSPS + 0x248) +/* u8, then left, right, top, bottom (chroma units) */ +#define HSPS_CONF_WIN (HSPS + 0x24c) +#define HSPS_BIT_DEPTH_LUMA (HSPS + 0x260) /* minus 8 */ +#define HSPS_BIT_DEPTH_CHROMA (HSPS + 0x264) +#define HSPS_LOG2_MAX_POC_LSB (HSPS + 0x268) /* minus 4 */ +#define HSPS_ORDERING_INFO (HSPS + 0x26c) /* u8 */ +/* minus1, [7]; +0x28c num_reorder, +0x2a8 latency */ +#define HSPS_MAX_DEC_PIC_BUF (HSPS + 0x270) +/* minus 3; then diff, min TB minus 2, diff, depths */ +#define HSPS_LOG2_MIN_CB (HSPS + 0x2c4) +#define HSPS_LOG2_DIFF_CB (HSPS + 0x2c8) +#define HSPS_LOG2_MIN_TB (HSPS + 0x2cc) +#define HSPS_LOG2_DIFF_TB (HSPS + 0x2d0) +#define HSPS_DEPTH_INTER (HSPS + 0x2d4) +#define HSPS_DEPTH_INTRA (HSPS + 0x2d8) +#define HSPS_AMP (HSPS + 0x1b88) /* u8; +0x2dc scaling_list_enabled_flag */ +#define HSPS_SAO (HSPS + 0x1b89) /* u8; +0x1b8a pcm_enabled_flag */ +#define HSPS_TMVP (HSPS + 0x1c24) /* u8 */ +#define HSPS_STRONG_INTRA (HSPS + 0x1c25) /* u8 */ +#define HSPS_VUI (HSPS + 0x1c28) /* u8 */ +#define HSPS_VIDEO_SIGNAL (HSPS + 0x1c39) /* u8 */ +#define HSPS_VIDEO_FORMAT (HSPS + 0x1c3c) +#define HSPS_FULL_RANGE (HSPS + 0x1c40) +#define HSPS_COLOUR_DESC (HSPS + 0x1c44) /* u8, then primaries, transfer, matrix */ +/* u8: then u8 tiles_fixed, mvs_over_bounds, restricted_lists */ +#define HSPS_RESTRICTION (HSPS + 0x1cb5) +/* then max_bits_per_min_cu_denom, log2 mv lengths */ +#define HSPS_MAX_BYTES_DENOM (HSPS + 0x1cc0) +#define HSPS_FW_HEADER (HSPS + 0x1cd1) /* u8 bFWCreatesHeader (the PPS's must match) */ +#define HSPS_BITS (HSPS + 0x1cd4) +#define HSPS_BYTES (HSPS + 0x1cd8) /* up to 0x200 */ +#define HSPS_EPB (HSPS + 0x1ed8) +#define HPPS_ID (HPPS + 0x04) /* +0x08 SPS id */ +#define HPPS_SIGN_HIDING (HPPS + 0x14) /* u8, then u8 cabac_init_present_flag */ +/* minus 26; +0x18, +0x1c num_ref_idx defaults minus 1 */ +#define HPPS_INIT_QP (HPPS + 0x20) +/* u8; +0x24 constrained intra, +0x25 transform skip */ +#define HPPS_CU_QP_DELTA (HPPS + 0x26) +#define HPPS_CU_QP_DEPTH (HPPS + 0x28) /* diff_cu_qp_delta_depth */ +#define HPPS_ENTROPY_SYNC (HPPS + 0x71) /* u8; +0x70 tiles_enabled_flag */ +#define HPPS_LF_ACROSS_SLICES (HPPS + 0x881) /* u8; +0x882 deblocking_filter_control_present */ +#define HPPS_FW_HEADER (HPPS + 0x2190) /* u8 */ +#define HPPS_BITS (HPPS + 0x2194) +#define HPPS_BYTES (HPPS + 0x2198) /* up to 0x400 */ +#define HPPS_EPB (HPPS + 0x2598) +/* the RPS struct: the SPS's short-term sets (65 x 0x184), long-term, the picture's */ +#define RPS_NUM_ST (HRPS + 0x0) +#define RPS_ST(i) (HRPS + 0x4 + 0x184 * (i)) /* st_ref_pic_set() */ +#define ST_NUM_NEG 0x30 /* +0x00 u8 inter_ref_pic_set_prediction_flag */ +#define ST_NUM_POS 0x34 +#define ST_DELTA_POC_S0(j) (0x38 + 4 * (j)) /* minus 1 */ +#define ST_USED_S0(j) (0x78 + (j)) /* u8 */ +#define ST_NUM_NEGATIVE 0xd8 /* derived: NumNegativePics, NumPositivePics */ +#define ST_NUM_POSITIVE 0xdc +#define ST_USED_CURR_S0(j) (0xe0 + (j)) /* u8 UsedByCurrPicS0 */ +#define ST_DELTA_S0(j) (0x100 + 4 * (j)) /* DeltaPocS0 */ +#define ST_DELTA_POC_S1(j) (0x88 + 4 * (j)) /* minus 1 */ +#define ST_USED_S1(j) (0xc8 + (j)) /* u8 */ +#define ST_USED_CURR_S1(j) (0xf0 + (j)) /* u8 UsedByCurrPicS1 */ +#define ST_DELTA_S1(j) (0x140 + 4 * (j)) /* DeltaPocS1 */ +#define ST_NUM_DELTA 0x180 /* NumDeltaPocs */ +/* the picture's: u8 short_term_ref_pic_set_sps_flag, +4 idx, +8 a set */ +#define RPS_PIC 0x62e0 +#define RPS_PIC_LEN 0x334 /* (and its long-term part at +0x646c), sent per picture */ + +/* + * HEVC_ENCODE: the slice struct at +0x18 (0x5164 bytes, the firmware takes + * the first 0x964), PicMgmtParams at +0x5180 as in AVC_ENCODE, 12 bytes of + * the frame record at +0x5d58, the picture's RPS (RPS + 0x62e0) at +0x5d64. + */ +#define HSH 0x18 +#define HSH_SIZE_WORD (HSH + 0x000) +#define HSH_NAL_TYPE (HSH + 0x004) +#define HSH_FIRST_SLICE (HSH + 0x008) /* u8; the fw sets it (and the address) per slice */ +#define HSH_SLICE_TYPE (HSH + 0x018) /* as H.264's: 0 P, 1 B, 2 I */ +#define HSH_PIC_OUTPUT (HSH + 0x01c) /* u8 */ +#define HSH_POC_LSB (HSH + 0x024) +#define HSH_ST_RPS_SPS (HSH + 0x028) /* u8 (the fw writes RPS_PIC's) */ +#define HSH_TMVP (HSH + 0x118) /* u8, then u8 sao luma, sao chroma, ref override */ +#define HSH_SAO_LUMA (HSH + 0x119) +#define HSH_SAO_CHROMA (HSH + 0x11a) +#define HSH_NUM_REF_L0 (HSH + 0x11c) /* num_ref_idx_l0_active_minus1, -1: no list */ +#define HSH_NUM_REF_L1 (HSH + 0x120) +#define HSH_MVD_L1_ZERO (HSH + 0x1a4) /* u8; +0x1a5 cabac_init_flag */ +#define HSH_COLOC_FROM_L0 (HSH + 0x1a6) /* u8; +0x1a8 collocated_ref_idx */ +/* five_minus_max_num_merge_cand (also to the pipe) */ +#define HSH_MERGE (HSH + 0x3d0) +#define HSH_REF_MASK (HSH + 0x3d4) /* 4: L0[1] used, 0x100: L1[0] used */ +#define HSH_DIST_SCALE (HSH + 0x3dc) /* u16 [4][4]: MV distance scale, 0x100 = 1 */ +#define HSH_TMVP_SCALE (HSH + 0x3fc) /* u16 [4][4]: [col's ref slot][ref slot] (TMVP) */ +#define HSH_QP_DELTA (HSH + 0x420) /* slice_qp_delta */ +/* u8 slice_loop_filter_across_slices_enabled_flag */ +#define HSH_LF_ACROSS (HSH + 0x438) +#define HSH_SLICE_MAP (HSH + 0x448) /* u8 [256]: the slice of each CTB row */ +#define HSH_ROWS_PER_SLICE (HSH + 0x548) +#define HSH_ROWS_PER_SEGMENT (HSH + 0x54c) +#define HSH_HDR_ADDR(n) (HSH + 0x560 + 4 * (n)) /* where slice n's header goes (256) */ +#define HSH_LEN 0x5164 +#define HPM 0x5180 +#define HEVC_PIC_RPS 0x5d64 +#define SLICE_HDR_STEP 0x400 /* per slice in the slice header buffer */ +#define HEVC_SLICE_HDR_SIZE (256 * SLICE_HDR_STEP) + +#define N_SLOTS 2 /* coded buffers and headers: BFrames + 2 */ +#define N_RECON 3 /* references + 1: 2, with B pictures 3 */ +#define N_LOWRES_RESULT 16 +#define N_ENTROPY 8 +#define N_ENTROPY_HEVC 4 /* the firmware uses [0][0..1] and [1][0..1] only */ +#define OUT_ALIGN 64 /* where the slices (HEVC: their data) start */ +#define AVC_LOG2_MAX_POC 8 /* H.264 with B pictures: pic_order_cnt_lsb bits */ +#define PARAM_SETS_SIZE 0x1000 +#define SLICE_HDR_SIZE 0x1000 +#define MAX_STREAMS 4 /* streams at once (the firmware has 12 clients) */ + +/* the mode decision's scales, 10-bit fixed point (1024 = 1.0); the last is an intra cost offset */ +static const u32 lambda_scales[] = { 1024, 1024, 1024, 1024, 1024, 0 }; + +/* + * HEVC coding tools in the SPS/PPS (and the registers the firmware sets + * from them), tested on the phone: SAO, TMVP, strong intra smoothing and + * 1-5 merge candidates work and are followed by the hardware. The others + * break the stream: with amp_enabled_flag the P pictures do not decode + * (the transcoder codes part_mode without AMP), with sign data hiding + * nothing does (it codes every sign: the pipe's bit changes nothing), and + * cu_qp_delta_enabled_flag hangs the transcoder, WPP or not (an encode + * timeout; the next stream recovers, but a second timeout in a row hung + * the phone), unless the firmware's QP modulation is on: the pipe codes + * the deltas only then, so the flag comes with adaptive quantization + * (ave_video_params()). The parallel merge level is in no register. + */ +#define HEVC_SAO BIT(1) +#define HEVC_TMVP BIT(2) +#define HEVC_STRONG_INTRA BIT(3) +#define HEVC_CU_QP_DELTA BIT(5) /* hangs the transcoder without QPMod */ +/* the tools of every HEVC stream (HEVC_CU_QP_DELTA too with adaptive quantization) */ +#define HEVC_TOOLS (HEVC_SAO | HEVC_TMVP | HEVC_STRONG_INTRA) +#define HEVC_MERGE_CAND 5 /* MaxNumMergeCand */ + +/* + * Speed. The encoder's clock follows the fabric performance level, which + * the PMGR's SoC state sets: at the fast level every picture takes 1/1.37 of + * the time (3840 x 2160 HEVC 23.5 -> 32 pictures/s). apple-pmgr-misc keeps + * the A10's fabric fast while the system runs, so the encoder needs no vote. + */ + +struct ave_heap { + unsigned long *map; + unsigned int order, nbits; + u32 base; /* fw-relative */ +}; + +struct ave_chan { + char name[32]; + u32 type, src, num, rel; + u32 *ring; + u32 cursor; + u32 posted[64]; /* H2T: the command memory of each slot (0 none) */ + u32 posted_len[64]; +}; + +/* a piece of the window */ +struct ave_mem { + void *va; + u32 rel; /* fw-relative */ + u32 iova; /* DART address */ + u32 size; +}; + +/* + * The sizes of a stream's internal buffers (iOS's, per codec). A recon + * picture is [Y LSB][UV LSB][Y MSB][UV MSB]: the 2-bit planes of 10-bit + * HEVC (lsb_y, lsb; else 0), then the 8-bit planes (recon_luma: Y's). + */ +struct ave_sizes { + size_t recon_luma, recon, colocated, lowres, result, entropy; + size_t nbr_info, nbr_pixels, nbr_data, coded, slice_hdr; + size_t lsb_y, lsb; +}; + +/* a picture the firmware has: one per coded slot */ +struct ave_pic { + struct vb2_v4l2_buffer *dst; /* NULL: the slot is free */ + enum ave_pic_type type; + int cur; /* the recon buffer it writes */ + int res; /* the low-res result set it writes */ + u32 out_off; /* where the slices start in the capture buffer */ + u32 data_off; /* HEVC: where the slice data goes (its header before it) */ + u8 hdr_pred[64]; /* HEVC: the slice header the firmware should write, */ + unsigned int hdr_pred_len; /* up to its entry points */ + unsigned int hdr_max; /* HEVC: the longest it can be */ +}; + +/* the recon sets a picture uses, its POC and its references' */ +struct ave_refs { + enum ave_pic_type type; + int cur, l0, l1; /* the one it writes, its references */ + int res; /* the low-res result set it writes */ + u32 poc, poc_l0, poc_l1; /* from the last IDR picture */ + u32 poc_new, poc_old; /* the last anchor, and the one before it */ + bool col_has_ref; /* the last anchor has a reference (TMVP) */ +}; + +/* one stream's buffers and state */ +struct ave_session { + struct ave_ctx *ctx; + bool hevc; + bool ten; /* HEVC Main 10 */ + u32 client; /* the firmware's client id */ + u32 gen; /* the firmware boot it is registered in (hw->gen) */ + struct list_head node; /* in hw->sessions */ + u32 width, height, wmb, hmb; + u32 ctb_w, ctb_h; /* HEVC: 32 x 32 CTBs */ + /* the buffers only the hardware touches: a DMA block of the stream's own */ + void *hwbuf; + dma_addr_t hwbuf_iova; + size_t hwbuf_size, hwbuf_used; + u8 slice_map[256]; /* the slice of each macroblock (HEVC: CTB) row */ + u32 n_slices, rows0; /* slices a picture, rows in the first */ + struct ave_sizes sz; + struct ave_mem area; /* all of the below */ + struct ave_mem recon[N_RECON], colocated[N_RECON], lowres[N_RECON]; + struct ave_mem lowres_result[N_LOWRES_RESULT], entropy[N_ENTROPY]; + struct ave_mem nbr_info, nbr_pixels, nbr_data; + struct ave_mem coded[N_SLOTS], coded_hdr[N_SLOTS], slice_hdr[N_SLOTS], param_sets; + u8 headers[0x300]; /* SPS and PPS (HEVC: VPS, SPS, PPS), Annex B */ + unsigned int headers_len; + u32 log2_max_frame_num; + u32 frame_num; /* of the next picture posted (HEVC: its POC) */ + u32 idr_pic_id; + /* + * References: the recon sets of the last anchor (I or P) and the one + * before, with their POCs. Anchors take turns in sets 0 and 1, B + * pictures (not references) write set 2. + */ + u32 n_recon; + int ref_new, ref_old; + u32 poc_new, poc_old; + int res; /* the low-res result set of the last picture posted */ + u32 bframes; + u32 poc_base; /* the display number of the last IDR picture */ + bool have_ref; /* the last picture posted is a reference */ + bool cabac, deblock_ctrl, transform_8x8; + /* HEVC: the tools of the stream, the level */ + unsigned int tools; + u8 level_idc; + const struct ave_params *params; + /* + * The pictures in flight, in slots: the next one is posted to @slot, + * the firmware finishes them in order from @done_slot. + */ + struct ave_pic pic[N_SLOTS]; + u32 slot, done_slot; + unsigned int inflight; + bool fail_next; /* the picture before failed: so did this reference */ + /* rate control (updated as pictures finish: one picture late with two in flight) */ + int qp, qp_min, qp_max; + s64 fullness; /* bits sent beyond the target */ + u32 target; /* bits per picture */ +}; + +struct ave_hw { + struct ave_dev *ave; + struct device *dev; + void __iomem *cpu, *mbox, *smmu; + phys_addr_t pmgr_phys; + struct dev_pm_domain_list *pds; + int irq; + const char *fw_name; + + struct mutex lock; /* power, boot, sessions, commands */ + struct mutex ipc_lock; /* the rings */ + bool powered, booted, configured; + bool mbox_ok; /* the mailbox answers reads: once the CPU runs */ + bool irq_on; /* after the handshake, which polls the status */ + unsigned int pipes; /* which of the domains are on (bit per index) */ + + void *win; + dma_addr_t win_iova; + size_t win_size; + struct ave_heap shared, area; + dma_addr_t pmgr_iova; + + struct ave_chan chans[MAX_CHANS]; + unsigned int n_chan; + struct ave_chan *terminal, *io, *io_t2h, *smalloc, *buf_t2h; + struct { u32 rel, size; } smallocs[MAX_SMALLOC]; + + /* the answer a synchronous command waits for */ + struct completion done; + u16 wait_id; + u32 wait_status; + + struct ave_session *session; /* the one that posted last (its pictures are in flight) */ + struct list_head sessions; /* every open stream */ + unsigned int n_sessions; + u32 next_client; /* the client id of the next stream (from 1 after a boot) */ + struct delayed_work poll, off_work; + /* ENCODE_DONE, handled in process context under hw->lock */ + struct work_struct enc_work; + spinlock_t ans_lock; /* ans[], ans_head and ans_count */ + /* ENCODE_DONE answers not handled yet (two pictures can finish close together) */ + struct { u32 client, plane, status, gen; } ans[4]; + unsigned int ans_head, ans_count; + u32 gen; /* firmware boots: answers from an earlier one are stale */ +}; + +/* + * The pictures a stream may have at the firmware at once: AVE_MAX_INFLIGHT + * (two, as iOS without B pictures), but 1 while several streams are open + * (ave_hw_session_start()) and with B pictures, as iOS has them with its + * rate control. With two in flight under memory load (the GPU rendering, or + * the first half minute after boot) a stream with B pictures had pictures + * answered without their coded data, then a firmware exception. + */ +unsigned int ave_hw_max_inflight(const struct ave_ctx *ctx) +{ + if (ctx->params.bframes || READ_ONCE(ctx->ave->hw->n_sessions) > 1) + return 1; + return AVE_MAX_INFLIGHT; +} + +static void cpu_wr(struct ave_hw *hw, u32 off, u32 val) +{ + writel(val, hw->cpu + off); +} + +static u32 mb_rd(struct ave_hw *hw, u32 off) +{ + return readl(hw->mbox + off); +} + +static void mb_wr(struct ave_hw *hw, u32 off, u32 val) +{ + writel(val, hw->mbox + off); +} + +/* memory in the window */ + +static int heap_init(struct ave_heap *h, u32 base, size_t size, unsigned int order) +{ + h->base = base; + h->order = order; + h->nbits = size >> order; + h->map = bitmap_zalloc(h->nbits, GFP_KERNEL); + return h->map ? 0 : -ENOMEM; +} + +static void heap_destroy(struct ave_heap *h) +{ + bitmap_free(h->map); + h->map = NULL; +} + +static void *ave_alloc(struct ave_hw *hw, struct ave_heap *h, size_t size, u32 *rel) +{ + unsigned int n = DIV_ROUND_UP(size, 1UL << h->order); + unsigned long start; + + if (!h->map || !n) + return NULL; + start = bitmap_find_next_zero_area(h->map, h->nbits, 0, n, 0); + if (start >= h->nbits) + return NULL; + bitmap_set(h->map, start, n); + *rel = h->base + (start << h->order); + memset(hw->win + *rel, 0, (size_t)n << h->order); + return hw->win + *rel; +} + +static void ave_free(struct ave_hw *hw, struct ave_heap *h, u32 rel, size_t size) +{ + if (h->map && rel >= h->base) + bitmap_clear(h->map, (rel - h->base) >> h->order, + DIV_ROUND_UP(size, 1UL << h->order)); +} + +static void *ave_ptr(struct ave_hw *hw, u32 rel, size_t len) +{ + if (!hw->win || rel >= hw->win_size || len > hw->win_size - rel) + return NULL; + return hw->win + rel; +} + +static u32 ave_iova(struct ave_hw *hw, u32 rel) +{ + return lower_32_bits(hw->win_iova) + rel; +} + +/* rings */ + +static u32 *ring_slot(struct ave_chan *c, u32 i) +{ + return c->ring + i * (SLOT_SIZE / 4); +} + +static void ring_doorbell(struct ave_hw *hw, struct ave_chan *c) +{ + /* pairs with the firmware's read of the slot after the doorbell */ + wmb(); + mb_wr(hw, MB_DOORBELL, BIT(c->src)); +} + +/* a slot the firmware posted to us: owner bit clear */ +static bool ring_pending(struct ave_chan *c, u32 **slot) +{ + u32 *s = ring_slot(c, c->cursor); + + if (READ_ONCE(s[0]) & 1) + return false; + dma_rmb(); + if (!s[0] && !s[1] && !s[2]) /* never written */ + return false; + *slot = s; + return true; +} + +static void ring_next(struct ave_chan *c) +{ + c->cursor = (c->cursor + 1) % c->num; +} + +static void service_terminal(struct ave_hw *hw) +{ + struct ave_chan *c = hw->terminal; + u32 *s; + int n = 0; + + while (c && n++ < c->num && ring_pending(c, &s)) { + u32 rel = s[0] & ~3, len = s[1] ? min_t(u32, s[1], 0x100) : 0x80; + const char *line = ave_ptr(hw, rel, len); + char buf[0x101]; + + if (line && rel && len) { + memcpy(buf, line, len); + buf[len] = 0; + strim(buf); + /* the firmware's asserts and errors; the rest is for debugging */ + if (strstr(buf, "ASSERT") || strstr(buf, "ERROR")) + dev_warn(hw->dev, "fw: %s\n", buf); + else if (buf[0]) + dev_dbg(hw->dev, "fw: %s\n", buf); + } + WRITE_ONCE(s[0], s[0] | 1); + ring_next(c); + } +} + +static void service_smalloc(struct ave_hw *hw) +{ + struct ave_chan *c = hw->smalloc; + u32 *s; + int n = 0; + + while (c && n++ < c->num && ring_pending(c, &s)) { + u32 req = s[0] & ~3, size = s[1], rel = 0; + unsigned int i; + + if (!req) { + for (i = 0; i < MAX_SMALLOC && hw->smallocs[i].rel; i++) + ; + if (i == MAX_SMALLOC || !ave_alloc(hw, &hw->shared, size, &rel)) { + dev_err(hw->dev, "shared malloc of %#x failed\n", size); + rel = 0; + } else { + hw->smallocs[i].rel = rel; + hw->smallocs[i].size = size; + } + } else { + for (i = 0; i < MAX_SMALLOC && hw->smallocs[i].rel != req; i++) + ; + if (i < MAX_SMALLOC) { + ave_free(hw, &hw->shared, req, hw->smallocs[i].size); + hw->smallocs[i].rel = 0; + } + } + WRITE_ONCE(s[1], 0); + WRITE_ONCE(s[2], 0); + dma_wmb(); + WRITE_ONCE(s[0], rel | 1); + ring_next(c); + ring_doorbell(hw, c); + } +} + +/* requests nobody here answers: hand them back */ +static void service_return(struct ave_hw *hw, struct ave_chan *c) +{ + u32 *s; + int n = 0; + + while (c && n++ < c->num && ring_pending(c, &s)) { + dev_dbg(hw->dev, "%s: %#x %#x %#x\n", c->name, s[0], s[1], s[2]); + dma_wmb(); + WRITE_ONCE(s[0], s[0] | 1); + ring_next(c); + ring_doorbell(hw, c); + } +} + +/* commands whose slot came back: their memory is free */ +static void service_io(struct ave_hw *hw) +{ + struct ave_chan *c = hw->io; + unsigned int i; + + for (i = 0; c && i < c->num; i++) { + if (c->posted[i] && (READ_ONCE(ring_slot(c, i)[0]) & 1)) { + ave_free(hw, &hw->shared, c->posted[i], c->posted_len[i]); + c->posted[i] = 0; + } + } +} + +struct ave_answer { + u16 id; + u32 client, plane, status; +}; + +/* answers on IO_T2H; returns how many it put in @a */ +static unsigned int service_answers(struct ave_hw *hw, struct ave_answer *a, unsigned int max) +{ + struct ave_chan *c = hw->io_t2h; + unsigned int got = 0; + u32 *s; + int n = 0; + + while (c && n++ < c->num && got < max && ring_pending(c, &s)) { + u32 w0 = s[0], w1 = s[1], w2 = s[2]; + const u8 *rec = ave_ptr(hw, w0 & ~3, 0x1c); + + if (rec) { + a[got].id = get_unaligned_le16(rec + 4); + a[got].client = get_unaligned_le32(rec + 8); + a[got].plane = get_unaligned_le32(rec + 0x10); + a[got].status = get_unaligned_le32(rec + (a[got].id == ANS_COMPLETE ? + 0x20 : 0x18)); + dev_dbg(hw->dev, "answer %#x plane %u status %#x\n", a[got].id, + a[got].plane, a[got].status); + got++; + } + WRITE_ONCE(s[1], w1); + WRITE_ONCE(s[2], w2); + dma_wmb(); + WRITE_ONCE(s[0], w0 | 1); + ring_next(c); + ring_doorbell(hw, c); + } + return got; +} + +/* everything the firmware has for us */ +static void ave_service(struct ave_hw *hw) +{ + struct ave_answer a[8]; + unsigned int n, i; + + do { + mutex_lock(&hw->ipc_lock); + if (!hw->terminal) { /* no firmware (or its window is going) */ + mutex_unlock(&hw->ipc_lock); + return; + } + service_terminal(hw); + service_smalloc(hw); + service_return(hw, hw->buf_t2h); + service_io(hw); + n = service_answers(hw, a, ARRAY_SIZE(a)); + mutex_unlock(&hw->ipc_lock); + + for (i = 0; i < n; i++) { + if (a[i].id == ANS_ENCODE) { + spin_lock(&hw->ans_lock); + if (hw->ans_count < ARRAY_SIZE(hw->ans)) { + unsigned int k = (hw->ans_head + hw->ans_count++) % + ARRAY_SIZE(hw->ans); + + hw->ans[k].client = a[i].client; + hw->ans[k].plane = a[i].plane; + hw->ans[k].status = a[i].status; + hw->ans[k].gen = READ_ONCE(hw->gen); + } else { + dev_err(hw->dev, "ENCODE_DONE for slot %u lost\n", + a[i].plane); + } + spin_unlock(&hw->ans_lock); + queue_work(system_highpri_wq, &hw->enc_work); + } else if (a[i].id == ANS_SLICE) { + continue; + } else if (a[i].id == ANS_TIMEOUT) { + dev_err(hw->dev, "firmware: frame-done timeout\n"); + } else if (a[i].id == READ_ONCE(hw->wait_id)) { + WRITE_ONCE(hw->wait_status, a[i].status); + WRITE_ONCE(hw->wait_id, 0); + complete(&hw->done); + } else { + dev_warn(hw->dev, "unexpected answer %#x (status %#x)\n", + a[i].id, a[i].status); + } + } + } while (n == ARRAY_SIZE(a)); +} + +static irqreturn_t ave_irq_thread(int irq, void *data) +{ + struct ave_hw *hw = data; + u32 st; + + if (!READ_ONCE(hw->irq_on)) + return IRQ_NONE; + st = mb_rd(hw, MB_STATUS); + if (st) + mb_wr(hw, MB_STATUS, st); + ave_service(hw); + return IRQ_HANDLED; +} + +/* a safety net: the interrupt does the work */ +static void ave_poll_work(struct work_struct *work) +{ + struct ave_hw *hw = container_of(work, struct ave_hw, poll.work); + + if (!READ_ONCE(hw->booted)) + return; + ave_service(hw); + schedule_delayed_work(&hw->poll, msecs_to_jiffies(200)); +} + +/* + * Post a command on IO: copied into shared memory (the firmware copies it + * before it hands the slot back, so the memory goes then). + */ +static int ave_post(struct ave_hw *hw, const void *cmd, u32 len) +{ + struct ave_chan *c = hw->io; + u32 *s, rel; + void *p; + int ret = 0; + + mutex_lock(&hw->ipc_lock); + service_io(hw); + s = ring_slot(c, c->cursor); + if (!(READ_ONCE(s[0]) & 1)) { + dev_err(hw->dev, "IO slot %u busy\n", c->cursor); + ret = -EBUSY; + goto out; + } + p = ave_alloc(hw, &hw->shared, len, &rel); + if (!p) { + ret = -ENOMEM; + goto out; + } + memcpy(p, cmd, len); + c->posted[c->cursor] = rel; + c->posted_len[c->cursor] = len; + if (mb_rd(hw, MB_IDLE)) + mb_wr(hw, MB_IDLE, 0); + WRITE_ONCE(s[1], len); + WRITE_ONCE(s[2], len); + dma_wmb(); + WRITE_ONCE(s[0], rel); + ring_next(c); + ring_doorbell(hw, c); +out: + mutex_unlock(&hw->ipc_lock); + return ret; +} + +static u32 ave_codec(const struct ave_session *s) +{ + return s->hevc ? CODEC_HEVC : CODEC_AVC; +} + +static void ave_cmd_header(u8 *cmd, u16 id, u32 client, u32 codec, u32 plane, u32 key) +{ + put_unaligned_le16(id, cmd + 4); + put_unaligned_le32(client, cmd + 8); + put_unaligned_le32(codec, cmd + 0xc); + put_unaligned_le32(plane, cmd + 0x10); + put_unaligned_le32(key, cmd + 0x14); +} + +/* a command and its answer (hw->lock held) */ +static int ave_cmd_sync(struct ave_hw *hw, const void *cmd, u32 len, u16 answer, + unsigned int timeout_ms) +{ + int ret; + + reinit_completion(&hw->done); + WRITE_ONCE(hw->wait_status, 0); + WRITE_ONCE(hw->wait_id, answer); + ret = ave_post(hw, cmd, len); + if (ret) { + WRITE_ONCE(hw->wait_id, 0); + return ret; + } + if (!wait_for_completion_timeout(&hw->done, msecs_to_jiffies(timeout_ms))) { + ave_service(hw); /* the interrupt may be lost */ + if (!try_wait_for_completion(&hw->done)) { + WRITE_ONCE(hw->wait_id, 0); + dev_err(hw->dev, "command %#x: no answer\n", + get_unaligned_le16((u8 *)cmd + 4)); + return -ETIMEDOUT; + } + } + if (hw->wait_status != STATUS_OK) { + dev_err(hw->dev, "command %#x: status %#x\n", get_unaligned_le16((u8 *)cmd + 4), + hw->wait_status); + return -EIO; + } + return 0; +} + +/* power */ + +#define PD_SYS 0 +#define PD_PIPE4 1 +#define PD_PIPE5 2 +#define PD_ME0 3 +#define PD_ME1 4 + +static void ave_power_off(struct ave_hw *hw); + +static int ave_power_on(struct ave_hw *hw) +{ + /* + * VENC_SYS first, then the pipes and both motion estimators. H.264 + * needs PIPE5 too: the firmware reads registers there (encoder core + * +0x1a1000) after the CABAC transcode, an external abort without it. + */ + static const unsigned int order[] = { PD_SYS, PD_PIPE4, PD_PIPE5, PD_ME0, PD_ME1 }; + unsigned int i; + int ret; + + if (hw->powered) + return 0; + ret = pm_runtime_resume_and_get(hw->dev); /* and dart-ave */ + if (ret < 0) + return ret; + hw->pipes = 0; + for (i = 0; i < ARRAY_SIZE(order); i++) { + unsigned int d = order[i]; + + if (d >= hw->pds->num_pds) + continue; + ret = pm_runtime_resume_and_get(hw->pds->pd_devs[d]); + if (ret < 0) { + dev_err(hw->dev, "power domain %u: %d\n", d, ret); + hw->powered = true; + ave_power_off(hw); + return ret; + } + hw->pipes |= BIT(d); + } + WRITE_ONCE(hw->powered, true); + /* iOS votes right after VENC_SYS, before the firmware boots */ + return 0; +} + +static void ave_power_off(struct ave_hw *hw) +{ + /* iOS: ME1, ME0, the pipes, then VENC_SYS */ + static const unsigned int order[] = { PD_ME1, PD_ME0, PD_PIPE4, PD_PIPE5, PD_SYS }; + unsigned int i; + + if (!hw->powered) + return; + if (hw->irq_on) { + disable_irq(hw->irq); + hw->irq_on = false; + } + if (hw->mbox_ok) { + mb_wr(hw, MB_IDLE, 1); + WRITE_ONCE(hw->mbox_ok, false); + } + WRITE_ONCE(hw->powered, false); + for (i = 0; i < ARRAY_SIZE(order); i++) + if (hw->pipes & BIT(order[i])) + pm_runtime_put_sync(hw->pds->pd_devs[order[i]]); + hw->pipes = 0; + pm_runtime_put_sync(hw->dev); + /* iOS drops its votes last but one, before VENC_SYS */ +} + +/* boot */ + +static void ave_unboot(struct ave_hw *hw) +{ + u32 v; + + if (hw->booted && hw->powered) { + u8 cmd[HDR_SIZE] = {}; + + ave_cmd_header(cmd, CMD_POWERDOWN, CLIENT_POWERDOWN, CODEC_AVC, PLANE_POWERDOWN, + 0x7fffffff); + mb_wr(hw, MB_SCRATCH(0), 0); + if (!ave_post(hw, cmd, sizeof(cmd)) && + readl_poll_timeout(hw->mbox + MB_SCRATCH(0), v, v == MAGIC_HOST, 1000, 220000)) + dev_warn(hw->dev, "no answer to POWERDOWN\n"); + } + /* + * Stop the encoder's CPU itself. POWERDOWN is only a request to the + * firmware, and powering the domains off does not stop it: after + * ~100 back-to-back streams, dart-ave faulted on reads inside the + * firmware image of a window freed two streams before (an old + * firmware still running), and the phone hung. The window goes only + * after this and the power-off (ave_release()). + */ + if (hw->powered) { + cpu_wr(hw, CPU_RUN, 0); + usleep_range(1000, 2000); + } + WRITE_ONCE(hw->booted, false); + WRITE_ONCE(hw->gen, hw->gen + 1); + spin_lock_irq(&hw->ans_lock); + hw->ans_count = 0; + spin_unlock_irq(&hw->ans_lock); + cancel_delayed_work_sync(&hw->poll); + mutex_lock(&hw->ipc_lock); + hw->terminal = NULL; + hw->io = NULL; + hw->io_t2h = NULL; + hw->smalloc = NULL; + hw->buf_t2h = NULL; + hw->n_chan = 0; + mutex_unlock(&hw->ipc_lock); + hw->configured = false; + memset(hw->smallocs, 0, sizeof(hw->smallocs)); +} + +/* the firmware's memory, once its CPU is stopped and the encoder powered off */ +static void ave_release(struct ave_hw *hw) +{ + WARN_ON(hw->powered); + heap_destroy(&hw->shared); + heap_destroy(&hw->area); + if (hw->pmgr_iova) + dma_unmap_resource(hw->dev, hw->pmgr_iova, SZ_16K, DMA_BIDIRECTIONAL, 0); + hw->pmgr_iova = 0; + if (hw->win) + dma_free_coherent(hw->dev, hw->win_size, hw->win, hw->win_iova); + hw->win = NULL; +} + +static struct ave_chan *ave_find_chan(struct ave_hw *hw, const char *name) +{ + unsigned int i; + + for (i = 0; i < hw->n_chan; i++) + if (!strcmp(hw->chans[i].name, name)) + return &hw->chans[i]; + dev_err(hw->dev, "no channel %s\n", name); + return NULL; +} + +static int ave_wait_status(struct ave_hw *hw, const char *what) +{ + u32 v; + + if (readl_poll_timeout(hw->mbox + MB_STATUS, v, v & 1, 1000, 5000000)) { + dev_err(hw->dev, "%s: no answer (status %#x, scratch %#x %#x %#x %#x)\n", what, v, + mb_rd(hw, MB_SCRATCH(0)), mb_rd(hw, MB_SCRATCH(1)), + mb_rd(hw, MB_SCRATCH(2)), mb_rd(hw, MB_SCRATCH(3))); + return -ETIMEDOUT; + } + mb_wr(hw, MB_STATUS, 1); + return 0; +} + +/* power on and boot the firmware with a window of @area bytes for a stream's buffers */ +static int ave_boot(struct ave_hw *hw, size_t area) +{ + const struct firmware *fw; + u32 n_chan, ipc_size, heap_size, ipc_rel, args_rel, table_rel, heap_rel = 0, v, *args; + unsigned int i; + int ret; + + ret = request_firmware(&fw, hw->fw_name, hw->dev); + if (ret) + return ret; + if (fw->size > FW_SIZE) { + release_firmware(fw); + return -EFBIG; + } + ret = ave_power_on(hw); + if (ret) { + release_firmware(fw); + return ret; + } + + hw->win_size = WIN_FIXED + ALIGN(area, SZ_1M); + hw->win = dma_alloc_coherent(hw->dev, hw->win_size, &hw->win_iova, GFP_KERNEL); + if (!hw->win) { + release_firmware(fw); + ret = -ENOMEM; + goto fail; + } + memcpy(hw->win, fw->data, fw->size); + release_firmware(fw); + if (upper_32_bits(hw->win_iova + hw->win_size - 1) || hw->win_size > WIN_CPU_MAX) { + dev_err(hw->dev, "window at %pad beyond 32 bits\n", &hw->win_iova); + ret = -ERANGE; + goto fail; + } + ret = heap_init(&hw->shared, FW_SIZE, SHARED_SIZE, SHARED_ORDER); + if (!ret) + ret = heap_init(&hw->area, WIN_FIXED, hw->win_size - WIN_FIXED, PAGE_SHIFT); + if (ret) + goto fail; + + /* the firmware drives the pipes' power states through this page */ + hw->pmgr_iova = dma_map_resource(hw->dev, hw->pmgr_phys, SZ_16K, DMA_BIDIRECTIONAL, 0); + if (dma_mapping_error(hw->dev, hw->pmgr_iova)) { + hw->pmgr_iova = 0; + ret = -ENOMEM; + goto fail; + } + + /* the encoder's accesses go through dart-ave */ + writel(readl(hw->smmu + 0xc) | 0x80808080, hw->smmu + 0xc); + + cpu_wr(hw, 0x18, 0); + cpu_wr(hw, 0x20, 0); + cpu_wr(hw, CPU_WINDOW, WIN_CPU_MAX); + cpu_wr(hw, 0x30, 0); + cpu_wr(hw, CPU_BASE, lower_32_bits(hw->win_iova)); + cpu_wr(hw, 0x10, 0); + cpu_wr(hw, 0x38, 1); + cpu_wr(hw, 0x808, 1); + cpu_wr(hw, 0xb80, 0); + cpu_wr(hw, 0xba0, 1); + if (readl_poll_timeout(hw->cpu + CPU_STATUS, v, !v, 1000, 500000)) { + dev_err(hw->dev, "CPU status %#x\n", v); + ret = -ETIMEDOUT; + goto fail; + } + /* the mailbox takes writes now; reads only once the CPU runs (iOS's order) */ + mb_wr(hw, MB_SCRATCH(0), MAGIC_HOST); + cpu_wr(hw, CPU_RUN, 0); + cpu_wr(hw, CPU_RUN, CPU_RUN_GO); + usleep_range(1000, 2000); + WRITE_ONCE(hw->mbox_ok, true); + + ret = ave_wait_status(hw, "start"); + if (ret) + goto fail; + n_chan = mb_rd(hw, MB_SCRATCH(0)); + ipc_size = mb_rd(hw, MB_SCRATCH(1)); + heap_size = mb_rd(hw, MB_SCRATCH(3)); + dev_dbg(hw->dev, "awake: %u channels, IPC %#x, heap %#x\n", n_chan, ipc_size, heap_size); + if (!n_chan || n_chan > MAX_CHANS || !ipc_size || ipc_size > SHARED_SIZE / 2) { + dev_err(hw->dev, "bad handshake: %u channels, IPC %#x\n", n_chan, ipc_size); + ret = -EINVAL; + goto fail; + } + ret = -ENOMEM; + if (!ave_alloc(hw, &hw->shared, ipc_size, &ipc_rel)) + goto fail; + args = ave_alloc(hw, &hw->shared, 0x40, &args_rel); + if (!args) + goto fail; + /* the extra heap: 16 KiB aligned, after the shared memory */ + if (heap_size) { + heap_size = ALIGN(max_t(u32, heap_size, 0x1000), SZ_16K); + if (heap_size > HEAP_SIZE) { + dev_err(hw->dev, "heap of %#x wanted\n", heap_size); + ret = -ENOSPC; + goto fail; + } + heap_rel = FW_SIZE + SHARED_SIZE; + } + args[0] = lower_32_bits(hw->win_iova); + args[1] = ipc_rel; + args[2] = FW_SIZE; + args[3] = SHARED_SIZE; + args[4] = heap_size ? ave_iova(hw, heap_rel) : 0; + args[5] = heap_size; + args[6] = 1; + /* pairs with the firmware's read of the arguments after the doorbell */ + wmb(); + mb_wr(hw, MB_SCRATCH(0), args_rel); + mb_wr(hw, MB_DOORBELL, 1); + + ret = ave_wait_status(hw, "channel table"); + if (ret) + goto fail; + table_rel = mb_rd(hw, MB_SCRATCH(0)); + mutex_lock(&hw->ipc_lock); + for (i = 0; i < n_chan; i++) { + const u8 *e = ave_ptr(hw, table_rel + 0x100 * i, 0x100); + struct ave_chan *c = &hw->chans[i]; + + memset(c, 0, sizeof(*c)); + if (!e) { + ret = -EINVAL; + break; + } + strscpy(c->name, e, sizeof(c->name)); + c->type = get_unaligned_le32(e + 0x40); + c->src = get_unaligned_le32(e + 0x44); + c->num = get_unaligned_le32(e + 0x48); + c->rel = get_unaligned_le32(e + 0x4c); + c->ring = ave_ptr(hw, c->rel, c->num * SLOT_SIZE); + dev_dbg(hw->dev, "channel %-12s type %u src %u slots %u at %#x\n", c->name, + c->type, c->src, c->num, c->rel); + if (!c->ring || !c->num || c->num > 4096 || c->src > 31) { + ret = -EINVAL; + break; + } + if (c->type == RING_H2T) { + unsigned int j; + + for (j = 0; j < c->num; j++) { + u32 *s = ring_slot(c, j); + + s[1] = 0; + s[2] = 0; + s[0] = 1; + } + } + } + hw->n_chan = i; + if (!ret) { + hw->terminal = ave_find_chan(hw, "TERMINAL"); + hw->io = ave_find_chan(hw, "IO"); + hw->io_t2h = ave_find_chan(hw, "IO_T2H"); + hw->smalloc = ave_find_chan(hw, "SHAREDMALLOC"); + hw->buf_t2h = ave_find_chan(hw, "BUF_T2H"); + if (!hw->terminal || !hw->io || !hw->io_t2h || !hw->smalloc || + hw->io->num > ARRAY_SIZE(hw->io->posted)) + ret = -ENODEV; + } + mutex_unlock(&hw->ipc_lock); + if (ret) + goto fail; + /* pairs with the firmware's read of the rings after MAGIC_HOST */ + wmb(); + mb_wr(hw, MB_SCRATCH(3), MAGIC_HOST); + if (readl_poll_timeout(hw->mbox + MB_SCRATCH(3), v, !v, 1000, 2002000)) { + dev_err(hw->dev, "channel table not taken (scratch3 %#x)\n", v); + ret = -ETIMEDOUT; + goto fail; + } + /* from here the interrupt takes the status bits */ + mb_wr(hw, MB_STATUS, mb_rd(hw, MB_STATUS)); + hw->irq_on = true; + enable_irq(hw->irq); + WRITE_ONCE(hw->booted, true); + schedule_delayed_work(&hw->poll, msecs_to_jiffies(200)); + ave_service(hw); + dev_dbg(hw->dev, "firmware up (window %zu MB at %pad)\n", hw->win_size >> 20, + &hw->win_iova); + return 0; + +fail: + if (hw->terminal) + ave_service(hw); + ave_unboot(hw); + ave_power_off(hw); + ave_release(hw); + return ret; +} + +/* the H.264 headers */ + +struct bitw { + u8 *buf; + unsigned int size, bits; + bool overflow; +}; + +static void bw_put(struct bitw *b, u32 val, unsigned int n) +{ + while (n--) { + unsigned int byte = b->bits >> 3; + u8 mask = 0x80 >> (b->bits & 7); + + if (byte >= b->size) { + b->overflow = true; + return; + } + if ((val >> n) & 1) + b->buf[byte] |= mask; + else + b->buf[byte] &= ~mask; + b->bits++; + } +} + +static void bw_ue(struct bitw *b, u32 v) +{ + u64 x = (u64)v + 1; + unsigned int len = fls64(x); + + bw_put(b, 0, len - 1); + bw_put(b, (u32)x, len); +} + +static void bw_se(struct bitw *b, s32 v) +{ + bw_ue(b, v > 0 ? 2 * v - 1 : -2 * v); +} + +static void bw_trailing(struct bitw *b) +{ + bw_put(b, 1, 1); + while (b->bits & 7) + bw_put(b, 0, 1); +} + +/* + * Start code, NAL header (1 byte for H.264, 2 for HEVC) and the RBSP with + * emulation prevention; @epb counts the bytes that adds. + */ +static int nal_wrap_hdr(u8 *out, unsigned int max, const u8 *hdr, unsigned int hdr_len, + const u8 *rbsp, unsigned int len, unsigned int *epb) +{ + unsigned int o = 0, zeros = 0, i; + + if (max < 4 + hdr_len) + return -ENOSPC; + out[o++] = 0; + out[o++] = 0; + out[o++] = 0; + out[o++] = 1; + for (i = 0; i < hdr_len; i++) + out[o++] = hdr[i]; + if (epb) + *epb = 0; + for (i = 0; i < len; i++) { + if (zeros >= 2 && rbsp[i] <= 3) { + if (o >= max) + return -ENOSPC; + out[o++] = 3; + zeros = 0; + if (epb) + (*epb)++; + } + if (o >= max) + return -ENOSPC; + out[o++] = rbsp[i]; + zeros = rbsp[i] ? 0 : zeros + 1; + } + return o; +} + +static int nal_wrap(u8 *out, unsigned int max, u8 nal, const u8 *rbsp, unsigned int len) +{ + return nal_wrap_hdr(out, max, &nal, 1, rbsp, len, NULL); +} + +/* HEVC: nal_unit_header() with layer 0, temporal id 0 */ +static int hevc_nal_wrap(u8 *out, unsigned int max, u8 type, const u8 *rbsp, unsigned int len, + unsigned int *epb) +{ + const u8 hdr[2] = { type << 1, 1 }; + + return nal_wrap_hdr(out, max, hdr, 2, rbsp, len, epb); +} + +/* H.264 Table A-1: MaxMBPS, MaxFS, MaxBR (kbit/s, Baseline/Main) */ +static const struct { u8 idc; u32 mbps, fs, br; } avc_levels[] = { + { 10, 1485, 99, 64 }, { 9, 1485, 99, 128 }, { 11, 3000, 396, 192 }, + { 12, 6000, 396, 384 }, { 13, 11880, 396, 768 }, { 20, 11880, 396, 2000 }, + { 21, 19800, 792, 4000 }, { 22, 20250, 1620, 4000 }, { 30, 40500, 1620, 10000 }, + { 31, 108000, 3600, 14000 }, { 32, 216000, 5120, 20000 }, + { 40, 245760, 8192, 20000 }, { 41, 245760, 8192, 50000 }, + { 42, 522240, 8704, 50000 }, { 50, 589824, 22080, 135000 }, + { 51, 983040, 36864, 240000 }, { 52, 2073600, 36864, 240000 }, +}; + +/* the lowest level at or above the control's that the stream fits */ +static u8 avc_level(const struct ave_params *p, u32 wmb, u32 hmb) +{ + u32 fs = wmb * hmb; + u64 mbps = div_u64((u64)fs * p->fps_num + p->fps_den - 1, p->fps_den); + u32 br = (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ ? 0 : + (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR ? + p->bitrate_peak : p->bitrate)) / 1000; + bool high = p->profile == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH; + unsigned int i; + + for (i = min_t(u32, p->level, ARRAY_SIZE(avc_levels) - 1); i < ARRAY_SIZE(avc_levels); i++) + if (fs <= avc_levels[i].fs && mbps <= avc_levels[i].mbps && + br <= avc_levels[i].br * (high ? 5 : 4) / 4 && + (u64)wmb * wmb <= 8ULL * avc_levels[i].fs && + (u64)hmb * hmb <= 8ULL * avc_levels[i].fs) + return avc_levels[i].idc; + return 52; +} + +/* V4L2 colorimetry to the VUI's codes */ +static void avc_colour(const struct ave_params *p, u8 *prim, u8 *xfer, u8 *matrix, bool *full) +{ + switch (p->colorspace) { + case V4L2_COLORSPACE_SMPTE170M: + *prim = 6; + break; + case V4L2_COLORSPACE_BT2020: + *prim = 9; + break; + case V4L2_COLORSPACE_470_SYSTEM_BG: + *prim = 5; + break; + default: + *prim = 1; + break; + } + switch (p->xfer_func ? p->xfer_func : V4L2_MAP_XFER_FUNC_DEFAULT(p->colorspace)) { + case V4L2_XFER_FUNC_SRGB: + *xfer = 13; + break; + case V4L2_XFER_FUNC_SMPTE2084: + *xfer = 16; + break; + default: + *xfer = 1; + break; + } + switch (p->ycbcr_enc ? p->ycbcr_enc : V4L2_MAP_YCBCR_ENC_DEFAULT(p->colorspace)) { + case V4L2_YCBCR_ENC_601: + *matrix = 6; + break; + case V4L2_YCBCR_ENC_BT2020: + *matrix = 9; + break; + default: + *matrix = 1; + break; + } + *full = p->quantization == V4L2_QUANTIZATION_FULL_RANGE || + (p->quantization == V4L2_QUANTIZATION_DEFAULT && + p->colorspace == V4L2_COLORSPACE_JPEG); +} + +/* fill the SPS and PPS structs of AVC_INIT and write their bits there and in s->headers */ +static int avc_headers(struct ave_session *s, const struct ave_params *p, u8 *init) +{ + unsigned int i; + u8 rbsp[256] = {}, prim, xfer, matrix; + struct bitw b = { rbsp, sizeof(rbsp) }; + u32 profile = p->profile, crop_r, crop_b, num, den; + u8 profile_idc, level_idc = avc_level(p, s->wmb, s->hmb); + bool cbp = profile == V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE; + bool baseline = cbp || profile == V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE; + bool high = profile == V4L2_MPEG_VIDEO_H264_PROFILE_HIGH, full; + int n1, n2; + + profile_idc = high ? 100 : baseline ? 66 : 77; + s->cabac = p->cabac && !baseline; + s->transform_8x8 = high; + s->deblock_ctrl = true; + s->log2_max_frame_num = 4; + crop_r = (s->wmb * 16 - p->crop.width - p->crop.left) / 2; + crop_b = (s->hmb * 16 - p->crop.height - p->crop.top) / 2; + avc_colour(p, &prim, &xfer, &matrix, &full); + + put_unaligned_le32(profile_idc, init + SPS_PROFILE); + put_unaligned_le32(baseline, init + SPS_CONSTRAINT(0)); + put_unaligned_le32(baseline || !high, init + SPS_CONSTRAINT(1)); + put_unaligned_le32(level_idc, init + SPS_LEVEL); + put_unaligned_le32(1, init + SPS_CHROMA_FORMAT); + put_unaligned_le32(s->log2_max_frame_num - 4, init + SPS_LOG2_MAX_FRAME_NUM); + /* + * Without B pictures POC type 2 (output order = decoding order); with + * them type 0, the POC (display number from the IDR) in each slice + * header, and the two anchors as references. + */ + put_unaligned_le32(s->bframes ? 0 : 2, init + SPS_POC_TYPE); + put_unaligned_le32(AVC_LOG2_MAX_POC - 4, init + SPS_LOG2_MAX_POC); + put_unaligned_le32(s->bframes ? 2 : 1, init + SPS_MAX_NUM_REF); + put_unaligned_le32(s->wmb - 1, init + SPS_WIDTH_MBS); + put_unaligned_le32(s->hmb - 1, init + SPS_HEIGHT_MBS); + put_unaligned_le32(1, init + SPS_FRAME_MBS_ONLY); + put_unaligned_le32(1, init + SPS_DIRECT_8X8); + /* + * The quantiser's weights: the firmware programs 0x10000 / w and w from + * these lists whether or not the stream signals a matrix (0 quantises + * everything away). Flat 16, H.264's default without matrices. + */ + for (i = 0; i < SPS_N_SCALING; i++) + put_unaligned_le16(16, init + SPS_SCALING_LISTS + 2 * i); + init[SPS_VUI] = 1; + init[SPS_VIDEO_SIGNAL] = 1; + put_unaligned_le32(5, init + SPS_VIDEO_FORMAT); + put_unaligned_le32(full, init + SPS_FULL_RANGE); + init[SPS_COLOUR_DESC] = 1; + put_unaligned_le32(prim, init + SPS_PRIMARIES); + put_unaligned_le32(xfer, init + SPS_TRANSFER); + put_unaligned_le32(matrix, init + SPS_MATRIX); + init[SPS_TIMING] = 1; + init[SPS_RESTRICTION] = 1; + if (crop_r || crop_b || p->crop.left || p->crop.top) { + init[SPS_CROP] = 1; + put_unaligned_le32(p->crop.left / 2, init + SPS_CROP + 4); + put_unaligned_le32(crop_r, init + SPS_CROP + 8); + put_unaligned_le32(p->crop.top / 2, init + SPS_CROP + 12); + put_unaligned_le32(crop_b, init + SPS_CROP + 16); + } + + /* seq_parameter_set_rbsp() */ + bw_put(&b, profile_idc, 8); + bw_put(&b, baseline, 1); /* constraint_set0 */ + bw_put(&b, baseline || !high, 1); /* constraint_set1: constrained baseline, main */ + bw_put(&b, 0, 6); + bw_put(&b, level_idc, 8); + bw_ue(&b, 0); /* seq_parameter_set_id */ + if (high) { + bw_ue(&b, 1); /* chroma_format_idc */ + bw_ue(&b, 0); /* bit_depth_luma_minus8 */ + bw_ue(&b, 0); /* bit_depth_chroma_minus8 */ + bw_put(&b, 0, 1); /* qpprime_y_zero_transform_bypass_flag */ + bw_put(&b, 0, 1); /* seq_scaling_matrix_present_flag */ + } + bw_ue(&b, s->log2_max_frame_num - 4); + if (s->bframes) { + bw_ue(&b, 0); /* pic_order_cnt_type */ + bw_ue(&b, AVC_LOG2_MAX_POC - 4); /* log2_max_pic_order_cnt_lsb_minus4 */ + bw_ue(&b, 2); /* max_num_ref_frames */ + } else { + /* pic_order_cnt_type: output order = decoding order */ + bw_ue(&b, 2); + bw_ue(&b, 1); /* max_num_ref_frames */ + } + bw_put(&b, 0, 1); /* gaps_in_frame_num_value_allowed_flag */ + bw_ue(&b, s->wmb - 1); + bw_ue(&b, s->hmb - 1); + bw_put(&b, 1, 1); /* frame_mbs_only_flag */ + bw_put(&b, 1, 1); /* direct_8x8_inference_flag */ + bw_put(&b, init[SPS_CROP], 1); + if (init[SPS_CROP]) { + bw_ue(&b, p->crop.left / 2); + bw_ue(&b, crop_r); + bw_ue(&b, p->crop.top / 2); + bw_ue(&b, crop_b); + } + bw_put(&b, 1, 1); /* vui_parameters_present_flag */ + bw_put(&b, 0, 1); /* aspect_ratio_info_present_flag */ + bw_put(&b, 0, 1); /* overscan_info_present_flag */ + bw_put(&b, 1, 1); /* video_signal_type_present_flag */ + bw_put(&b, 5, 3); /* video_format: unspecified */ + bw_put(&b, full, 1); + bw_put(&b, 1, 1); /* colour_description_present_flag */ + bw_put(&b, prim, 8); + bw_put(&b, xfer, 8); + bw_put(&b, matrix, 8); + bw_put(&b, 0, 1); /* chroma_loc_info_present_flag */ + /* timing: a tick per field, so frames take two */ + num = p->fps_den; + den = p->fps_num * 2; + bw_put(&b, 1, 1); /* timing_info_present_flag */ + bw_put(&b, num, 32); /* num_units_in_tick */ + bw_put(&b, den, 32); /* time_scale */ + bw_put(&b, 0, 1); /* fixed_frame_rate_flag */ + bw_put(&b, 0, 1); /* nal_hrd_parameters_present_flag */ + bw_put(&b, 0, 1); /* vcl_hrd_parameters_present_flag */ + bw_put(&b, 0, 1); /* pic_struct_present_flag */ + bw_put(&b, 1, 1); /* bitstream_restriction_flag */ + bw_put(&b, 1, 1); /* motion_vectors_over_pic_boundaries_flag */ + bw_ue(&b, 2); /* max_bytes_per_pic_denom */ + bw_ue(&b, 1); /* max_bits_per_mb_denom */ + bw_ue(&b, 16); /* log2_max_mv_length_horizontal */ + bw_ue(&b, 16); /* log2_max_mv_length_vertical */ + bw_ue(&b, !!s->bframes); /* max_num_reorder_frames: B before their anchor */ + bw_ue(&b, s->bframes ? 2 : 1); /* max_dec_frame_buffering */ + bw_trailing(&b); + if (b.overflow) + return -ENOSPC; + n1 = nal_wrap(init + SPS_BYTES, 0x200, 0x67, rbsp, b.bits / 8); + if (n1 < 0) + return n1; + put_unaligned_le32(n1 * 8, init + SPS_BITS); + + memset(rbsp, 0, sizeof(rbsp)); + b = (struct bitw){ rbsp, sizeof(rbsp) }; + put_unaligned_le32(s->cabac, init + PPS_CABAC); + init[PPS_DEBLOCKING_CTRL] = s->deblock_ctrl; + init[PPS_TRANSFORM_8X8] = s->transform_8x8; + /* pic_parameter_set_rbsp() */ + bw_ue(&b, 0); /* pic_parameter_set_id */ + bw_ue(&b, 0); /* seq_parameter_set_id */ + bw_put(&b, s->cabac, 1); /* entropy_coding_mode_flag */ + bw_put(&b, 0, 1); /* bottom_field_pic_order_in_frame_present_flag */ + bw_ue(&b, 0); /* num_slice_groups_minus1 */ + bw_ue(&b, 0); /* num_ref_idx_l0_default_active_minus1 */ + bw_ue(&b, 0); /* num_ref_idx_l1_default_active_minus1 */ + bw_put(&b, 0, 1); /* weighted_pred_flag */ + bw_put(&b, 0, 2); /* weighted_bipred_idc */ + bw_se(&b, 0); /* pic_init_qp_minus26 */ + bw_se(&b, 0); /* pic_init_qs_minus26 */ + bw_se(&b, 0); /* chroma_qp_index_offset */ + bw_put(&b, s->deblock_ctrl, 1); /* deblocking_filter_control_present_flag */ + bw_put(&b, 0, 1); /* constrained_intra_pred_flag */ + bw_put(&b, 0, 1); /* redundant_pic_cnt_present_flag */ + if (s->transform_8x8) { + bw_put(&b, 1, 1); /* transform_8x8_mode_flag */ + bw_put(&b, 0, 1); /* pic_scaling_matrix_present_flag */ + bw_se(&b, 0); /* second_chroma_qp_index_offset */ + } + bw_trailing(&b); + if (b.overflow) + return -ENOSPC; + n2 = nal_wrap(init + PPS_BYTES, 0x100, 0x68, rbsp, b.bits / 8); + if (n2 < 0) + return n2; + put_unaligned_le32(n2 * 8, init + PPS_BITS); + + if (n1 + n2 > sizeof(s->headers)) + return -ENOSPC; + memcpy(s->headers, init + SPS_BYTES, n1); + memcpy(s->headers + n1, init + PPS_BYTES, n2); + s->headers_len = n1 + n2; + return 0; +} + +/* the slice header from slice_type on, for AVC_ENCODE */ +static int avc_slice_header(struct ave_session *s, u8 *cmd, enum ave_pic_type type, int qp, + u32 poc) +{ + u8 *bits = cmd + SH_BYTES; + struct bitw b = { bits, 0x400 }; + bool idr = type == AVE_PIC_IDR, bpic = type == AVE_PIC_B; + u32 slice_type = idr ? 2 : bpic ? 1 : 0; /* I, B, P */ + u32 lsb = poc & (BIT(AVC_LOG2_MAX_POC) - 1); + + put_unaligned_le32(bpic ? 0 : 3, cmd + SH_NAL_REF_IDC); + put_unaligned_le32(idr ? 5 : 1, cmd + SH_NAL_TYPE); + put_unaligned_le32(slice_type, cmd + SH_SLICE_TYPE); + put_unaligned_le32(s->frame_num, cmd + SH_FRAME_NUM); + cmd[SH_IDR] = idr; + put_unaligned_le32(s->idr_pic_id, cmd + SH_IDR_PIC_ID); + if (s->bframes) + put_unaligned_le32(lsb, cmd + SH_POC_LSB); + if (bpic) { + /* spatial direct; the colocated picture (L1[0]) is short-term */ + cmd[SH_DIRECT_SPATIAL] = 1; + put_unaligned_le16(0x100, cmd + SH_DIRECT_COLZERO); + } + put_unaligned_le32(qp - 26, cmd + SH_QP_DELTA); + /* + * Slices: a map of macroblock rows, as iOS (the firmware starts each + * slice with its first_mb_in_slice and these bits). One slice: a + * count of macroblocks per slice instead, as before. + */ + if (s->n_slices > 1) + memcpy(cmd + SH_SLICE_MAP, s->slice_map, sizeof(s->slice_map)); + else + put_unaligned_le32(s->wmb * s->hmb, cmd + SH_MBS_PER_SLICE); + /* + * The firmware sets up motion search from these: none for I, one L0 + * reference for P, one in each list for B (the PPS's defaults). + */ + put_unaligned_le32(idr ? -1 : 0, cmd + SH_NUM_REF_L0); + put_unaligned_le32(bpic ? 0 : -1, cmd + SH_NUM_REF_L1); + + bw_ue(&b, slice_type); + bw_ue(&b, 0); /* pic_parameter_set_id */ + bw_put(&b, s->frame_num, s->log2_max_frame_num); + if (idr) + bw_ue(&b, s->idr_pic_id); + if (s->bframes) + bw_put(&b, lsb, AVC_LOG2_MAX_POC); /* pic_order_cnt_lsb */ + if (bpic) + bw_put(&b, 1, 1); /* direct_spatial_mv_pred_flag */ + if (!idr) { + bw_put(&b, 0, 1); /* num_ref_idx_active_override_flag */ + bw_put(&b, 0, 1); /* ref_pic_list_modification_flag_l0 */ + if (bpic) + bw_put(&b, 0, 1); /* ref_pic_list_modification_flag_l1 */ + } + /* dec_ref_pic_marking(): references only (nal_ref_idc != 0) */ + if (idr) { + bw_put(&b, 0, 1); /* no_output_of_prior_pics_flag */ + bw_put(&b, 0, 1); /* long_term_reference_flag */ + } else if (!bpic) { + bw_put(&b, 0, 1); /* adaptive_ref_pic_marking_mode_flag */ + } + if (s->cabac && !idr) + bw_ue(&b, 0); /* cabac_init_idc */ + bw_se(&b, qp - 26); /* slice_qp_delta */ + if (s->deblock_ctrl) { + bw_ue(&b, 0); /* disable_deblocking_filter_idc */ + bw_se(&b, 0); /* slice_alpha_c0_offset_div2 */ + bw_se(&b, 0); /* slice_beta_offset_div2 */ + } + if (b.overflow) + return -ENOSPC; + put_unaligned_le32(b.bits, cmd + SH_BITS); + return 0; +} + +/* + * A stream's buffers: iOS's sizes. + * HEVC works in 32 x 32 CTBs: its sizes count + * CTBs (cw x ch) or MBs rounded up to whole CTBs. + */ +static void ave_buffer_sizes(bool hevc, bool ten, u32 w, u32 h, struct ave_sizes *z) +{ + u32 wmb = DIV_ROUND_UP(w, 16), hmb = DIV_ROUND_UP(h, 16); + u32 cw = DIV_ROUND_UP(w, 32), ch = DIV_ROUND_UP(h, 32); + + z->lsb_y = 0; + z->lsb = 0; + z->coded = max_t(size_t, (size_t)w * h * 3 / 2, 0x70800); + if (!hevc) { + z->recon_luma = ALIGN(wmb * hmb * 0x100, 0x200); + z->recon = z->recon_luma + wmb * hmb * 0x80; + z->colocated = wmb * hmb * 0x80; + z->lowres = (size_t)DIV_ROUND_UP(wmb, 4) * ((h + 63) / 16) * 0x180; + z->result = (size_t)ALIGN(wmb * 0x18, 64) * DIV_ROUND_UP(hmb, 4); + z->entropy = (size_t)DIV_ROUND_UP(hmb, 4) * wmb * 0x180; + z->nbr_info = max(0x4000U, (w * 0x10 + 0xf0) & ~0xffU); + z->nbr_pixels = max(0x4000U, (w * 0x40 + 0x3c0) & ~0x3ffU); + z->nbr_data = max(0x4000U, wmb * 0x38); + z->slice_hdr = SLICE_HDR_SIZE; + return; + } + /* 4:2:0; 10-bit adds the 2-bit planes in front (as iOS lays them out) */ + if (ten) { + z->lsb_y = ALIGN((size_t)(2 * ch) * ((4 * w + 0x7c) & ~0x7fU), 0x200); + z->lsb = z->lsb_y + ALIGN((size_t)(2 * cw) * (2 * ch) * 0x20, 0x200); + } + z->recon_luma = (size_t)(2 * cw) * (2 * ch) * 0x100; + z->recon = z->lsb + z->recon_luma + (size_t)(2 * cw) * (2 * ch) * 0x80; + z->colocated = (size_t)cw * ALIGN(ch, 2) * 0x40; + z->lowres = ALIGN((size_t)((h + 63) >> 6) * DIV_ROUND_UP(2 * cw, 4) * 0x100, 0x200) + + (size_t)((h + 63) >> 6) * DIV_ROUND_UP(2 * cw, 4) * 0x80; + z->result = (size_t)ALIGN(cw * 0x60, 64) * DIV_ROUND_UP(ch, 2); + z->entropy = (size_t)cw * DIV_ROUND_UP(ch, 2) * 0x600 * (ten ? 2 : 1); + z->nbr_info = max_t(size_t, 0x4000, (size_t)cw * (DIV_ROUND_UP(ch, 2) - 1) * 0xc0); + z->nbr_pixels = max_t(size_t, 0x4000, (size_t)cw * (DIV_ROUND_UP(ch, 2) - 1) * 0x300); + z->nbr_data = max(0x4000U, cw * 4); + z->slice_hdr = HEVC_SLICE_HDR_SIZE; /* 0x400 per slice, 256 slices */ +} + +/* + * A stream's buffers come in two kinds. The coded-data headers, slice + * headers and parameter sets are read and written by the firmware's CPU, + * which reaches only its window: they go there, session_cpu_size() at + * most. Everything else only the hardware touches through the DART: the + * recon, co-located and low-res pictures, motion-search results, CAVLC + * intermediates, line buffers and internal coded buffers, which grow with + * the picture; they are a DMA block of the stream's own. So the window's + * size does not depend on the stream, and a larger stream than the last + * needs no new firmware boot. + */ +static size_t session_cpu_size(void) +{ + return N_SLOTS * (PAGE_ALIGN(CDH_SIZE) + PAGE_ALIGN(HEVC_SLICE_HDR_SIZE)) + + PAGE_ALIGN(PARAM_SETS_SIZE); +} + +static size_t session_hw_size(bool hevc, bool ten, u32 w, u32 h, u32 n_recon) +{ + struct ave_sizes z; + size_t total = 0; + + ave_buffer_sizes(hevc, ten, w, h, &z); + total += n_recon * (PAGE_ALIGN(z.recon) + PAGE_ALIGN(z.colocated) + PAGE_ALIGN(z.lowres)); + total += N_LOWRES_RESULT * PAGE_ALIGN(z.result); + total += (hevc ? N_ENTROPY_HEVC : N_ENTROPY) * PAGE_ALIGN(z.entropy); + total += PAGE_ALIGN(z.nbr_info) + PAGE_ALIGN(z.nbr_pixels) + PAGE_ALIGN(z.nbr_data); + total += N_SLOTS * PAGE_ALIGN(z.coded); + return total; +} + +/* a buffer in the firmware's window */ +static int session_mem(struct ave_hw *hw, struct ave_mem *m, size_t size) +{ + m->size = size; + m->va = ave_alloc(hw, &hw->area, size, &m->rel); + if (!m->va) + return -ENOMEM; + m->iova = ave_iova(hw, m->rel); + return 0; +} + +/* a buffer in the stream's DMA block */ +static void session_hwmem(struct ave_session *s, struct ave_mem *m, size_t size) +{ + m->size = size; + m->rel = 0; + m->va = s->hwbuf + s->hwbuf_used; + m->iova = lower_32_bits(s->hwbuf_iova) + s->hwbuf_used; + s->hwbuf_used += PAGE_ALIGN(size); +} + +/* the hardware's buffers, once for the stream (they outlive firmware boots) */ +static int session_hw_buffers(struct ave_hw *hw, struct ave_session *s) +{ + const struct ave_sizes *z = &s->sz; + int i; + + s->hwbuf_size = session_hw_size(s->hevc, s->ten, s->width, s->height, s->n_recon); + s->hwbuf = dma_alloc_coherent(hw->dev, s->hwbuf_size, &s->hwbuf_iova, GFP_KERNEL); + if (!s->hwbuf) + return -ENOMEM; + s->hwbuf_used = 0; + for (i = 0; i < s->n_recon; i++) { + session_hwmem(s, &s->recon[i], z->recon); + session_hwmem(s, &s->colocated[i], z->colocated); + session_hwmem(s, &s->lowres[i], z->lowres); + } + for (i = 0; i < N_LOWRES_RESULT; i++) + session_hwmem(s, &s->lowres_result[i], z->result); + for (i = 0; i < (s->hevc ? N_ENTROPY_HEVC : N_ENTROPY); i++) + session_hwmem(s, &s->entropy[i], z->entropy); + session_hwmem(s, &s->nbr_info, z->nbr_info); + session_hwmem(s, &s->nbr_pixels, z->nbr_pixels); + session_hwmem(s, &s->nbr_data, z->nbr_data); + for (i = 0; i < N_SLOTS; i++) + session_hwmem(s, &s->coded[i], z->coded); + return 0; +} + +static void session_hw_free(struct ave_hw *hw, struct ave_session *s) +{ + if (s->hwbuf) + dma_free_coherent(hw->dev, s->hwbuf_size, s->hwbuf, s->hwbuf_iova); + s->hwbuf = NULL; +} + +/* the window's part, after every firmware boot */ +static int session_cpu_buffers(struct ave_hw *hw, struct ave_session *s) +{ + int i, ret = 0; + + for (i = 0; i < N_SLOTS && !ret; i++) { + ret = session_mem(hw, &s->coded_hdr[i], CDH_SIZE); + ret = ret ?: session_mem(hw, &s->slice_hdr[i], s->sz.slice_hdr); + } + return ret ?: session_mem(hw, &s->param_sets, PARAM_SETS_SIZE); +} + +/* + * The per-QP tables of the mode decision, from H.264's usual motion lambda + * (the square root of the mode lambda 0.85 * 2^((QP - 12) / 3)): + * lambda[52] max(1, round(2^((QP - 12) / 6))) + * thresh[52] lambda - 1 up to QP 33, then QP - 23 + * costs for each distinct lambda, ascending: lambda, then 16 * lambda eight times + * 52 + 52 + 29 * 9 words = the 0x5b4 bytes the firmware takes at RC + 0x70. + */ +static const u8 avc_lambda[52] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* QP 0-15 */ + 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, /* QP 16-31 */ + 10, 11, 13, 14, 16, 18, 20, 23, 25, 29, 32, 36, 40, 45, 51, 57, /* QP 32-47 */ + 64, 72, 81, 91, /* QP 48-51 */ +}; + +static void avc_qp_tables(u8 *t) +{ + unsigned int q, n = 0, last = 0, j; + + for (q = 0; q < 52; q++) { + put_unaligned_le32(avc_lambda[q], t + 4 * q); + put_unaligned_le32(q < 34 ? avc_lambda[q] - 1 : q - 23, t + 0xd0 + 4 * q); + } + for (q = 0; q < 52; q++) { + if (avc_lambda[q] == last) + continue; + last = avc_lambda[q]; + put_unaligned_le32(last, t + 0x1a0 + 36 * n); + for (j = 1; j < 9; j++) + put_unaligned_le32(16 * last, t + 0x1a0 + 36 * n + 4 * j); + n++; + } +} + +/* + * VideoParams and RateControllerSettings, the same in AVC_INIT and + * HEVC_INIT: the stream's buffers and settings. + */ +static void ave_video_params(struct ave_session *s, const struct ave_params *p, u8 *cmd) +{ + u32 fps = DIV_ROUND_CLOSEST(p->fps_num, p->fps_den); + int i, n; + + put_unaligned_le32(s->width, cmd + VP_WIDTH); + put_unaligned_le32(s->height, cmd + VP_HEIGHT); + put_unaligned_le32(s->bframes, cmd + VP_BFRAMES); + put_unaligned_le32(!s->bframes, cmd + VP_LOW_DELAY); + /* + * B pictures need the second motion estimator: without it the pipe + * stops a few macroblock rows into every B picture and the firmware + * never answers (P pictures are the same either way, bit for bit). + */ + cmd[VP_DUAL_ME] = !!s->bframes; + for (i = 0; i < s->n_recon; i++) { + /* iOS: {Y MSB, base}, both the base for 8-bit (this driver's {UV, Y} works too) */ + put_unaligned_le32(s->recon[i].iova + (s->ten ? s->sz.lsb : s->sz.recon_luma), + cmd + VP_RECON(i)); + put_unaligned_le32(s->recon[i].iova, cmd + VP_RECON(i) + 4); + put_unaligned_le32(s->lowres[i].iova, cmd + VP_LOWRES(i)); + put_unaligned_le32(s->colocated[i].iova, cmd + VP_COLOCATED(i)); + } + for (i = 0; i < N_LOWRES_RESULT; i++) + put_unaligned_le32(s->lowres_result[i].iova, cmd + VP_LOWRES_RESULT(i)); + for (i = 0; i < N_SLOTS; i++) { + put_unaligned_le32(s->coded[i].iova, cmd + VP_CODED(i)); + put_unaligned_le32(s->coded[i].size, cmd + VP_CODED_SIZE(i)); + put_unaligned_le32(s->coded_hdr[i].iova, cmd + VP_CODED_HDR(i)); + put_unaligned_le32(CDH_CLEAR, cmd + VP_CODED_HDR_SIZE(i)); + if (!s->hevc) { + put_unaligned_le32(s->slice_hdr[i].iova, cmd + VP_SLICE_HDR(i, 0)); + put_unaligned_le32(SLICE_HDR_SIZE, cmd + VP_SLICE_HDR_SIZE(i, 0)); + continue; + } + for (n = 0; n < 256; n++) { /* iOS: 0x400 per slice */ + put_unaligned_le32(s->slice_hdr[i].iova + n * SLICE_HDR_STEP, + cmd + VP_SLICE_HDR(i, n)); + put_unaligned_le32(SLICE_HDR_STEP, cmd + VP_SLICE_HDR_SIZE(i, n)); + } + } + put_unaligned_le32(s->nbr_info.iova, cmd + VP_SRC_NBR_INFO); + put_unaligned_le32(s->nbr_pixels.iova, cmd + VP_SRC_NBR_PIXELS); + put_unaligned_le32(s->nbr_data.iova, cmd + VP_SRC_NBR_DATA); + for (i = 0; i < N_ENTROPY; i++) { /* [4][2], as PM_ENTROPY */ + put_unaligned_le32(s->entropy[i].iova, cmd + VP_ENTROPY(i)); + put_unaligned_le32(s->entropy[i].size, cmd + VP_ENTROPY_SIZE(i)); + } + put_unaligned_le32(s->param_sets.iova, cmd + VP_PARAM_SETS); + put_unaligned_le32(PARAM_SETS_SIZE, cmd + VP_PARAM_SETS_SIZE); + put_unaligned_le16(1, cmd + VP_SEARCH_RANGE); + /* HEVC: stored, never used (2 is the firmware's default) */ + put_unaligned_le32(s->transform_8x8 || s->hevc ? 2 : 0, cmd + VP_TRANSFORM_8X8); + put_unaligned_le32(p->crop.left, cmd + VP_VISIBLE); + put_unaligned_le32(p->crop.top, cmd + VP_VISIBLE + 4); + put_unaligned_le32(p->crop.width, cmd + VP_VISIBLE + 8); + put_unaligned_le32(p->crop.height, cmd + VP_VISIBLE + 12); + /* a 10-bit source the firmware converts for Main, an 8-bit one for Main 10 */ + put_unaligned_le32(p->src_ten ? 10 : 8, cmd + VP_INPUT_BITDEPTH); + cmd[VP_PIX_PCK] = p->src_ten; + put_unaligned_le32(s->bframes ? 2 : 1, cmd + VP_MAX_NUM_REF); + if (s->hevc) { + /* + * SAO set-up: the firmware's defaults (its SetDefaultParameters, + * which INIT overwrites); the slice flags decide whether it is used. + */ + put_unaligned_le32(0xffff, cmd + VP_SAO_ENB); + put_unaligned_le32(0xffffffff, cmd + VP_SAO_EO_BO); + put_unaligned_le32(0, cmd + VP_PPS_ID(0)); + put_unaligned_le32(1, cmd + VP_NUM_PPS); + } + + /* rate control stays here: the QP of each picture is in its slice header */ + put_unaligned_le32(p->bitrate, cmd + RC_BITRATE); + put_unaligned_le32(p->gop, cmd + RC_IDR_PERIOD); + put_unaligned_le32(p->gop, cmd + RC_GOP); + cmd[RC_REORDER] = !!s->bframes; + put_unaligned_le32(fps, cmd + RC_AVG_FPS); + put_unaligned_le32(fps, cmd + RC_EXPECTED_FPS); + put_unaligned_le32(0, cmd + RC_FLAG); + /* + * Adaptive quantization (MB_RC_ENABLE, with a bit rate): the + * firmware's QP modulation in its threshold mode. The pipe's + * macroblock-input processor compares each 16x16 block's luma + * variance with thresholds the firmware scales from the average + * variance of the pictures before (PM_AVG_VARIANCE) and moves the + * block's QP from 4 below the slice's to 6 above. Without the + * average (0) it does nothing, without the thresholds byte nothing + * either. The pipe then codes QP deltas, so HEVC's PPS has + * cu_qp_delta_enabled_flag with it (and only with it: the flag alone + * hangs the transcoder). Left off: bEnableLamdaMod (+0x22, the + * lambda following the QP: more bytes again for the same quality), + * the variance mode (+0x27: dithered, it drops the residual of flat + * blocks, worse at every rate measured and the encoder 2.3 times + * slower), chroma (+0x21: no change measured) and iOS's CRC, + * refresh, flat-area and static-area modes (+0x26, +0x28, +0x2b, + * +0x30). + */ + cmd[RC_QPMOD] = p->aq; + cmd[RC_QPMOD_THRESH] = p->aq; + put_unaligned_le32(1, cmd + RC_REALTIME); + put_unaligned_le32(p->qp_min, cmd + RC_SOFT_MIN_QP); + put_unaligned_le32(p->qp_max, cmd + RC_SOFT_MAX_QP); + put_unaligned_le32(p->qp_i, cmd + RC_INIT_QP_I); + put_unaligned_le32(p->qp_p, cmd + RC_INIT_QP_P); + put_unaligned_le32(p->qp_b, cmd + RC_INIT_QP_B); + for (i = 0; i < ARRAY_SIZE(lambda_scales); i++) + put_unaligned_le32(lambda_scales[i], cmd + RC_LAMBDA(i)); + avc_qp_tables(cmd + RC_TABLES); +} + +/* the AVC_INIT command */ +static int avc_init(struct ave_hw *hw, struct ave_session *s, const struct ave_params *p) +{ + u8 *cmd = kzalloc(AVC_INIT_SIZE, GFP_KERNEL); + int ret; + + if (!cmd) + return -ENOMEM; + ave_cmd_header(cmd, CMD_AVC_INIT, s->client, CODEC_AVC, PLANE_CONFIG, 0); + /* the SPS and PPS first: they decide CABAC and the 8x8 transform */ + ret = avc_headers(s, p, cmd); + if (ret) { + kfree(cmd); + return ret; + } + ave_video_params(s, p, cmd); + ret = ave_cmd_sync(hw, cmd, AVC_INIT_SIZE, ANS_INIT, 2000); + kfree(cmd); + return ret; +} + +/* + * HEVC. The coding structure is the pipeline's, fixed (the firmware gives it + * the SPS word 0x1c80): 32 x 32 CTBs, 8 x 8 CUs, transforms 4 x 4 to + * 32 x 32, transform hierarchy depth 1 for inter and 0 for intra. The SPS + * must say the same: the CABAC transcoder is set up from it. + */ +#define HEVC_LOG2_POC 8 /* log2_max_pic_order_cnt_lsb */ +#define HEVC_NAL_TRAIL_R 1 +#define HEVC_NAL_IDR_N_LP 20 +#define HEVC_NAL_VPS 32 +#define HEVC_NAL_SPS 33 +#define HEVC_NAL_PPS 34 + +/* H.265 Table A.8 by V4L2 level: MaxLumaPs, MaxLumaSr, MaxBR (1000 bit/s; Main, High tier) */ +static const struct { u8 idc; u32 ps; u64 sr; u32 br, br_high; } hevc_levels[] = { + { 30, 36864, 552960, 128, 128 }, { 60, 122880, 3686400, 1500, 1500 }, + { 63, 245760, 7372800, 3000, 3000 }, { 90, 552960, 16588800, 6000, 6000 }, + { 93, 983040, 33177600, 10000, 10000 }, { 120, 2228224, 66846720, 12000, 30000 }, + { 123, 2228224, 133693440, 20000, 50000 }, { 150, 8912896, 267386880, 25000, 100000 }, + { 153, 8912896, 534773760, 40000, 160000 }, { 156, 8912896, 1069547520, 60000, 240000 }, + { 180, 35651584, 1069547520, 60000, 240000 }, { 183, 35651584, 2139095040, 120000, 480000 }, + { 186, 35651584, 4278190080ULL, 240000, 800000 }, +}; + +/* the lowest level at or above the control's that the stream fits (and the tier: High from 4 on) */ +static u8 hevc_level(const struct ave_session *s, const struct ave_params *p, bool *high) +{ + u64 w = s->wmb * 16, h = s->hmb * 16; + u64 sr = div_u64(w * h * p->fps_num + p->fps_den - 1, p->fps_den); + u32 rate = p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ ? 0 : + p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR ? p->bitrate_peak : p->bitrate; + u32 br = DIV_ROUND_UP(rate, 1100); /* the NAL limit: 1100 x MaxBR bit/s */ + unsigned int i; + + for (i = min_t(u32, p->level, ARRAY_SIZE(hevc_levels) - 1); + i < ARRAY_SIZE(hevc_levels); i++) { + bool hi = p->tier == V4L2_MPEG_VIDEO_HEVC_TIER_HIGH && hevc_levels[i].idc >= 120; + + if (w * h <= hevc_levels[i].ps && sr <= hevc_levels[i].sr && + br <= (hi ? hevc_levels[i].br_high : hevc_levels[i].br) && + w * w <= 8ULL * hevc_levels[i].ps && h * h <= 8ULL * hevc_levels[i].ps) { + *high = hi; + return hevc_levels[i].idc; + } + } + *high = p->tier == V4L2_MPEG_VIDEO_HEVC_TIER_HIGH; + return 186; +} + +/* profile_tier_level(1, 0): Main, or Main 10 */ +static void hevc_ptl(struct bitw *b, u8 *ptl, bool high, u8 level, bool ten) +{ + unsigned int j; + + ptl[PTL_TIER] = high; + put_unaligned_le32(ten ? 2 : 1, ptl + PTL_PROFILE); + ptl[PTL_COMPAT(1)] = !ten; + ptl[PTL_COMPAT(2)] = 1; + ptl[PTL_PROGRESSIVE] = 1; + ptl[PTL_FRAME_ONLY] = 1; + put_unaligned_le32(level, ptl + PTL_LEVEL); + + bw_put(b, 0, 2); /* general_profile_space */ + bw_put(b, high, 1); /* general_tier_flag */ + bw_put(b, ten ? 2 : 1, 5); /* general_profile_idc: Main, Main 10 */ + /* general_profile_compatibility_flag: Main (8-bit), Main 10 */ + for (j = 0; j < 32; j++) + bw_put(b, (j == 1 && !ten) || j == 2, 1); + bw_put(b, 1, 1); /* general_progressive_source_flag */ + bw_put(b, 0, 1); /* general_interlaced_source_flag */ + bw_put(b, 0, 1); /* general_non_packed_constraint_flag */ + bw_put(b, 1, 1); /* general_frame_only_constraint_flag */ + bw_put(b, 0, 32); /* general_reserved_zero_43bits */ + bw_put(b, 0, 11); + bw_put(b, 0, 1); /* general_inbld_flag */ + bw_put(b, level, 8); /* general_level_idc */ +} + +/* the RBSP in @b as a NAL unit into a struct's bytes, its length in bits, its EP bytes */ +static int hevc_nal_out(struct bitw *b, u8 type, u8 *cmd, u32 bits_off, u32 bytes_off, + u32 epb_off, unsigned int max) +{ + unsigned int epb; + int n; + + bw_trailing(b); + if (b->overflow) + return -ENOSPC; + n = hevc_nal_wrap(cmd + bytes_off, max, type, b->buf, b->bits / 8, &epb); + if (n < 0) + return n; + put_unaligned_le32(n * 8, cmd + bits_off); + put_unaligned_le32(epb, cmd + epb_off); + return n; +} + +/* + * The VPS, SPS and PPS structs of HEVC_INIT with their bits (the firmware + * copies them to the parameter-set buffer), the RPS struct, s->headers. + */ +static int hevc_headers(struct ave_session *s, const struct ave_params *p, u8 *cmd) +{ + u8 rbsp[256] = {}, prim, xfer, matrix; + struct bitw b = { rbsp, sizeof(rbsp) }; + u32 w = s->wmb * 16, h = s->hmb * 16, crop_r, crop_b; + bool high, full, conf, sao = s->tools & HEVC_SAO, tmvp = s->tools & HEVC_TMVP; + bool strong = s->tools & HEVC_STRONG_INTRA, cuqpd = s->tools & HEVC_CU_QP_DELTA; + u8 *st = cmd + RPS_ST(0); + int n1, n2, n3; + + s->level_idc = hevc_level(s, p, &high); + crop_r = (w - p->crop.width - p->crop.left) / 2; + crop_b = (h - p->crop.height - p->crop.top) / 2; + conf = crop_r || crop_b || p->crop.left || p->crop.top; + avc_colour(p, &prim, &xfer, &matrix, &full); + + /* video_parameter_set_rbsp() */ + put_unaligned_le32(HVPS_LEN, cmd + HVPS); + cmd[VPS_BASE_LAYER] = 1; + cmd[VPS_BASE_LAYER + 1] = 1; + cmd[VPS_TEMPORAL_NESTING] = 1; + cmd[VPS_ORDERING_INFO] = 1; + /* B pictures: two references and the picture, one reordered */ + put_unaligned_le32(s->bframes ? 2 : 1, cmd + VPS_MAX_DEC_PIC_BUF); + put_unaligned_le32(!!s->bframes, cmd + VPS_MAX_DEC_PIC_BUF + 0x20); + bw_put(&b, 0, 4); /* vps_video_parameter_set_id */ + bw_put(&b, 1, 1); /* vps_base_layer_internal_flag */ + bw_put(&b, 1, 1); /* vps_base_layer_available_flag */ + bw_put(&b, 0, 6); /* vps_max_layers_minus1 */ + bw_put(&b, 0, 3); /* vps_max_sub_layers_minus1 */ + bw_put(&b, 1, 1); /* vps_temporal_id_nesting_flag */ + bw_put(&b, 0xffff, 16); /* vps_reserved_0xffff_16bits */ + hevc_ptl(&b, cmd + VPS_PTL, high, s->level_idc, s->ten); + bw_put(&b, 1, 1); /* vps_sub_layer_ordering_info_present_flag */ + /* vps_max_dec_pic_buffering_minus1: references + 1 */ + bw_ue(&b, s->bframes ? 2 : 1); + bw_ue(&b, !!s->bframes); /* vps_max_num_reorder_pics */ + bw_ue(&b, 0); /* vps_max_latency_increase_plus1 */ + bw_put(&b, 0, 6); /* vps_max_layer_id */ + bw_ue(&b, 0); /* vps_num_layer_sets_minus1 */ + bw_put(&b, 0, 1); /* vps_timing_info_present_flag */ + bw_put(&b, 0, 1); /* vps_extension_flag */ + n1 = hevc_nal_out(&b, HEVC_NAL_VPS, cmd, VPS_BITS, VPS_BYTES, VPS_EPB, 0x100); + if (n1 < 0) + return n1; + + /* the reference picture set: one, the picture before */ + put_unaligned_le32(1, cmd + RPS_NUM_ST); + put_unaligned_le32(1, st + ST_NUM_NEG); + st[ST_USED_S0(0)] = 1; /* delta_poc_s0_minus1[0] = 0 */ + put_unaligned_le32(1, st + ST_NUM_NEGATIVE); + st[ST_USED_CURR_S0(0)] = 1; + put_unaligned_le32(-1, st + ST_DELTA_S0(0)); + put_unaligned_le32(1, st + ST_NUM_DELTA); + cmd[HRPS + RPS_PIC] = 1; /* pictures use the SPS's set */ + + /* seq_parameter_set_rbsp() */ + memset(rbsp, 0, sizeof(rbsp)); + b = (struct bitw){ rbsp, sizeof(rbsp) }; + put_unaligned_le32(HSPS_LEN, cmd + HSPS); + cmd[HSPS_TEMPORAL_NESTING] = 1; + put_unaligned_le32(1, cmd + HSPS_CHROMA_FORMAT); + put_unaligned_le32(w, cmd + HSPS_WIDTH); + put_unaligned_le32(h, cmd + HSPS_HEIGHT); + put_unaligned_le32(s->ctb_w, cmd + HSPS_WIDTH_CTBS); + put_unaligned_le32(s->ctb_h, cmd + HSPS_HEIGHT_CTBS); + if (conf) { + cmd[HSPS_CONF_WIN] = 1; + put_unaligned_le32(p->crop.left / 2, cmd + HSPS_CONF_WIN + 4); + put_unaligned_le32(crop_r, cmd + HSPS_CONF_WIN + 8); + put_unaligned_le32(p->crop.top / 2, cmd + HSPS_CONF_WIN + 12); + put_unaligned_le32(crop_b, cmd + HSPS_CONF_WIN + 16); + } + put_unaligned_le32(s->ten ? 2 : 0, cmd + HSPS_BIT_DEPTH_LUMA); + put_unaligned_le32(s->ten ? 2 : 0, cmd + HSPS_BIT_DEPTH_CHROMA); + put_unaligned_le32(HEVC_LOG2_POC - 4, cmd + HSPS_LOG2_MAX_POC_LSB); + cmd[HSPS_ORDERING_INFO] = 1; + put_unaligned_le32(s->bframes ? 2 : 1, cmd + HSPS_MAX_DEC_PIC_BUF); + put_unaligned_le32(!!s->bframes, cmd + HSPS_MAX_DEC_PIC_BUF + 0x1c); + put_unaligned_le32(0, cmd + HSPS_LOG2_MIN_CB); + put_unaligned_le32(2, cmd + HSPS_LOG2_DIFF_CB); + put_unaligned_le32(0, cmd + HSPS_LOG2_MIN_TB); + put_unaligned_le32(3, cmd + HSPS_LOG2_DIFF_TB); + put_unaligned_le32(1, cmd + HSPS_DEPTH_INTER); + put_unaligned_le32(0, cmd + HSPS_DEPTH_INTRA); + cmd[HSPS_SAO] = sao; + cmd[HSPS_TMVP] = tmvp; + cmd[HSPS_STRONG_INTRA] = strong; + /* the VUI as fields too, for the firmware's own writer (without timing: iOS's has none) */ + cmd[HSPS_VUI] = 1; + cmd[HSPS_VIDEO_SIGNAL] = 1; + put_unaligned_le32(5, cmd + HSPS_VIDEO_FORMAT); + put_unaligned_le32(full, cmd + HSPS_FULL_RANGE); + cmd[HSPS_COLOUR_DESC] = 1; + put_unaligned_le32(prim, cmd + HSPS_COLOUR_DESC + 4); + put_unaligned_le32(xfer, cmd + HSPS_COLOUR_DESC + 8); + put_unaligned_le32(matrix, cmd + HSPS_COLOUR_DESC + 12); + cmd[HSPS_RESTRICTION] = 1; + cmd[HSPS_RESTRICTION + 2] = 1; /* motion_vectors_over_pic_boundaries_flag */ + cmd[HSPS_RESTRICTION + 3] = 1; /* restricted_ref_pic_lists_flag */ + /* max_bytes_per_pic_denom, max_bits_per_min_cu_denom: 0, no limit (QP 0 pictures) */ + put_unaligned_le32(15, cmd + HSPS_MAX_BYTES_DENOM + 8); + put_unaligned_le32(15, cmd + HSPS_MAX_BYTES_DENOM + 12); + bw_put(&b, 0, 4); /* sps_video_parameter_set_id */ + bw_put(&b, 0, 3); /* sps_max_sub_layers_minus1 */ + bw_put(&b, 1, 1); /* sps_temporal_id_nesting_flag */ + hevc_ptl(&b, cmd + HSPS_PTL, high, s->level_idc, s->ten); + bw_ue(&b, 0); /* sps_seq_parameter_set_id */ + bw_ue(&b, 1); /* chroma_format_idc: 4:2:0 */ + bw_ue(&b, w); /* pic_width_in_luma_samples */ + bw_ue(&b, h); /* pic_height_in_luma_samples */ + bw_put(&b, conf, 1); /* conformance_window_flag */ + if (conf) { + bw_ue(&b, p->crop.left / 2); + bw_ue(&b, crop_r); + bw_ue(&b, p->crop.top / 2); + bw_ue(&b, crop_b); + } + bw_ue(&b, s->ten ? 2 : 0); /* bit_depth_luma_minus8 */ + bw_ue(&b, s->ten ? 2 : 0); /* bit_depth_chroma_minus8 */ + bw_ue(&b, HEVC_LOG2_POC - 4); /* log2_max_pic_order_cnt_lsb_minus4 */ + bw_put(&b, 1, 1); /* sps_sub_layer_ordering_info_present_flag */ + bw_ue(&b, s->bframes ? 2 : 1); /* sps_max_dec_pic_buffering_minus1 */ + bw_ue(&b, !!s->bframes); /* sps_max_num_reorder_pics */ + bw_ue(&b, 0); /* sps_max_latency_increase_plus1 */ + bw_ue(&b, 0); /* log2_min_luma_coding_block_size_minus3: 8 */ + bw_ue(&b, 2); /* log2_diff_max_min_luma_coding_block_size: 32 */ + bw_ue(&b, 0); /* log2_min_luma_transform_block_size_minus2: 4 */ + /* log2_diff_max_min_luma_transform_block_size: 32 */ + bw_ue(&b, 3); + bw_ue(&b, 1); /* max_transform_hierarchy_depth_inter */ + bw_ue(&b, 0); /* max_transform_hierarchy_depth_intra */ + bw_put(&b, 0, 1); /* scaling_list_enabled_flag */ + bw_put(&b, 0, 1); /* amp_enabled_flag */ + bw_put(&b, sao, 1); /* sample_adaptive_offset_enabled_flag */ + bw_put(&b, 0, 1); /* pcm_enabled_flag */ + bw_ue(&b, 1); /* num_short_term_ref_pic_sets */ + bw_ue(&b, 1); /* st_ref_pic_set(0): num_negative_pics */ + bw_ue(&b, 0); /* num_positive_pics */ + bw_ue(&b, 0); /* delta_poc_s0_minus1[0] */ + bw_put(&b, 1, 1); /* used_by_curr_pic_s0_flag[0] */ + bw_put(&b, 0, 1); /* long_term_ref_pics_present_flag */ + bw_put(&b, tmvp, 1); /* sps_temporal_mvp_enabled_flag */ + bw_put(&b, strong, 1); /* strong_intra_smoothing_enabled_flag */ + bw_put(&b, 1, 1); /* vui_parameters_present_flag */ + bw_put(&b, 0, 1); /* aspect_ratio_info_present_flag */ + bw_put(&b, 0, 1); /* overscan_info_present_flag */ + bw_put(&b, 1, 1); /* video_signal_type_present_flag */ + bw_put(&b, 5, 3); /* video_format: unspecified */ + bw_put(&b, full, 1); /* video_full_range_flag */ + bw_put(&b, 1, 1); /* colour_description_present_flag */ + bw_put(&b, prim, 8); + bw_put(&b, xfer, 8); + bw_put(&b, matrix, 8); + bw_put(&b, 0, 1); /* chroma_loc_info_present_flag */ + bw_put(&b, 0, 1); /* neutral_chroma_indication_flag */ + bw_put(&b, 0, 1); /* field_seq_flag */ + bw_put(&b, 0, 1); /* frame_field_info_present_flag */ + bw_put(&b, 0, 1); /* default_display_window_flag */ + bw_put(&b, 1, 1); /* vui_timing_info_present_flag */ + bw_put(&b, p->fps_den, 32); /* vui_num_units_in_tick */ + bw_put(&b, p->fps_num, 32); /* vui_time_scale */ + bw_put(&b, 0, 1); /* vui_poc_proportional_to_timing_flag */ + bw_put(&b, 0, 1); /* vui_hrd_parameters_present_flag */ + bw_put(&b, 1, 1); /* bitstream_restriction_flag */ + bw_put(&b, 0, 1); /* tiles_fixed_structure_flag */ + bw_put(&b, 1, 1); /* motion_vectors_over_pic_boundaries_flag */ + bw_put(&b, 1, 1); /* restricted_ref_pic_lists_flag */ + bw_ue(&b, 0); /* min_spatial_segmentation_idc */ + bw_ue(&b, 0); /* max_bytes_per_pic_denom */ + bw_ue(&b, 0); /* max_bits_per_min_cu_denom */ + bw_ue(&b, 15); /* log2_max_mv_length_horizontal */ + bw_ue(&b, 15); /* log2_max_mv_length_vertical */ + bw_put(&b, 0, 1); /* sps_extension_present_flag */ + n2 = hevc_nal_out(&b, HEVC_NAL_SPS, cmd, HSPS_BITS, HSPS_BYTES, HSPS_EPB, 0x200); + if (n2 < 0) + return n2; + + /* pic_parameter_set_rbsp() */ + memset(rbsp, 0, sizeof(rbsp)); + b = (struct bitw){ rbsp, sizeof(rbsp) }; + put_unaligned_le32(HPPS_LEN, cmd + HPPS); + cmd[HPPS_CU_QP_DELTA] = cuqpd; + /* a QP per 16x16, the modulation's grid (with one per CTB it changes nothing) */ + put_unaligned_le32(cuqpd ? 1 : 0, cmd + HPPS_CU_QP_DEPTH); + cmd[HPPS_ENTROPY_SYNC] = 1; + cmd[HPPS_LF_ACROSS_SLICES] = 1; + bw_ue(&b, 0); /* pps_pic_parameter_set_id */ + bw_ue(&b, 0); /* pps_seq_parameter_set_id */ + bw_put(&b, 0, 1); /* dependent_slice_segments_enabled_flag */ + bw_put(&b, 0, 1); /* output_flag_present_flag */ + bw_put(&b, 0, 3); /* num_extra_slice_header_bits */ + bw_put(&b, 0, 1); /* sign_data_hiding_enabled_flag */ + bw_put(&b, 0, 1); /* cabac_init_present_flag */ + bw_ue(&b, 0); /* num_ref_idx_l0_default_active_minus1 */ + bw_ue(&b, 0); /* num_ref_idx_l1_default_active_minus1 */ + bw_se(&b, 0); /* init_qp_minus26 */ + bw_put(&b, 0, 1); /* constrained_intra_pred_flag */ + bw_put(&b, 0, 1); /* transform_skip_enabled_flag */ + bw_put(&b, cuqpd, 1); /* cu_qp_delta_enabled_flag */ + if (cuqpd) + bw_ue(&b, 1); /* diff_cu_qp_delta_depth */ + bw_se(&b, 0); /* pps_cb_qp_offset */ + bw_se(&b, 0); /* pps_cr_qp_offset */ + bw_put(&b, 0, 1); /* pps_slice_chroma_qp_offsets_present_flag */ + bw_put(&b, 0, 1); /* weighted_pred_flag */ + bw_put(&b, 0, 1); /* weighted_bipred_flag */ + bw_put(&b, 0, 1); /* transquant_bypass_enabled_flag */ + bw_put(&b, 0, 1); /* tiles_enabled_flag */ + /* entropy_coding_sync_enabled_flag: see hevc_slice_header() */ + bw_put(&b, 1, 1); + bw_put(&b, 1, 1); /* pps_loop_filter_across_slices_enabled_flag */ + bw_put(&b, 0, 1); /* deblocking_filter_control_present_flag */ + bw_put(&b, 0, 1); /* pps_scaling_list_data_present_flag */ + bw_put(&b, 0, 1); /* lists_modification_present_flag */ + bw_ue(&b, 0); /* log2_parallel_merge_level_minus2 */ + bw_put(&b, 0, 1); /* slice_segment_header_extension_present_flag */ + bw_put(&b, 0, 1); /* pps_extension_present_flag */ + n3 = hevc_nal_out(&b, HEVC_NAL_PPS, cmd, HPPS_BITS, HPPS_BYTES, HPPS_EPB, 0x400); + if (n3 < 0) + return n3; + + if (n1 + n2 + n3 > sizeof(s->headers)) + return -ENOSPC; + memcpy(s->headers, cmd + VPS_BYTES, n1); + memcpy(s->headers + n1, cmd + HSPS_BYTES, n2); + memcpy(s->headers + n1 + n2, cmd + HPPS_BYTES, n3); + s->headers_len = n1 + n2 + n3; + return 0; +} + +static unsigned int ue_bits(u32 v) +{ + return 2 * fls64((u64)v + 1) - 1; +} + +/* + * The slice header the firmware writes (its 0xc4fc) for exactly what + * hevc_headers() and hevc_slice() set: from the start code up to the entry + * points into @out (the firmware's is checked against it), the most it can + * be with them into @max_len (where the slice data goes is chosen from it). + * + * The transcoder always codes a CTB row as a WPP substream (CABAC contexts + * synced from the row above, terminated and byte-aligned): the stream + * needs entropy_coding_sync_enabled_flag, with which the firmware puts + * the substreams' entry points (only known after encoding) in the header. + * A substream is no bigger than the buffer: @out_size bounds offset_len. + */ +static int hevc_slice_header(struct ave_session *s, const struct ave_refs *r, int qp, + u32 out_size, u8 *out, unsigned int max, unsigned int *max_len) +{ + bool idr = r->type == AVE_PIC_IDR, bpic = r->type == AVE_PIC_B; + unsigned int n_ep = s->rows0 - 1, bits; /* the first slice's rows */ + u8 rbsp[32] = {}; + struct bitw b = { rbsp, sizeof(rbsp) }; + bool sao = s->tools & HEVC_SAO; + int n; + + bw_put(&b, 1, 1); /* first_slice_segment_in_pic_flag */ + if (idr) + bw_put(&b, 0, 1); /* no_output_of_prior_pics_flag */ + bw_ue(&b, 0); /* slice_pic_parameter_set_id */ + bw_ue(&b, idr ? 2 : bpic ? 0 : 1); /* slice_type: I, B, P */ + if (!idr) { + bw_put(&b, r->poc & (BIT(HEVC_LOG2_POC) - 1), HEVC_LOG2_POC); + if (!s->bframes) { + /* short_term_ref_pic_set_sps_flag (one set: no idx) */ + bw_put(&b, 1, 1); + } else { + /* the picture's own set, after the SPS's one */ + bw_put(&b, 0, 1); /* short_term_ref_pic_set_sps_flag */ + bw_put(&b, 0, 1); /* inter_ref_pic_set_prediction_flag */ + bw_ue(&b, 1); /* num_negative_pics */ + bw_ue(&b, bpic); /* num_positive_pics */ + bw_ue(&b, r->poc - r->poc_l0 - 1); /* delta_poc_s0_minus1 */ + bw_put(&b, 1, 1); /* used_by_curr_pic_s0_flag */ + if (bpic) { + bw_ue(&b, r->poc_l1 - r->poc - 1); /* delta_poc_s1_minus1 */ + bw_put(&b, 1, 1); /* used_by_curr_pic_s1_flag */ + } + } + if (s->tools & HEVC_TMVP) + bw_put(&b, 1, 1); /* slice_temporal_mvp_enabled_flag */ + } + if (sao) { + bw_put(&b, 1, 1); /* slice_sao_luma_flag */ + bw_put(&b, 1, 1); /* slice_sao_chroma_flag */ + } + if (!idr) { + bw_put(&b, 0, 1); /* num_ref_idx_active_override_flag */ + if (bpic) + bw_put(&b, 0, 1); /* mvd_l1_zero_flag */ + /* TMVP: B from L1[0]; collocated_ref_idx only with more than one reference */ + if (bpic && (s->tools & HEVC_TMVP)) + bw_put(&b, 0, 1); /* collocated_from_l0_flag */ + bw_ue(&b, 5 - HEVC_MERGE_CAND); /* five_minus_max_num_merge_cand */ + } + bw_se(&b, qp - 26); /* slice_qp_delta */ + bw_put(&b, 1, 1); /* slice_loop_filter_across_slices_enabled_flag */ + if (b.overflow) + return -ENOSPC; + /* num_entry_point_offsets, offset_len_minus1, the offsets, byte_alignment() */ + bits = b.bits + ue_bits(n_ep) + 1; + if (n_ep) + bits += ue_bits(31) + n_ep * fls(out_size); + /* the whole bytes before them: start code, NAL header, RBSP (+ emulation prevention) */ + n = hevc_nal_wrap(out, max, idr ? HEVC_NAL_IDR_N_LP : HEVC_NAL_TRAIL_R, rbsp, + b.bits / 8, NULL); + if (n < 0) + return n; + *max_len = n + DIV_ROUND_UP(bits - b.bits / 8 * 8, 8) + 2; + return n; +} + +/* + * iOS's scale of a motion vector to reference @j's distance from one + * to reference @i's (the HEVC temporal scaling): POC distances from the + * picture, 0x100 = 1, 13 bits. + */ +/* HEVC's MV scale for POC distances td (the MV's) and tb (the target's), 13 bits */ +static u16 hevc_scale(int td, int tb) +{ + int tx; + + td = clamp(td, -128, 127); + tb = clamp(tb, -128, 127); + tx = (16384 + abs(td) / 2) / td; + return clamp((tb * tx + 32) >> 6, -4096, 4095) & 0x1fff; +} + +static u16 hevc_mv_scale(int poc, int poc_i, int poc_j) +{ + return hevc_scale(poc - poc_i, poc - poc_j); +} + +/* a short-term RPS struct: the reference @neg before and (if any) @pos after */ +static void hevc_st_rps(u8 *st, u32 neg, u32 pos) +{ + put_unaligned_le32(1, st + ST_NUM_NEG); + put_unaligned_le32(neg - 1, st + ST_DELTA_POC_S0(0)); + st[ST_USED_S0(0)] = 1; + put_unaligned_le32(1, st + ST_NUM_NEGATIVE); + st[ST_USED_CURR_S0(0)] = 1; + put_unaligned_le32(-neg, st + ST_DELTA_S0(0)); + if (pos) { + put_unaligned_le32(1, st + ST_NUM_POS); + put_unaligned_le32(pos - 1, st + ST_DELTA_POC_S1(0)); + st[ST_USED_S1(0)] = 1; + put_unaligned_le32(1, st + ST_NUM_POSITIVE); + st[ST_USED_CURR_S1(0)] = 1; + put_unaligned_le32(pos, st + ST_DELTA_S1(0)); + } + put_unaligned_le32(1 + !!pos, st + ST_NUM_DELTA); +} + +/* the slice struct of HEVC_ENCODE (the firmware writes the bits) and the picture's RPS */ +static int hevc_slice(struct ave_session *s, struct ave_pic *p, u8 *cmd, + const struct ave_refs *r, int qp, u32 out_size) +{ + bool idr = r->type == AVE_PIC_IDR, bpic = r->type == AVE_PIC_B; + bool sao = s->tools & HEVC_SAO; + int n; + + put_unaligned_le32(HSH_LEN, cmd + HSH_SIZE_WORD); + put_unaligned_le32(idr ? HEVC_NAL_IDR_N_LP : HEVC_NAL_TRAIL_R, cmd + HSH_NAL_TYPE); + cmd[HSH_FIRST_SLICE] = 1; + put_unaligned_le32(idr ? 2 : bpic ? 1 : 0, cmd + HSH_SLICE_TYPE); + cmd[HSH_PIC_OUTPUT] = 1; + put_unaligned_le32(r->poc & (BIT(HEVC_LOG2_POC) - 1), cmd + HSH_POC_LSB); + /* + * References: without B pictures the SPS's set ({-1}); with them each + * picture's own (as iOS does it): the anchor before, and for a B + * picture the one after. The firmware writes it into the header. + */ + cmd[HSH_ST_RPS_SPS] = !s->bframes; + if (s->bframes && !idr) { + cmd[HEVC_PIC_RPS] = 0; + put_unaligned_le32(1, cmd + HEVC_PIC_RPS + 4); /* after the SPS's one */ + hevc_st_rps(cmd + HEVC_PIC_RPS + 8, r->poc - r->poc_l0, + bpic ? r->poc_l1 - r->poc : 0); + } else { + cmd[HEVC_PIC_RPS] = 1; /* short_term_ref_pic_set_sps_flag, set 0 */ + } + cmd[HSH_TMVP] = !idr && (s->tools & HEVC_TMVP); + cmd[HSH_SAO_LUMA] = sao; + cmd[HSH_SAO_CHROMA] = sao; + /* + * The firmware sets up motion search from these: none for I, one L0 + * reference for P, one in each list for B. + */ + put_unaligned_le32(idr ? -1 : 0, cmd + HSH_NUM_REF_L0); + put_unaligned_le32(bpic ? 0 : -1, cmd + HSH_NUM_REF_L1); + cmd[HSH_COLOC_FROM_L0] = !idr && !bpic; /* B: TMVP from L1[0], the next anchor */ + put_unaligned_le32(5 - HEVC_MERGE_CAND, cmd + HSH_MERGE); + if (bpic) { + /* + * The scales between L0[0] and L1[0]: [i][j] for the hardware's + * reference slots, L0[0] in 0 and L1[0] in 1 (as the firmware's + * pipe and the reference mask have them), and iOS's indices + * (L1 at 2) too. + */ + static const u8 l1_slot[] = { 1, 2 }; + unsigned int m; + + put_unaligned_le32(0x100, cmd + HSH_REF_MASK); + put_unaligned_le16(hevc_mv_scale(r->poc, r->poc_l0, r->poc_l0), + cmd + HSH_DIST_SCALE); + for (m = 0; m < ARRAY_SIZE(l1_slot); m++) { + u32 k = l1_slot[m]; + + put_unaligned_le16(hevc_mv_scale(r->poc, r->poc_l0, r->poc_l1), + cmd + HSH_DIST_SCALE + 2 * k); + put_unaligned_le16(hevc_mv_scale(r->poc, r->poc_l1, r->poc_l0), + cmd + HSH_DIST_SCALE + 8 * k); + put_unaligned_le16(hevc_mv_scale(r->poc, r->poc_l1, r->poc_l1), + cmd + HSH_DIST_SCALE + 10 * k); + } + } else if (!idr) { /* iOS's MV scale for (L0[0], L0[0]) */ + put_unaligned_le16(0x100, cmd + HSH_DIST_SCALE); + } + /* + * TMVP's scales (the firmware computes them only with its own rate + * control): the co-located picture is the last anchor (B: L1[0], P: + * L0[0]), whose one reference, in its slot 0, is the anchor before it + * (none after the IDR: no temporal candidates then). + */ + if (!idr && r->col_has_ref) { + int td = r->poc_new - r->poc_old; + + put_unaligned_le16(hevc_scale(td, r->poc - (bpic ? r->poc_l0 : r->poc_l1)), + cmd + HSH_TMVP_SCALE); + if (bpic) + put_unaligned_le16(hevc_scale(td, r->poc - r->poc_l1), + cmd + HSH_TMVP_SCALE + 2); + } + put_unaligned_le32(qp - 26, cmd + HSH_QP_DELTA); + cmd[HSH_LF_ACROSS] = 1; + /* + * The slices: the map of CTB rows (zeros: one slice); the row counts + * stay at the picture's (the firmware divides by them, and with a map + * it follows the map), no segment boundary. + */ + memcpy(cmd + HSH_SLICE_MAP, s->slice_map, sizeof(s->slice_map)); + put_unaligned_le32(s->ctb_h, cmd + HSH_ROWS_PER_SLICE); + put_unaligned_le32(s->ctb_h, cmd + HSH_ROWS_PER_SEGMENT); + for (n = 0; n < 256; n++) + put_unaligned_le32(s->slice_hdr[s->slot].iova + n * SLICE_HDR_STEP, + cmd + HSH_HDR_ADDR(n)); + + n = hevc_slice_header(s, r, qp, out_size, p->hdr_pred, sizeof(p->hdr_pred), &p->hdr_max); + if (n < 0) + return n; + p->hdr_pred_len = n; + return 0; +} + +/* + * The parameter sets in the firmware's buffer after HEVC_INIT (up to the last + * nonzero byte): a copy of ours. + */ +static void hevc_check_headers(struct ave_hw *hw, struct ave_session *s) +{ + const u8 *ps = s->param_sets.va; + int n = PARAM_SETS_SIZE; + + while (n > 0 && !ps[n - 1]) + n--; + if (n != s->headers_len || memcmp(ps, s->headers, n)) + dev_warn(hw->dev, "parameter sets: the firmware's %d bytes %*ph, ours %u\n", n, + min(n, 48), ps, s->headers_len); +} + +/* the HEVC_INIT command */ +static int hevc_init(struct ave_hw *hw, struct ave_session *s, const struct ave_params *p) +{ + u8 *cmd = kvzalloc(HEVC_INIT_SIZE, GFP_KERNEL); + int ret; + + if (!cmd) + return -ENOMEM; + ave_cmd_header(cmd, CMD_HEVC_INIT, s->client, CODEC_HEVC, PLANE_CONFIG, 0); + ret = hevc_headers(s, p, cmd); + if (ret) + goto out; + ave_video_params(s, p, cmd); + memset(s->param_sets.va, 0, PARAM_SETS_SIZE); + ret = ave_cmd_sync(hw, cmd, HEVC_INIT_SIZE, ANS_INIT, 2000); + if (!ret) + hevc_check_headers(hw, s); +out: + kvfree(cmd); + return ret; +} + +/* + * The slices of a picture: whole macroblock rows (HEVC: CTB rows), at most + * slice_mbs macroblocks each, at most MAX_SLICES, the rows spread evenly as + * iOS does (each slice gets round(rows left / slices left)). + */ +static void ave_slice_map(struct ave_session *s, const struct ave_params *p) +{ + u32 rows = s->hevc ? s->ctb_h : s->hmb; + u32 row_mbs = s->hevc ? 2 * s->wmb : s->wmb; + u32 n = 1, i, r, k; + + if (p->slice_mbs) + n = DIV_ROUND_UP(rows, max(p->slice_mbs / row_mbs, 1U)); + n = clamp(n, 1U, min_t(u32, rows, MAX_SLICES)); + memset(s->slice_map, 0, sizeof(s->slice_map)); + for (i = 0, r = 0; i < n; i++, r += k) { + k = max(DIV_ROUND_CLOSEST(rows - r, n - i), 1U); + memset(s->slice_map + r, i, k); + if (!i) + s->rows0 = k; + } + s->n_slices = n; +} + +/* rate control: the QP of the next picture */ + +static void rc_init(struct ave_session *s, const struct ave_params *p) +{ + s->qp_min = p->qp_min; + s->qp_max = p->qp_max; + s->fullness = 0; + s->target = 0; + if (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ) { + s->qp = p->qp_p; + return; + } + s->target = max_t(u32, div_u64((u64)p->bitrate * p->fps_den, p->fps_num), 1000); + /* a start from bits per pixel: about 0.1 at QP 28 */ + s->qp = 28; + if ((u64)s->target * 10 < (u64)s->width * s->height) + s->qp = 34; + else if ((u64)s->target * 3 > (u64)s->width * s->height) + s->qp = 24; + /* + * Adaptive quantization puts most blocks below the slice's QP (on a + * camera picture 3.2 on average): start that much higher, or the + * first second goes over the rate and the rest pays for it. + */ + if (p->aq) + s->qp += 3; + s->qp = clamp(s->qp, s->qp_min, s->qp_max); +} + +static int rc_qp(struct ave_session *s, const struct ave_params *p, enum ave_pic_type type) +{ + if (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ) + return type == AVE_PIC_IDR ? p->qp_i : type == AVE_PIC_B ? p->qp_b : p->qp_p; + /* + * I pictures a little finer, as their quality carries over; B + * pictures coarser, as nothing refers to them. + */ + return clamp(s->qp + (type == AVE_PIC_IDR ? -3 : type == AVE_PIC_B ? 2 : 0), + s->qp_min, s->qp_max); +} + +static void rc_update(struct ave_session *s, const struct ave_params *p, u32 bytes, + enum ave_pic_type type) +{ + bool idr = type == AVE_PIC_IDR; + + s64 window, err; + + if (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ || !s->target) + return; + /* a second of buffer for VBR, a third for CBR */ + window = (s64)s->target * DIV_ROUND_UP(p->fps_num, p->fps_den); + if (p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CBR) + window /= 3; + s->fullness += (s64)bytes * 8 - s->target; + s->fullness = clamp(s->fullness, -window, window); + /* a QP step is about 12 % in size: move by the error in pictures' worth */ + err = div_s64(s->fullness * 4, max_t(s64, window, 1)); + if (err >= 1 || (!idr && (s64)bytes * 8 > 2LL * s->target)) + s->qp += err >= 3 ? 2 : 1; + else if (err <= -1 && (s64)bytes * 8 < s->target) + s->qp -= err <= -3 ? 2 : 1; + s->qp = clamp(s->qp, s->qp_min, s->qp_max); +} + +int ave_hw_set_bitrate(struct ave_ctx *ctx, u32 bitrate) +{ + struct ave_hw *hw = ctx->ave->hw; + struct ave_session *s = ctx->session; + + mutex_lock(&hw->lock); + if (s && ctx->params.rc_mode != V4L2_MPEG_VIDEO_BITRATE_MODE_CQ) { + ctx->params.bitrate = bitrate; + s->target = max_t(u32, div_u64((u64)bitrate * ctx->params.fps_den, + ctx->params.fps_num), 1000); + } + mutex_unlock(&hw->lock); + return 0; +} + +/* sessions */ + +static void ave_off_later(struct ave_hw *hw) +{ + mod_delayed_work(system_percpu_wq, &hw->off_work, 3 * HZ); +} + +static void ave_off_work(struct work_struct *work) +{ + struct ave_hw *hw = container_of(work, struct ave_hw, off_work.work); + + mutex_lock(&hw->lock); + if (list_empty(&hw->sessions)) { + ave_unboot(hw); + ave_power_off(hw); + ave_release(hw); + } + mutex_unlock(&hw->lock); +} + +static void ave_reset(struct ave_hw *hw) +{ + ave_unboot(hw); + ave_power_off(hw); + ave_release(hw); +} + +/* + * Firmware up (with room for the stream's buffers), CONFIG or START, the + * buffers, AVC_INIT or HEVC_INIT. Also what a stream goes through again + * after a reset. + */ +/* the stream's buffers in the firmware window, if it has them in this boot */ +static void session_cpu_free(struct ave_hw *hw, struct ave_session *s) +{ + int i; + + if (!hw->booted || s->gen != hw->gen || !hw->area.map) + return; + for (i = 0; i < N_SLOTS; i++) { + if (s->coded_hdr[i].va) + ave_free(hw, &hw->area, s->coded_hdr[i].rel, s->coded_hdr[i].size); + if (s->slice_hdr[i].va) + ave_free(hw, &hw->area, s->slice_hdr[i].rel, s->slice_hdr[i].size); + } + if (s->param_sets.va) + ave_free(hw, &hw->area, s->param_sets.rel, s->param_sets.size); +} + +/* pictures of other streams at the firmware */ +static unsigned int ave_others_inflight(struct ave_hw *hw, struct ave_session *s) +{ + struct ave_session *o; + unsigned int n = 0; + + list_for_each_entry(o, &hw->sessions, node) + if (o != s) + n += o->inflight; + return n; +} + +static int ave_session_setup(struct ave_hw *hw, struct ave_session *s) +{ + const struct ave_params *p = s->params; + int ret; + + cancel_delayed_work(&hw->off_work); + if (!hw->booted) { /* with room for every stream's buffers */ + ret = ave_boot(hw, MAX_STREAMS * session_cpu_size()); + if (ret) + return ret; + } + ret = session_cpu_buffers(hw, s); + if (ret) + goto err; + + /* + * A client id of its own: the firmware keeps per-client state, and + * the same id again after STOP had the next stream (an HEVC one of IDR + * pictures only) hang at its first picture. iOS never reuses one. + */ + if (!hw->configured) + hw->next_client = 1; + s->client = hw->next_client++; + dev_dbg(hw->dev, "stream: %s, client %u\n", hw->configured ? "START" : "CONFIG", + s->client); + if (!hw->configured) { + u8 cmd[CONFIG_SIZE] = {}; + + ave_cmd_header(cmd, CMD_CONFIG, s->client, ave_codec(s), PLANE_CONFIG, 0); + cmd[0x19] = 1; /* the pipeline controllers on */ + /* + * iOS: 1 (AppleAVE2 +0x770). The firmware then starts a + * picture's motion search and pipe while the one before is + * still in the transcoder (fw ProcessQueue 0x4298), which + * needs a second picture posted. With two in flight the AP's + * turnaround between pictures is hidden: 2 % faster at + * 3840 x 2160, 8 % at 1920 x 1080 (HEVC), 12 % at 1280 x 720 + * (H.264). + */ + cmd[0x1a] = 1; + cmd[0x1b] = 1; + put_unaligned_le32(lower_32_bits(hw->pmgr_iova), cmd + 0x1c); + ret = ave_cmd_sync(hw, cmd, sizeof(cmd), ANS_CONFIG, 2000); + if (ret) + goto err; + hw->configured = true; + } else { + u8 cmd[HDR_SIZE] = {}; + + ave_cmd_header(cmd, CMD_START, s->client, ave_codec(s), PLANE_START, 0); + ret = ave_cmd_sync(hw, cmd, sizeof(cmd), ANS_START, 2000); + if (ret) + goto err; + } + ret = s->hevc ? hevc_init(hw, s, p) : avc_init(hw, s, p); + if (ret) + goto err; + s->have_ref = false; + s->frame_num = 0; + memset(s->pic, 0, sizeof(s->pic)); + s->slot = 0; + s->done_slot = 0; + s->inflight = 0; + s->fail_next = false; + s->gen = hw->gen; + return 0; + +err: + /* a firmware in an unknown state: boot it again next time (every stream sets up again) */ + ave_reset(hw); + return ret; +} + +int ave_hw_session_start(struct ave_ctx *ctx) +{ + struct ave_hw *hw = ctx->ave->hw; + const struct ave_params *p = &ctx->params; + struct ave_session *s; + int ret; + + if (p->codec != V4L2_PIX_FMT_H264 && p->codec != V4L2_PIX_FMT_HEVC) + return -EOPNOTSUPP; + if (p->codec == V4L2_PIX_FMT_H264 && (p->width < AVE_MIN_W || p->height < AVE_MIN_H)) + return -EINVAL; + s = kzalloc_obj(*s); + if (!s) + return -ENOMEM; + s->ctx = ctx; + s->params = p; + s->hevc = p->codec == V4L2_PIX_FMT_HEVC; + s->ten = s->hevc && p->profile == V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10; + s->width = p->width; + s->height = p->height; + s->wmb = DIV_ROUND_UP(p->width, 16); + s->hmb = DIV_ROUND_UP(p->height, 16); + s->ctb_w = DIV_ROUND_UP(p->width, 32); + s->ctb_h = DIV_ROUND_UP(p->height, 32); + s->tools = HEVC_TOOLS; + if (p->aq) + s->tools |= HEVC_CU_QP_DELTA; /* with QPMod, as iOS; alone it hangs */ + ave_slice_map(s, p); + s->bframes = min_t(u32, p->bframes, AVE_MAX_B); + s->n_recon = s->bframes ? 3 : 2; + s->ref_new = 0; /* the first anchor writes set 1 */ + s->ref_old = -1; + ave_buffer_sizes(s->hevc, s->ten, s->width, s->height, &s->sz); + + mutex_lock(&hw->lock); + if (hw->n_sessions >= MAX_STREAMS) { + ret = -EBUSY; + goto err; + } + ret = session_hw_buffers(hw, s); + if (ret) + goto err; + ret = ave_session_setup(hw, s); + if (ret) { + session_hw_free(hw, s); + goto err; + } + rc_init(s, p); + list_add_tail(&s->node, &hw->sessions); + hw->n_sessions++; + ctx->session = s; + /* + * With several streams each has one picture at the firmware at a time + * and holds its job until it is done, so the pictures in flight are + * always the running job's (ave_hw_max_inflight()). Pictures another + * stream posted two at a time before this one opened finish first. + */ + if (hw->n_sessions > 1) { + unsigned long end = jiffies + msecs_to_jiffies(2 * AVE_TIMEOUT_MS); + + while (ave_others_inflight(hw, s) && time_before(jiffies, end)) { + mutex_unlock(&hw->lock); + usleep_range(2000, 4000); + mutex_lock(&hw->lock); + } + } + mutex_unlock(&hw->lock); + if (s->hevc) + dev_dbg(hw->dev, "HEVC %ux%u, %s from %s, level_idc %u, tools %#x, %u merge candidates, mode decision %u, %u/%u fps, %s%s\n", + s->width, s->height, s->ten ? "Main 10" : "Main", + p->src_ten ? "P010" : "NV12", + s->level_idc, s->tools, HEVC_MERGE_CAND, HEVC_MD_MODE, + p->fps_num, p->fps_den, + p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ ? "constant QP" : "bitrate", + p->aq ? ", adaptive quantization" : ""); + else + dev_dbg(hw->dev, "H.264 %ux%u, profile_idc %u level_idc %u, %s, %u/%u fps, %s%s\n", + s->width, s->height, s->headers[5], s->headers[7], + s->cabac ? "CABAC" : "CAVLC", p->fps_num, p->fps_den, + p->rc_mode == V4L2_MPEG_VIDEO_BITRATE_MODE_CQ ? "constant QP" : "bitrate", + p->aq ? ", adaptive quantization" : ""); + return 0; + +err: + mutex_unlock(&hw->lock); + kfree(s); + return ret; +} + +void ave_hw_session_stop(struct ave_ctx *ctx) +{ + struct ave_hw *hw = ctx->ave->hw; + struct ave_session *s = ctx->session; + + if (!s) + return; + mutex_lock(&hw->lock); + if (hw->booted && s->gen == hw->gen) { + u8 cmd[HDR_SIZE] = {}; + + ave_cmd_header(cmd, CMD_STOP, s->client, ave_codec(s), PLANE_STOP, 0x7fffffff); + if (ave_cmd_sync(hw, cmd, sizeof(cmd), ANS_STOP, 1000)) + ave_reset(hw); /* the other streams set up again */ + } + session_cpu_free(hw, s); + session_hw_free(hw, s); + list_del(&s->node); + hw->n_sessions--; + if (hw->session == s) + hw->session = NULL; + ctx->session = NULL; + kfree(s); + if (list_empty(&hw->sessions)) + ave_off_later(hw); + mutex_unlock(&hw->lock); +} + +int ave_hw_headers(struct ave_ctx *ctx, struct vb2_v4l2_buffer *dst, u32 *bytes) +{ + struct ave_session *s = ctx->session; + void *va = vb2_plane_vaddr(&dst->vb2_buf, 0); + + if (!s || !va || vb2_plane_size(&dst->vb2_buf, 0) < s->headers_len) + return -EINVAL; + memcpy(va, s->headers, s->headers_len); + *bytes = s->headers_len; + return 0; +} + +/* + * PicMgmtParams, the same in AVC_ENCODE and HEVC_ENCODE: the picture's + * buffers. @c is the command, shifted for HEVC so that PM_* land in its + * PicMgmtParams; the slices go to @out (@out_size bytes). + */ +static void ave_pic_mgmt(struct ave_session *s, u8 *c, u32 in, u32 out, u32 out_size, + const struct ave_refs *r) +{ + static const u8 fw_type[] = { [AVE_PIC_IDR] = 3, [AVE_PIC_P] = 1, [AVE_PIC_B] = 2 }; + const struct ave_params *p = s->params; + bool bpic = r->type == AVE_PIC_B; + u32 lsb = s->sz.lsb, luma = lsb + s->sz.recon_luma; /* from a recon's base */ + unsigned int i, j; + int l1; + + put_unaligned_le32(PICMGMT_SIZE, c + PM_SIZE_WORD); + put_unaligned_le32(0xffffffff, c + PM_AVG_VARIANCE); /* read only with QPMod */ + for (i = 0; i < 52; i++) + put_unaligned_le32(avc_lambda[i], c + PM_LAMBDA_TABLE + 4 * i); + if (r->type != AVE_PIC_IDR) { + for (i = 0; i < 2; i++) { + put_unaligned_le32(s->recon[r->l0].iova + lsb, c + PM_REF_Y(i)); + put_unaligned_le32(s->recon[r->l0].iova + luma, c + PM_REF_UV(i)); + put_unaligned_le32(s->lowres[r->l0].iova, c + PM_REF_LOWRES(i)); + } + /* P: the L1 slots too get the L0 reference, as iOS fills them */ + l1 = bpic ? r->l1 : r->l0; + put_unaligned_le32(s->recon[l1].iova + lsb, c + PM_REF_Y_L1); + put_unaligned_le32(s->recon[l1].iova + luma, c + PM_REF_UV_L1); + if (bpic) + put_unaligned_le32(s->lowres[l1].iova, c + PM_REF_LOWRES_L1); + /* the motion of L1[0]'s picture: H.264 direct, HEVC TMVP (sRef.Colocated_L1) */ + if (bpic || (s->hevc && (s->tools & HEVC_TMVP))) + put_unaligned_le32(s->colocated[l1].iova, c + PM_REF_COLOCATED); + } + /* with B pictures each picture's type, number and references' POCs (as iOS sets them) */ + if (s->bframes) { + put_unaligned_le32(r->poc, c + PM_FRAME_NUM); + put_unaligned_le32(fw_type[r->type], c + PM_FRAME_TYPE); + if (r->type != AVE_PIC_IDR) { + put_unaligned_le32(r->poc_l0, c + PM_POC_L0(0)); + put_unaligned_le32(r->poc_l0, c + PM_POC_L0(1)); + put_unaligned_le32(bpic ? r->poc_l1 : r->poc_l0, c + PM_POC_L1); + } + } + put_unaligned_le32(s->recon[r->cur].iova + lsb, c + PM_RECON_Y); + put_unaligned_le32(s->recon[r->cur].iova + luma, c + PM_RECON_UV); + if (s->ten) { + /* + * The 2-bit planes. The firmware programs every one of them for + * 10-bit, with no check for 0: all point into a recon buffer, + * also where no reference is read (an IDR picture's: its own). + */ + u32 rb = s->recon[r->cur].iova, l0b = rb, l1b = rb; + + if (r->type != AVE_PIC_IDR) { + l0b = s->recon[r->l0].iova; + l1b = s->recon[bpic ? r->l1 : r->l0].iova; + } + put_unaligned_le32(rb, c + PM_RECON_Y_LSB); + put_unaligned_le32(rb + s->sz.lsb_y, c + PM_RECON_UV_LSB); + for (i = 0; i < 2; i++) { + put_unaligned_le32(l0b, c + PM_REF_Y_LSB(i)); + put_unaligned_le32(l0b + s->sz.lsb_y, c + PM_REF_UV_LSB(i)); + } + put_unaligned_le32(l1b, c + PM_REF_Y_LSB_L1); + put_unaligned_le32(l1b + s->sz.lsb_y, c + PM_REF_UV_LSB_L1); + } + put_unaligned_le32(s->colocated[r->cur].iova, c + PM_RECON_COLOCATED); + put_unaligned_le32(s->lowres[r->cur].iova, c + PM_RECON_LOWRES); + for (i = 0; i < 8; i++) /* two sets, a picture each in turn */ + put_unaligned_le32(s->lowres_result[8 * r->res + i].iova, c + PM_LOWRES_RESULT(i)); + put_unaligned_le32(in, c + PM_INPUT_Y); + put_unaligned_le32(p->stride, c + PM_INPUT_Y_STRIDE); + put_unaligned_le32(in + p->stride * p->height, c + PM_INPUT_UV); + put_unaligned_le32(p->stride, c + PM_INPUT_UV_STRIDE); + put_unaligned_le32(s->nbr_info.iova, c + PM_SRC_NBR_INFO); + put_unaligned_le32(s->nbr_pixels.iova, c + PM_SRC_NBR_PIXELS); + put_unaligned_le32(s->nbr_data.iova, c + PM_SRC_NBR_DATA); + for (i = 0; i < N_ENTROPY / 2; i++) + for (j = 0; j < 2; j++) + put_unaligned_le32(s->entropy[2 * i + j].iova, c + PM_ENTROPY(i, j)); + /* the capture buffer, with its own size; the slot's coded-data header */ + c[PM_OUT_SIZE_OVERRIDE] = 1; + put_unaligned_le32(s->slot, c + PM_OUT_SLOT); + put_unaligned_le32(out, c + PM_OUT_ADDR); + put_unaligned_le32(s->coded_hdr[s->slot].iova, c + PM_OUT_CDH); + put_unaligned_le32(out_size, c + PM_OUT_SIZE); +} + +int ave_hw_encode(struct ave_ctx *ctx, struct vb2_v4l2_buffer *src, + struct vb2_v4l2_buffer *dst, enum ave_pic_type type, u32 disp) +{ + struct ave_hw *hw = ctx->ave->hw; + struct ave_session *s = ctx->session; + const struct ave_params *p = &ctx->params; + u32 in = vb2_dma_contig_plane_dma_addr(&src->vb2_buf, 0); + u32 out = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0); + u32 out_size = vb2_plane_size(&dst->vb2_buf, 0), len; + struct ave_refs r = {}; + struct ave_pic *pic; + u8 *va = NULL; + bool headers, idr; + int ret, qp; + u8 *cmd; + + if (!s) + return -EINVAL; + len = s->hevc ? HEVC_ENCODE_SIZE : AVC_ENCODE_SIZE; + cmd = kzalloc(len, GFP_KERNEL); + if (!cmd) + return -ENOMEM; + + mutex_lock(&hw->lock); + /* after a reset (for any stream) it registers again and starts with a key frame */ + if (!hw->booted || s->gen != hw->gen) { + ret = ave_session_setup(hw, s); + if (ret) + goto out; + type = AVE_PIC_IDR; + } + idr = type == AVE_PIC_IDR; + if (type == AVE_PIC_B && (!s->bframes || s->ref_old < 0)) { + ret = -EINVAL; /* no anchor before it */ + goto out; + } + if (s->inflight >= ave_hw_max_inflight(ctx)) { + ret = -EBUSY; + goto out; + } + pic = &s->pic[s->slot]; + headers = idr && !p->headers_separate && (p->headers_every_idr || !ctx->headers_sent); + if (headers || s->hevc) + va = vb2_plane_vaddr(&dst->vb2_buf, 0); + /* HEVC: the slice header goes in front of the slice data here, afterwards */ + if (s->hevc && !va) { + ret = -EINVAL; + goto out; + } + /* the parameter sets go first, then the slices */ + pic->out_off = 0; + if (headers) { + pic->out_off = s->hevc ? s->headers_len : ALIGN(s->headers_len, OUT_ALIGN); + if (!va || out_size < pic->out_off + SZ_64K) { + ret = -ENOSPC; + goto out; + } + memcpy(va, s->headers, s->headers_len); + memset(va + s->headers_len, 0, pic->out_off - s->headers_len); + ctx->headers_sent = true; + } + if (idr) { + s->frame_num = 0; + s->have_ref = false; + s->idr_pic_id ^= 1; + s->ref_old = -1; + s->poc_base = disp; /* (not 0 after a reset) */ + } + /* + * The recon sets: an anchor (I, P) writes the one of sets 0 and 1 the + * last anchor did not (the next picture's motion search may read the + * last one's while it is still in flight), a B picture set 2, which + * nothing reads. P predicts from the last anchor, B from the one + * before it (L0) and the last (L1). The low-res result sets take + * turns picture by picture. + */ + r.type = type; + r.cur = type == AVE_PIC_B ? 2 : !s->ref_new; + r.l0 = type == AVE_PIC_B ? s->ref_old : s->ref_new; + r.l1 = s->ref_new; + r.poc = disp - s->poc_base; + r.poc_l0 = type == AVE_PIC_B ? s->poc_old : s->poc_new; + r.poc_l1 = s->poc_new; + r.poc_new = s->poc_new; /* the last anchor (TMVP's co-located picture) */ + r.poc_old = s->poc_old; /* and its reference, unless it is the IDR */ + r.col_has_ref = s->ref_old >= 0; + r.res = !s->res; + memset(s->coded_hdr[s->slot].va, 0, CDH_CLEAR); + qp = rc_qp(s, p, type); + + if (!s->hevc) { + ave_cmd_header(cmd, CMD_AVC_ENCODE, s->client, CODEC_AVC, s->slot, 0); + ret = avc_slice_header(s, cmd, type, qp, r.poc); + if (ret) + goto out; + ave_pic_mgmt(s, cmd, in, out + pic->out_off, out_size - pic->out_off, &r); + } else { + ave_cmd_header(cmd, CMD_HEVC_ENCODE, s->client, CODEC_HEVC, s->slot, 0); + ret = hevc_slice(s, pic, cmd, &r, qp, out_size); + if (ret) + goto out; + /* + * The data where it follows the header the firmware will + * write, aligned (zeros before the header are trailing_zero_8bits). + */ + pic->data_off = ALIGN(pic->out_off + pic->hdr_max, OUT_ALIGN); + if (out_size < pic->data_off + SZ_64K) { + ret = -ENOSPC; + goto out; + } + memset(va + pic->out_off, 0, pic->data_off - pic->out_off); + ave_pic_mgmt(s, cmd + HPM - PM, in, out + pic->data_off, out_size - pic->data_off, + &r); + /* the mode decision's candidate set, with the values iOS sends */ + put_unaligned_le32(HEVC_MD_MODE, cmd + HPM - PM + PM_MD_MODE); + put_unaligned_le32(HEVC_MD_EARLY, cmd + HPM - PM + PM_MD_EARLY); + } + hw->session = s; + ret = ave_post(hw, cmd, len); + if (ret) + goto out; + pic->type = type; + pic->cur = r.cur; + pic->res = r.res; + pic->dst = dst; + s->slot = (s->slot + 1) % N_SLOTS; + s->inflight++; + s->res = r.res; + /* + * An anchor: the next pictures' references, and the next frame_num + * (H.264: only references advance it; HEVC: the POC, a picture each). + */ + if (type != AVE_PIC_B) { + s->have_ref = true; + s->ref_old = idr ? -1 : s->ref_new; + s->poc_old = s->poc_new; + s->ref_new = r.cur; + s->poc_new = r.poc; + if (!s->hevc) + s->frame_num = (s->frame_num + 1) & ((1 << s->log2_max_frame_num) - 1); + } + if (s->hevc) + s->frame_num++; +out: + mutex_unlock(&hw->lock); + kfree(cmd); + return ret; +} + +/* + * A picture's slices are contiguous in the capture buffer, each with the + * bytes to drop at its end (padding after a context switch, which this + * driver does not ask for). HEVC's slice headers are in the slot's + * slice-header buffer, where the firmware wrote them: each goes right + * before its slice's data (zeros in front of the first, if any, are + * trailing_zero_8bits). Returns where the access unit ends in the capture + * buffer, 0 if it cannot be put together; @hbytes: the headers' bytes. + */ +static u32 ave_place_slices(struct ave_hw *hw, struct ave_session *s, u32 slot, const u8 *cdh, + const u32 *size, const u32 *drop, u32 n, u32 *hbytes) +{ + const struct ave_pic *pic = &s->pic[slot]; + u32 out_size = vb2_plane_size(&pic->dst->vb2_buf, 0); + u32 data_off = s->hevc ? pic->data_off : pic->out_off; + u32 hs[MAX_SLICES], hoff[MAX_SLICES], len[MAX_SLICES]; + u32 i, src, dst, start, htot = 0, dtot = 0; + const u8 *hdr = s->slice_hdr[slot].va; + bool dropped = false; + u8 *va; + + *hbytes = 0; + for (i = 0; i < n; i++) { + len[i] = size[i] - drop[i]; + dtot += len[i]; + dropped |= drop[i] != 0; + } + if (!s->hevc && !dropped) + return data_off + dtot; + va = vb2_plane_vaddr(&pic->dst->vb2_buf, 0); + if (!va) + return 0; + if (dropped) /* the padding out: the data contiguous at data_off */ + for (i = 0, src = dst = data_off; i < n; src += size[i], dst += len[i], i++) + memmove(va + dst, va + src, len[i]); + if (!s->hevc) + return data_off + dtot; + + for (i = 0; i < n; i++) { + const u8 *rec = cdh + CDH_SLICE(i); + u32 haddr = get_unaligned_le32(rec + CDH_SLICE_HDR_ADDR); + + hs[i] = get_unaligned_le32(rec + CDH_SLICE_HDR_SIZE); + hoff[i] = haddr - s->slice_hdr[slot].iova; + if (hs[i] < 6 || hs[i] > SLICE_HDR_STEP || haddr < s->slice_hdr[slot].iova || + hoff[i] > s->slice_hdr[slot].size - hs[i]) { + dev_err(hw->dev, "HEVC slice %u: header of %u bytes at %#x\n", + i, hs[i], haddr); + return 0; + } + if (hoff[i] != i * SLICE_HDR_STEP) + dev_warn_once(hw->dev, "HEVC slice %u: header at %#x, not %#x\n", i, haddr, + s->slice_hdr[slot].iova + i * SLICE_HDR_STEP); + htot += hs[i]; + } + if (hs[0] < pic->hdr_pred_len || hs[0] > pic->hdr_max || + memcmp(hdr + hoff[0], pic->hdr_pred, pic->hdr_pred_len)) + dev_warn_ratelimited(hw->dev, "HEVC slice header %*ph, expected %*ph..., %u max\n", + min(hs[0], 32U), hdr + hoff[0], pic->hdr_pred_len, + pic->hdr_pred, pic->hdr_max); + /* + * The first header right before the data, or, longer than foreseen, + * at out_off. Either way every slice's data moves up (or stays): move + * them the last first, each header in front of its slice. + */ + start = data_off >= pic->out_off + hs[0] ? data_off - hs[0] : pic->out_off; + if (start + htot + dtot > out_size) + return 0; + dst = start + htot + dtot; + src = data_off + dtot; + for (i = n; i-- > 0;) { + dst -= len[i]; + src -= len[i]; + if (dst != src) + memmove(va + dst, va + src, len[i]); + dst -= hs[i]; + memcpy(va + dst, hdr + hoff[i], hs[i]); + } + *hbytes = htot; + return start + htot + dtot; +} + +/* the stream registered in this firmware boot as @client */ +static struct ave_session *ave_find_session(struct ave_hw *hw, u32 client) +{ + struct ave_session *s; + + list_for_each_entry(s, &hw->sessions, node) + if (s->client == client && s->gen == hw->gen) + return s; + return NULL; +} + +/* ENCODE_DONE of the oldest picture: its slices' sizes are in its slot's coded-data header */ +static void ave_enc_done(struct ave_hw *hw, u32 client, u32 plane, u32 status, u32 gen) +{ + struct ave_session *s; + struct ave_pic *pic; + u32 bytes = 0, n, au = 0, slot, hbytes; + u32 size[MAX_SLICES], drop[MAX_SLICES]; + enum ave_pic_type type; + bool ok; + const u8 *cdh; + + mutex_lock(&hw->lock); + if (gen != hw->gen) { /* from before a reset: its picture was failed then */ + mutex_unlock(&hw->lock); + return; + } + s = ave_find_session(hw, client); + if (s != hw->session) { /* only the last poster's pictures are in flight */ + mutex_unlock(&hw->lock); + dev_warn(hw->dev, "ENCODE_DONE of client %u, slot %u: not the stream in flight\n", + client, plane); + return; + } + if (!s || !s->inflight || plane != s->done_slot || !s->pic[plane].dst) { + mutex_unlock(&hw->lock); + dev_warn(hw->dev, "ENCODE_DONE for slot %u: not the oldest in flight\n", plane); + return; + } + slot = s->done_slot; + pic = &s->pic[slot]; + type = pic->type; + ok = status == STATUS_OK && !s->fail_next; + cdh = s->coded_hdr[slot].va; + for (n = 0; ok && n < MAX_SLICES; n++) { + size[n] = get_unaligned_le32(cdh + CDH_SLICE(n)); + if (!size[n]) + break; + drop[n] = min_t(u32, size[n], cdh[CDH_SLICE(n) + CDH_SLICE_DROP]); + bytes += size[n] - drop[n]; + } + if (ok && n != s->n_slices) + dev_warn_ratelimited(hw->dev, "picture with %u slices, not %u\n", n, s->n_slices); + if (ok && !bytes) { + dev_err(hw->dev, "picture without slices: %*ph\n", 32, cdh + CDH_SLICE(0)); + ok = false; + } + if (ok) { + au = ave_place_slices(hw, s, slot, cdh, size, drop, n, &hbytes); + ok = au; + bytes += hbytes; + } + pic->dst = NULL; + s->done_slot = (slot + 1) % N_SLOTS; + s->inflight--; + if (!ok) { + dev_err_ratelimited(hw->dev, "picture in slot %u failed: status %#x\n", + slot, status); + /* a picture posted after it referenced it: report it failed too */ + s->fail_next = s->inflight; + s->have_ref = false; + } else { + s->fail_next = false; + rc_update(s, s->params, bytes, type); + } + mutex_unlock(&hw->lock); + ave_frame_done(hw->ave, ok ? au : 0, type, ok); +} + +static void ave_enc_work(struct work_struct *work) +{ + struct ave_hw *hw = container_of(work, struct ave_hw, enc_work); + u32 client, plane, status, gen; + + for (;;) { + spin_lock_irq(&hw->ans_lock); + if (!hw->ans_count) { + spin_unlock_irq(&hw->ans_lock); + return; + } + client = hw->ans[hw->ans_head].client; + plane = hw->ans[hw->ans_head].plane; + status = hw->ans[hw->ans_head].status; + gen = hw->ans[hw->ans_head].gen; + hw->ans_head = (hw->ans_head + 1) % ARRAY_SIZE(hw->ans); + hw->ans_count--; + spin_unlock_irq(&hw->ans_lock); + ave_enc_done(hw, client, plane, status, gen); + } +} + +void ave_hw_timeout(struct ave_dev *ave) +{ + struct ave_hw *hw = ave->hw; + + mutex_lock(&hw->lock); + if (hw->mbox_ok) + dev_err(hw->dev, "encode timed out (scratch %#x %#x %#x %#x, status %#x)\n", + mb_rd(hw, MB_SCRATCH(0)), mb_rd(hw, MB_SCRATCH(1)), + mb_rd(hw, MB_SCRATCH(2)), mb_rd(hw, MB_SCRATCH(3)), mb_rd(hw, MB_STATUS)); + if (hw->booted) { + struct ave_chan *c = hw->io; + u32 *sl = c ? ring_slot(c, (c->cursor + c->num - 1) % c->num) : NULL; + + ave_service(hw); /* the firmware's last words */ + if (sl) /* was the command taken (owner bit back)? */ + dev_err(hw->dev, "last IO slot: %08x %08x %08x; coded header %*ph\n", + sl[0], sl[1], sl[2], 16, + hw->session ? hw->session->coded_hdr[0].va : sl); + } + if (hw->session) { + struct ave_session *s = hw->session; + + /* every picture in flight is lost: the caller fails them */ + memset(s->pic, 0, sizeof(s->pic)); + s->slot = 0; + s->done_slot = 0; + s->inflight = 0; + s->fail_next = false; + s->have_ref = false; + } + /* the firmware may still write the buffers: stop it; the next picture boots it again */ + ave_reset(hw); + mutex_unlock(&hw->lock); +} + +/* probe */ + +int ave_hw_init(struct ave_dev *ave, struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct resource *res; + struct ave_hw *hw; + int ret; + + hw = devm_kzalloc(dev, sizeof(*hw), GFP_KERNEL); + if (!hw) + return -ENOMEM; + hw->ave = ave; + hw->dev = dev; + ave->hw = hw; + mutex_init(&hw->lock); + mutex_init(&hw->ipc_lock); + init_completion(&hw->done); + spin_lock_init(&hw->ans_lock); + INIT_LIST_HEAD(&hw->sessions); + INIT_WORK(&hw->enc_work, ave_enc_work); + INIT_DELAYED_WORK(&hw->poll, ave_poll_work); + INIT_DELAYED_WORK(&hw->off_work, ave_off_work); + + /* mapped, never touched unpowered */ + hw->cpu = devm_platform_ioremap_resource_byname(pdev, "cpu"); + if (IS_ERR(hw->cpu)) + return PTR_ERR(hw->cpu); + hw->mbox = hw->cpu + MBOX_OFFSET; + hw->smmu = devm_platform_ioremap_resource_byname(pdev, "smmu"); + if (IS_ERR(hw->smmu)) + return PTR_ERR(hw->smmu); + /* the PMGR's page: the PMGR driver has it; only its address goes to the firmware */ + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pmgr"); + if (!res) + return -EINVAL; + hw->pmgr_phys = res->start; + if (of_property_read_string(dev->of_node, "firmware-name", &hw->fw_name)) + hw->fw_name = "apple/ave-t8010.bin"; + + ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); + if (ret) + return ret; + ret = devm_pm_domain_attach_list(dev, NULL, &hw->pds); + if (ret < 0) + return dev_err_probe(dev, ret, "power domains\n"); + if (!hw->pds || hw->pds->num_pds < 4) + return dev_err_probe(dev, -EINVAL, "power domains: sys, pipe4, pipe5, me0, me1\n"); + + hw->irq = platform_get_irq(pdev, 0); + if (hw->irq < 0) + return hw->irq; + /* only while powered: unpowered, the line may read high */ + ret = devm_request_threaded_irq(dev, hw->irq, NULL, ave_irq_thread, + IRQF_ONESHOT | IRQF_NO_AUTOEN, dev_name(dev), hw); + if (ret) + return ret; + pm_runtime_enable(dev); + return 0; +} + +/* + * System sleep: power the encoder off now. The delayed power-off (3 s after + * a stream) must not run while the system sleeps: its POWERDOWN and register + * writes then reach a block whose power domain is off, and the phone hung + * (an encode and a suspend right after it). A stream still open boots the + * firmware again with its next picture, as after a reset. + */ +void ave_hw_suspend(struct ave_dev *ave) +{ + struct ave_hw *hw = ave->hw; + + cancel_delayed_work_sync(&hw->off_work); + mutex_lock(&hw->lock); + ave_reset(hw); + mutex_unlock(&hw->lock); +} + +void ave_hw_remove(struct ave_dev *ave) +{ + struct ave_hw *hw = ave->hw; + + cancel_delayed_work_sync(&hw->off_work); + cancel_work_sync(&hw->enc_work); + mutex_lock(&hw->lock); + ave_unboot(hw); + ave_power_off(hw); + ave_release(hw); + mutex_unlock(&hw->lock); + pm_runtime_disable(hw->dev); +} diff --git a/drivers/media/platform/apple/ave/ave_v4l2.c b/drivers/media/platform/apple/ave/ave_v4l2.c new file mode 100644 index 00000000000000..f81600453a2f94 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave_v4l2.c @@ -0,0 +1,1214 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T8010 video encoder: the V4L2 stateful encoder interface (mem2mem). + * + * OUTPUT takes NV12 frames, CAPTURE gives H.264 or HEVC access units in + * Annex B form, in coding order: with B pictures a group's last frame (its + * anchor) is coded before the frames before it, and the capture buffers + * carry the timestamps of the frames they code. Every source frame gives + * one access unit. One job finishes one picture; the firmware gets the + * next one before the one before is done (their buffers stay queued until + * then). The stream's settings are latched + * from the formats and controls when its first picture is encoded; the + * bitrate and key-frame requests also apply while it runs (from the next + * picture posted). ENC_CMD_STOP drains (the last access unit carries + * V4L2_BUF_FLAG_LAST), and stopping the CAPTURE queue ends the stream: the + * next one starts with an IDR picture and its headers. + */ + +#include +#include +#include +#include + +#include "ave.h" + +static inline struct ave_ctx *file_to_ctx(struct file *file) +{ + return ave_fh_to_ctx(file_to_v4l2_fh(file)); +} + +static const u32 ave_coded_fmts[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC }; + +static bool ave_is_coded(u32 fourcc) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(ave_coded_fmts); i++) + if (fourcc == ave_coded_fmts[i]) + return true; + return false; +} + +/* the smallest picture of the codec (the firmware's limits) */ +static u32 ave_min_w(u32 codec) +{ + return codec == V4L2_PIX_FMT_HEVC ? AVE_MIN_W_HEVC : AVE_MIN_W; +} + +static u32 ave_min_h(u32 codec) +{ + return codec == V4L2_PIX_FMT_HEVC ? AVE_MIN_H_HEVC : AVE_MIN_H; +} + +/* + * The source: NV12 in one plane, chroma right after height lines of luma; + * for HEVC also P010, the same with 16-bit samples (10 bits in the top). + */ +static void ave_fill_raw(struct v4l2_pix_format_mplane *f, u32 codec) +{ + u32 w = ALIGN(clamp(f->width, ave_min_w(codec), AVE_MAX_W), 2); + u32 h = ALIGN(clamp(f->height, ave_min_h(codec), AVE_MAX_H), 2); + bool ten = f->pixelformat == V4L2_PIX_FMT_P010 && codec == V4L2_PIX_FMT_HEVC; + u32 bpl = f->plane_fmt[0].bytesperline, row = ten ? 2 * w : w; + + if (bpl < row || bpl > AVE_MAX_STRIDE || bpl % AVE_STRIDE_ALIGN) + bpl = ALIGN(row, AVE_STRIDE_ALIGN); + f->width = w; + f->height = h; + f->pixelformat = ten ? V4L2_PIX_FMT_P010 : V4L2_PIX_FMT_NV12; + f->field = V4L2_FIELD_NONE; + f->num_planes = 1; + f->flags = 0; + f->plane_fmt[0].bytesperline = bpl; + f->plane_fmt[0].sizeimage = bpl * h * 3 / 2; + if (f->colorspace == V4L2_COLORSPACE_DEFAULT) + f->colorspace = V4L2_COLORSPACE_REC709; + memset(f->plane_fmt[0].reserved, 0, sizeof(f->plane_fmt[0].reserved)); + memset(f->reserved, 0, sizeof(f->reserved)); +} + +/* an access unit: at least half a source frame, at most 32 MB */ +static void ave_fill_coded(const struct ave_ctx *ctx, struct v4l2_pix_format_mplane *f) +{ + const struct v4l2_pix_format_mplane *src = &ctx->src_fmt; + u32 min = max_t(u32, src->width * src->height * 3 / 4, SZ_512K); + + if (!ave_is_coded(f->pixelformat)) + f->pixelformat = V4L2_PIX_FMT_H264; + f->width = src->width; + f->height = src->height; + f->field = V4L2_FIELD_NONE; + f->num_planes = 1; + f->flags = 0; + f->plane_fmt[0].bytesperline = 0; + f->plane_fmt[0].sizeimage = clamp_t(u32, f->plane_fmt[0].sizeimage, min, SZ_32M); + f->colorspace = src->colorspace; + f->xfer_func = src->xfer_func; + f->ycbcr_enc = src->ycbcr_enc; + f->quantization = src->quantization; + memset(f->plane_fmt[0].reserved, 0, sizeof(f->plane_fmt[0].reserved)); + memset(f->reserved, 0, sizeof(f->reserved)); +} + +static int ave_querycap(struct file *file, void *priv, struct v4l2_capability *cap) +{ + strscpy(cap->driver, "apple-ave", sizeof(cap->driver)); + strscpy(cap->card, "Apple T8010 video encoder", sizeof(cap->card)); + strscpy(cap->bus_info, "platform:apple-ave", sizeof(cap->bus_info)); + return 0; +} + +static int ave_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) +{ + if (f->index >= ARRAY_SIZE(ave_coded_fmts)) + return -EINVAL; + f->pixelformat = ave_coded_fmts[f->index]; + f->flags = V4L2_FMT_FLAG_COMPRESSED; + return 0; +} + +static int ave_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) +{ + bool hevc = file_to_ctx(file)->dst_fmt.pixelformat == V4L2_PIX_FMT_HEVC; + + if (f->index > (hevc ? 1 : 0)) + return -EINVAL; + f->pixelformat = f->index ? V4L2_PIX_FMT_P010 : V4L2_PIX_FMT_NV12; + return 0; +} + +static int ave_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) +{ + /* the source's: those of the coded format set */ + u32 codec = ave_is_coded(fs->pixel_format) ? fs->pixel_format : + file_to_ctx(file)->dst_fmt.pixelformat; + + if (fs->index || + (!ave_is_coded(fs->pixel_format) && fs->pixel_format != V4L2_PIX_FMT_NV12 && + fs->pixel_format != V4L2_PIX_FMT_P010)) + return -EINVAL; + fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; + fs->stepwise.min_width = ave_min_w(codec); + fs->stepwise.max_width = AVE_MAX_W; + fs->stepwise.step_width = 2; + fs->stepwise.min_height = ave_min_h(codec); + fs->stepwise.max_height = AVE_MAX_H; + fs->stepwise.step_height = 2; + return 0; +} + +static int ave_g_fmt_out(struct file *file, void *priv, struct v4l2_format *f) +{ + f->fmt.pix_mp = file_to_ctx(file)->src_fmt; + return 0; +} + +static int ave_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) +{ + f->fmt.pix_mp = file_to_ctx(file)->dst_fmt; + return 0; +} + +static int ave_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) +{ + ave_fill_raw(&f->fmt.pix_mp, file_to_ctx(file)->dst_fmt.pixelformat); + return 0; +} + +static int ave_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) +{ + ave_fill_coded(file_to_ctx(file), &f->fmt.pix_mp); + return 0; +} + +static int ave_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) +{ + struct ave_ctx *ctx = file_to_ctx(file); + + /* a running stream keeps its size: stop the CAPTURE queue first */ + if (vb2_is_busy(v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type)) || ctx->session) + return -EBUSY; + ave_fill_raw(&f->fmt.pix_mp, ctx->dst_fmt.pixelformat); + ctx->src_fmt = f->fmt.pix_mp; + ctx->crop = (struct v4l2_rect){ 0, 0, ctx->src_fmt.width, ctx->src_fmt.height }; + /* the coded size follows (while the CAPTURE queue has no buffers) */ + if (!vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) + ave_fill_coded(ctx, &ctx->dst_fmt); + return 0; +} + +static int ave_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) +{ + struct ave_ctx *ctx = file_to_ctx(file); + + if (vb2_is_busy(v4l2_m2m_get_vq(ctx->fh.m2m_ctx, f->type))) + return -EBUSY; + ave_fill_coded(ctx, &f->fmt.pix_mp); + ctx->dst_fmt = f->fmt.pix_mp; + /* H.264's smallest picture is larger than HEVC's: the source follows if it can */ + if (!vb2_is_busy(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) && + (ctx->src_fmt.width < ave_min_w(ctx->dst_fmt.pixelformat) || + ctx->src_fmt.height < ave_min_h(ctx->dst_fmt.pixelformat))) { + ave_fill_raw(&ctx->src_fmt, ctx->dst_fmt.pixelformat); + ctx->crop = (struct v4l2_rect){ 0, 0, ctx->src_fmt.width, ctx->src_fmt.height }; + ave_fill_coded(ctx, &ctx->dst_fmt); + f->fmt.pix_mp = ctx->dst_fmt; + } + return 0; +} + +/* the visible rectangle: OUTPUT crop */ +static int ave_g_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct ave_ctx *ctx = file_to_ctx(file); + + if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT) + return -EINVAL; + switch (s->target) { + case V4L2_SEL_TGT_CROP: + s->r = ctx->crop; + return 0; + case V4L2_SEL_TGT_CROP_DEFAULT: + case V4L2_SEL_TGT_CROP_BOUNDS: + s->r = (struct v4l2_rect){ 0, 0, ctx->src_fmt.width, ctx->src_fmt.height }; + return 0; + default: + return -EINVAL; + } +} + +static int ave_s_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct ave_ctx *ctx = file_to_ctx(file); + struct v4l2_rect r = s->r; + + if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT || s->target != V4L2_SEL_TGT_CROP) + return -EINVAL; + if (ctx->session) + return -EBUSY; + /* the stream's frame cropping starts at the top left; even sizes for 4:2:0 */ + r.left = 0; + r.top = 0; + r.width = ALIGN(clamp_t(u32, r.width, ave_min_w(ctx->dst_fmt.pixelformat), + ctx->src_fmt.width), 2); + r.height = ALIGN(clamp_t(u32, r.height, ave_min_h(ctx->dst_fmt.pixelformat), + ctx->src_fmt.height), 2); + r.width = min(r.width, ctx->src_fmt.width); + r.height = min(r.height, ctx->src_fmt.height); + ctx->crop = r; + s->r = r; + return 0; +} + +static int ave_g_parm(struct file *file, void *priv, struct v4l2_streamparm *a) +{ + struct ave_ctx *ctx = file_to_ctx(file); + struct v4l2_fract *tpf; + + if (V4L2_TYPE_IS_OUTPUT(a->type)) { + a->parm.output.capability = V4L2_CAP_TIMEPERFRAME; + tpf = &a->parm.output.timeperframe; + } else { + a->parm.capture.capability = V4L2_CAP_TIMEPERFRAME; + tpf = &a->parm.capture.timeperframe; + } + tpf->numerator = ctx->fps_den; + tpf->denominator = ctx->fps_num; + return 0; +} + +static int ave_s_parm(struct file *file, void *priv, struct v4l2_streamparm *a) +{ + struct ave_ctx *ctx = file_to_ctx(file); + struct v4l2_fract *tpf = V4L2_TYPE_IS_OUTPUT(a->type) ? &a->parm.output.timeperframe : + &a->parm.capture.timeperframe; + + /* 1 to 240 frames per second */ + if (tpf->numerator && tpf->denominator && + tpf->denominator <= 240ULL * tpf->numerator && tpf->denominator >= tpf->numerator) { + ctx->fps_num = tpf->denominator; + ctx->fps_den = tpf->numerator; + } + return ave_g_parm(file, priv, a); +} + +static int ave_encoder_cmd(struct file *file, void *priv, struct v4l2_encoder_cmd *ec) +{ + struct ave_ctx *ctx = file_to_ctx(file); + static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; + int ret; + + ret = v4l2_m2m_ioctl_try_encoder_cmd(file, priv, ec); + if (ret) + return ret; + if (!vb2_is_streaming(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || + !vb2_is_streaming(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) + return 0; + ret = v4l2_m2m_ioctl_encoder_cmd(file, priv, ec); + if (ret) + return ret; + if (ec->cmd == V4L2_ENC_CMD_STOP) { + struct v4l2_m2m_ctx *m = ctx->fh.m2m_ctx; + + spin_lock_irq(&ctx->sched_lock); + if (m->is_draining && m->last_src_buf) + ctx->drain_seq = m->last_src_buf->sequence; + spin_unlock_irq(&ctx->sched_lock); + } + if (ec->cmd == V4L2_ENC_CMD_STOP && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) + v4l2_event_queue_fh(&ctx->fh, &eos); + if (ec->cmd == V4L2_ENC_CMD_START) + vb2_clear_last_buffer_dequeued(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx)); + v4l2_m2m_try_schedule(ctx->fh.m2m_ctx); + return 0; +} + +static int ave_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subscription *sub) +{ + switch (sub->type) { + case V4L2_EVENT_EOS: + return v4l2_event_subscribe(fh, sub, 0, NULL); + default: + return v4l2_ctrl_subscribe_event(fh, sub); + } +} + +static const struct v4l2_ioctl_ops ave_ioctl_ops = { + .vidioc_querycap = ave_querycap, + .vidioc_enum_fmt_vid_cap = ave_enum_fmt_cap, + .vidioc_enum_fmt_vid_out = ave_enum_fmt_out, + .vidioc_enum_framesizes = ave_enum_framesizes, + .vidioc_g_fmt_vid_cap_mplane = ave_g_fmt_cap, + .vidioc_g_fmt_vid_out_mplane = ave_g_fmt_out, + .vidioc_try_fmt_vid_cap_mplane = ave_try_fmt_cap, + .vidioc_try_fmt_vid_out_mplane = ave_try_fmt_out, + .vidioc_s_fmt_vid_cap_mplane = ave_s_fmt_cap, + .vidioc_s_fmt_vid_out_mplane = ave_s_fmt_out, + .vidioc_g_selection = ave_g_selection, + .vidioc_s_selection = ave_s_selection, + .vidioc_g_parm = ave_g_parm, + .vidioc_s_parm = ave_s_parm, + .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, + .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, + .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, + .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, + .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, + .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, + .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, + .vidioc_streamon = v4l2_m2m_ioctl_streamon, + .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, + .vidioc_encoder_cmd = ave_encoder_cmd, + .vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd, + .vidioc_subscribe_event = ave_subscribe_event, + .vidioc_unsubscribe_event = v4l2_event_unsubscribe, +}; + +/* controls */ + +static int ave_s_ctrl(struct v4l2_ctrl *ctrl) +{ + struct ave_ctx *ctx = container_of(ctrl->handler, struct ave_ctx, ctrls); + + switch (ctrl->id) { + case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME: + ctx->force_idr = true; + return 0; + case V4L2_CID_MPEG_VIDEO_BITRATE: + /* the rate control takes it at the next picture */ + if (ctx->session) + return ave_hw_set_bitrate(ctx, ctrl->val); + return 0; + case V4L2_CID_MPEG_VIDEO_B_FRAMES: + /* a group's frames are all queued before its anchor is coded */ + if (ctx->ctrl_min_out) + __v4l2_ctrl_s_ctrl(ctx->ctrl_min_out, 1 + ctrl->val); + return 0; + default: + return 0; /* read when the stream starts */ + } +} + +static const struct v4l2_ctrl_ops ave_ctrl_ops = { + .s_ctrl = ave_s_ctrl, +}; + +static int ave_init_ctrls(struct ave_ctx *ctx) +{ + struct v4l2_ctrl_handler *h = &ctx->ctrls; + const struct v4l2_ctrl_ops *ops = &ave_ctrl_ops; + struct v4l2_ctrl *c; + + v4l2_ctrl_handler_init(h, 32); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_BITRATE_MODE, + V4L2_MPEG_VIDEO_BITRATE_MODE_CQ, 0, + V4L2_MPEG_VIDEO_BITRATE_MODE_VBR); + ctx->ctrl_bitrate = v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_BITRATE, + 64000, 160000000, 1, 10000000); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_BITRATE_PEAK, 64000, 240000000, 1, 20000000); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE, 0, 1, 1, 1); + /* + * Adaptive quantization by the blocks' variance, with a bit rate only. + * Off by default: on camera pictures it costs bytes for the same PSNR + * and SSIM (it moves quality from busy blocks to flat ones). + */ + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE, 0, 1, 1, 0); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_GOP_SIZE, 0, 32767, 1, 60); + /* (not with H.264 baseline) each one is coded after the next anchor */ + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_B_FRAMES, 0, AVE_MAX_B, 1, 0); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_HEADER_MODE, + V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME, 0, + V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR, 0, 1, 1, 1); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 0, 0, 0, 0); + /* slices of whole rows (H.264: macroblock rows, HEVC: CTB rows), at most 32 */ + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE, + V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_MAX_MB, 0, + V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB, 1, + (AVE_MAX_W / 16) * (AVE_MAX_H / 16), 1, 1); + + /* H.264 */ + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_H264_PROFILE, + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH, + ~(BIT(V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE) | + BIT(V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE) | + BIT(V4L2_MPEG_VIDEO_H264_PROFILE_MAIN) | + BIT(V4L2_MPEG_VIDEO_H264_PROFILE_HIGH)), + V4L2_MPEG_VIDEO_H264_PROFILE_HIGH); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_H264_LEVEL, + V4L2_MPEG_VIDEO_H264_LEVEL_5_2, 0, V4L2_MPEG_VIDEO_H264_LEVEL_4_0); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE, + V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC, 0, + V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_I_PERIOD, 0, 32767, 1, 0); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP, 0, 51, 1, 26); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP, 0, 51, 1, 28); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP, 0, 51, 1, 30); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_MIN_QP, 0, 51, 1, 10); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_H264_MAX_QP, 0, 51, 1, 51); + + /* HEVC */ + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_PROFILE, + V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10, + ~(BIT(V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN) | + BIT(V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10)), + V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_LEVEL, + V4L2_MPEG_VIDEO_HEVC_LEVEL_6_2, 0, V4L2_MPEG_VIDEO_HEVC_LEVEL_4); + v4l2_ctrl_new_std_menu(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_TIER, + V4L2_MPEG_VIDEO_HEVC_TIER_HIGH, 0, V4L2_MPEG_VIDEO_HEVC_TIER_MAIN); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_I_FRAME_QP, 0, 51, 1, 28); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_P_FRAME_QP, 0, 51, 1, 30); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_B_FRAME_QP, 0, 51, 1, 32); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_MIN_QP, 0, 51, 1, 10); + v4l2_ctrl_new_std(h, ops, V4L2_CID_MPEG_VIDEO_HEVC_MAX_QP, 0, 51, 1, 51); + + c = v4l2_ctrl_new_std(h, ops, V4L2_CID_MIN_BUFFERS_FOR_OUTPUT, 1, 1 + AVE_MAX_B, 1, 1); + if (c) + c->flags |= V4L2_CTRL_FLAG_READ_ONLY; + ctx->ctrl_min_out = c; + if (h->error) { + int ret = h->error; + + v4l2_ctrl_handler_free(h); + return ret; + } + ctx->fh.ctrl_handler = h; + return v4l2_ctrl_handler_setup(h); +} + +static s32 ave_ctrl(struct ave_ctx *ctx, u32 id) +{ + return v4l2_ctrl_g_ctrl(v4l2_ctrl_find(&ctx->ctrls, id)); +} + +/* the stream's settings, from the formats and controls */ +static void ave_latch_params(struct ave_ctx *ctx) +{ + struct ave_params *p = &ctx->params; + bool h264 = ctx->dst_fmt.pixelformat == V4L2_PIX_FMT_H264; + + memset(p, 0, sizeof(*p)); + p->codec = ctx->dst_fmt.pixelformat; + p->width = ctx->src_fmt.width; + p->height = ctx->src_fmt.height; + p->stride = ctx->src_fmt.plane_fmt[0].bytesperline; + p->src_ten = ctx->src_fmt.pixelformat == V4L2_PIX_FMT_P010; + p->crop = ctx->crop; + p->fps_num = ctx->fps_num; + p->fps_den = ctx->fps_den; + p->rc_mode = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE) ? + ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_BITRATE_MODE) : + V4L2_MPEG_VIDEO_BITRATE_MODE_CQ; + p->bitrate = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_BITRATE); + p->bitrate_peak = max_t(u32, p->bitrate, ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_BITRATE_PEAK)); + p->gop = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_GOP_SIZE); + p->slice_mbs = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE) == + V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_MAX_MB ? + ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB) : 0; + p->headers_separate = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEADER_MODE) == + V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE; + p->headers_every_idr = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR); + if (h264) { + p->profile = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_PROFILE); + p->level = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_LEVEL); + p->cabac = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE) == + V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC && + p->profile != V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE && + p->profile != V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE; + p->qp_i = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP); + p->qp_p = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP); + p->qp_b = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP); + /* (baseline has no B slices) */ + if (p->profile != V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE && + p->profile != V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE) + p->bframes = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_B_FRAMES); + p->qp_min = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_MIN_QP); + p->qp_max = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_H264_MAX_QP); + } else { + p->profile = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_PROFILE); + p->level = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_LEVEL); + p->tier = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_TIER); + p->qp_i = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_I_FRAME_QP); + p->qp_p = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_P_FRAME_QP); + p->qp_b = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_B_FRAME_QP); + p->bframes = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_B_FRAMES); + p->qp_min = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_MIN_QP); + p->qp_max = ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_HEVC_MAX_QP); + } + if (p->qp_max < p->qp_min) + p->qp_max = p->qp_min; + /* + * Not with constant QP (as x264): the blocks would move around the + * QP asked for, most of them below it. + */ + p->aq = p->rc_mode != V4L2_MPEG_VIDEO_BITRATE_MODE_CQ && + ave_ctrl(ctx, V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE); + p->colorspace = ctx->src_fmt.colorspace; + p->xfer_func = ctx->src_fmt.xfer_func; + p->ycbcr_enc = ctx->src_fmt.ycbcr_enc; + p->quantization = ctx->src_fmt.quantization; +} + +/* buffers */ + +static void ave_fail_all(struct ave_dev *ave); + +static int ave_queue_setup(struct vb2_queue *vq, unsigned int *nbufs, unsigned int *nplanes, + unsigned int sizes[], struct device *alloc_devs[]) +{ + struct ave_ctx *ctx = vb2_get_drv_priv(vq); + const struct v4l2_pix_format_mplane *f = + V4L2_TYPE_IS_OUTPUT(vq->type) ? &ctx->src_fmt : &ctx->dst_fmt; + + if (*nplanes) + return *nplanes == 1 && sizes[0] >= f->plane_fmt[0].sizeimage ? 0 : -EINVAL; + *nplanes = 1; + sizes[0] = f->plane_fmt[0].sizeimage; + return 0; +} + +static int ave_buf_prepare(struct vb2_buffer *vb) +{ + struct ave_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); + const struct v4l2_pix_format_mplane *f = + V4L2_TYPE_IS_OUTPUT(vb->type) ? &ctx->src_fmt : &ctx->dst_fmt; + + if (vb2_plane_size(vb, 0) < f->plane_fmt[0].sizeimage) + return -EINVAL; + if (V4L2_TYPE_IS_OUTPUT(vb->type)) { + if (!vb2_get_plane_payload(vb, 0)) + vb2_set_plane_payload(vb, 0, f->plane_fmt[0].sizeimage); + if (vb2_get_plane_payload(vb, 0) < f->plane_fmt[0].sizeimage) + return -EINVAL; + } + return 0; +} + +static void ave_buf_queue(struct vb2_buffer *vb) +{ + struct ave_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); + struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); + static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; + + /* drained with nothing left to encode: this buffer is the empty last one */ + if (V4L2_TYPE_IS_CAPTURE(vb->type) && vb2_is_streaming(vb->vb2_queue) && + v4l2_m2m_dst_buf_is_last(ctx->fh.m2m_ctx)) { + vb2_set_plane_payload(vb, 0, 0); + vbuf->field = V4L2_FIELD_NONE; + vbuf->sequence = ctx->cap_seq++; + v4l2_m2m_last_buffer_done(ctx->fh.m2m_ctx, vbuf); + v4l2_event_queue_fh(&ctx->fh, &eos); + return; + } + if (V4L2_TYPE_IS_OUTPUT(vb->type)) + vbuf->sequence = ctx->out_seq++; + v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, vbuf); +} + +static int ave_start_streaming(struct vb2_queue *q, unsigned int count) +{ + struct ave_ctx *ctx = vb2_get_drv_priv(q); + + v4l2_m2m_update_start_streaming_state(ctx->fh.m2m_ctx, q); + if (V4L2_TYPE_IS_OUTPUT(q->type)) { + ctx->out_seq = 0; + } else { + ctx->cap_seq = 0; + ctx->frame_num = 0; + ctx->headers_sent = false; + /* a new stream: frames held for B pictures start it again */ + spin_lock_irq(&ctx->sched_lock); + ctx->n_held = 0; + ctx->next_held = 0; + spin_unlock_irq(&ctx->sched_lock); + } + return 0; +} + +static void ave_stop_streaming(struct vb2_queue *q) +{ + struct ave_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_v4l2_buffer *vb; + static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; + + /* + * The mem2mem core has waited for the job (the oldest picture); the + * firmware may still have a later one, writing into its buffer. + */ + if (!wait_event_timeout(ctx->idle, !READ_ONCE(ctx->posted), + msecs_to_jiffies(AVE_TIMEOUT_MS))) { + ave_hw_timeout(ctx->ave); + ave_fail_all(ctx->ave); + } + if (V4L2_TYPE_IS_OUTPUT(q->type)) { + spin_lock_irq(&ctx->sched_lock); + ctx->n_held = 0; + ctx->next_held = 0; + spin_unlock_irq(&ctx->sched_lock); + while ((vb = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx))) + v4l2_m2m_buf_done(vb, VB2_BUF_STATE_ERROR); + /* the source restarts: the next picture is a key frame */ + ctx->force_idr = true; + } else { + if (ctx->session) + ave_hw_session_stop(ctx); + while ((vb = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx))) + v4l2_m2m_buf_done(vb, VB2_BUF_STATE_ERROR); + } + v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, q); + if (V4L2_TYPE_IS_OUTPUT(q->type) && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) + v4l2_event_queue_fh(&ctx->fh, &eos); +} + +static const struct vb2_ops ave_qops = { + .queue_setup = ave_queue_setup, + .buf_prepare = ave_buf_prepare, + .buf_queue = ave_buf_queue, + .start_streaming = ave_start_streaming, + .stop_streaming = ave_stop_streaming, +}; + +static int ave_queue_init(void *priv, struct vb2_queue *src, struct vb2_queue *dst) +{ + struct ave_ctx *ctx = priv; + struct ave_dev *ave = ctx->ave; + struct vb2_queue *q[] = { src, dst }; + int i, ret; + + for (i = 0; i < 2; i++) { + q[i]->type = i ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + q[i]->io_modes = VB2_MMAP | VB2_DMABUF; + q[i]->drv_priv = ctx; + q[i]->buf_struct_size = sizeof(struct v4l2_m2m_buffer); + q[i]->ops = &ave_qops; + q[i]->mem_ops = &vb2_dma_contig_memops; + q[i]->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; + q[i]->lock = &ave->lock; + q[i]->dev = ave->dev; + q[i]->min_queued_buffers = 1; + ret = vb2_queue_init(q[i]); + if (ret) + return ret; + } + return 0; +} + +/* jobs: one picture (or the separate headers) each */ + +static void ave_job_fail(struct ave_ctx *ctx, bool src_too) +{ + struct vb2_v4l2_buffer *vb; + + if (src_too) { + vb = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx); + if (vb) + v4l2_m2m_buf_done(vb, VB2_BUF_STATE_ERROR); + } + vb = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); + if (vb) + v4l2_m2m_buf_done(vb, VB2_BUF_STATE_ERROR); + v4l2_m2m_job_finish(ctx->ave->m2m, ctx->fh.m2m_ctx); +} + +/* the first @max ready buffers of a queue, oldest first */ +static unsigned int ave_ready_bufs(struct v4l2_m2m_queue_ctx *q, struct vb2_v4l2_buffer **b, + unsigned int max) +{ + struct v4l2_m2m_buffer *mb; + unsigned long flags; + unsigned int n = 0; + + spin_lock_irqsave(&q->rdy_spinlock, flags); + list_for_each_entry(mb, &q->rdy_queue, list) { + if (n == max) + break; + b[n++] = &mb->vb; + } + spin_unlock_irqrestore(&q->rdy_spinlock, flags); + return n; +} + +/* the next picture to post, in coding order */ +struct ave_next { + struct vb2_v4l2_buffer *src; + enum ave_pic_type type; + u32 disp; /* its frame's display number from the IDR */ + unsigned int n_held; /* an anchor: the frames before it, to code as B */ + struct vb2_v4l2_buffer *held[AVE_MAX_B]; +}; + +/* + * The source frames not in a group yet, display order, at most @max; while + * draining none queued after ENC_CMD_STOP (*@last: the last one before it + * is among them). sched_lock held. + */ +static unsigned int ave_new_frames(struct ave_ctx *ctx, struct vb2_v4l2_buffer **b, + unsigned int max, bool *last) +{ + struct v4l2_m2m_ctx *m = ctx->fh.m2m_ctx; + struct v4l2_m2m_queue_ctx *q = &m->out_q_ctx; + struct v4l2_m2m_buffer *mb; + unsigned int n = 0, i; + unsigned long flags; + bool taken; + + *last = false; + spin_lock_irqsave(&q->rdy_spinlock, flags); + list_for_each_entry(mb, &q->rdy_queue, list) { + taken = false; + for (i = 0; i < ctx->posted; i++) + taken |= ctx->flight[i] == &mb->vb; + for (i = ctx->next_held; i < ctx->n_held; i++) + taken |= ctx->held[i] == &mb->vb; + if (taken) + continue; + if (m->is_draining && (s32)(mb->vb.sequence - ctx->drain_seq) > 0) + break; + if (n == max) + break; + b[n++] = &mb->vb; + if (m->is_draining && mb->vb.sequence == ctx->drain_seq) { + *last = true; + break; + } + } + spin_unlock_irqrestore(&q->rdy_spinlock, flags); + return n; +} + +/* + * What to post next (sched_lock held): a held B picture, or a new group: + * an IDR picture when one is due, else up to bframes + 1 frames, not past + * the next IDR, whose last is the anchor (P). Returns false when it has to + * wait for more source frames. + */ +static bool ave_next_pic(struct ave_ctx *ctx, struct ave_next *nx) +{ + const struct ave_params *p = &ctx->params; + struct vb2_v4l2_buffer *f[AVE_MAX_B + 1]; + unsigned int n, k, i; + bool last; + + nx->n_held = 0; + if (ctx->next_held < ctx->n_held) { + nx->src = ctx->held[ctx->next_held]; + nx->type = AVE_PIC_B; + nx->disp = ctx->held_disp + ctx->next_held; + return true; + } + n = ave_new_frames(ctx, f, p->bframes + 1, &last); + if (!n) + return false; + if (!ctx->frame_num || ctx->force_idr || (p->gop && ctx->disp >= p->gop)) { + nx->src = f[0]; + nx->type = AVE_PIC_IDR; + nx->disp = 0; + return true; + } + k = p->bframes + 1; + if (p->gop) + k = min(k, p->gop - ctx->disp); + if (n < k) { + if (!last) + return false; + k = n; /* the stream ends: a shorter group */ + } + nx->src = f[k - 1]; + nx->type = AVE_PIC_P; + nx->disp = ctx->disp + k - 1; + nx->n_held = k - 1; + for (i = 0; i < k - 1; i++) + nx->held[i] = f[i]; + return true; +} + +/* it is posted (sched_lock held) */ +static void ave_take_pic(struct ave_ctx *ctx, const struct ave_next *nx) +{ + unsigned int i; + + switch (nx->type) { + case AVE_PIC_B: + ctx->next_held++; + break; + case AVE_PIC_IDR: + ctx->disp = 1; + ctx->n_held = 0; + ctx->next_held = 0; + ctx->force_idr = false; + break; + case AVE_PIC_P: + for (i = 0; i < nx->n_held; i++) + ctx->held[i] = nx->held[i]; + ctx->held_disp = ctx->disp; + ctx->n_held = nx->n_held; + ctx->next_held = 0; + ctx->disp += nx->n_held + 1; + break; + } + ctx->flight[ctx->posted++] = nx->src; + ctx->frame_num++; +} + +/* + * Give the firmware the next pictures (run_lock held), up to + * ave_hw_max_inflight() and the capture buffers ready. Returns false if + * the oldest picture could not be posted (it is then in flight[0], and + * the caller fails it). + */ +static bool ave_post_more(struct ave_ctx *ctx, enum ave_pic_type *failed) +{ + struct v4l2_m2m_ctx *m = ctx->fh.m2m_ctx; + struct vb2_v4l2_buffer *dst[AVE_MAX_INFLIGHT]; + unsigned int max = min_t(unsigned int, ave_hw_max_inflight(ctx), ARRAY_SIZE(dst)); + unsigned int nd = ave_ready_bufs(&m->cap_q_ctx, dst, max); + struct ave_next nx; + bool more; + int ret; + + for (;;) { + spin_lock_irq(&ctx->sched_lock); + more = ctx->posted < nd && ave_next_pic(ctx, &nx); + spin_unlock_irq(&ctx->sched_lock); + if (!more) + return true; + ret = ave_hw_encode(ctx, nx.src, dst[ctx->posted], nx.type, nx.disp); + if (ret) { + dev_err_ratelimited(ctx->ave->dev, "cannot encode: %d\n", ret); + if (ctx->posted) + return true; /* tried again after the oldest */ + spin_lock_irq(&ctx->sched_lock); + ave_take_pic(ctx, &nx); + spin_unlock_irq(&ctx->sched_lock); + *failed = nx.type; + return false; + } + spin_lock_irq(&ctx->sched_lock); + ave_take_pic(ctx, &nx); + spin_unlock_irq(&ctx->sched_lock); + } +} + +/* mem2mem: whether device_run would post a picture */ +static int ave_job_ready(void *priv) +{ + struct ave_ctx *ctx = priv; + struct ave_next nx; + unsigned long flags; + bool ready; + + if (!ctx->session) + return 1; /* device_run starts the stream */ + spin_lock_irqsave(&ctx->sched_lock, flags); + ready = ave_next_pic(ctx, &nx); + spin_unlock_irqrestore(&ctx->sched_lock, flags); + return ready; +} + +static void ave_device_run(void *priv) +{ + struct ave_ctx *ctx = priv; + struct ave_dev *ave = ctx->ave; + struct vb2_v4l2_buffer *src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); + struct vb2_v4l2_buffer *dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); + enum ave_pic_type type = AVE_PIC_P; + unsigned long flags; + bool ok; + u32 bytes; + int ret; + + if (!ctx->session) { + ave_latch_params(ctx); + ret = ave_hw_session_start(ctx); + if (ret) { + dev_err_ratelimited(ave->dev, "cannot start the stream: %d%s\n", ret, + ret == -EBUSY ? " (too many streams open)" : ""); + ave_job_fail(ctx, true); + return; + } + } + + /* separate header mode: the stream's first buffer holds only its headers */ + if (ctx->params.headers_separate && !ctx->headers_sent && !ctx->posted) { + ret = ave_hw_headers(ctx, dst, &bytes); + if (ret) { + ave_job_fail(ctx, false); + return; + } + ctx->headers_sent = true; + dst = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); + v4l2_m2m_buf_copy_metadata(src, dst); + dst->flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME | + V4L2_BUF_FLAG_BFRAME); + dst->sequence = ctx->cap_seq++; + vb2_set_plane_payload(&dst->vb2_buf, 0, bytes); + v4l2_m2m_buf_done(dst, VB2_BUF_STATE_DONE); + v4l2_m2m_job_finish(ave->m2m, ctx->fh.m2m_ctx); + return; + } + + /* + * The job lasts until the oldest picture is done; meanwhile the + * firmware may have the next one too (ave_hw_max_inflight()). + */ + mutex_lock(&ave->run_lock); + spin_lock_irqsave(&ave->irq_lock, flags); + ave->running = ctx; + spin_unlock_irqrestore(&ave->irq_lock, flags); + ctx->job_held = true; + if (!ctx->posted) + mod_delayed_work(system_percpu_wq, &ave->watchdog, + msecs_to_jiffies(AVE_TIMEOUT_MS)); + ok = ave_post_more(ctx, &type); + if (!ok) /* the oldest one failed: as if the firmware had */ + ctx->posted = 1; + if (!ctx->posted) { + /* + * Nothing to post after all (the capture buffer went to a + * drain's empty last buffer since the job was queued, or the + * rest of a group of B pictures is not queued yet): done for + * now, or no picture would ever finish the job (a close then + * waited forever in v4l2_m2m_cancel_job()). + */ + cancel_delayed_work(&ave->watchdog); + spin_lock_irqsave(&ave->irq_lock, flags); + ave->running = NULL; + spin_unlock_irqrestore(&ave->irq_lock, flags); + ctx->job_held = false; + mutex_unlock(&ave->run_lock); + v4l2_m2m_job_finish(ave->m2m, ctx->fh.m2m_ctx); + return; + } + mutex_unlock(&ave->run_lock); + if (!ok) + ave_frame_done(ave, 0, type, false); +} + +/* the oldest picture in flight is done (ok false: failed or lost) */ +void ave_frame_done(struct ave_dev *ave, u32 bytes, enum ave_pic_type type, bool ok) +{ + static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; + struct vb2_v4l2_buffer *src, *dst, *rest; + struct v4l2_m2m_ctx *m; + struct ave_ctx *ctx; + unsigned long flags; + bool finish = false, last, rest_last; + + mutex_lock(&ave->run_lock); + spin_lock_irqsave(&ave->irq_lock, flags); + ctx = ave->running; + spin_unlock_irqrestore(&ave->irq_lock, flags); + if (!ctx || !ctx->posted) { + mutex_unlock(&ave->run_lock); + return; + } + m = ctx->fh.m2m_ctx; + spin_lock_irqsave(&ctx->sched_lock, flags); + src = ctx->flight[0]; + ctx->posted--; + memmove(ctx->flight, ctx->flight + 1, ctx->posted * sizeof(ctx->flight[0])); + if (!ok) /* its group's B pictures lost their anchor: group them again */ + ctx->n_held = ctx->next_held; + if (src) + v4l2_m2m_src_buf_remove_by_buf(m, src); + /* drained: nothing in flight, held, or queued before ENC_CMD_STOP is left */ + last = m->is_draining && !ctx->posted && ctx->next_held == ctx->n_held && + !ave_new_frames(ctx, &rest, 1, &rest_last); + spin_unlock_irqrestore(&ctx->sched_lock, flags); + dst = v4l2_m2m_dst_buf_remove(m); + if (WARN_ON(!src || !dst)) + goto out; + v4l2_m2m_buf_copy_metadata(src, dst); + dst->flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME); + dst->flags |= type == AVE_PIC_IDR ? V4L2_BUF_FLAG_KEYFRAME : + type == AVE_PIC_B ? V4L2_BUF_FLAG_BFRAME : V4L2_BUF_FLAG_PFRAME; + dst->sequence = ctx->cap_seq++; + vb2_set_plane_payload(&dst->vb2_buf, 0, ok ? bytes : 0); + if (!ok) + ctx->force_idr = true; /* the reference may be gone */ + if (last) { + dst->flags |= V4L2_BUF_FLAG_LAST; + v4l2_event_queue_fh(&ctx->fh, &eos); + v4l2_m2m_mark_stopped(m); + } + v4l2_m2m_buf_done(src, ok ? VB2_BUF_STATE_DONE : VB2_BUF_STATE_ERROR); + v4l2_m2m_buf_done(dst, ok ? VB2_BUF_STATE_DONE : VB2_BUF_STATE_ERROR); +out: + if (ctx->posted) + mod_delayed_work(system_percpu_wq, &ave->watchdog, + msecs_to_jiffies(AVE_TIMEOUT_MS)); + else + cancel_delayed_work(&ave->watchdog); + if (ctx->job_held) { + ctx->job_held = false; + finish = true; + } + if (!ctx->posted) { + spin_lock_irqsave(&ave->irq_lock, flags); + ave->running = NULL; + spin_unlock_irqrestore(&ave->irq_lock, flags); + wake_up(&ctx->idle); + } + mutex_unlock(&ave->run_lock); + if (finish) + v4l2_m2m_job_finish(ave->m2m, ctx->fh.m2m_ctx); +} + +/* every picture in flight is lost (the firmware was reset) */ +static void ave_fail_all(struct ave_dev *ave) +{ + struct ave_ctx *ctx; + unsigned long flags; + + for (;;) { + spin_lock_irqsave(&ave->irq_lock, flags); + ctx = ave->running; + spin_unlock_irqrestore(&ave->irq_lock, flags); + if (!ctx) + return; + if (!READ_ONCE(ctx->posted)) + break; + ave_frame_done(ave, 0, AVE_PIC_P, false); + } + /* a job held with nothing in flight: finish it (see ave_device_run()) */ + mutex_lock(&ave->run_lock); + if (ave->running == ctx && !ctx->posted && ctx->job_held) { + spin_lock_irqsave(&ave->irq_lock, flags); + ave->running = NULL; + spin_unlock_irqrestore(&ave->irq_lock, flags); + ctx->job_held = false; + mutex_unlock(&ave->run_lock); + v4l2_m2m_job_finish(ave->m2m, ctx->fh.m2m_ctx); + return; + } + mutex_unlock(&ave->run_lock); +} + +static void ave_watchdog(struct work_struct *work) +{ + struct ave_dev *ave = container_of(to_delayed_work(work), struct ave_dev, watchdog); + bool busy; + + spin_lock_irq(&ave->irq_lock); + busy = ave->running; + spin_unlock_irq(&ave->irq_lock); + if (!busy) + return; + dev_err_ratelimited(ave->dev, "picture timed out\n"); + ave_hw_timeout(ave); + ave_fail_all(ave); +} + +static const struct v4l2_m2m_ops ave_m2m_ops = { + .device_run = ave_device_run, + .job_ready = ave_job_ready, +}; + +/* files */ + +static int ave_open(struct file *file) +{ + struct ave_dev *ave = video_drvdata(file); + struct ave_ctx *ctx; + int ret; + + ctx = kzalloc_obj(*ctx); + if (!ctx) + return -ENOMEM; + ctx->ave = ave; + ctx->src_fmt.width = 1920; + ctx->src_fmt.height = 1080; + ave_fill_raw(&ctx->src_fmt, V4L2_PIX_FMT_H264); + ctx->crop = (struct v4l2_rect){ 0, 0, ctx->src_fmt.width, ctx->src_fmt.height }; + ctx->dst_fmt.pixelformat = V4L2_PIX_FMT_H264; + ave_fill_coded(ctx, &ctx->dst_fmt); + ctx->fps_num = 30; + ctx->fps_den = 1; + init_waitqueue_head(&ctx->idle); + spin_lock_init(&ctx->sched_lock); + + v4l2_fh_init(&ctx->fh, video_devdata(file)); + ret = ave_init_ctrls(ctx); + if (ret) + goto err_free; + ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(ave->m2m, ctx, ave_queue_init); + if (IS_ERR(ctx->fh.m2m_ctx)) { + ret = PTR_ERR(ctx->fh.m2m_ctx); + goto err_ctrls; + } + v4l2_fh_add(&ctx->fh, file); + return 0; + +err_ctrls: + v4l2_ctrl_handler_free(&ctx->ctrls); +err_free: + v4l2_fh_exit(&ctx->fh); + kfree(ctx); + return ret; +} + +static int ave_release(struct file *file) +{ + struct ave_ctx *ctx = file_to_ctx(file); + struct ave_dev *ave = ctx->ave; + + v4l2_fh_del(&ctx->fh, file); + mutex_lock(&ave->lock); + v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); /* stops both queues */ + if (ctx->session) + ave_hw_session_stop(ctx); + mutex_unlock(&ave->lock); + v4l2_ctrl_handler_free(&ctx->ctrls); + v4l2_fh_exit(&ctx->fh); + kfree(ctx); + return 0; +} + +static const struct v4l2_file_operations ave_fops = { + .owner = THIS_MODULE, + .open = ave_open, + .release = ave_release, + .poll = v4l2_m2m_fop_poll, + .unlocked_ioctl = video_ioctl2, + .mmap = v4l2_m2m_fop_mmap, +}; + +int ave_v4l2_register(struct ave_dev *ave) +{ + struct video_device *vdev = &ave->vdev; + int ret; + + spin_lock_init(&ave->irq_lock); + mutex_init(&ave->run_lock); + INIT_DELAYED_WORK(&ave->watchdog, ave_watchdog); + ret = v4l2_device_register(ave->dev, &ave->v4l2); + if (ret) + return ret; + ave->m2m = v4l2_m2m_init(&ave_m2m_ops); + if (IS_ERR(ave->m2m)) { + ret = PTR_ERR(ave->m2m); + goto err_v4l2; + } + strscpy(vdev->name, "apple-ave", sizeof(vdev->name)); + vdev->fops = &ave_fops; + vdev->ioctl_ops = &ave_ioctl_ops; + vdev->release = video_device_release_empty; + vdev->lock = &ave->lock; + vdev->v4l2_dev = &ave->v4l2; + vdev->vfl_dir = VFL_DIR_M2M; + vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + video_set_drvdata(vdev, ave); + /* after the decoder and the cameras, whose numbers scripts know */ + ret = video_register_device(vdev, VFL_TYPE_VIDEO, 3); + if (ret) + goto err_m2m; + dev_info(ave->dev, "H.264/HEVC encoder at /dev/video%d\n", vdev->num); + return 0; + +err_m2m: + v4l2_m2m_release(ave->m2m); +err_v4l2: + v4l2_device_unregister(&ave->v4l2); + return ret; +} + +void ave_v4l2_unregister(struct ave_dev *ave) +{ + video_unregister_device(&ave->vdev); + cancel_delayed_work_sync(&ave->watchdog); + v4l2_m2m_release(ave->m2m); + v4l2_device_unregister(&ave->v4l2); +}