radeon_uvd.c revision 01e04c3f
1/**************************************************************************
2 *
3 * Copyright 2011 Advanced Micro Devices, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28/*
29 * Authors:
30 *	Christian König <christian.koenig@amd.com>
31 *
32 */
33
34#include <sys/types.h>
35#include <assert.h>
36#include <errno.h>
37#include <unistd.h>
38#include <stdio.h>
39
40#include "pipe/p_video_codec.h"
41
42#include "util/u_memory.h"
43#include "util/u_video.h"
44
45#include "vl/vl_defines.h"
46#include "vl/vl_mpeg12_decoder.h"
47
48#include "r600_pipe_common.h"
49#include "radeon_video.h"
50#include "radeon_uvd.h"
51
52#define NUM_BUFFERS 4
53
54#define NUM_MPEG2_REFS 6
55#define NUM_H264_REFS 17
56#define NUM_VC1_REFS 5
57
58#define FB_BUFFER_OFFSET 0x1000
59#define FB_BUFFER_SIZE 2048
60#define FB_BUFFER_SIZE_TONGA (2048 * 64)
61#define IT_SCALING_TABLE_SIZE 992
62#define UVD_SESSION_CONTEXT_SIZE (128 * 1024)
63
64/* UVD decoder representation */
65struct ruvd_decoder {
66	struct pipe_video_codec		base;
67
68	ruvd_set_dtb			set_dtb;
69
70	unsigned			stream_handle;
71	unsigned			stream_type;
72	unsigned			frame_number;
73
74	struct pipe_screen		*screen;
75	struct radeon_winsys*		ws;
76	struct radeon_cmdbuf*	cs;
77
78	unsigned			cur_buffer;
79
80	struct rvid_buffer		msg_fb_it_buffers[NUM_BUFFERS];
81	struct ruvd_msg			*msg;
82	uint32_t			*fb;
83	unsigned			fb_size;
84	uint8_t				*it;
85
86	struct rvid_buffer		bs_buffers[NUM_BUFFERS];
87	void*				bs_ptr;
88	unsigned			bs_size;
89
90	struct rvid_buffer		dpb;
91	bool				use_legacy;
92	struct rvid_buffer		ctx;
93	struct rvid_buffer		sessionctx;
94	struct {
95		unsigned 		data0;
96		unsigned		data1;
97		unsigned		cmd;
98		unsigned		cntl;
99	} reg;
100};
101
102/* flush IB to the hardware */
103static int flush(struct ruvd_decoder *dec, unsigned flags)
104{
105	return dec->ws->cs_flush(dec->cs, flags, NULL);
106}
107
108/* add a new set register command to the IB */
109static void set_reg(struct ruvd_decoder *dec, unsigned reg, uint32_t val)
110{
111	radeon_emit(dec->cs, RUVD_PKT0(reg >> 2, 0));
112	radeon_emit(dec->cs, val);
113}
114
115/* send a command to the VCPU through the GPCOM registers */
116static void send_cmd(struct ruvd_decoder *dec, unsigned cmd,
117		     struct pb_buffer* buf, uint32_t off,
118		     enum radeon_bo_usage usage, enum radeon_bo_domain domain)
119{
120	int reloc_idx;
121
122	reloc_idx = dec->ws->cs_add_buffer(dec->cs, buf, usage | RADEON_USAGE_SYNCHRONIZED,
123					   domain, 0);
124	if (!dec->use_legacy) {
125		uint64_t addr;
126		addr = dec->ws->buffer_get_virtual_address(buf);
127		addr = addr + off;
128		set_reg(dec, dec->reg.data0, addr);
129		set_reg(dec, dec->reg.data1, addr >> 32);
130	} else {
131		off += dec->ws->buffer_get_reloc_offset(buf);
132		set_reg(dec, RUVD_GPCOM_VCPU_DATA0, off);
133		set_reg(dec, RUVD_GPCOM_VCPU_DATA1, reloc_idx * 4);
134	}
135	set_reg(dec, dec->reg.cmd, cmd << 1);
136}
137
138/* do the codec needs an IT buffer ?*/
139static bool have_it(struct ruvd_decoder *dec)
140{
141	return dec->stream_type == RUVD_CODEC_H264_PERF ||
142		dec->stream_type == RUVD_CODEC_H265;
143}
144
145/* map the next available message/feedback/itscaling buffer */
146static void map_msg_fb_it_buf(struct ruvd_decoder *dec)
147{
148	struct rvid_buffer* buf;
149	uint8_t *ptr;
150
151	/* grab the current message/feedback buffer */
152	buf = &dec->msg_fb_it_buffers[dec->cur_buffer];
153
154	/* and map it for CPU access */
155	ptr = dec->ws->buffer_map(buf->res->buf, dec->cs, PIPE_TRANSFER_WRITE);
156
157	/* calc buffer offsets */
158	dec->msg = (struct ruvd_msg *)ptr;
159	memset(dec->msg, 0, sizeof(*dec->msg));
160
161	dec->fb = (uint32_t *)(ptr + FB_BUFFER_OFFSET);
162	if (have_it(dec))
163		dec->it = (uint8_t *)(ptr + FB_BUFFER_OFFSET + dec->fb_size);
164}
165
166/* unmap and send a message command to the VCPU */
167static void send_msg_buf(struct ruvd_decoder *dec)
168{
169	struct rvid_buffer* buf;
170
171	/* ignore the request if message/feedback buffer isn't mapped */
172	if (!dec->msg || !dec->fb)
173		return;
174
175	/* grab the current message buffer */
176	buf = &dec->msg_fb_it_buffers[dec->cur_buffer];
177
178	/* unmap the buffer */
179	dec->ws->buffer_unmap(buf->res->buf);
180	dec->msg = NULL;
181	dec->fb = NULL;
182	dec->it = NULL;
183
184
185	if (dec->sessionctx.res)
186		send_cmd(dec, RUVD_CMD_SESSION_CONTEXT_BUFFER,
187			 dec->sessionctx.res->buf, 0, RADEON_USAGE_READWRITE,
188			 RADEON_DOMAIN_VRAM);
189
190	/* and send it to the hardware */
191	send_cmd(dec, RUVD_CMD_MSG_BUFFER, buf->res->buf, 0,
192		 RADEON_USAGE_READ, RADEON_DOMAIN_GTT);
193}
194
195/* cycle to the next set of buffers */
196static void next_buffer(struct ruvd_decoder *dec)
197{
198	++dec->cur_buffer;
199	dec->cur_buffer %= NUM_BUFFERS;
200}
201
202/* convert the profile into something UVD understands */
203static uint32_t profile2stream_type(struct ruvd_decoder *dec, unsigned family)
204{
205	switch (u_reduce_video_profile(dec->base.profile)) {
206	case PIPE_VIDEO_FORMAT_MPEG4_AVC:
207		return RUVD_CODEC_H264;
208
209	case PIPE_VIDEO_FORMAT_VC1:
210		return RUVD_CODEC_VC1;
211
212	case PIPE_VIDEO_FORMAT_MPEG12:
213		return RUVD_CODEC_MPEG2;
214
215	case PIPE_VIDEO_FORMAT_MPEG4:
216		return RUVD_CODEC_MPEG4;
217
218	case PIPE_VIDEO_FORMAT_HEVC:
219		return RUVD_CODEC_H265;
220
221	case PIPE_VIDEO_FORMAT_JPEG:
222		return RUVD_CODEC_MJPEG;
223
224	default:
225		assert(0);
226		return 0;
227	}
228}
229
230static unsigned calc_ctx_size_h265_main(struct ruvd_decoder *dec)
231{
232	unsigned width = align(dec->base.width, VL_MACROBLOCK_WIDTH);
233	unsigned height = align(dec->base.height, VL_MACROBLOCK_HEIGHT);
234
235	unsigned max_references = dec->base.max_references + 1;
236
237	if (dec->base.width * dec->base.height >= 4096*2000)
238		max_references = MAX2(max_references, 8);
239	else
240		max_references = MAX2(max_references, 17);
241
242	width = align (width, 16);
243	height = align (height, 16);
244	return ((width + 255) / 16) * ((height + 255) / 16) * 16 * max_references + 52 * 1024;
245}
246
247static unsigned calc_ctx_size_h265_main10(struct ruvd_decoder *dec, struct pipe_h265_picture_desc *pic)
248{
249	unsigned block_size, log2_ctb_size, width_in_ctb, height_in_ctb, num_16x16_block_per_ctb;
250	unsigned context_buffer_size_per_ctb_row, cm_buffer_size, max_mb_address, db_left_tile_pxl_size;
251	unsigned db_left_tile_ctx_size = 4096 / 16 * (32 + 16 * 4);
252
253	unsigned width = align(dec->base.width, VL_MACROBLOCK_WIDTH);
254	unsigned height = align(dec->base.height, VL_MACROBLOCK_HEIGHT);
255	unsigned coeff_10bit = (pic->pps->sps->bit_depth_luma_minus8 || pic->pps->sps->bit_depth_chroma_minus8) ? 2 : 1;
256
257	unsigned max_references = dec->base.max_references + 1;
258
259	if (dec->base.width * dec->base.height >= 4096*2000)
260		max_references = MAX2(max_references, 8);
261	else
262		max_references = MAX2(max_references, 17);
263
264	block_size = (1 << (pic->pps->sps->log2_min_luma_coding_block_size_minus3 + 3));
265	log2_ctb_size = block_size + pic->pps->sps->log2_diff_max_min_luma_coding_block_size;
266
267	width_in_ctb = (width + ((1 << log2_ctb_size) - 1)) >> log2_ctb_size;
268	height_in_ctb = (height + ((1 << log2_ctb_size) - 1)) >> log2_ctb_size;
269
270	num_16x16_block_per_ctb = ((1 << log2_ctb_size) >> 4) * ((1 << log2_ctb_size) >> 4);
271	context_buffer_size_per_ctb_row = align(width_in_ctb * num_16x16_block_per_ctb * 16, 256);
272	max_mb_address = (unsigned) ceil(height * 8 / 2048.0);
273
274	cm_buffer_size = max_references * context_buffer_size_per_ctb_row * height_in_ctb;
275	db_left_tile_pxl_size = coeff_10bit * (max_mb_address * 2 * 2048 + 1024);
276
277	return cm_buffer_size + db_left_tile_ctx_size + db_left_tile_pxl_size;
278}
279
280static unsigned get_db_pitch_alignment(struct ruvd_decoder *dec)
281{
282	return 16;
283}
284
285/* calculate size of reference picture buffer */
286static unsigned calc_dpb_size(struct ruvd_decoder *dec)
287{
288	unsigned width_in_mb, height_in_mb, image_size, dpb_size;
289
290	// always align them to MB size for dpb calculation
291	unsigned width = align(dec->base.width, VL_MACROBLOCK_WIDTH);
292	unsigned height = align(dec->base.height, VL_MACROBLOCK_HEIGHT);
293
294	// always one more for currently decoded picture
295	unsigned max_references = dec->base.max_references + 1;
296
297	// aligned size of a single frame
298	image_size = align(width, get_db_pitch_alignment(dec)) * height;
299	image_size += image_size / 2;
300	image_size = align(image_size, 1024);
301
302	// picture width & height in 16 pixel units
303	width_in_mb = width / VL_MACROBLOCK_WIDTH;
304	height_in_mb = align(height / VL_MACROBLOCK_HEIGHT, 2);
305
306	switch (u_reduce_video_profile(dec->base.profile)) {
307	case PIPE_VIDEO_FORMAT_MPEG4_AVC: {
308		if (!dec->use_legacy) {
309			unsigned fs_in_mb = width_in_mb * height_in_mb;
310			unsigned alignment = 64, num_dpb_buffer;
311
312			if (dec->stream_type == RUVD_CODEC_H264_PERF)
313				alignment = 256;
314			switch(dec->base.level) {
315			case 30:
316				num_dpb_buffer = 8100 / fs_in_mb;
317				break;
318			case 31:
319				num_dpb_buffer = 18000 / fs_in_mb;
320				break;
321			case 32:
322				num_dpb_buffer = 20480 / fs_in_mb;
323				break;
324			case 41:
325				num_dpb_buffer = 32768 / fs_in_mb;
326				break;
327			case 42:
328				num_dpb_buffer = 34816 / fs_in_mb;
329				break;
330			case 50:
331				num_dpb_buffer = 110400 / fs_in_mb;
332				break;
333			case 51:
334				num_dpb_buffer = 184320 / fs_in_mb;
335				break;
336			default:
337				num_dpb_buffer = 184320 / fs_in_mb;
338				break;
339			}
340			num_dpb_buffer++;
341			max_references = MAX2(MIN2(NUM_H264_REFS, num_dpb_buffer), max_references);
342			dpb_size = image_size * max_references;
343			if ((dec->stream_type != RUVD_CODEC_H264_PERF)) {
344				dpb_size += max_references * align(width_in_mb * height_in_mb  * 192, alignment);
345				dpb_size += align(width_in_mb * height_in_mb * 32, alignment);
346			}
347		} else {
348			// the firmware seems to allways assume a minimum of ref frames
349			max_references = MAX2(NUM_H264_REFS, max_references);
350			// reference picture buffer
351			dpb_size = image_size * max_references;
352			if ((dec->stream_type != RUVD_CODEC_H264_PERF)) {
353				// macroblock context buffer
354				dpb_size += width_in_mb * height_in_mb * max_references * 192;
355				// IT surface buffer
356				dpb_size += width_in_mb * height_in_mb * 32;
357			}
358		}
359		break;
360	}
361
362	case PIPE_VIDEO_FORMAT_HEVC:
363		if (dec->base.width * dec->base.height >= 4096*2000)
364			max_references = MAX2(max_references, 8);
365		else
366			max_references = MAX2(max_references, 17);
367
368		width = align (width, 16);
369		height = align (height, 16);
370		if (dec->base.profile == PIPE_VIDEO_PROFILE_HEVC_MAIN_10)
371			dpb_size = align((align(width, get_db_pitch_alignment(dec)) * height * 9) / 4, 256) * max_references;
372		else
373			dpb_size = align((align(width, get_db_pitch_alignment(dec)) * height * 3) / 2, 256) * max_references;
374		break;
375
376	case PIPE_VIDEO_FORMAT_VC1:
377		// the firmware seems to allways assume a minimum of ref frames
378		max_references = MAX2(NUM_VC1_REFS, max_references);
379
380		// reference picture buffer
381		dpb_size = image_size * max_references;
382
383		// CONTEXT_BUFFER
384		dpb_size += width_in_mb * height_in_mb * 128;
385
386		// IT surface buffer
387		dpb_size += width_in_mb * 64;
388
389		// DB surface buffer
390		dpb_size += width_in_mb * 128;
391
392		// BP
393		dpb_size += align(MAX2(width_in_mb, height_in_mb) * 7 * 16, 64);
394		break;
395
396	case PIPE_VIDEO_FORMAT_MPEG12:
397		// reference picture buffer, must be big enough for all frames
398		dpb_size = image_size * NUM_MPEG2_REFS;
399		break;
400
401	case PIPE_VIDEO_FORMAT_MPEG4:
402		// reference picture buffer
403		dpb_size = image_size * max_references;
404
405		// CM
406		dpb_size += width_in_mb * height_in_mb * 64;
407
408		// IT surface buffer
409		dpb_size += align(width_in_mb * height_in_mb * 32, 64);
410
411		dpb_size = MAX2(dpb_size, 30 * 1024 * 1024);
412		break;
413
414	case PIPE_VIDEO_FORMAT_JPEG:
415		dpb_size = 0;
416		break;
417
418	default:
419		// something is missing here
420		assert(0);
421
422		// at least use a sane default value
423		dpb_size = 32 * 1024 * 1024;
424		break;
425	}
426	return dpb_size;
427}
428
429/* free associated data in the video buffer callback */
430static void ruvd_destroy_associated_data(void *data)
431{
432	/* NOOP, since we only use an intptr */
433}
434
435/* get h264 specific message bits */
436static struct ruvd_h264 get_h264_msg(struct ruvd_decoder *dec, struct pipe_h264_picture_desc *pic)
437{
438	struct ruvd_h264 result;
439
440	memset(&result, 0, sizeof(result));
441	switch (pic->base.profile) {
442	case PIPE_VIDEO_PROFILE_MPEG4_AVC_BASELINE:
443	case PIPE_VIDEO_PROFILE_MPEG4_AVC_CONSTRAINED_BASELINE:
444		result.profile = RUVD_H264_PROFILE_BASELINE;
445		break;
446
447	case PIPE_VIDEO_PROFILE_MPEG4_AVC_MAIN:
448		result.profile = RUVD_H264_PROFILE_MAIN;
449		break;
450
451	case PIPE_VIDEO_PROFILE_MPEG4_AVC_HIGH:
452		result.profile = RUVD_H264_PROFILE_HIGH;
453		break;
454
455	default:
456		assert(0);
457		break;
458	}
459
460	result.level = dec->base.level;
461
462	result.sps_info_flags = 0;
463	result.sps_info_flags |= pic->pps->sps->direct_8x8_inference_flag << 0;
464	result.sps_info_flags |= pic->pps->sps->mb_adaptive_frame_field_flag << 1;
465	result.sps_info_flags |= pic->pps->sps->frame_mbs_only_flag << 2;
466	result.sps_info_flags |= pic->pps->sps->delta_pic_order_always_zero_flag << 3;
467
468	result.bit_depth_luma_minus8 = pic->pps->sps->bit_depth_luma_minus8;
469	result.bit_depth_chroma_minus8 = pic->pps->sps->bit_depth_chroma_minus8;
470	result.log2_max_frame_num_minus4 = pic->pps->sps->log2_max_frame_num_minus4;
471	result.pic_order_cnt_type = pic->pps->sps->pic_order_cnt_type;
472	result.log2_max_pic_order_cnt_lsb_minus4 = pic->pps->sps->log2_max_pic_order_cnt_lsb_minus4;
473
474	switch (dec->base.chroma_format) {
475	case PIPE_VIDEO_CHROMA_FORMAT_NONE:
476		/* TODO: assert? */
477		break;
478	case PIPE_VIDEO_CHROMA_FORMAT_400:
479		result.chroma_format = 0;
480		break;
481	case PIPE_VIDEO_CHROMA_FORMAT_420:
482		result.chroma_format = 1;
483		break;
484	case PIPE_VIDEO_CHROMA_FORMAT_422:
485		result.chroma_format = 2;
486		break;
487	case PIPE_VIDEO_CHROMA_FORMAT_444:
488		result.chroma_format = 3;
489		break;
490	}
491
492	result.pps_info_flags = 0;
493	result.pps_info_flags |= pic->pps->transform_8x8_mode_flag << 0;
494	result.pps_info_flags |= pic->pps->redundant_pic_cnt_present_flag << 1;
495	result.pps_info_flags |= pic->pps->constrained_intra_pred_flag << 2;
496	result.pps_info_flags |= pic->pps->deblocking_filter_control_present_flag << 3;
497	result.pps_info_flags |= pic->pps->weighted_bipred_idc << 4;
498	result.pps_info_flags |= pic->pps->weighted_pred_flag << 6;
499	result.pps_info_flags |= pic->pps->bottom_field_pic_order_in_frame_present_flag << 7;
500	result.pps_info_flags |= pic->pps->entropy_coding_mode_flag << 8;
501
502	result.num_slice_groups_minus1 = pic->pps->num_slice_groups_minus1;
503	result.slice_group_map_type = pic->pps->slice_group_map_type;
504	result.slice_group_change_rate_minus1 = pic->pps->slice_group_change_rate_minus1;
505	result.pic_init_qp_minus26 = pic->pps->pic_init_qp_minus26;
506	result.chroma_qp_index_offset = pic->pps->chroma_qp_index_offset;
507	result.second_chroma_qp_index_offset = pic->pps->second_chroma_qp_index_offset;
508
509	memcpy(result.scaling_list_4x4, pic->pps->ScalingList4x4, 6*16);
510	memcpy(result.scaling_list_8x8, pic->pps->ScalingList8x8, 2*64);
511
512	if (dec->stream_type == RUVD_CODEC_H264_PERF) {
513		memcpy(dec->it, result.scaling_list_4x4, 6*16);
514		memcpy((dec->it + 96), result.scaling_list_8x8, 2*64);
515	}
516
517	result.num_ref_frames = pic->num_ref_frames;
518
519	result.num_ref_idx_l0_active_minus1 = pic->num_ref_idx_l0_active_minus1;
520	result.num_ref_idx_l1_active_minus1 = pic->num_ref_idx_l1_active_minus1;
521
522	result.frame_num = pic->frame_num;
523	memcpy(result.frame_num_list, pic->frame_num_list, 4*16);
524	result.curr_field_order_cnt_list[0] = pic->field_order_cnt[0];
525	result.curr_field_order_cnt_list[1] = pic->field_order_cnt[1];
526	memcpy(result.field_order_cnt_list, pic->field_order_cnt_list, 4*16*2);
527
528	result.decoded_pic_idx = pic->frame_num;
529
530	return result;
531}
532
533/* get h265 specific message bits */
534static struct ruvd_h265 get_h265_msg(struct ruvd_decoder *dec, struct pipe_video_buffer *target,
535				     struct pipe_h265_picture_desc *pic)
536{
537	struct ruvd_h265 result;
538	unsigned i;
539
540	memset(&result, 0, sizeof(result));
541
542	result.sps_info_flags = 0;
543	result.sps_info_flags |= pic->pps->sps->scaling_list_enabled_flag << 0;
544	result.sps_info_flags |= pic->pps->sps->amp_enabled_flag << 1;
545	result.sps_info_flags |= pic->pps->sps->sample_adaptive_offset_enabled_flag << 2;
546	result.sps_info_flags |= pic->pps->sps->pcm_enabled_flag << 3;
547	result.sps_info_flags |= pic->pps->sps->pcm_loop_filter_disabled_flag << 4;
548	result.sps_info_flags |= pic->pps->sps->long_term_ref_pics_present_flag << 5;
549	result.sps_info_flags |= pic->pps->sps->sps_temporal_mvp_enabled_flag << 6;
550	result.sps_info_flags |= pic->pps->sps->strong_intra_smoothing_enabled_flag << 7;
551	result.sps_info_flags |= pic->pps->sps->separate_colour_plane_flag << 8;
552	if (pic->UseRefPicList == true)
553		result.sps_info_flags |= 1 << 10;
554
555	result.chroma_format = pic->pps->sps->chroma_format_idc;
556	result.bit_depth_luma_minus8 = pic->pps->sps->bit_depth_luma_minus8;
557	result.bit_depth_chroma_minus8 = pic->pps->sps->bit_depth_chroma_minus8;
558	result.log2_max_pic_order_cnt_lsb_minus4 = pic->pps->sps->log2_max_pic_order_cnt_lsb_minus4;
559	result.sps_max_dec_pic_buffering_minus1 = pic->pps->sps->sps_max_dec_pic_buffering_minus1;
560	result.log2_min_luma_coding_block_size_minus3 = pic->pps->sps->log2_min_luma_coding_block_size_minus3;
561	result.log2_diff_max_min_luma_coding_block_size = pic->pps->sps->log2_diff_max_min_luma_coding_block_size;
562	result.log2_min_transform_block_size_minus2 = pic->pps->sps->log2_min_transform_block_size_minus2;
563	result.log2_diff_max_min_transform_block_size = pic->pps->sps->log2_diff_max_min_transform_block_size;
564	result.max_transform_hierarchy_depth_inter = pic->pps->sps->max_transform_hierarchy_depth_inter;
565	result.max_transform_hierarchy_depth_intra = pic->pps->sps->max_transform_hierarchy_depth_intra;
566	result.pcm_sample_bit_depth_luma_minus1 = pic->pps->sps->pcm_sample_bit_depth_luma_minus1;
567	result.pcm_sample_bit_depth_chroma_minus1 = pic->pps->sps->pcm_sample_bit_depth_chroma_minus1;
568	result.log2_min_pcm_luma_coding_block_size_minus3 = pic->pps->sps->log2_min_pcm_luma_coding_block_size_minus3;
569	result.log2_diff_max_min_pcm_luma_coding_block_size = pic->pps->sps->log2_diff_max_min_pcm_luma_coding_block_size;
570	result.num_short_term_ref_pic_sets = pic->pps->sps->num_short_term_ref_pic_sets;
571
572	result.pps_info_flags = 0;
573	result.pps_info_flags |= pic->pps->dependent_slice_segments_enabled_flag << 0;
574	result.pps_info_flags |= pic->pps->output_flag_present_flag << 1;
575	result.pps_info_flags |= pic->pps->sign_data_hiding_enabled_flag << 2;
576	result.pps_info_flags |= pic->pps->cabac_init_present_flag << 3;
577	result.pps_info_flags |= pic->pps->constrained_intra_pred_flag << 4;
578	result.pps_info_flags |= pic->pps->transform_skip_enabled_flag << 5;
579	result.pps_info_flags |= pic->pps->cu_qp_delta_enabled_flag << 6;
580	result.pps_info_flags |= pic->pps->pps_slice_chroma_qp_offsets_present_flag << 7;
581	result.pps_info_flags |= pic->pps->weighted_pred_flag << 8;
582	result.pps_info_flags |= pic->pps->weighted_bipred_flag << 9;
583	result.pps_info_flags |= pic->pps->transquant_bypass_enabled_flag << 10;
584	result.pps_info_flags |= pic->pps->tiles_enabled_flag << 11;
585	result.pps_info_flags |= pic->pps->entropy_coding_sync_enabled_flag << 12;
586	result.pps_info_flags |= pic->pps->uniform_spacing_flag << 13;
587	result.pps_info_flags |= pic->pps->loop_filter_across_tiles_enabled_flag << 14;
588	result.pps_info_flags |= pic->pps->pps_loop_filter_across_slices_enabled_flag << 15;
589	result.pps_info_flags |= pic->pps->deblocking_filter_override_enabled_flag << 16;
590	result.pps_info_flags |= pic->pps->pps_deblocking_filter_disabled_flag << 17;
591	result.pps_info_flags |= pic->pps->lists_modification_present_flag << 18;
592	result.pps_info_flags |= pic->pps->slice_segment_header_extension_present_flag << 19;
593	//result.pps_info_flags |= pic->pps->deblocking_filter_control_present_flag; ???
594
595	result.num_extra_slice_header_bits = pic->pps->num_extra_slice_header_bits;
596	result.num_long_term_ref_pic_sps = pic->pps->sps->num_long_term_ref_pics_sps;
597	result.num_ref_idx_l0_default_active_minus1 = pic->pps->num_ref_idx_l0_default_active_minus1;
598	result.num_ref_idx_l1_default_active_minus1 = pic->pps->num_ref_idx_l1_default_active_minus1;
599	result.pps_cb_qp_offset = pic->pps->pps_cb_qp_offset;
600	result.pps_cr_qp_offset = pic->pps->pps_cr_qp_offset;
601	result.pps_beta_offset_div2 = pic->pps->pps_beta_offset_div2;
602	result.pps_tc_offset_div2 = pic->pps->pps_tc_offset_div2;
603	result.diff_cu_qp_delta_depth = pic->pps->diff_cu_qp_delta_depth;
604	result.num_tile_columns_minus1 = pic->pps->num_tile_columns_minus1;
605	result.num_tile_rows_minus1 = pic->pps->num_tile_rows_minus1;
606	result.log2_parallel_merge_level_minus2 = pic->pps->log2_parallel_merge_level_minus2;
607	result.init_qp_minus26 = pic->pps->init_qp_minus26;
608
609	for (i = 0; i < 19; ++i)
610		result.column_width_minus1[i] = pic->pps->column_width_minus1[i];
611
612	for (i = 0; i < 21; ++i)
613		result.row_height_minus1[i] = pic->pps->row_height_minus1[i];
614
615	result.num_delta_pocs_ref_rps_idx = pic->NumDeltaPocsOfRefRpsIdx;
616	result.curr_idx = pic->CurrPicOrderCntVal;
617	result.curr_poc = pic->CurrPicOrderCntVal;
618
619	vl_video_buffer_set_associated_data(target, &dec->base,
620					    (void *)(uintptr_t)pic->CurrPicOrderCntVal,
621					    &ruvd_destroy_associated_data);
622
623	for (i = 0; i < 16; ++i) {
624		struct pipe_video_buffer *ref = pic->ref[i];
625		uintptr_t ref_pic = 0;
626
627		result.poc_list[i] = pic->PicOrderCntVal[i];
628
629		if (ref)
630			ref_pic = (uintptr_t)vl_video_buffer_get_associated_data(ref, &dec->base);
631		else
632			ref_pic = 0x7F;
633		result.ref_pic_list[i] = ref_pic;
634	}
635
636	for (i = 0; i < 8; ++i) {
637		result.ref_pic_set_st_curr_before[i] = 0xFF;
638		result.ref_pic_set_st_curr_after[i] = 0xFF;
639		result.ref_pic_set_lt_curr[i] = 0xFF;
640	}
641
642	for (i = 0; i < pic->NumPocStCurrBefore; ++i)
643		result.ref_pic_set_st_curr_before[i] = pic->RefPicSetStCurrBefore[i];
644
645	for (i = 0; i < pic->NumPocStCurrAfter; ++i)
646		result.ref_pic_set_st_curr_after[i] = pic->RefPicSetStCurrAfter[i];
647
648	for (i = 0; i < pic->NumPocLtCurr; ++i)
649		result.ref_pic_set_lt_curr[i] = pic->RefPicSetLtCurr[i];
650
651	for (i = 0; i < 6; ++i)
652		result.ucScalingListDCCoefSizeID2[i] = pic->pps->sps->ScalingListDCCoeff16x16[i];
653
654	for (i = 0; i < 2; ++i)
655		result.ucScalingListDCCoefSizeID3[i] = pic->pps->sps->ScalingListDCCoeff32x32[i];
656
657	memcpy(dec->it, pic->pps->sps->ScalingList4x4, 6 * 16);
658	memcpy(dec->it + 96, pic->pps->sps->ScalingList8x8, 6 * 64);
659	memcpy(dec->it + 480, pic->pps->sps->ScalingList16x16, 6 * 64);
660	memcpy(dec->it + 864, pic->pps->sps->ScalingList32x32, 2 * 64);
661
662	for (i = 0 ; i < 2 ; i++) {
663		for (int j = 0 ; j < 15 ; j++)
664			result.direct_reflist[i][j] = pic->RefPicList[i][j];
665	}
666
667	if (pic->base.profile == PIPE_VIDEO_PROFILE_HEVC_MAIN_10) {
668		if (target->buffer_format == PIPE_FORMAT_P016) {
669			result.p010_mode = 1;
670			result.msb_mode = 1;
671		} else {
672			result.luma_10to8 = 5;
673			result.chroma_10to8 = 5;
674			result.sclr_luma10to8 = 4;
675			result.sclr_chroma10to8 = 4;
676		}
677	}
678
679	/* TODO
680	result.highestTid;
681	result.isNonRef;
682
683	IDRPicFlag;
684	RAPPicFlag;
685	NumPocTotalCurr;
686	NumShortTermPictureSliceHeaderBits;
687	NumLongTermPictureSliceHeaderBits;
688
689	IsLongTerm[16];
690	*/
691
692	return result;
693}
694
695/* get vc1 specific message bits */
696static struct ruvd_vc1 get_vc1_msg(struct pipe_vc1_picture_desc *pic)
697{
698	struct ruvd_vc1 result;
699
700	memset(&result, 0, sizeof(result));
701
702	switch(pic->base.profile) {
703	case PIPE_VIDEO_PROFILE_VC1_SIMPLE:
704		result.profile = RUVD_VC1_PROFILE_SIMPLE;
705		result.level = 1;
706		break;
707
708	case PIPE_VIDEO_PROFILE_VC1_MAIN:
709		result.profile = RUVD_VC1_PROFILE_MAIN;
710		result.level = 2;
711		break;
712
713	case PIPE_VIDEO_PROFILE_VC1_ADVANCED:
714		result.profile = RUVD_VC1_PROFILE_ADVANCED;
715		result.level = 4;
716		break;
717
718	default:
719		assert(0);
720	}
721
722	/* fields common for all profiles */
723	result.sps_info_flags |= pic->postprocflag << 7;
724	result.sps_info_flags |= pic->pulldown << 6;
725	result.sps_info_flags |= pic->interlace << 5;
726	result.sps_info_flags |= pic->tfcntrflag << 4;
727	result.sps_info_flags |= pic->finterpflag << 3;
728	result.sps_info_flags |= pic->psf << 1;
729
730	result.pps_info_flags |= pic->range_mapy_flag << 31;
731	result.pps_info_flags |= pic->range_mapy << 28;
732	result.pps_info_flags |= pic->range_mapuv_flag << 27;
733	result.pps_info_flags |= pic->range_mapuv << 24;
734	result.pps_info_flags |= pic->multires << 21;
735	result.pps_info_flags |= pic->maxbframes << 16;
736	result.pps_info_flags |= pic->overlap << 11;
737	result.pps_info_flags |= pic->quantizer << 9;
738	result.pps_info_flags |= pic->panscan_flag << 7;
739	result.pps_info_flags |= pic->refdist_flag << 6;
740	result.pps_info_flags |= pic->vstransform << 0;
741
742	/* some fields only apply to main/advanced profile */
743	if (pic->base.profile != PIPE_VIDEO_PROFILE_VC1_SIMPLE) {
744		result.pps_info_flags |= pic->syncmarker << 20;
745		result.pps_info_flags |= pic->rangered << 19;
746		result.pps_info_flags |= pic->loopfilter << 5;
747		result.pps_info_flags |= pic->fastuvmc << 4;
748		result.pps_info_flags |= pic->extended_mv << 3;
749		result.pps_info_flags |= pic->extended_dmv << 8;
750		result.pps_info_flags |= pic->dquant << 1;
751	}
752
753	result.chroma_format = 1;
754
755#if 0
756//(((unsigned int)(pPicParams->advance.reserved1))        << SPS_INFO_VC1_RESERVED_SHIFT)
757uint32_t 	slice_count
758uint8_t 	picture_type
759uint8_t 	frame_coding_mode
760uint8_t 	deblockEnable
761uint8_t 	pquant
762#endif
763
764	return result;
765}
766
767/* extract the frame number from a referenced video buffer */
768static uint32_t get_ref_pic_idx(struct ruvd_decoder *dec, struct pipe_video_buffer *ref)
769{
770	uint32_t min = MAX2(dec->frame_number, NUM_MPEG2_REFS) - NUM_MPEG2_REFS;
771	uint32_t max = MAX2(dec->frame_number, 1) - 1;
772	uintptr_t frame;
773
774	/* seems to be the most sane fallback */
775	if (!ref)
776		return max;
777
778	/* get the frame number from the associated data */
779	frame = (uintptr_t)vl_video_buffer_get_associated_data(ref, &dec->base);
780
781	/* limit the frame number to a valid range */
782	return MAX2(MIN2(frame, max), min);
783}
784
785/* get mpeg2 specific msg bits */
786static struct ruvd_mpeg2 get_mpeg2_msg(struct ruvd_decoder *dec,
787				       struct pipe_mpeg12_picture_desc *pic)
788{
789	const int *zscan = pic->alternate_scan ? vl_zscan_alternate : vl_zscan_normal;
790	struct ruvd_mpeg2 result;
791	unsigned i;
792
793	memset(&result, 0, sizeof(result));
794	result.decoded_pic_idx = dec->frame_number;
795	for (i = 0; i < 2; ++i)
796		result.ref_pic_idx[i] = get_ref_pic_idx(dec, pic->ref[i]);
797
798	result.load_intra_quantiser_matrix = 1;
799	result.load_nonintra_quantiser_matrix = 1;
800
801	for (i = 0; i < 64; ++i) {
802		result.intra_quantiser_matrix[i] = pic->intra_matrix[zscan[i]];
803		result.nonintra_quantiser_matrix[i] = pic->non_intra_matrix[zscan[i]];
804	}
805
806	result.profile_and_level_indication = 0;
807	result.chroma_format = 0x1;
808
809	result.picture_coding_type = pic->picture_coding_type;
810	result.f_code[0][0] = pic->f_code[0][0] + 1;
811	result.f_code[0][1] = pic->f_code[0][1] + 1;
812	result.f_code[1][0] = pic->f_code[1][0] + 1;
813	result.f_code[1][1] = pic->f_code[1][1] + 1;
814	result.intra_dc_precision = pic->intra_dc_precision;
815	result.pic_structure = pic->picture_structure;
816	result.top_field_first = pic->top_field_first;
817	result.frame_pred_frame_dct = pic->frame_pred_frame_dct;
818	result.concealment_motion_vectors = pic->concealment_motion_vectors;
819	result.q_scale_type = pic->q_scale_type;
820	result.intra_vlc_format = pic->intra_vlc_format;
821	result.alternate_scan = pic->alternate_scan;
822
823	return result;
824}
825
826/* get mpeg4 specific msg bits */
827static struct ruvd_mpeg4 get_mpeg4_msg(struct ruvd_decoder *dec,
828				       struct pipe_mpeg4_picture_desc *pic)
829{
830	struct ruvd_mpeg4 result;
831	unsigned i;
832
833	memset(&result, 0, sizeof(result));
834	result.decoded_pic_idx = dec->frame_number;
835	for (i = 0; i < 2; ++i)
836		result.ref_pic_idx[i] = get_ref_pic_idx(dec, pic->ref[i]);
837
838	result.variant_type = 0;
839	result.profile_and_level_indication = 0xF0; // ASP Level0
840
841	result.video_object_layer_verid = 0x5; // advanced simple
842	result.video_object_layer_shape = 0x0; // rectangular
843
844	result.video_object_layer_width = dec->base.width;
845	result.video_object_layer_height = dec->base.height;
846
847	result.vop_time_increment_resolution = pic->vop_time_increment_resolution;
848
849	result.flags |= pic->short_video_header << 0;
850	//result.flags |= obmc_disable << 1;
851	result.flags |= pic->interlaced << 2;
852        result.flags |= 1 << 3; // load_intra_quant_mat
853	result.flags |= 1 << 4; // load_nonintra_quant_mat
854	result.flags |= pic->quarter_sample << 5;
855	result.flags |= 1 << 6; // complexity_estimation_disable
856	result.flags |= pic->resync_marker_disable << 7;
857	//result.flags |= data_partitioned << 8;
858	//result.flags |= reversible_vlc << 9;
859	result.flags |= 0 << 10; // newpred_enable
860	result.flags |= 0 << 11; // reduced_resolution_vop_enable
861	//result.flags |= scalability << 12;
862	//result.flags |= is_object_layer_identifier << 13;
863	//result.flags |= fixed_vop_rate << 14;
864	//result.flags |= newpred_segment_type << 15;
865
866	result.quant_type = pic->quant_type;
867
868	for (i = 0; i < 64; ++i) {
869		result.intra_quant_mat[i] = pic->intra_matrix[vl_zscan_normal[i]];
870		result.nonintra_quant_mat[i] = pic->non_intra_matrix[vl_zscan_normal[i]];
871	}
872
873	/*
874	int32_t 	trd [2]
875	int32_t 	trb [2]
876	uint8_t 	vop_coding_type
877	uint8_t 	vop_fcode_forward
878	uint8_t 	vop_fcode_backward
879	uint8_t 	rounding_control
880	uint8_t 	alternate_vertical_scan_flag
881	uint8_t 	top_field_first
882	*/
883
884	return result;
885}
886
887static void get_mjpeg_slice_header(struct ruvd_decoder *dec, struct pipe_mjpeg_picture_desc *pic)
888{
889	int size = 0, saved_size, len_pos, i;
890	uint16_t *bs;
891	uint8_t *buf = dec->bs_ptr;
892
893	/* SOI */
894	buf[size++] = 0xff;
895	buf[size++] = 0xd8;
896
897	/* DQT */
898	buf[size++] = 0xff;
899	buf[size++] = 0xdb;
900
901	len_pos = size++;
902	size++;
903
904	for (i = 0; i < 4; ++i) {
905		if (pic->quantization_table.load_quantiser_table[i] == 0)
906			continue;
907
908		buf[size++] = i;
909		memcpy((buf + size), &pic->quantization_table.quantiser_table[i], 64);
910		size += 64;
911	}
912
913	bs = (uint16_t*)&buf[len_pos];
914	*bs = util_bswap16(size - 4);
915
916	saved_size = size;
917
918	/* DHT */
919	buf[size++] = 0xff;
920	buf[size++] = 0xc4;
921
922	len_pos = size++;
923	size++;
924
925	for (i = 0; i < 2; ++i) {
926		if (pic->huffman_table.load_huffman_table[i] == 0)
927			continue;
928
929		buf[size++] = 0x00 | i;
930		memcpy((buf + size), &pic->huffman_table.table[i].num_dc_codes, 16);
931		size += 16;
932		memcpy((buf + size), &pic->huffman_table.table[i].dc_values, 12);
933		size += 12;
934	}
935
936	for (i = 0; i < 2; ++i) {
937		if (pic->huffman_table.load_huffman_table[i] == 0)
938			continue;
939
940		buf[size++] = 0x10 | i;
941		memcpy((buf + size), &pic->huffman_table.table[i].num_ac_codes, 16);
942		size += 16;
943		memcpy((buf + size), &pic->huffman_table.table[i].ac_values, 162);
944		size += 162;
945	}
946
947	bs = (uint16_t*)&buf[len_pos];
948	*bs = util_bswap16(size - saved_size - 2);
949
950	saved_size = size;
951
952	/* DRI */
953	if (pic->slice_parameter.restart_interval) {
954		buf[size++] = 0xff;
955		buf[size++] = 0xdd;
956		buf[size++] = 0x00;
957		buf[size++] = 0x04;
958		bs = (uint16_t*)&buf[size++];
959		*bs = util_bswap16(pic->slice_parameter.restart_interval);
960		saved_size = ++size;
961	}
962
963	/* SOF */
964	buf[size++] = 0xff;
965	buf[size++] = 0xc0;
966
967	len_pos = size++;
968	size++;
969
970	buf[size++] = 0x08;
971
972	bs = (uint16_t*)&buf[size++];
973	*bs = util_bswap16(pic->picture_parameter.picture_height);
974	size++;
975
976	bs = (uint16_t*)&buf[size++];
977	*bs = util_bswap16(pic->picture_parameter.picture_width);
978	size++;
979
980	buf[size++] = pic->picture_parameter.num_components;
981
982	for (i = 0; i < pic->picture_parameter.num_components; ++i) {
983		buf[size++] = pic->picture_parameter.components[i].component_id;
984		buf[size++] = pic->picture_parameter.components[i].h_sampling_factor << 4 |
985			pic->picture_parameter.components[i].v_sampling_factor;
986		buf[size++] = pic->picture_parameter.components[i].quantiser_table_selector;
987	}
988
989	bs = (uint16_t*)&buf[len_pos];
990	*bs = util_bswap16(size - saved_size - 2);
991
992	saved_size = size;
993
994	/* SOS */
995	buf[size++] = 0xff;
996	buf[size++] = 0xda;
997
998	len_pos = size++;
999	size++;
1000
1001	buf[size++] = pic->slice_parameter.num_components;
1002
1003	for (i = 0; i < pic->slice_parameter.num_components; ++i) {
1004		buf[size++] = pic->slice_parameter.components[i].component_selector;
1005		buf[size++] = pic->slice_parameter.components[i].dc_table_selector << 4 |
1006			pic->slice_parameter.components[i].ac_table_selector;
1007	}
1008
1009	buf[size++] = 0x00;
1010	buf[size++] = 0x3f;
1011	buf[size++] = 0x00;
1012
1013	bs = (uint16_t*)&buf[len_pos];
1014	*bs = util_bswap16(size - saved_size - 2);
1015
1016	dec->bs_ptr += size;
1017	dec->bs_size += size;
1018}
1019
1020/**
1021 * destroy this video decoder
1022 */
1023static void ruvd_destroy(struct pipe_video_codec *decoder)
1024{
1025	struct ruvd_decoder *dec = (struct ruvd_decoder*)decoder;
1026	unsigned i;
1027
1028	assert(decoder);
1029
1030	map_msg_fb_it_buf(dec);
1031	dec->msg->size = sizeof(*dec->msg);
1032	dec->msg->msg_type = RUVD_MSG_DESTROY;
1033	dec->msg->stream_handle = dec->stream_handle;
1034	send_msg_buf(dec);
1035
1036	flush(dec, 0);
1037
1038	dec->ws->cs_destroy(dec->cs);
1039
1040	for (i = 0; i < NUM_BUFFERS; ++i) {
1041		rvid_destroy_buffer(&dec->msg_fb_it_buffers[i]);
1042		rvid_destroy_buffer(&dec->bs_buffers[i]);
1043	}
1044
1045	rvid_destroy_buffer(&dec->dpb);
1046	rvid_destroy_buffer(&dec->ctx);
1047	rvid_destroy_buffer(&dec->sessionctx);
1048
1049	FREE(dec);
1050}
1051
1052/**
1053 * start decoding of a new frame
1054 */
1055static void ruvd_begin_frame(struct pipe_video_codec *decoder,
1056			     struct pipe_video_buffer *target,
1057			     struct pipe_picture_desc *picture)
1058{
1059	struct ruvd_decoder *dec = (struct ruvd_decoder*)decoder;
1060	uintptr_t frame;
1061
1062	assert(decoder);
1063
1064	frame = ++dec->frame_number;
1065	vl_video_buffer_set_associated_data(target, decoder, (void *)frame,
1066					    &ruvd_destroy_associated_data);
1067
1068	dec->bs_size = 0;
1069	dec->bs_ptr = dec->ws->buffer_map(
1070		dec->bs_buffers[dec->cur_buffer].res->buf,
1071		dec->cs, PIPE_TRANSFER_WRITE);
1072}
1073
1074/**
1075 * decode a macroblock
1076 */
1077static void ruvd_decode_macroblock(struct pipe_video_codec *decoder,
1078				   struct pipe_video_buffer *target,
1079				   struct pipe_picture_desc *picture,
1080				   const struct pipe_macroblock *macroblocks,
1081				   unsigned num_macroblocks)
1082{
1083	/* not supported (yet) */
1084	assert(0);
1085}
1086
1087/**
1088 * decode a bitstream
1089 */
1090static void ruvd_decode_bitstream(struct pipe_video_codec *decoder,
1091				  struct pipe_video_buffer *target,
1092				  struct pipe_picture_desc *picture,
1093				  unsigned num_buffers,
1094				  const void * const *buffers,
1095				  const unsigned *sizes)
1096{
1097	struct ruvd_decoder *dec = (struct ruvd_decoder*)decoder;
1098	enum pipe_video_format format = u_reduce_video_profile(picture->profile);
1099	unsigned i;
1100
1101	assert(decoder);
1102
1103	if (!dec->bs_ptr)
1104		return;
1105
1106	if (format == PIPE_VIDEO_FORMAT_JPEG)
1107		get_mjpeg_slice_header(dec, (struct pipe_mjpeg_picture_desc*)picture);
1108
1109	for (i = 0; i < num_buffers; ++i) {
1110		struct rvid_buffer *buf = &dec->bs_buffers[dec->cur_buffer];
1111		unsigned new_size = dec->bs_size + sizes[i];
1112
1113		if (format == PIPE_VIDEO_FORMAT_JPEG)
1114			new_size += 2; /* save for EOI */
1115
1116		if (new_size > buf->res->buf->size) {
1117			dec->ws->buffer_unmap(buf->res->buf);
1118			if (!rvid_resize_buffer(dec->screen, dec->cs, buf, new_size)) {
1119				RVID_ERR("Can't resize bitstream buffer!");
1120				return;
1121			}
1122
1123			dec->bs_ptr = dec->ws->buffer_map(buf->res->buf, dec->cs,
1124							  PIPE_TRANSFER_WRITE);
1125			if (!dec->bs_ptr)
1126				return;
1127
1128			dec->bs_ptr += dec->bs_size;
1129		}
1130
1131		memcpy(dec->bs_ptr, buffers[i], sizes[i]);
1132		dec->bs_size += sizes[i];
1133		dec->bs_ptr += sizes[i];
1134	}
1135
1136	if (format == PIPE_VIDEO_FORMAT_JPEG) {
1137		((uint8_t *)dec->bs_ptr)[0] = 0xff;	/* EOI */
1138		((uint8_t *)dec->bs_ptr)[1] = 0xd9;
1139		dec->bs_size += 2;
1140		dec->bs_ptr += 2;
1141	}
1142}
1143
1144/**
1145 * end decoding of the current frame
1146 */
1147static void ruvd_end_frame(struct pipe_video_codec *decoder,
1148			   struct pipe_video_buffer *target,
1149			   struct pipe_picture_desc *picture)
1150{
1151	struct ruvd_decoder *dec = (struct ruvd_decoder*)decoder;
1152	struct pb_buffer *dt;
1153	struct rvid_buffer *msg_fb_it_buf, *bs_buf;
1154	unsigned bs_size;
1155
1156	assert(decoder);
1157
1158	if (!dec->bs_ptr)
1159		return;
1160
1161	msg_fb_it_buf = &dec->msg_fb_it_buffers[dec->cur_buffer];
1162	bs_buf = &dec->bs_buffers[dec->cur_buffer];
1163
1164	bs_size = align(dec->bs_size, 128);
1165	memset(dec->bs_ptr, 0, bs_size - dec->bs_size);
1166	dec->ws->buffer_unmap(bs_buf->res->buf);
1167
1168	map_msg_fb_it_buf(dec);
1169	dec->msg->size = sizeof(*dec->msg);
1170	dec->msg->msg_type = RUVD_MSG_DECODE;
1171	dec->msg->stream_handle = dec->stream_handle;
1172	dec->msg->status_report_feedback_number = dec->frame_number;
1173
1174	dec->msg->body.decode.stream_type = dec->stream_type;
1175	dec->msg->body.decode.decode_flags = 0x1;
1176	dec->msg->body.decode.width_in_samples = dec->base.width;
1177	dec->msg->body.decode.height_in_samples = dec->base.height;
1178
1179	if ((picture->profile == PIPE_VIDEO_PROFILE_VC1_SIMPLE) ||
1180	    (picture->profile == PIPE_VIDEO_PROFILE_VC1_MAIN)) {
1181		dec->msg->body.decode.width_in_samples = align(dec->msg->body.decode.width_in_samples, 16) / 16;
1182		dec->msg->body.decode.height_in_samples = align(dec->msg->body.decode.height_in_samples, 16) / 16;
1183	}
1184
1185	if (dec->dpb.res)
1186		dec->msg->body.decode.dpb_size = dec->dpb.res->buf->size;
1187	dec->msg->body.decode.bsd_size = bs_size;
1188	dec->msg->body.decode.db_pitch = align(dec->base.width, get_db_pitch_alignment(dec));
1189
1190	dt = dec->set_dtb(dec->msg, (struct vl_video_buffer *)target);
1191
1192	switch (u_reduce_video_profile(picture->profile)) {
1193	case PIPE_VIDEO_FORMAT_MPEG4_AVC:
1194		dec->msg->body.decode.codec.h264 = get_h264_msg(dec, (struct pipe_h264_picture_desc*)picture);
1195		break;
1196
1197	case PIPE_VIDEO_FORMAT_HEVC:
1198		dec->msg->body.decode.codec.h265 = get_h265_msg(dec, target, (struct pipe_h265_picture_desc*)picture);
1199		if (dec->ctx.res == NULL) {
1200			unsigned ctx_size;
1201			if (dec->base.profile == PIPE_VIDEO_PROFILE_HEVC_MAIN_10)
1202				ctx_size = calc_ctx_size_h265_main10(dec, (struct pipe_h265_picture_desc*)picture);
1203			else
1204				ctx_size = calc_ctx_size_h265_main(dec);
1205			if (!rvid_create_buffer(dec->screen, &dec->ctx, ctx_size, PIPE_USAGE_DEFAULT)) {
1206				RVID_ERR("Can't allocated context buffer.\n");
1207			}
1208			rvid_clear_buffer(decoder->context, &dec->ctx);
1209		}
1210
1211		if (dec->ctx.res)
1212			dec->msg->body.decode.dpb_reserved = dec->ctx.res->buf->size;
1213		break;
1214
1215	case PIPE_VIDEO_FORMAT_VC1:
1216		dec->msg->body.decode.codec.vc1 = get_vc1_msg((struct pipe_vc1_picture_desc*)picture);
1217		break;
1218
1219	case PIPE_VIDEO_FORMAT_MPEG12:
1220		dec->msg->body.decode.codec.mpeg2 = get_mpeg2_msg(dec, (struct pipe_mpeg12_picture_desc*)picture);
1221		break;
1222
1223	case PIPE_VIDEO_FORMAT_MPEG4:
1224		dec->msg->body.decode.codec.mpeg4 = get_mpeg4_msg(dec, (struct pipe_mpeg4_picture_desc*)picture);
1225		break;
1226
1227	case PIPE_VIDEO_FORMAT_JPEG:
1228		break;
1229
1230	default:
1231		assert(0);
1232		return;
1233	}
1234
1235	dec->msg->body.decode.db_surf_tile_config = dec->msg->body.decode.dt_surf_tile_config;
1236	dec->msg->body.decode.extension_support = 0x1;
1237
1238	/* set at least the feedback buffer size */
1239	dec->fb[0] = dec->fb_size;
1240
1241	send_msg_buf(dec);
1242
1243	if (dec->dpb.res)
1244		send_cmd(dec, RUVD_CMD_DPB_BUFFER, dec->dpb.res->buf, 0,
1245			RADEON_USAGE_READWRITE, RADEON_DOMAIN_VRAM);
1246
1247	if (dec->ctx.res)
1248		send_cmd(dec, RUVD_CMD_CONTEXT_BUFFER, dec->ctx.res->buf, 0,
1249			RADEON_USAGE_READWRITE, RADEON_DOMAIN_VRAM);
1250	send_cmd(dec, RUVD_CMD_BITSTREAM_BUFFER, bs_buf->res->buf,
1251		 0, RADEON_USAGE_READ, RADEON_DOMAIN_GTT);
1252	send_cmd(dec, RUVD_CMD_DECODING_TARGET_BUFFER, dt, 0,
1253		 RADEON_USAGE_WRITE, RADEON_DOMAIN_VRAM);
1254	send_cmd(dec, RUVD_CMD_FEEDBACK_BUFFER, msg_fb_it_buf->res->buf,
1255		 FB_BUFFER_OFFSET, RADEON_USAGE_WRITE, RADEON_DOMAIN_GTT);
1256	if (have_it(dec))
1257		send_cmd(dec, RUVD_CMD_ITSCALING_TABLE_BUFFER, msg_fb_it_buf->res->buf,
1258			 FB_BUFFER_OFFSET + dec->fb_size, RADEON_USAGE_READ, RADEON_DOMAIN_GTT);
1259	set_reg(dec, dec->reg.cntl, 1);
1260
1261	flush(dec, PIPE_FLUSH_ASYNC);
1262	next_buffer(dec);
1263}
1264
1265/**
1266 * flush any outstanding command buffers to the hardware
1267 */
1268static void ruvd_flush(struct pipe_video_codec *decoder)
1269{
1270}
1271
1272/**
1273 * create and UVD decoder
1274 */
1275struct pipe_video_codec *ruvd_create_decoder(struct pipe_context *context,
1276					     const struct pipe_video_codec *templ,
1277					     ruvd_set_dtb set_dtb)
1278{
1279	struct radeon_winsys* ws = ((struct r600_common_context *)context)->ws;
1280	struct r600_common_context *rctx = (struct r600_common_context*)context;
1281	unsigned dpb_size;
1282	unsigned width = templ->width, height = templ->height;
1283	unsigned bs_buf_size;
1284	struct radeon_info info;
1285	struct ruvd_decoder *dec;
1286	int r, i;
1287
1288	ws->query_info(ws, &info);
1289
1290	switch(u_reduce_video_profile(templ->profile)) {
1291	case PIPE_VIDEO_FORMAT_MPEG12:
1292		if (templ->entrypoint > PIPE_VIDEO_ENTRYPOINT_BITSTREAM || info.family < CHIP_PALM)
1293			return vl_create_mpeg12_decoder(context, templ);
1294
1295		/* fall through */
1296	case PIPE_VIDEO_FORMAT_MPEG4:
1297		width = align(width, VL_MACROBLOCK_WIDTH);
1298		height = align(height, VL_MACROBLOCK_HEIGHT);
1299		break;
1300	case PIPE_VIDEO_FORMAT_MPEG4_AVC:
1301		width = align(width, VL_MACROBLOCK_WIDTH);
1302		height = align(height, VL_MACROBLOCK_HEIGHT);
1303		break;
1304
1305	default:
1306		break;
1307	}
1308
1309
1310	dec = CALLOC_STRUCT(ruvd_decoder);
1311
1312	if (!dec)
1313		return NULL;
1314
1315	if (info.drm_major < 3)
1316		dec->use_legacy = true;
1317
1318	dec->base = *templ;
1319	dec->base.context = context;
1320	dec->base.width = width;
1321	dec->base.height = height;
1322
1323	dec->base.destroy = ruvd_destroy;
1324	dec->base.begin_frame = ruvd_begin_frame;
1325	dec->base.decode_macroblock = ruvd_decode_macroblock;
1326	dec->base.decode_bitstream = ruvd_decode_bitstream;
1327	dec->base.end_frame = ruvd_end_frame;
1328	dec->base.flush = ruvd_flush;
1329
1330	dec->stream_type = profile2stream_type(dec, info.family);
1331	dec->set_dtb = set_dtb;
1332	dec->stream_handle = rvid_alloc_stream_handle();
1333	dec->screen = context->screen;
1334	dec->ws = ws;
1335	dec->cs = ws->cs_create(rctx->ctx, RING_UVD, NULL, NULL);
1336	if (!dec->cs) {
1337		RVID_ERR("Can't get command submission context.\n");
1338		goto error;
1339	}
1340
1341	dec->fb_size = FB_BUFFER_SIZE;
1342	bs_buf_size = width * height * (512 / (16 * 16));
1343	for (i = 0; i < NUM_BUFFERS; ++i) {
1344		unsigned msg_fb_it_size = FB_BUFFER_OFFSET + dec->fb_size;
1345		STATIC_ASSERT(sizeof(struct ruvd_msg) <= FB_BUFFER_OFFSET);
1346		if (have_it(dec))
1347			msg_fb_it_size += IT_SCALING_TABLE_SIZE;
1348		if (!rvid_create_buffer(dec->screen, &dec->msg_fb_it_buffers[i],
1349					msg_fb_it_size, PIPE_USAGE_STAGING)) {
1350			RVID_ERR("Can't allocated message buffers.\n");
1351			goto error;
1352		}
1353
1354		if (!rvid_create_buffer(dec->screen, &dec->bs_buffers[i],
1355					bs_buf_size, PIPE_USAGE_STAGING)) {
1356			RVID_ERR("Can't allocated bitstream buffers.\n");
1357			goto error;
1358		}
1359
1360		rvid_clear_buffer(context, &dec->msg_fb_it_buffers[i]);
1361		rvid_clear_buffer(context, &dec->bs_buffers[i]);
1362	}
1363
1364	dpb_size = calc_dpb_size(dec);
1365	if (dpb_size) {
1366		if (!rvid_create_buffer(dec->screen, &dec->dpb, dpb_size, PIPE_USAGE_DEFAULT)) {
1367			RVID_ERR("Can't allocated dpb.\n");
1368			goto error;
1369		}
1370		rvid_clear_buffer(context, &dec->dpb);
1371	}
1372
1373	dec->reg.data0 = RUVD_GPCOM_VCPU_DATA0;
1374	dec->reg.data1 = RUVD_GPCOM_VCPU_DATA1;
1375	dec->reg.cmd = RUVD_GPCOM_VCPU_CMD;
1376	dec->reg.cntl = RUVD_ENGINE_CNTL;
1377
1378	map_msg_fb_it_buf(dec);
1379	dec->msg->size = sizeof(*dec->msg);
1380	dec->msg->msg_type = RUVD_MSG_CREATE;
1381	dec->msg->stream_handle = dec->stream_handle;
1382	dec->msg->body.create.stream_type = dec->stream_type;
1383	dec->msg->body.create.width_in_samples = dec->base.width;
1384	dec->msg->body.create.height_in_samples = dec->base.height;
1385	dec->msg->body.create.dpb_size = dpb_size;
1386	send_msg_buf(dec);
1387	r = flush(dec, 0);
1388	if (r)
1389		goto error;
1390
1391	next_buffer(dec);
1392
1393	return &dec->base;
1394
1395error:
1396	if (dec->cs) dec->ws->cs_destroy(dec->cs);
1397
1398	for (i = 0; i < NUM_BUFFERS; ++i) {
1399		rvid_destroy_buffer(&dec->msg_fb_it_buffers[i]);
1400		rvid_destroy_buffer(&dec->bs_buffers[i]);
1401	}
1402
1403	rvid_destroy_buffer(&dec->dpb);
1404	rvid_destroy_buffer(&dec->ctx);
1405	rvid_destroy_buffer(&dec->sessionctx);
1406
1407	FREE(dec);
1408
1409	return NULL;
1410}
1411
1412/* calculate top/bottom offset */
1413static unsigned texture_offset(struct radeon_surf *surface, unsigned layer)
1414{
1415	return surface->u.legacy.level[0].offset +
1416		layer * (uint64_t)surface->u.legacy.level[0].slice_size_dw * 4;
1417}
1418
1419/* hw encode the aspect of macro tiles */
1420static unsigned macro_tile_aspect(unsigned macro_tile_aspect)
1421{
1422	switch (macro_tile_aspect) {
1423	default:
1424	case 1: macro_tile_aspect = 0;  break;
1425	case 2: macro_tile_aspect = 1;  break;
1426	case 4: macro_tile_aspect = 2;  break;
1427	case 8: macro_tile_aspect = 3;  break;
1428	}
1429	return macro_tile_aspect;
1430}
1431
1432/* hw encode the bank width and height */
1433static unsigned bank_wh(unsigned bankwh)
1434{
1435	switch (bankwh) {
1436	default:
1437	case 1: bankwh = 0;     break;
1438	case 2: bankwh = 1;     break;
1439	case 4: bankwh = 2;     break;
1440	case 8: bankwh = 3;     break;
1441	}
1442	return bankwh;
1443}
1444
1445/**
1446 * fill decoding target field from the luma and chroma surfaces
1447 */
1448void ruvd_set_dt_surfaces(struct ruvd_msg *msg, struct radeon_surf *luma,
1449			  struct radeon_surf *chroma)
1450{
1451	msg->body.decode.dt_pitch = luma->u.legacy.level[0].nblk_x * luma->blk_w;
1452	switch (luma->u.legacy.level[0].mode) {
1453	case RADEON_SURF_MODE_LINEAR_ALIGNED:
1454		msg->body.decode.dt_tiling_mode = RUVD_TILE_LINEAR;
1455		msg->body.decode.dt_array_mode = RUVD_ARRAY_MODE_LINEAR;
1456		break;
1457	case RADEON_SURF_MODE_1D:
1458		msg->body.decode.dt_tiling_mode = RUVD_TILE_8X8;
1459		msg->body.decode.dt_array_mode = RUVD_ARRAY_MODE_1D_THIN;
1460		break;
1461	case RADEON_SURF_MODE_2D:
1462		msg->body.decode.dt_tiling_mode = RUVD_TILE_8X8;
1463		msg->body.decode.dt_array_mode = RUVD_ARRAY_MODE_2D_THIN;
1464		break;
1465	default:
1466		assert(0);
1467		break;
1468	}
1469
1470	msg->body.decode.dt_luma_top_offset = texture_offset(luma, 0);
1471	if (chroma)
1472		msg->body.decode.dt_chroma_top_offset = texture_offset(chroma, 0);
1473	if (msg->body.decode.dt_field_mode) {
1474		msg->body.decode.dt_luma_bottom_offset = texture_offset(luma, 1);
1475		if (chroma)
1476			msg->body.decode.dt_chroma_bottom_offset = texture_offset(chroma, 1);
1477	} else {
1478		msg->body.decode.dt_luma_bottom_offset = msg->body.decode.dt_luma_top_offset;
1479		msg->body.decode.dt_chroma_bottom_offset = msg->body.decode.dt_chroma_top_offset;
1480	}
1481
1482	if (chroma) {
1483		assert(luma->u.legacy.bankw == chroma->u.legacy.bankw);
1484		assert(luma->u.legacy.bankh == chroma->u.legacy.bankh);
1485		assert(luma->u.legacy.mtilea == chroma->u.legacy.mtilea);
1486	}
1487
1488	msg->body.decode.dt_surf_tile_config |= RUVD_BANK_WIDTH(bank_wh(luma->u.legacy.bankw));
1489	msg->body.decode.dt_surf_tile_config |= RUVD_BANK_HEIGHT(bank_wh(luma->u.legacy.bankh));
1490	msg->body.decode.dt_surf_tile_config |= RUVD_MACRO_TILE_ASPECT_RATIO(macro_tile_aspect(luma->u.legacy.mtilea));
1491}
1492