vp8.c 24.5 KB
Newer Older
1
 /*
Simon Morlat's avatar
Simon Morlat committed
2
 * vp8.c -VP8 encoder/decoder wrapper
3 4 5 6 7 8 9 10 11 12 13 14
 *
 *
 * Copyright (C) 2011  Belledonne Communications, Grenoble, France
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Simon Morlat's avatar
Simon Morlat committed
15
 *  GNU General Public License for more details.
16 17 18 19 20 21
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

22 23 24 25 26 27 28 29
#include "mediastreamer2/msfilter.h"
#include "mediastreamer2/msticker.h"
#include "mediastreamer2/msvideo.h"

#define VPX_CODEC_DISABLE_COMPAT 1
#include <vpx/vpx_encoder.h>
#include <vpx/vp8cx.h>

30
#undef interface
31 32
#define interface (vpx_codec_vp8_cx())

33 34 35 36 37
#define VP8_PAYLOAD_DESC_X_MASK      0x80
#define VP8_PAYLOAD_DESC_RSV_MASK    0x40
#define VP8_PAYLOAD_DESC_N_MASK      0x20
#define VP8_PAYLOAD_DESC_S_MASK      0x10
#define VP8_PAYLOAD_DESC_PARTID_MASK 0x0F
38

39
#undef FRAGMENT_ON_PARTITIONS
40
/*#define FRAGMENT_ON_PARTITIONS*/
41

42
#define MS_VP8_CONF(required_bitrate, bitrate_limit, resolution, fps) \
Ghislain MARY's avatar
Ghislain MARY committed
43
	{ required_bitrate, bitrate_limit, { MS_VIDEO_SIZE_ ## resolution ## _W, MS_VIDEO_SIZE_ ## resolution ## _H }, fps, NULL }
44 45

static const MSVideoConfiguration vp8_conf_list[] = {
Ghislain MARY's avatar
Ghislain MARY committed
46
#if defined(ANDROID) || (TARGET_OS_IPHONE == 1) || defined(__arm__)
47 48 49 50
	MS_VP8_CONF(300000, 600000,    VGA, 12),
	MS_VP8_CONF(100000, 300000,   QVGA, 12),
	MS_VP8_CONF(  64000,  100000, QCIF, 12),
	MS_VP8_CONF(      0,   64000, QCIF,  5)
51
#else
52 53 54 55 56 57 58
	MS_VP8_CONF(1024000, 1536000,  VGA, 25),
	MS_VP8_CONF( 350000,  600000,  VGA, 15),
	MS_VP8_CONF( 200000,  350000,  CIF, 15),
	MS_VP8_CONF( 150000,  200000, QVGA, 15),
	MS_VP8_CONF( 100000,  150000, QVGA, 10),
	MS_VP8_CONF(  64000,  100000, QCIF, 12),
	MS_VP8_CONF(      0,   64000, QCIF,  5)
59 60 61
#endif
};

62
static const MSVideoConfiguration multicore_vp8_conf_list[] = {
Ghislain MARY's avatar
Ghislain MARY committed
63
#if defined(ANDROID) || (TARGET_OS_IPHONE == 1) || defined(__arm__)
64 65 66 67 68
	MS_VP8_CONF(2048000, 2560000,       UXGA, 12),
	MS_VP8_CONF(1024000, 1536000, SXGA_MINUS, 12),
	MS_VP8_CONF( 750000, 1024000,        XGA, 12),
	MS_VP8_CONF( 500000,  750000,       SVGA, 12),
	MS_VP8_CONF( 300000,  500000,        VGA, 12),
69 70 71
	MS_VP8_CONF( 100000,  300000,       QVGA, 12),
	MS_VP8_CONF(  64000,  100000,       QCIF, 12),
	MS_VP8_CONF(      0,   64000,       QCIF,  5)
72
#else
Margaux Clerc's avatar
Margaux Clerc committed
73 74 75 76 77 78 79 80 81 82
	MS_VP8_CONF(1536000,  2560000, SXGA_MINUS, 15),
	MS_VP8_CONF(1536000,  2560000,       720P, 15),
	MS_VP8_CONF(1024000,  1536000,        XGA, 15),
	MS_VP8_CONF( 600000,  1024000,       SVGA, 15),
	MS_VP8_CONF( 350000,   600000,        VGA, 15),
	MS_VP8_CONF( 200000,   350000,        CIF, 15),
	MS_VP8_CONF( 150000,   200000,       QVGA, 15),
	MS_VP8_CONF( 100000,   150000,       QVGA, 10),
	MS_VP8_CONF(  64000,   100000,       QCIF, 12),
	MS_VP8_CONF(      0,    64000,       QCIF,  5)
83 84
#endif
};
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/* the goal of this small object is to tell when to send I frames at startup:
at 2 and 4 seconds*/
typedef struct VideoStarter{
	uint64_t next_time;
	int i_frame_count;
}VideoStarter;

static void video_starter_init(VideoStarter *vs){
	vs->next_time=0;
	vs->i_frame_count=0;
}

static void video_starter_first_frame(VideoStarter *vs, uint64_t curtime){
	vs->next_time=curtime+2000;
}

static bool_t video_starter_need_i_frame(VideoStarter *vs, uint64_t curtime){
	if (vs->next_time==0) return FALSE;
	if (curtime>=vs->next_time){
		vs->i_frame_count++;
		if (vs->i_frame_count==1){
			vs->next_time+=2000;
		}else{
			vs->next_time=0;
		}
		return TRUE;
	}
	return FALSE;
}

116 117 118
typedef struct EncState {
	vpx_codec_ctx_t codec;
	vpx_codec_enc_cfg_t cfg;
119
	long long frame_count;
120
	unsigned int mtu;
121 122
	VideoStarter starter;
	bool_t req_vfu;
123
	bool_t ready;
124 125 126
#ifdef FRAGMENT_ON_PARTITIONS
	uint8_t token_partition_count;
#endif
127 128
	const MSVideoConfiguration *vconf_list;
	MSVideoConfiguration vconf;
129 130
} EncState;

131
static void vp8_fragment_and_send(MSFilter *f,EncState *s,mblk_t *frame, uint32_t timestamp, const vpx_codec_cx_pkt_t *pkt, bool_t lastPartition);
132 133 134

static void enc_init(MSFilter *f) {
	vpx_codec_err_t res;
135
	MSVideoSize vsize;
136
	EncState *s=(EncState *)ms_new0(EncState,1);
137 138 139 140 141 142 143

	ms_message("Using %s\n",vpx_codec_iface_name(interface));

	/* Populate encoder configuration */
	res = vpx_codec_enc_config_default(interface, &s->cfg, 0);
	if(res) {
		ms_error("Failed to get config: %s\n", vpx_codec_err_to_string(res));
144
	}
145

146 147 148 149
	if (ms_get_cpu_count() > 1) s->vconf_list = &multicore_vp8_conf_list[0];
	else s->vconf_list = &vp8_conf_list[0];
	MS_VIDEO_SIZE_ASSIGN(vsize, CIF);
	s->vconf = ms_video_find_best_configuration_for_size(s->vconf_list, vsize);
150
	s->frame_count = 0;
151 152
	s->cfg.g_w = s->vconf.vsize.width;
	s->cfg.g_h = s->vconf.vsize.height;
153 154
	/* encoder automatically places keyframes */
	s->cfg.kf_mode = VPX_KF_AUTO;
155
	s->cfg.kf_max_dist = 300;
156
	s->cfg.rc_target_bitrate = ((float)s->vconf.required_bitrate)*0.92/1024.0; //0.9=take into account IP/UDP/RTP overhead, in average.
157
	s->cfg.g_pass = VPX_RC_ONE_PASS; /* -p 1 */
158
	s->cfg.g_timebase.num = 1;
159
	s->cfg.g_timebase.den = s->vconf.fps;
160
	s->cfg.rc_end_usage = VPX_CBR; /* --end-usage=cbr */
161 162 163
#if TARGET_IPHONE_SIMULATOR
	s->cfg.g_threads = 1; /*workaround to remove crash on ipad simulator*/ 
#else
164
	s->cfg.g_threads = ms_get_cpu_count();
165
#endif
166
	ms_message("VP8 g_threads=%d", s->cfg.g_threads);
167
	s->cfg.rc_undershoot_pct = 95; /* --undershoot-pct=95 */
168
	s->cfg.g_error_resilient = VPX_ERROR_RESILIENT_DEFAULT|VPX_ERROR_RESILIENT_PARTITIONS;
169
	s->cfg.g_lag_in_frames = 0;
170 171
	s->mtu=ms_get_payload_max_size()-1;/*-1 for the vp8 payload header*/

172 173 174 175 176
	f->data = s;
}

static void enc_uninit(MSFilter *f) {
	EncState *s=(EncState*)f->data;
177
	
178 179 180 181
	ms_free(s);
}

static void enc_preprocess(MSFilter *f) {
182
	vpx_codec_err_t res;
183
	EncState *s=(EncState*)f->data;
184

185 186 187
	s->cfg.g_w = s->vconf.vsize.width;
	s->cfg.g_h = s->vconf.vsize.height;
	s->cfg.g_timebase.den=s->vconf.fps;
188
	/* Initialize codec */
189 190 191 192
	#ifdef FRAGMENT_ON_PARTITIONS
	/* VPX_CODEC_USE_OUTPUT_PARTITION: output 1 frame per partition */
	res =  vpx_codec_enc_init(&s->codec, interface, &s->cfg, VPX_CODEC_USE_OUTPUT_PARTITION);
	#else
193
	res =  vpx_codec_enc_init(&s->codec, interface, &s->cfg, 0);
194
	#endif
195 196 197
	if (res) {
		ms_error("vpx_codec_enc_init failed: %s (%s)n", vpx_codec_err_to_string(res), vpx_codec_error_detail(&s->codec));
	}
198
	/*cpu/quality tradeoff: positive values decrease CPU usage at the expense of quality*/
199
	vpx_codec_control(&s->codec, VP8E_SET_CPUUSED, (s->cfg.g_threads > 1) ? 10 : 10); 
200 201
	vpx_codec_control(&s->codec, VP8E_SET_STATIC_THRESHOLD, 0);
	vpx_codec_control(&s->codec, VP8E_SET_ENABLEAUTOALTREF, 1);
202 203
	vpx_codec_control(&s->codec, VP8E_SET_MAX_INTRA_BITRATE_PCT, 400); /*limite iFrame size to 4 pframe*/
	#ifndef FRAGMENT_ON_PARTITIONS
204 205 206 207 208 209 210
	if (s->cfg.g_threads > 1) {
		if (vpx_codec_control(&s->codec, VP8E_SET_TOKEN_PARTITIONS, 2) != VPX_CODEC_OK) {
			ms_error("VP8: failed to set multiple token partition");
		} else {
			ms_message("VP8: multiple token partitions used");
		}
	}
211
	#endif
212 213 214 215
	#ifdef FRAGMENT_ON_PARTITIONS
	vpx_codec_control(&s->codec, VP8E_SET_TOKEN_PARTITIONS, 0x3);
	s->token_partition_count = 8;
	#endif
216
	/* vpx_codec_control(&s->codec, VP8E_SET_CPUUSED, 0);*/ /* -16 (quality) .. 16 (speed) */
217 218

	video_starter_init(&s->starter);
219
	s->ready=TRUE;
220 221 222 223 224 225 226 227 228
}

static void enc_process(MSFilter *f) {
	mblk_t *im,*om;
	uint64_t timems=f->ticker->time;
	uint32_t timestamp=timems*90;
	EncState *s=(EncState*)f->data;
	unsigned int flags = 0;
	vpx_codec_err_t err;
229
	YuvBuf yuv;
230

231
	ms_filter_lock(f);
232
	while((im=ms_queue_get(f->inputs[0]))!=NULL){
233
		vpx_image_t img;
234

235 236 237
		om = NULL;
		flags = 0;

238
		ms_yuv_buf_init_from_mblk(&yuv, im);
239
		vpx_img_wrap(&img, VPX_IMG_FMT_I420, s->vconf.vsize.width, s->vconf.vsize.height, 1, yuv.planes[0]);
240
		
241 242 243 244 245
		if (video_starter_need_i_frame (&s->starter,f->ticker->time)){
			/*sends an I frame at 2 seconds and 4 seconds after the beginning of the call*/
			s->req_vfu=TRUE;
		}
		if (s->req_vfu){
246
			ms_message("Forcing vp8 key frame for filter [%p]",f);
247 248 249 250
			flags = VPX_EFLAG_FORCE_KF;
			s->req_vfu=FALSE;
		}

251
		err = vpx_codec_encode(&s->codec, &img, s->frame_count, 1, flags, VPX_DL_REALTIME);
252

253 254 255 256
		if (err) {
			ms_error("vpx_codec_encode failed : %d %s (%s)\n", err, vpx_codec_err_to_string(err), vpx_codec_error_detail(&s->codec));
		} else {
			vpx_codec_iter_t iter = NULL;
257
			const vpx_codec_cx_pkt_t *pkt;
258

259 260 261 262 263
			s->frame_count++;
			if (s->frame_count==1){
				video_starter_first_frame (&s->starter,f->ticker->time);
			}

264
			while( (pkt = vpx_codec_get_cx_data(&s->codec, &iter)) ) {
265
				if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
266
					if (pkt->data.frame.sz > 0) {
267 268 269 270 271 272 273 274
						om = allocb(pkt->data.frame.sz,0);
						memcpy(om->b_wptr, pkt->data.frame.buf, pkt->data.frame.sz);
						om->b_wptr += pkt->data.frame.sz;
						#ifdef FRAGMENT_ON_PARTITIONS
						vp8_fragment_and_send(f, s, om, timestamp, pkt, (pkt->data.frame.partition_id == s->token_partition_count));
						#else
						vp8_fragment_and_send(f, s, om, timestamp, pkt, 1);
						#endif
275
					}
276 277 278 279 280
				}
			}
		}
		freemsg(im);
	}
281
	ms_filter_unlock(f);
282 283 284
}

static void enc_postprocess(MSFilter *f) {
285 286 287
	EncState *s=(EncState*)f->data;
	if (s->ready) vpx_codec_destroy(&s->codec);
	s->ready=FALSE;
288 289
}

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
static int enc_set_configuration(MSFilter *f, void *data) {
	EncState *s = (EncState *)f->data;
	const MSVideoConfiguration *vconf = (const MSVideoConfiguration *)data;
	if (vconf != &s->vconf) memcpy(&s->vconf, vconf, sizeof(MSVideoConfiguration));

	if (s->vconf.required_bitrate > s->vconf.bitrate_limit)
		s->vconf.required_bitrate = s->vconf.bitrate_limit;
	s->cfg.rc_target_bitrate = ((float)s->vconf.required_bitrate) * 0.92 / 1024.0; //0.9=take into account IP/UDP/RTP overhead, in average.
	if (s->ready) {
		ms_filter_lock(f);
		enc_postprocess(f);
		enc_preprocess(f);
		ms_filter_unlock(f);
		return 0;
	}

	ms_message("Video configuration set: bitrate=%dbits/s, fps=%f, vsize=%dx%d", s->vconf.required_bitrate, s->vconf.fps, s->vconf.vsize.width, s->vconf.vsize.height);
	return 0;
}

static int enc_set_vsize(MSFilter *f, void *data) {
	MSVideoConfiguration best_vconf;
	MSVideoSize *vs = (MSVideoSize *)data;
	EncState *s = (EncState *)f->data;
	best_vconf = ms_video_find_best_configuration_for_size(s->vconf_list, *vs);
	s->vconf.vsize = *vs;
	s->vconf.fps = best_vconf.fps;
	s->vconf.bitrate_limit = best_vconf.bitrate_limit;
	enc_set_configuration(f, &s->vconf);
319 320 321 322 323 324
	return 0;
}

static int enc_get_vsize(MSFilter *f, void *data){
	EncState *s=(EncState*)f->data;
	MSVideoSize *vs=(MSVideoSize*)data;
325
	*vs = s->vconf.vsize;
326 327 328 329 330 331 332 333 334 335 336 337
	return 0;
}

static int enc_add_attr(MSFilter *f, void*data){
	/*const char *attr=(const char*)data;
	EncState *s=(EncState*)f->data;*/
	return 0;
}

static int enc_set_fps(MSFilter *f, void *data){
	float *fps=(float*)data;
	EncState *s=(EncState*)f->data;
338 339
	s->vconf.fps=*fps;
	enc_set_configuration(f, &s->vconf);
340 341 342 343 344 345
	return 0;
}

static int enc_get_fps(MSFilter *f, void *data){
	EncState *s=(EncState*)f->data;
	float *fps=(float*)data;
346
	*fps=s->vconf.fps;
347 348 349
	return 0;
}

350 351
static int enc_get_br(MSFilter *f, void*data){
	EncState *s=(EncState*)f->data;
352
	*(int*)data=s->vconf.required_bitrate;
353 354 355 356
	return 0;
}

static int enc_set_br(MSFilter *f, void*data) {
357 358
	EncState *s = (EncState *)f->data;
	int br = *(int *)data;
359 360 361
	if (s->ready) {
		/* Encoding is already ongoing, do not change video size, only bitrate. */
		s->vconf.required_bitrate = br;
362
		enc_set_configuration(f, &s->vconf);
363 364 365 366
	} else {
		MSVideoConfiguration best_vconf = ms_video_find_best_configuration_for_bitrate(s->vconf_list, br);
		enc_set_configuration(f, &best_vconf);
	}
367 368 369 370 371 372 373 374 375
	return 0;
}

static int enc_set_mtu(MSFilter *f, void*data){
	EncState *s=(EncState*)f->data;
	s->mtu=*(int*)data;
	return 0;
}

376 377 378 379 380 381
static int enc_req_vfu(MSFilter *f, void *unused){
	EncState *s=(EncState*)f->data;
	s->req_vfu=TRUE;
	return 0;
}

382
static int enc_get_configuration_list(MSFilter *f, void *data) {
383
	EncState *s = (EncState *)f->data;
384
	const MSVideoConfiguration **vconf_list = (const MSVideoConfiguration **)data;
385
	*vconf_list = s->vconf_list;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	return 0;
}

static MSFilterMethod enc_methods[] = {
	{ MS_FILTER_SET_VIDEO_SIZE,                enc_set_vsize              },
	{ MS_FILTER_SET_FPS,                       enc_set_fps                },
	{ MS_FILTER_GET_VIDEO_SIZE,                enc_get_vsize              },
	{ MS_FILTER_GET_FPS,                       enc_get_fps                },
	{ MS_FILTER_ADD_ATTR,                      enc_add_attr               },
	{ MS_FILTER_SET_BITRATE,                   enc_set_br                 },
	{ MS_FILTER_GET_BITRATE,                   enc_get_br                 },
	{ MS_FILTER_SET_MTU,                       enc_set_mtu                },
	{ MS_FILTER_REQ_VFU,                       enc_req_vfu                },
	{ MS_VIDEO_ENCODER_REQ_VFU,                enc_req_vfu                },
	{ MS_VIDEO_ENCODER_GET_CONFIGURATION_LIST, enc_get_configuration_list },
	{ MS_VIDEO_ENCODER_SET_CONFIGURATION,      enc_set_configuration      },
	{ 0,                                       NULL                       }
403 404
};

405 406 407 408 409 410
#ifdef _MSC_VER
MSFilterDesc ms_vp8_enc_desc={
	MS_VP8_ENC_ID,
	"MSVp8Enc",
	N_("A video VP8 encoder using libvpx library."),
	MS_FILTER_ENCODER,
411
	"VP8",
412 413 414 415 416 417 418 419 420 421
	1, /*MS_YUV420P is assumed on this input */
	1,
	enc_init,
	enc_preprocess,
	enc_process,
	enc_postprocess,
	enc_uninit,
	enc_methods
};
#else
422 423 424 425 426
MSFilterDesc ms_vp8_enc_desc={
	.id=MS_VP8_ENC_ID,
	.name="MSVp8Enc",
	.text=N_("A video VP8 encoder using libvpx library."),
	.category=MS_FILTER_ENCODER,
427
	.enc_fmt="VP8",
428 429 430 431 432 433 434 435 436
	.ninputs=1, /*MS_YUV420P is assumed on this input */
	.noutputs=1,
	.init=enc_init,
	.preprocess=enc_preprocess,
	.process=enc_process,
	.postprocess=enc_postprocess,
	.uninit=enc_uninit,
	.methods=enc_methods
};
437
#endif
438 439 440 441

MS_FILTER_DESC_EXPORT(ms_vp8_enc_desc)


442
static void vp8_fragment_and_send(MSFilter *f,EncState *s,mblk_t *frame, uint32_t timestamp, const vpx_codec_cx_pkt_t *pkt, bool_t lastPartition){
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
	uint8_t *rptr;
	mblk_t *packet=NULL;
	mblk_t* vp8_payload_desc = NULL;
	int len;

#if 0
	if ((pkt->data.frame.flags & VPX_FRAME_IS_KEY) == 0) {
		ms_debug("P-FRAME: %u\n", pkt->data.frame.sz);
	} else {
		ms_debug("I-FRAME: %u\n", pkt->data.frame.sz);
	}
#endif

	for (rptr=frame->b_rptr;rptr<frame->b_wptr;){
		vp8_payload_desc = allocb(1, 0);
		vp8_payload_desc->b_wptr=vp8_payload_desc->b_rptr+1;

		len=MIN(s->mtu,(frame->b_wptr-rptr));
		packet=dupb(frame);
		packet->b_rptr=rptr;
		packet->b_wptr=rptr+len;
		mblk_set_timestamp_info(packet,timestamp);
		mblk_set_timestamp_info(vp8_payload_desc,timestamp);

		/* insert 1 byte vp8 payload descriptor */
		(*vp8_payload_desc->b_rptr) = 0;
469 470
		/* X (extended) field, 0 */
		(*vp8_payload_desc->b_rptr) &= ~VP8_PAYLOAD_DESC_X_MASK;
471 472 473 474
		/* RSV field, always 0 */
		(*vp8_payload_desc->b_rptr) &= ~VP8_PAYLOAD_DESC_RSV_MASK;
		/* N : set to 1 if non reference frame */
		if ((pkt->data.frame.flags & VPX_FRAME_IS_KEY) == 0)
475 476
			(*vp8_payload_desc->b_rptr) |= VP8_PAYLOAD_DESC_N_MASK;
		/* S : partition start */
477
		if (rptr == frame->b_rptr) {
478
			(*vp8_payload_desc->b_rptr) |= VP8_PAYLOAD_DESC_S_MASK;
479
		}
480
		/* PartID : partition id */
481
		#ifdef FRAGMENT_ON_PARTITIONS
482
		(*vp8_payload_desc->b_rptr) |= (pkt->data.frame.partition_id & VP8_PAYLOAD_DESC_PARTID_MASK);
483
		#endif
484 485 486 487 488 489 490 491 492 493

		vp8_payload_desc->b_cont = packet;

		ms_queue_put(f->outputs[0], vp8_payload_desc);
		rptr+=len;
	}

	freeb(frame);

	/*set marker bit on last packet*/
494 495 496 497
	if (lastPartition) {
		mblk_set_marker_info(packet,TRUE);
		mblk_set_marker_info(vp8_payload_desc,TRUE);
	}
498 499 500 501 502 503 504 505 506 507 508
}

#undef interface
#include <assert.h>
#include <vpx/vpx_decoder.h>
#include <vpx/vp8dx.h>
#define interface (vpx_codec_vp8_dx())

typedef struct DecState {
	vpx_codec_ctx_t codec;
	mblk_t *curframe;
509 510
	long last_cseq; /*last receive sequence number, used to locate missing partition fragment*/
	int current_partition_id; /*current partition id*/
511
	uint64_t last_error_reported_time;
512 513 514 515
	mblk_t *yuv_msg;
	MSPicture outbuf;
	int yuv_width, yuv_height;
	MSQueue q;
516
	MSAverageFPS fps;
517
	bool_t first_image_decoded;
518
	bool_t on_error; /*a decoding error occurs*/
519 520 521 522 523
} DecState;


static void dec_init(MSFilter *f) {
	DecState *s=(DecState *)ms_new(DecState,1);
524 525 526 527
	vpx_codec_flags_t  flags = 0/*VPX_CODEC_USE_ERROR_CONCEALMENT*/;
#ifdef FRAGMENT_ON_PARTITIONS
	flags |= VPX_CODEC_USE_INPUT_FRAGMENTS;
#endif
528

529 530
	ms_message("Using %s\n",vpx_codec_iface_name(interface));

531
	/* Initialize codec */
532
	if(vpx_codec_dec_init(&s->codec, interface, NULL, flags))
533 534 535
		ms_error("Failed to initialize decoder");

	s->curframe = NULL;
536
	s->last_error_reported_time = 0;
537 538 539 540
	s->yuv_width = 0;
	s->yuv_height = 0;
	s->yuv_msg = 0;
	ms_queue_init(&s->q);
541
	s->first_image_decoded = FALSE;
542
	f->data = s;
543
	ms_video_init_average_fps(&s->fps, "VP8 decoder: FPS: %f");
544
	s->on_error=FALSE;
545 546 547
}

static void dec_preprocess(MSFilter* f) {
548 549
	DecState *s=(DecState*)f->data;
	s->first_image_decoded = FALSE;
550 551 552 553 554 555 556 557
}

static void dec_uninit(MSFilter *f) {
	DecState *s=(DecState*)f->data;
	vpx_codec_destroy(&s->codec);

	if (s->curframe!=NULL)
		freemsg(s->curframe);
558
	if (s->yuv_msg)
Simon Morlat's avatar
Simon Morlat committed
559
		freemsg(s->yuv_msg);
560 561

	ms_queue_flush(&s->q);
562 563 564 565

	ms_free(s);
}

566
/* remove payload header and aggregates fragmented packets */
567
static void dec_unpacketize(MSFilter *f, DecState *s, mblk_t *im, MSQueue *out){
568
	int xbit = (im->b_rptr[0] & 0x80) >> 7;
569 570 571 572 573 574 575 576
#ifdef FRAGMENT_ON_PARTITIONS
	int sbit = (im->b_rptr[0] & VP8_PAYLOAD_DESC_S_MASK) >> 4;
	int partition_id = im->b_rptr[0] & 0b00000111;
	int current_cseq=mblk_get_cseq(im);
	int discontinuity_detected=(current_cseq-s->last_cseq)-1;
	bool_t end_of_frame=mblk_get_marker_info(im);
#endif

577
	im->b_rptr++;
578 579 580 581 582 583 584 585 586 587
	if (xbit) {
		/* Ignore extensions if some are present */
		int ibit = (im->b_rptr[0] & 0x80) >> 7;
		int lbit = (im->b_rptr[0] & 0x40) >> 6;
		int tbit = (im->b_rptr[0] & 0x20) >> 5;
		int kbit = (im->b_rptr[0] & 0x10) >> 4;
		int mbit = 0;
		if (ibit) {
			mbit = (im->b_rptr[1] & 0x80) >> 7;
		}
588
		im->b_rptr += (xbit + ibit + lbit + (tbit | kbit) + mbit);
589
	}
590

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
#ifdef FRAGMENT_ON_PARTITIONS
	/*first, check for discontinuity*/
	if (discontinuity_detected) {
		ms_warning("vp8 detect discontinuity at cseq [%i] on filter [%p]",current_cseq,f);
		if (s->curframe) {
			ms_warning("vp8 discarding previous partition on filter [%p]",f);
			/*reset frame size to tell decoder there is a missing partition*/
			/*s->curframe->b_wptr=s->curframe->b_rptr;
			ms_queue_put(out, s->curframe);*/
			freemsg(s->curframe);
			s->curframe=NULL;
		}
	}

	/*it it a partition start ?*/
	if (sbit) {
		if (s->curframe) {
			/*previous partition is over*/
			if (mblk_get_timestamp_info(im) != mblk_get_timestamp_info(s->curframe)) {
				/*previous partition is over but last partition is probably lost*/
				mblk_set_marker_info(s->curframe,1);
			}
			ms_queue_put(out, s->curframe);
		}
		s->curframe=im;
	} else {
		if (s->current_partition_id == partition_id && s->curframe){
			/*good, this is a continuation*/
			concatb(s->curframe,im);
			msgpullup(s->curframe,-1);
		} else {
			/*well, this is probably a tailing partition segment*/
			ms_warning("vp8 trashing tailing partitions on filter [%p]",f);
			freemsg(im);
		}

	}

	s->current_partition_id=partition_id;
	s->last_cseq=current_cseq;
	if (end_of_frame) {
		/*end of frame*/
		if (s->curframe) {
			/*copy marker bit*/
			mblk_set_marker_info(s->curframe,1);
			/*push last partition*/
			ms_queue_put(out, s->curframe);
			s->curframe=NULL;
		}
	}

#else /*FRAGMENT_ON_PARTITIONS*/
643
	/* end of frame bit ? */
644 645 646
	if (mblk_get_marker_info(im)) {
		/* should be aggregated with previous packet ? */
		if (s->curframe!=NULL){
647
			/* same timestamp ? */
648
			if (mblk_get_timestamp_info(im) == mblk_get_timestamp_info(s->curframe)) {
649
				concatb(s->curframe,im);
650
				msgpullup(s->curframe,-1);
651 652
				/* transmit complete frame */
				ms_queue_put(out, s->curframe);
653 654
				s->curframe=NULL;
			} else {
655 656
				/* transmit partial frame */
				ms_queue_put(out, s->curframe);
657
				s->curframe = NULL;
658 659
				/* transmit new one (be it complete or not) */
				ms_queue_put(out, im);
660 661
			}
		} else {
662 663
			/* transmit new one (be it complete or not) */
			ms_queue_put(out, im);
664
		}
665
	} else {
666 667 668 669 670
		if (s->curframe!=NULL) {
			/* append if same timestamp */
			if (mblk_get_timestamp_info(im) == mblk_get_timestamp_info(s->curframe)) {
				concatb(s->curframe,im);
			} else {
671 672 673
				/* transmit partial frame */
				ms_queue_put(out, s->curframe);
				s->curframe = im;
674 675 676
			}
		}
		else {
677
			s->curframe = im;
678
		}
679
	}
680
#endif /*FRAGMENT_ON_PARTITIONS*/
681 682 683 684 685 686 687
}

static void dec_process(MSFilter *f) {
	mblk_t *im;
	DecState *s=(DecState*)f->data;

	while( (im=ms_queue_get(f->inputs[0]))!=0) {
688 689 690 691 692 693
		mblk_t *m;

		dec_unpacketize(f, s, im, &s->q);

		while((m=ms_queue_get(&s->q))!=NULL){
			vpx_codec_err_t err;
694
			vpx_codec_iter_t  iter = NULL;
695
			vpx_image_t *img;
696

697 698 699 700 701 702 703 704 705 706 707 708 709
			/*
			 * 4.3.  VP8 Payload Header
			 *
			 *  0 1 2 3 4 5 6 7
			 *  +-+-+-+-+-+-+-+-+
			 *  |Size0|H| VER |P|
			 *  +-+-+-+-+-+-+-+-+
			 *  ...
			 *
			 * P: Inverse key frame flag.  When set to 0 the current frame is a key
			 * frame.  When set to 1 the current frame is an interframe.  Defined
			 * in [RFC6386]
			 */
710
			if (m->b_rptr[0] & 0x01) {
711 712 713 714 715 716 717 718
				/*not a key frame, freezing image until next keyframe*/
				/*if (s->first_image_decoded && s->on_error) {
					freemsg(m);
					continue;
				}*/
			} else
				ms_message("vp8 key frame received on filter [%p]",f);

719 720
			err = vpx_codec_decode(&s->codec, m->b_rptr, m->b_wptr - m->b_rptr, NULL, 0);
			if (err) {
721 722
				ms_warning("vp8 decode failed : %d %s (%s)\n", err, vpx_codec_err_to_string(err), vpx_codec_error_detail(&s->codec));
				s->on_error=TRUE;
723 724 725 726
				if ((f->ticker->time - s->last_error_reported_time)>5000 || s->last_error_reported_time==0) {
					s->last_error_reported_time=f->ticker->time;
					ms_filter_notify_no_arg(f,MS_VIDEO_DECODER_DECODING_ERRORS);
				}
727 728 729 730 731
				if (s->first_image_decoded == FALSE) {
					/* if no frames have been decoded yet, do not try to browse decoded frames */
					freemsg(m);
					continue;
				}
732 733 734 735 736 737 738 739 740 741 742
			} else {
#ifdef FRAGMENT_ON_PARTITIONS
				if (mblk_get_marker_info(m)) {
					/*end of partitions*/
					err=vpx_codec_decode(&s->codec, NULL,0, NULL, 0);
					if (0 /*err*/) {
						ms_warning("vp8 decode failed at end of partitions : %d %s (%s)\n", err, vpx_codec_err_to_string(err), vpx_codec_error_detail(&s->codec));
					}
				}
#endif /*FRAGMENT_ON_PARTITIONS*/
				s->on_error=FALSE;
743 744
			}

745

746
			/* browse decoded frames */
747
			while((img = vpx_codec_get_frame(&s->codec, &iter))) {
748
				int i,j;
749 750 751

				if (s->yuv_width != img->d_w || s->yuv_height != img->d_h) {
					if (s->yuv_msg)
Simon Morlat's avatar
Simon Morlat committed
752
						freemsg(s->yuv_msg);
753 754 755 756 757
					s->yuv_msg = ms_yuv_buf_alloc(&s->outbuf, img->d_w, img->d_h);
					s->yuv_width = img->d_w;
					s->yuv_height = img->d_h;
				}

758
				/* scale/copy frame to destination mblk_t */
759
				for(i=0; i<3; i++) {
760 761
					uint8_t* dest = s->outbuf.planes[i];
					uint8_t* src = img->planes[i];
762
					int h = img->d_h >> ((i>0)?1:0);
763

764
					for(j=0; j<h; j++) {
765
						memcpy(dest, src, s->outbuf.strides[i]);
766

767
						dest += s->outbuf.strides[i];
768 769 770
						src += img->stride[i];
					}
				}
771
				ms_queue_put(f->outputs[0], dupmsg(s->yuv_msg));
772

773 774 775
				if (ms_video_update_average_fps(&s->fps, f->ticker->time)) {
					ms_message("VP8 decoder: Frame size: %dx%d", s->yuv_width, s->yuv_height);
				}
776 777
				if (!s->first_image_decoded) {
					s->first_image_decoded = TRUE;
778
					ms_filter_notify_no_arg(f,MS_VIDEO_DECODER_FIRST_IMAGE_DECODED);
779
				}
780 781 782 783 784 785
			}
			freemsg(m);
		}
	}
}

786
static int reset_first_image(MSFilter* f, void *data) {
787 788
	DecState *s=(DecState*)f->data;
	s->first_image_decoded = FALSE;
789
	return 0;
790 791
}

792 793 794 795 796 797 798
static int dec_get_vsize(MSFilter *f, void *data) {
	DecState *s = (DecState *)f->data;
	MSVideoSize *vsize = (MSVideoSize *)data;
	if (s->first_image_decoded == TRUE) {
		vsize->width = s->yuv_width;
		vsize->height = s->yuv_height;
	} else {
799 800
		vsize->width = MS_VIDEO_SIZE_UNKNOWN_W;
		vsize->height = MS_VIDEO_SIZE_UNKNOWN_H;
801 802 803 804
	}
	return 0;
}

805
static MSFilterMethod dec_methods[]={
806
	{	MS_VIDEO_DECODER_RESET_FIRST_IMAGE_NOTIFICATION, reset_first_image },
807
	{	MS_FILTER_GET_VIDEO_SIZE, dec_get_vsize	},
808
	{		0		,		NULL			}
809 810
};

811 812 813 814 815 816
#ifdef _MSC_VER
MSFilterDesc ms_vp8_dec_desc={
	MS_VP8_DEC_ID,
	"MSVp8Dec",
	"A VP8 decoder using libvpx library",
	MS_FILTER_DECODER,
817
	"VP8",
818 819 820 821 822 823 824
	1,
	1,
	dec_init,
	dec_preprocess,
	dec_process,
	NULL,
	dec_uninit,
825
	dec_methods
826 827
};
#else
828 829 830 831 832
MSFilterDesc ms_vp8_dec_desc={
	.id=MS_VP8_DEC_ID,
	.name="MSVp8Dec",
	.text="A VP8 decoder using libvpx library",
	.category=MS_FILTER_DECODER,
833
	.enc_fmt="VP8",
834 835 836 837 838 839 840
	.ninputs=1,
	.noutputs=1,
	.init=dec_init,
	.preprocess=dec_preprocess,
	.process=dec_process,
	.postprocess=NULL,
	.uninit=dec_uninit,
841
	.methods=dec_methods
842
};
843
#endif
844
MS_FILTER_DESC_EXPORT(ms_vp8_dec_desc)