blob: e4c3aea8a52a45575ac5f272d3ad8978870d6386 [file] [log] [blame]
Tristan Matthews0a329cc2013-07-17 13:20:14 -04001/* $Id$ */
2/*
3 * Copyright (C) 2010-2011 Teluu Inc. (http://www.teluu.com)
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19#include <pjmedia-codec/ffmpeg_vid_codecs.h>
20#include <pjmedia-codec/h263_packetizer.h>
21#include <pjmedia-codec/h264_packetizer.h>
22#include <pjmedia/errno.h>
23#include <pjmedia/vid_codec_util.h>
24#include <pj/assert.h>
25#include <pj/list.h>
26#include <pj/log.h>
27#include <pj/math.h>
28#include <pj/pool.h>
29#include <pj/string.h>
30#include <pj/os.h>
31
32
33/*
34 * Only build this file if PJMEDIA_HAS_FFMPEG_VID_CODEC != 0 and
35 * PJMEDIA_HAS_VIDEO != 0
36 */
37#if defined(PJMEDIA_HAS_FFMPEG_VID_CODEC) && \
38 PJMEDIA_HAS_FFMPEG_VID_CODEC != 0 && \
39 defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
40
41#define THIS_FILE "ffmpeg_vid_codecs.c"
42
43#define LIBAVCODEC_VER_AT_LEAST(major,minor) (LIBAVCODEC_VERSION_MAJOR > major || \
44 (LIBAVCODEC_VERSION_MAJOR == major && \
45 LIBAVCODEC_VERSION_MINOR >= minor))
46
47#include "../pjmedia/ffmpeg_util.h"
48#include <libavcodec/avcodec.h>
49#include <libavformat/avformat.h>
50#if LIBAVCODEC_VER_AT_LEAST(53,20)
51 /* Needed by 264 so far, on libavcodec 53.20 */
52# include <libavutil/opt.h>
53#endif
54
55
56/* Various compatibility */
57
58#if LIBAVCODEC_VER_AT_LEAST(53,20)
59# define AVCODEC_OPEN(ctx,c) avcodec_open2(ctx,c,NULL)
60#else
61# define AVCODEC_OPEN(ctx,c) avcodec_open(ctx,c)
62#endif
63
64#if LIBAVCODEC_VER_AT_LEAST(53,61)
65# if LIBAVCODEC_VER_AT_LEAST(54,59)
66 /* Not sure when AVCodec::encode is obsoleted/removed. */
67# define AVCODEC_HAS_ENCODE(c) (c->encode2)
68# else
69 /* Not sure when AVCodec::encode2 is introduced. It appears in
70 * libavcodec 53.61 where some codecs actually still use AVCodec::encode
71 * (e.g: H263, H264).
72 */
73# define AVCODEC_HAS_ENCODE(c) (c->encode || c->encode2)
74# endif
75# define AV_OPT_SET(obj,name,val,opt) (av_opt_set(obj,name,val,opt)==0)
76# define AV_OPT_SET_INT(obj,name,val) (av_opt_set_int(obj,name,val,0)==0)
77#else
78# define AVCODEC_HAS_ENCODE(c) (c->encode)
79# define AV_OPT_SET(obj,name,val,opt) (av_set_string3(obj,name,val,opt,NULL)==0)
80# define AV_OPT_SET_INT(obj,name,val) (av_set_int(obj,name,val)!=NULL)
81#endif
82#define AVCODEC_HAS_DECODE(c) (c->decode)
83
84
85/* Prototypes for FFMPEG codecs factory */
86static pj_status_t ffmpeg_test_alloc( pjmedia_vid_codec_factory *factory,
87 const pjmedia_vid_codec_info *id );
88static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory,
89 const pjmedia_vid_codec_info *info,
90 pjmedia_vid_codec_param *attr );
91static pj_status_t ffmpeg_enum_codecs( pjmedia_vid_codec_factory *factory,
92 unsigned *count,
93 pjmedia_vid_codec_info codecs[]);
94static pj_status_t ffmpeg_alloc_codec( pjmedia_vid_codec_factory *factory,
95 const pjmedia_vid_codec_info *info,
96 pjmedia_vid_codec **p_codec);
97static pj_status_t ffmpeg_dealloc_codec( pjmedia_vid_codec_factory *factory,
98 pjmedia_vid_codec *codec );
99
100/* Prototypes for FFMPEG codecs implementation. */
101static pj_status_t ffmpeg_codec_init( pjmedia_vid_codec *codec,
102 pj_pool_t *pool );
103static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec,
104 pjmedia_vid_codec_param *attr );
105static pj_status_t ffmpeg_codec_close( pjmedia_vid_codec *codec );
106static pj_status_t ffmpeg_codec_modify(pjmedia_vid_codec *codec,
107 const pjmedia_vid_codec_param *attr );
108static pj_status_t ffmpeg_codec_get_param(pjmedia_vid_codec *codec,
109 pjmedia_vid_codec_param *param);
110static pj_status_t ffmpeg_codec_encode_begin(pjmedia_vid_codec *codec,
111 const pjmedia_vid_encode_opt *opt,
112 const pjmedia_frame *input,
113 unsigned out_size,
114 pjmedia_frame *output,
115 pj_bool_t *has_more);
116static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec,
117 unsigned out_size,
118 pjmedia_frame *output,
119 pj_bool_t *has_more);
120static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec,
121 pj_size_t pkt_count,
122 pjmedia_frame packets[],
123 unsigned out_size,
124 pjmedia_frame *output);
125
126/* Definition for FFMPEG codecs operations. */
127static pjmedia_vid_codec_op ffmpeg_op =
128{
129 &ffmpeg_codec_init,
130 &ffmpeg_codec_open,
131 &ffmpeg_codec_close,
132 &ffmpeg_codec_modify,
133 &ffmpeg_codec_get_param,
134 &ffmpeg_codec_encode_begin,
135 &ffmpeg_codec_encode_more,
136 &ffmpeg_codec_decode,
137 NULL
138};
139
140/* Definition for FFMPEG codecs factory operations. */
141static pjmedia_vid_codec_factory_op ffmpeg_factory_op =
142{
143 &ffmpeg_test_alloc,
144 &ffmpeg_default_attr,
145 &ffmpeg_enum_codecs,
146 &ffmpeg_alloc_codec,
147 &ffmpeg_dealloc_codec
148};
149
150
151/* FFMPEG codecs factory */
152static struct ffmpeg_factory {
153 pjmedia_vid_codec_factory base;
154 pjmedia_vid_codec_mgr *mgr;
155 pj_pool_factory *pf;
156 pj_pool_t *pool;
157 pj_mutex_t *mutex;
158} ffmpeg_factory;
159
160
161typedef struct ffmpeg_codec_desc ffmpeg_codec_desc;
162
163
164/* FFMPEG codecs private data. */
165typedef struct ffmpeg_private
166{
167 const ffmpeg_codec_desc *desc;
168 pjmedia_vid_codec_param param; /**< Codec param */
169 pj_pool_t *pool; /**< Pool for each instance */
170
171 /* Format info and apply format param */
172 const pjmedia_video_format_info *enc_vfi;
173 pjmedia_video_apply_fmt_param enc_vafp;
174 const pjmedia_video_format_info *dec_vfi;
175 pjmedia_video_apply_fmt_param dec_vafp;
176
177 /* Buffers, only needed for multi-packets */
178 pj_bool_t whole;
179 void *enc_buf;
180 unsigned enc_buf_size;
181 pj_bool_t enc_buf_is_keyframe;
182 unsigned enc_frame_len;
183 unsigned enc_processed;
184 void *dec_buf;
185 unsigned dec_buf_size;
186 pj_timestamp last_dec_keyframe_ts;
187
188 /* The ffmpeg codec states. */
189 AVCodec *enc;
190 AVCodec *dec;
191 AVCodecContext *enc_ctx;
192 AVCodecContext *dec_ctx;
193
194 /* The ffmpeg decoder cannot set the output format, so format conversion
195 * may be needed for post-decoding.
196 */
197 enum PixelFormat expected_dec_fmt;
198 /**< Expected output format of
199 ffmpeg decoder */
200
201 void *data; /**< Codec specific data */
202} ffmpeg_private;
203
204
205/* Shortcuts for packetize & unpacketize function declaration,
206 * as it has long params and is reused many times!
207 */
208#define FUNC_PACKETIZE(name) \
209 pj_status_t(name)(ffmpeg_private *ff, pj_uint8_t *bits, \
210 pj_size_t bits_len, unsigned *bits_pos, \
211 const pj_uint8_t **payload, pj_size_t *payload_len)
212
213#define FUNC_UNPACKETIZE(name) \
214 pj_status_t(name)(ffmpeg_private *ff, const pj_uint8_t *payload, \
215 pj_size_t payload_len, pj_uint8_t *bits, \
216 pj_size_t bits_len, unsigned *bits_pos)
217
218#define FUNC_FMT_MATCH(name) \
219 pj_status_t(name)(pj_pool_t *pool, \
220 pjmedia_sdp_media *offer, unsigned o_fmt_idx, \
221 pjmedia_sdp_media *answer, unsigned a_fmt_idx, \
222 unsigned option)
223
224
225/* Type definition of codec specific functions */
226typedef FUNC_PACKETIZE(*func_packetize);
227typedef FUNC_UNPACKETIZE(*func_unpacketize);
228typedef pj_status_t (*func_preopen) (ffmpeg_private *ff);
229typedef pj_status_t (*func_postopen) (ffmpeg_private *ff);
230typedef FUNC_FMT_MATCH(*func_sdp_fmt_match);
231
232
233/* FFMPEG codec info */
234struct ffmpeg_codec_desc
235{
236 /* Predefined info */
237 pjmedia_vid_codec_info info;
238 pjmedia_format_id base_fmt_id; /**< Some codecs may be exactly
239 same or compatible with
240 another codec, base format
241 will tell the initializer
242 to copy this codec desc
243 from its base format */
244 pjmedia_rect_size size;
245 pjmedia_ratio fps;
246 pj_uint32_t avg_bps;
247 pj_uint32_t max_bps;
248 func_packetize packetize;
249 func_unpacketize unpacketize;
250 func_preopen preopen;
251 func_preopen postopen;
252 func_sdp_fmt_match sdp_fmt_match;
253 pjmedia_codec_fmtp dec_fmtp;
254
255 /* Init time defined info */
256 pj_bool_t enabled;
257 AVCodec *enc;
258 AVCodec *dec;
259};
260
261
262#if PJMEDIA_HAS_FFMPEG_CODEC_H264 && !LIBAVCODEC_VER_AT_LEAST(53,20)
263# error "Must use libavcodec version 53.20 or later to enable FFMPEG H264"
264#endif
265
266/* H264 constants */
267#define PROFILE_H264_BASELINE 66
268#define PROFILE_H264_MAIN 77
269
270/* Codec specific functions */
271#if PJMEDIA_HAS_FFMPEG_CODEC_H264
272static pj_status_t h264_preopen(ffmpeg_private *ff);
273static pj_status_t h264_postopen(ffmpeg_private *ff);
274static FUNC_PACKETIZE(h264_packetize);
275static FUNC_UNPACKETIZE(h264_unpacketize);
276#endif
277
278static pj_status_t h263_preopen(ffmpeg_private *ff);
279static FUNC_PACKETIZE(h263_packetize);
280static FUNC_UNPACKETIZE(h263_unpacketize);
281
282
283/* Internal codec info */
284static ffmpeg_codec_desc codec_desc[] =
285{
286#if PJMEDIA_HAS_FFMPEG_CODEC_H264
287 {
288 {PJMEDIA_FORMAT_H264, PJMEDIA_RTP_PT_H264, {"H264",4},
289 {"Constrained Baseline (level=30, pack=1)", 39}},
290 0,
291 {720, 480}, {15, 1}, 256000, 256000,
292 &h264_packetize, &h264_unpacketize, &h264_preopen, &h264_postopen,
293 &pjmedia_vid_codec_h264_match_sdp,
294 /* Leading space for better compatibility (strange indeed!) */
295 {2, { {{"profile-level-id",16}, {"42e01e",6}},
296 {{" packetization-mode",19}, {"1",1}}, } },
297 },
298#endif
299
300#if PJMEDIA_HAS_FFMPEG_CODEC_H263P
301 {
302 {PJMEDIA_FORMAT_H263P, PJMEDIA_RTP_PT_H263P, {"H263-1998",9}},
303 PJMEDIA_FORMAT_H263,
304 {352, 288}, {15, 1}, 256000, 256000,
305 &h263_packetize, &h263_unpacketize, &h263_preopen, NULL, NULL,
306 {2, { {{"CIF",3}, {"1",1}},
307 {{"QCIF",4}, {"1",1}}, } },
308 },
309#endif
310
311 {
312 {PJMEDIA_FORMAT_H263, PJMEDIA_RTP_PT_H263, {"H263",4}},
313 },
314 {
315 {PJMEDIA_FORMAT_H261, PJMEDIA_RTP_PT_H261, {"H261",4}},
316 },
317 {
318 {PJMEDIA_FORMAT_MJPEG, PJMEDIA_RTP_PT_JPEG, {"JPEG",4}},
319 PJMEDIA_FORMAT_MJPEG, {640, 480}, {25, 1},
320 },
321 {
322 {PJMEDIA_FORMAT_MPEG4, 0, {"MP4V",4}},
323 PJMEDIA_FORMAT_MPEG4, {640, 480}, {25, 1},
324 },
325};
326
327#if PJMEDIA_HAS_FFMPEG_CODEC_H264
328
329typedef struct h264_data
330{
331 pjmedia_vid_codec_h264_fmtp fmtp;
332 pjmedia_h264_packetizer *pktz;
333} h264_data;
334
335
336static pj_status_t h264_preopen(ffmpeg_private *ff)
337{
338 h264_data *data;
339 pjmedia_h264_packetizer_cfg pktz_cfg;
340 pj_status_t status;
341
342 data = PJ_POOL_ZALLOC_T(ff->pool, h264_data);
343 ff->data = data;
344
345 /* Parse remote fmtp */
346 status = pjmedia_vid_codec_h264_parse_fmtp(&ff->param.enc_fmtp,
347 &data->fmtp);
348 if (status != PJ_SUCCESS)
349 return status;
350
351 /* Create packetizer */
352 pktz_cfg.mtu = ff->param.enc_mtu;
353#if 0
354 if (data->fmtp.packetization_mode == 0)
355 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL;
356 else if (data->fmtp.packetization_mode == 1)
357 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED;
358 else
359 return PJ_ENOTSUP;
360#else
361 if (data->fmtp.packetization_mode!=
362 PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL &&
363 data->fmtp.packetization_mode!=
364 PJMEDIA_H264_PACKETIZER_MODE_NON_INTERLEAVED)
365 {
366 return PJ_ENOTSUP;
367 }
368 /* Better always send in single NAL mode for better compatibility */
369 pktz_cfg.mode = PJMEDIA_H264_PACKETIZER_MODE_SINGLE_NAL;
370#endif
371
372 status = pjmedia_h264_packetizer_create(ff->pool, &pktz_cfg, &data->pktz);
373 if (status != PJ_SUCCESS)
374 return status;
375
376 /* Apply SDP fmtp to format in codec param */
377 if (!ff->param.ignore_fmtp) {
378 status = pjmedia_vid_codec_h264_apply_fmtp(&ff->param);
379 if (status != PJ_SUCCESS)
380 return status;
381 }
382
383 if (ff->param.dir & PJMEDIA_DIR_ENCODING) {
384 pjmedia_video_format_detail *vfd;
385 AVCodecContext *ctx = ff->enc_ctx;
386 const char *profile = NULL;
387
388 vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt,
389 PJ_TRUE);
390
391 /* Override generic params after applying SDP fmtp */
392 ctx->width = vfd->size.w;
393 ctx->height = vfd->size.h;
394 ctx->time_base.num = vfd->fps.denum;
395 ctx->time_base.den = vfd->fps.num;
396
397 /* Apply profile. */
398 ctx->profile = data->fmtp.profile_idc;
399 switch (ctx->profile) {
400 case PROFILE_H264_BASELINE:
401 profile = "baseline";
402 break;
403 case PROFILE_H264_MAIN:
404 profile = "main";
405 break;
406 default:
407 break;
408 }
409 if (profile && !AV_OPT_SET(ctx->priv_data, "profile", profile, 0))
410 {
411 PJ_LOG(3, (THIS_FILE, "Failed to set H264 profile to '%s'",
412 profile));
413 }
414
415 /* Apply profile constraint bits. */
416 //PJ_TODO(set_h264_constraint_bits_properly_in_ffmpeg);
417 if (data->fmtp.profile_iop) {
418#if defined(FF_PROFILE_H264_CONSTRAINED)
419 ctx->profile |= FF_PROFILE_H264_CONSTRAINED;
420#endif
421 }
422
423 /* Apply profile level. */
424 ctx->level = data->fmtp.level;
425
426 /* Limit NAL unit size as we prefer single NAL unit packetization */
427 if (!AV_OPT_SET_INT(ctx->priv_data, "slice-max-size", ff->param.enc_mtu))
428 {
429 PJ_LOG(3, (THIS_FILE, "Failed to set H264 max NAL size to %d",
430 ff->param.enc_mtu));
431 }
432
433 /* Apply intra-refresh */
434 if (!AV_OPT_SET_INT(ctx->priv_data, "intra-refresh", 1))
435 {
436 PJ_LOG(3, (THIS_FILE, "Failed to set x264 intra-refresh"));
437 }
438
439 /* Misc x264 settings (performance, quality, latency, etc).
440 * Let's just use the x264 predefined preset & tune.
441 */
442 if (!AV_OPT_SET(ctx->priv_data, "preset", "veryfast", 0)) {
443 PJ_LOG(3, (THIS_FILE, "Failed to set x264 preset 'veryfast'"));
444 }
445 if (!AV_OPT_SET(ctx->priv_data, "tune", "animation+zerolatency", 0)) {
446 PJ_LOG(3, (THIS_FILE, "Failed to set x264 tune 'zerolatency'"));
447 }
448 }
449
450 if (ff->param.dir & PJMEDIA_DIR_DECODING) {
451 AVCodecContext *ctx = ff->dec_ctx;
452
453 /* Apply the "sprop-parameter-sets" fmtp from remote SDP to
454 * extradata of ffmpeg codec context.
455 */
456 if (data->fmtp.sprop_param_sets_len) {
457 ctx->extradata_size = (int)data->fmtp.sprop_param_sets_len;
458 ctx->extradata = data->fmtp.sprop_param_sets;
459 }
460 }
461
462 return PJ_SUCCESS;
463}
464
465static pj_status_t h264_postopen(ffmpeg_private *ff)
466{
467 h264_data *data = (h264_data*)ff->data;
468 PJ_UNUSED_ARG(data);
469 return PJ_SUCCESS;
470}
471
472static FUNC_PACKETIZE(h264_packetize)
473{
474 h264_data *data = (h264_data*)ff->data;
475 return pjmedia_h264_packetize(data->pktz, bits, bits_len, bits_pos,
476 payload, payload_len);
477}
478
479static FUNC_UNPACKETIZE(h264_unpacketize)
480{
481 h264_data *data = (h264_data*)ff->data;
482 return pjmedia_h264_unpacketize(data->pktz, payload, payload_len,
483 bits, bits_len, bits_pos);
484}
485
486#endif /* PJMEDIA_HAS_FFMPEG_CODEC_H264 */
487
488
489#if PJMEDIA_HAS_FFMPEG_CODEC_H263P
490
491typedef struct h263_data
492{
493 pjmedia_h263_packetizer *pktz;
494} h263_data;
495
496/* H263 pre-open */
497static pj_status_t h263_preopen(ffmpeg_private *ff)
498{
499 h263_data *data;
500 pjmedia_h263_packetizer_cfg pktz_cfg;
501 pj_status_t status;
502
503 data = PJ_POOL_ZALLOC_T(ff->pool, h263_data);
504 ff->data = data;
505
506 /* Create packetizer */
507 pktz_cfg.mtu = ff->param.enc_mtu;
508 pktz_cfg.mode = PJMEDIA_H263_PACKETIZER_MODE_RFC4629;
509 status = pjmedia_h263_packetizer_create(ff->pool, &pktz_cfg, &data->pktz);
510 if (status != PJ_SUCCESS)
511 return status;
512
513 /* Apply fmtp settings to codec param */
514 if (!ff->param.ignore_fmtp) {
515 status = pjmedia_vid_codec_h263_apply_fmtp(&ff->param);
516 }
517
518 /* Override generic params after applying SDP fmtp */
519 if (ff->param.dir & PJMEDIA_DIR_ENCODING) {
520 pjmedia_video_format_detail *vfd;
521 AVCodecContext *ctx = ff->enc_ctx;
522
523 vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt,
524 PJ_TRUE);
525
526 /* Override generic params after applying SDP fmtp */
527 ctx->width = vfd->size.w;
528 ctx->height = vfd->size.h;
529 ctx->time_base.num = vfd->fps.denum;
530 ctx->time_base.den = vfd->fps.num;
531 }
532
533 return status;
534}
535
536static FUNC_PACKETIZE(h263_packetize)
537{
538 h263_data *data = (h263_data*)ff->data;
539 return pjmedia_h263_packetize(data->pktz, bits, bits_len, bits_pos,
540 payload, payload_len);
541}
542
543static FUNC_UNPACKETIZE(h263_unpacketize)
544{
545 h263_data *data = (h263_data*)ff->data;
546 return pjmedia_h263_unpacketize(data->pktz, payload, payload_len,
547 bits, bits_len, bits_pos);
548}
549
550#endif /* PJMEDIA_HAS_FFMPEG_CODEC_H263P */
551
552
553static const ffmpeg_codec_desc* find_codec_desc_by_info(
554 const pjmedia_vid_codec_info *info)
555{
556 int i;
557
558 for (i=0; i<PJ_ARRAY_SIZE(codec_desc); ++i) {
559 ffmpeg_codec_desc *desc = &codec_desc[i];
560
561 if (desc->enabled &&
562 (desc->info.fmt_id == info->fmt_id) &&
563 ((desc->info.dir & info->dir) == info->dir) &&
564 (desc->info.pt == info->pt) &&
565 (desc->info.packings & info->packings))
566 {
567 return desc;
568 }
569 }
570
571 return NULL;
572}
573
574
575static int find_codec_idx_by_fmt_id(pjmedia_format_id fmt_id)
576{
577 int i;
578 for (i=0; i<PJ_ARRAY_SIZE(codec_desc); ++i) {
579 if (codec_desc[i].info.fmt_id == fmt_id)
580 return i;
581 }
582
583 return -1;
584}
585
586
587/*
588 * Initialize and register FFMPEG codec factory to pjmedia endpoint.
589 */
590PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_init(pjmedia_vid_codec_mgr *mgr,
591 pj_pool_factory *pf)
592{
593 pj_pool_t *pool;
594 AVCodec *c;
595 pj_status_t status;
596 unsigned i;
597
598 if (ffmpeg_factory.pool != NULL) {
599 /* Already initialized. */
600 return PJ_SUCCESS;
601 }
602
603 if (!mgr) mgr = pjmedia_vid_codec_mgr_instance();
604 PJ_ASSERT_RETURN(mgr, PJ_EINVAL);
605
606 /* Create FFMPEG codec factory. */
607 ffmpeg_factory.base.op = &ffmpeg_factory_op;
608 ffmpeg_factory.base.factory_data = NULL;
609 ffmpeg_factory.mgr = mgr;
610 ffmpeg_factory.pf = pf;
611
612 pool = pj_pool_create(pf, "ffmpeg codec factory", 256, 256, NULL);
613 if (!pool)
614 return PJ_ENOMEM;
615
616 /* Create mutex. */
617 status = pj_mutex_create_simple(pool, "ffmpeg codec factory",
618 &ffmpeg_factory.mutex);
619 if (status != PJ_SUCCESS)
620 goto on_error;
621
622 pjmedia_ffmpeg_add_ref();
623#if !LIBAVCODEC_VER_AT_LEAST(53,20)
624 /* avcodec_init() dissappeared between version 53.20 and 54.15, not sure
625 * exactly when
626 */
627 avcodec_init();
628#endif
629 avcodec_register_all();
630
631 /* Enum FFMPEG codecs */
632 for (c=av_codec_next(NULL); c; c=av_codec_next(c)) {
633 ffmpeg_codec_desc *desc;
634 pjmedia_format_id fmt_id;
635 int codec_info_idx;
636
637#if LIBAVCODEC_VERSION_MAJOR <= 52
638# define AVMEDIA_TYPE_VIDEO CODEC_TYPE_VIDEO
639#endif
640 if (c->type != AVMEDIA_TYPE_VIDEO)
641 continue;
642
643 /* Video encoder and decoder are usually implemented in separate
644 * AVCodec instances. While the codec attributes (e.g: raw formats,
645 * supported fps) are in the encoder.
646 */
647
648 //PJ_LOG(3, (THIS_FILE, "%s", c->name));
649 status = CodecID_to_pjmedia_format_id(c->id, &fmt_id);
650 /* Skip if format ID is unknown */
651 if (status != PJ_SUCCESS)
652 continue;
653
654 codec_info_idx = find_codec_idx_by_fmt_id(fmt_id);
655 /* Skip if codec is unwanted by this wrapper (not listed in
656 * the codec info array)
657 */
658 if (codec_info_idx < 0)
659 continue;
660
661 desc = &codec_desc[codec_info_idx];
662
663 /* Skip duplicated codec implementation */
664 if ((AVCODEC_HAS_ENCODE(c) && (desc->info.dir & PJMEDIA_DIR_ENCODING))
665 ||
666 (AVCODEC_HAS_DECODE(c) && (desc->info.dir & PJMEDIA_DIR_DECODING)))
667 {
668 continue;
669 }
670
671 /* Get raw/decoded format ids in the encoder */
672 if (c->pix_fmts && AVCODEC_HAS_ENCODE(c)) {
673 pjmedia_format_id raw_fmt[PJMEDIA_VID_CODEC_MAX_DEC_FMT_CNT];
674 unsigned raw_fmt_cnt = 0;
675 unsigned raw_fmt_cnt_should_be = 0;
676 const enum PixelFormat *p = c->pix_fmts;
677
678 for(;(p && *p != -1) &&
679 (raw_fmt_cnt < PJMEDIA_VID_CODEC_MAX_DEC_FMT_CNT);
680 ++p)
681 {
682 pjmedia_format_id fmt_id;
683
684 raw_fmt_cnt_should_be++;
685 status = PixelFormat_to_pjmedia_format_id(*p, &fmt_id);
686 if (status != PJ_SUCCESS) {
687 PJ_LOG(6, (THIS_FILE, "Unrecognized ffmpeg pixel "
688 "format %d", *p));
689 continue;
690 }
691
692 //raw_fmt[raw_fmt_cnt++] = fmt_id;
693 /* Disable some formats due to H.264 error:
694 * x264 [error]: baseline profile doesn't support 4:4:4
695 */
696 if (desc->info.pt != PJMEDIA_RTP_PT_H264 ||
697 fmt_id != PJMEDIA_FORMAT_RGB24)
698 {
699 raw_fmt[raw_fmt_cnt++] = fmt_id;
700 }
701 }
702
703 if (raw_fmt_cnt == 0) {
704 PJ_LOG(5, (THIS_FILE, "No recognized raw format "
705 "for codec [%s/%s], codec ignored",
706 c->name, c->long_name));
707 /* Skip this encoder */
708 continue;
709 }
710
711 if (raw_fmt_cnt < raw_fmt_cnt_should_be) {
712 PJ_LOG(6, (THIS_FILE, "Codec [%s/%s] have %d raw formats, "
713 "recognized only %d raw formats",
714 c->name, c->long_name,
715 raw_fmt_cnt_should_be, raw_fmt_cnt));
716 }
717
718 desc->info.dec_fmt_id_cnt = raw_fmt_cnt;
719 pj_memcpy(desc->info.dec_fmt_id, raw_fmt,
720 sizeof(raw_fmt[0])*raw_fmt_cnt);
721 }
722
723 /* Get supported framerates */
724 if (c->supported_framerates) {
725 const AVRational *fr = c->supported_framerates;
726 while ((fr->num != 0 || fr->den != 0) &&
727 desc->info.fps_cnt < PJMEDIA_VID_CODEC_MAX_FPS_CNT)
728 {
729 desc->info.fps[desc->info.fps_cnt].num = fr->num;
730 desc->info.fps[desc->info.fps_cnt].denum = fr->den;
731 ++desc->info.fps_cnt;
732 ++fr;
733 }
734 }
735
736 /* Get ffmpeg encoder instance */
737 if (AVCODEC_HAS_ENCODE(c) && !desc->enc) {
738 desc->info.dir |= PJMEDIA_DIR_ENCODING;
739 desc->enc = c;
740 }
741
742 /* Get ffmpeg decoder instance */
743 if (AVCODEC_HAS_DECODE(c) && !desc->dec) {
744 desc->info.dir |= PJMEDIA_DIR_DECODING;
745 desc->dec = c;
746 }
747
748 /* Enable this codec when any ffmpeg codec instance are recognized
749 * and the supported raw formats info has been collected.
750 */
751 if ((desc->dec || desc->enc) && desc->info.dec_fmt_id_cnt)
752 {
753 desc->enabled = PJ_TRUE;
754 }
755
756 /* Normalize default value of clock rate */
757 if (desc->info.clock_rate == 0)
758 desc->info.clock_rate = 90000;
759
760 /* Set supported packings */
761 desc->info.packings |= PJMEDIA_VID_PACKING_WHOLE;
762 if (desc->packetize && desc->unpacketize)
763 desc->info.packings |= PJMEDIA_VID_PACKING_PACKETS;
764
765 }
766
767 /* Review all codecs for applying base format, registering format match for
768 * SDP negotiation, etc.
769 */
770 for (i = 0; i < PJ_ARRAY_SIZE(codec_desc); ++i) {
771 ffmpeg_codec_desc *desc = &codec_desc[i];
772
773 /* Init encoder/decoder description from base format */
774 if (desc->base_fmt_id && (!desc->dec || !desc->enc)) {
775 ffmpeg_codec_desc *base_desc = NULL;
776 int base_desc_idx;
777 pjmedia_dir copied_dir = PJMEDIA_DIR_NONE;
778
779 base_desc_idx = find_codec_idx_by_fmt_id(desc->base_fmt_id);
780 if (base_desc_idx != -1)
781 base_desc = &codec_desc[base_desc_idx];
782 if (!base_desc || !base_desc->enabled)
783 continue;
784
785 /* Copy description from base codec */
786 if (!desc->info.dec_fmt_id_cnt) {
787 desc->info.dec_fmt_id_cnt = base_desc->info.dec_fmt_id_cnt;
788 pj_memcpy(desc->info.dec_fmt_id, base_desc->info.dec_fmt_id,
789 sizeof(pjmedia_format_id)*desc->info.dec_fmt_id_cnt);
790 }
791 if (!desc->info.fps_cnt) {
792 desc->info.fps_cnt = base_desc->info.fps_cnt;
793 pj_memcpy(desc->info.fps, base_desc->info.fps,
794 sizeof(desc->info.fps[0])*desc->info.fps_cnt);
795 }
796 if (!desc->info.clock_rate) {
797 desc->info.clock_rate = base_desc->info.clock_rate;
798 }
799 if (!desc->dec && base_desc->dec) {
800 copied_dir |= PJMEDIA_DIR_DECODING;
801 desc->dec = base_desc->dec;
802 }
803 if (!desc->enc && base_desc->enc) {
804 copied_dir |= PJMEDIA_DIR_ENCODING;
805 desc->enc = base_desc->enc;
806 }
807
808 desc->info.dir |= copied_dir;
809 desc->enabled = (desc->info.dir != PJMEDIA_DIR_NONE);
810
811 /* Set supported packings */
812 desc->info.packings |= PJMEDIA_VID_PACKING_WHOLE;
813 if (desc->packetize && desc->unpacketize)
814 desc->info.packings |= PJMEDIA_VID_PACKING_PACKETS;
815
816 if (copied_dir != PJMEDIA_DIR_NONE) {
817 const char *dir_name[] = {NULL, "encoder", "decoder", "codec"};
818 PJ_LOG(5, (THIS_FILE, "The %.*s %s is using base codec (%.*s)",
819 desc->info.encoding_name.slen,
820 desc->info.encoding_name.ptr,
821 dir_name[copied_dir],
822 base_desc->info.encoding_name.slen,
823 base_desc->info.encoding_name.ptr));
824 }
825 }
826
827 /* Registering format match for SDP negotiation */
828 if (desc->sdp_fmt_match) {
829 status = pjmedia_sdp_neg_register_fmt_match_cb(
830 &desc->info.encoding_name,
831 desc->sdp_fmt_match);
832 pj_assert(status == PJ_SUCCESS);
833 }
834
835 /* Print warning about missing encoder/decoder */
836 if (!desc->enc) {
837 PJ_LOG(4, (THIS_FILE, "Cannot find %.*s encoder in ffmpeg library",
838 desc->info.encoding_name.slen,
839 desc->info.encoding_name.ptr));
840 }
841 if (!desc->dec) {
842 PJ_LOG(4, (THIS_FILE, "Cannot find %.*s decoder in ffmpeg library",
843 desc->info.encoding_name.slen,
844 desc->info.encoding_name.ptr));
845 }
846 }
847
848 /* Register codec factory to codec manager. */
849 status = pjmedia_vid_codec_mgr_register_factory(mgr,
850 &ffmpeg_factory.base);
851 if (status != PJ_SUCCESS)
852 goto on_error;
853
854 ffmpeg_factory.pool = pool;
855
856 /* Done. */
857 return PJ_SUCCESS;
858
859on_error:
860 pj_pool_release(pool);
861 return status;
862}
863
864/*
865 * Unregister FFMPEG codecs factory from pjmedia endpoint.
866 */
867PJ_DEF(pj_status_t) pjmedia_codec_ffmpeg_vid_deinit(void)
868{
869 pj_status_t status = PJ_SUCCESS;
870
871 if (ffmpeg_factory.pool == NULL) {
872 /* Already deinitialized */
873 return PJ_SUCCESS;
874 }
875
876 pj_mutex_lock(ffmpeg_factory.mutex);
877
878 /* Unregister FFMPEG codecs factory. */
879 status = pjmedia_vid_codec_mgr_unregister_factory(ffmpeg_factory.mgr,
880 &ffmpeg_factory.base);
881
882 /* Destroy mutex. */
883 pj_mutex_destroy(ffmpeg_factory.mutex);
884
885 /* Destroy pool. */
886 pj_pool_release(ffmpeg_factory.pool);
887 ffmpeg_factory.pool = NULL;
888
889 pjmedia_ffmpeg_dec_ref();
890
891 return status;
892}
893
894
895/*
896 * Check if factory can allocate the specified codec.
897 */
898static pj_status_t ffmpeg_test_alloc( pjmedia_vid_codec_factory *factory,
899 const pjmedia_vid_codec_info *info )
900{
901 const ffmpeg_codec_desc *desc;
902
903 PJ_ASSERT_RETURN(factory==&ffmpeg_factory.base, PJ_EINVAL);
904 PJ_ASSERT_RETURN(info, PJ_EINVAL);
905
906 desc = find_codec_desc_by_info(info);
907 if (!desc) {
908 return PJMEDIA_CODEC_EUNSUP;
909 }
910
911 return PJ_SUCCESS;
912}
913
914/*
915 * Generate default attribute.
916 */
917static pj_status_t ffmpeg_default_attr( pjmedia_vid_codec_factory *factory,
918 const pjmedia_vid_codec_info *info,
919 pjmedia_vid_codec_param *attr )
920{
921 const ffmpeg_codec_desc *desc;
922 unsigned i;
923
924 PJ_ASSERT_RETURN(factory==&ffmpeg_factory.base, PJ_EINVAL);
925 PJ_ASSERT_RETURN(info && attr, PJ_EINVAL);
926
927 desc = find_codec_desc_by_info(info);
928 if (!desc) {
929 return PJMEDIA_CODEC_EUNSUP;
930 }
931
932 pj_bzero(attr, sizeof(pjmedia_vid_codec_param));
933
934 /* Scan the requested packings and use the lowest number */
935 attr->packing = 0;
936 for (i=0; i<15; ++i) {
937 unsigned packing = (1 << i);
938 if ((desc->info.packings & info->packings) & packing) {
939 attr->packing = (pjmedia_vid_packing)packing;
940 break;
941 }
942 }
943 if (attr->packing == 0) {
944 /* No supported packing in info */
945 return PJMEDIA_CODEC_EUNSUP;
946 }
947
948 /* Direction */
949 attr->dir = desc->info.dir;
950
951 /* Encoded format */
952 pjmedia_format_init_video(&attr->enc_fmt, desc->info.fmt_id,
953 desc->size.w, desc->size.h,
954 desc->fps.num, desc->fps.denum);
955
956 /* Decoded format */
957 pjmedia_format_init_video(&attr->dec_fmt, desc->info.dec_fmt_id[0],
958 desc->size.w, desc->size.h,
959 desc->fps.num, desc->fps.denum);
960
961 /* Decoding fmtp */
962 attr->dec_fmtp = desc->dec_fmtp;
963
964 /* Bitrate */
965 attr->enc_fmt.det.vid.avg_bps = desc->avg_bps;
966 attr->enc_fmt.det.vid.max_bps = desc->max_bps;
967
968 /* Encoding MTU */
969 attr->enc_mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE;
970
971 return PJ_SUCCESS;
972}
973
974/*
975 * Enum codecs supported by this factory.
976 */
977static pj_status_t ffmpeg_enum_codecs( pjmedia_vid_codec_factory *factory,
978 unsigned *count,
979 pjmedia_vid_codec_info codecs[])
980{
981 unsigned i, max_cnt;
982
983 PJ_ASSERT_RETURN(codecs && *count > 0, PJ_EINVAL);
984 PJ_ASSERT_RETURN(factory == &ffmpeg_factory.base, PJ_EINVAL);
985
986 max_cnt = PJ_MIN(*count, PJ_ARRAY_SIZE(codec_desc));
987 *count = 0;
988
989 for (i=0; i<max_cnt; ++i) {
990 if (codec_desc[i].enabled) {
991 pj_memcpy(&codecs[*count], &codec_desc[i].info,
992 sizeof(pjmedia_vid_codec_info));
993 (*count)++;
994 }
995 }
996
997 return PJ_SUCCESS;
998}
999
1000/*
1001 * Allocate a new codec instance.
1002 */
1003static pj_status_t ffmpeg_alloc_codec( pjmedia_vid_codec_factory *factory,
1004 const pjmedia_vid_codec_info *info,
1005 pjmedia_vid_codec **p_codec)
1006{
1007 ffmpeg_private *ff;
1008 const ffmpeg_codec_desc *desc;
1009 pjmedia_vid_codec *codec;
1010 pj_pool_t *pool = NULL;
1011 pj_status_t status = PJ_SUCCESS;
1012
1013 PJ_ASSERT_RETURN(factory && info && p_codec, PJ_EINVAL);
1014 PJ_ASSERT_RETURN(factory == &ffmpeg_factory.base, PJ_EINVAL);
1015
1016 desc = find_codec_desc_by_info(info);
1017 if (!desc) {
1018 return PJMEDIA_CODEC_EUNSUP;
1019 }
1020
1021 /* Create pool for codec instance */
1022 pool = pj_pool_create(ffmpeg_factory.pf, "ffmpeg codec", 512, 512, NULL);
1023 codec = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_codec);
1024 if (!codec) {
1025 status = PJ_ENOMEM;
1026 goto on_error;
1027 }
1028 codec->op = &ffmpeg_op;
1029 codec->factory = factory;
1030 ff = PJ_POOL_ZALLOC_T(pool, ffmpeg_private);
1031 if (!ff) {
1032 status = PJ_ENOMEM;
1033 goto on_error;
1034 }
1035 codec->codec_data = ff;
1036 ff->pool = pool;
1037 ff->enc = desc->enc;
1038 ff->dec = desc->dec;
1039 ff->desc = desc;
1040
1041 *p_codec = codec;
1042 return PJ_SUCCESS;
1043
1044on_error:
1045 if (pool)
1046 pj_pool_release(pool);
1047 return status;
1048}
1049
1050/*
1051 * Free codec.
1052 */
1053static pj_status_t ffmpeg_dealloc_codec( pjmedia_vid_codec_factory *factory,
1054 pjmedia_vid_codec *codec )
1055{
1056 ffmpeg_private *ff;
1057 pj_pool_t *pool;
1058
1059 PJ_ASSERT_RETURN(factory && codec, PJ_EINVAL);
1060 PJ_ASSERT_RETURN(factory == &ffmpeg_factory.base, PJ_EINVAL);
1061
1062 /* Close codec, if it's not closed. */
1063 ff = (ffmpeg_private*) codec->codec_data;
1064 pool = ff->pool;
1065 codec->codec_data = NULL;
1066 pj_pool_release(pool);
1067
1068 return PJ_SUCCESS;
1069}
1070
1071/*
1072 * Init codec.
1073 */
1074static pj_status_t ffmpeg_codec_init( pjmedia_vid_codec *codec,
1075 pj_pool_t *pool )
1076{
1077 PJ_UNUSED_ARG(codec);
1078 PJ_UNUSED_ARG(pool);
1079 return PJ_SUCCESS;
1080}
1081
1082static void print_ffmpeg_err(int err)
1083{
1084#if LIBAVCODEC_VER_AT_LEAST(52,72)
1085 char errbuf[512];
1086 if (av_strerror(err, errbuf, sizeof(errbuf)) >= 0)
1087 PJ_LOG(5, (THIS_FILE, "ffmpeg err %d: %s", err, errbuf));
1088#else
1089 PJ_LOG(5, (THIS_FILE, "ffmpeg err %d", err));
1090#endif
1091
1092}
1093
1094static pj_status_t open_ffmpeg_codec(ffmpeg_private *ff,
1095 pj_mutex_t *ff_mutex)
1096{
1097 enum PixelFormat pix_fmt;
1098 pjmedia_video_format_detail *vfd;
1099 pj_bool_t enc_opened = PJ_FALSE, dec_opened = PJ_FALSE;
1100 pj_status_t status;
1101
1102 /* Get decoded pixel format */
1103 status = pjmedia_format_id_to_PixelFormat(ff->param.dec_fmt.id,
1104 &pix_fmt);
1105 if (status != PJ_SUCCESS)
1106 return status;
1107 ff->expected_dec_fmt = pix_fmt;
1108
1109 /* Get video format detail for shortcut access to encoded format */
1110 vfd = pjmedia_format_get_video_format_detail(&ff->param.enc_fmt,
1111 PJ_TRUE);
1112
1113 /* Allocate ffmpeg codec context */
1114 if (ff->param.dir & PJMEDIA_DIR_ENCODING) {
1115#if LIBAVCODEC_VER_AT_LEAST(53,20)
1116 ff->enc_ctx = avcodec_alloc_context3(ff->enc);
1117#else
1118 ff->enc_ctx = avcodec_alloc_context();
1119#endif
1120 if (ff->enc_ctx == NULL)
1121 goto on_error;
1122 }
1123 if (ff->param.dir & PJMEDIA_DIR_DECODING) {
1124#if LIBAVCODEC_VER_AT_LEAST(53,20)
1125 ff->dec_ctx = avcodec_alloc_context3(ff->dec);
1126#else
1127 ff->dec_ctx = avcodec_alloc_context();
1128#endif
1129 if (ff->dec_ctx == NULL)
1130 goto on_error;
1131 }
1132
1133 /* Init generic encoder params */
1134 if (ff->param.dir & PJMEDIA_DIR_ENCODING) {
1135 AVCodecContext *ctx = ff->enc_ctx;
1136
1137 ctx->pix_fmt = pix_fmt;
1138 ctx->width = vfd->size.w;
1139 ctx->height = vfd->size.h;
1140 ctx->time_base.num = vfd->fps.denum;
1141 ctx->time_base.den = vfd->fps.num;
1142 if (vfd->avg_bps) {
1143 ctx->bit_rate = vfd->avg_bps;
1144 if (vfd->max_bps > vfd->avg_bps)
1145 ctx->bit_rate_tolerance = vfd->max_bps - vfd->avg_bps;
1146 }
1147 ctx->strict_std_compliance = FF_COMPLIANCE_STRICT;
1148 ctx->workaround_bugs = FF_BUG_AUTODETECT;
1149 ctx->opaque = ff;
1150
1151 /* Set no delay, note that this may cause some codec functionals
1152 * not working (e.g: rate control).
1153 */
1154#if LIBAVCODEC_VER_AT_LEAST(52,113) && !LIBAVCODEC_VER_AT_LEAST(53,20)
1155 ctx->rc_lookahead = 0;
1156#endif
1157 }
1158
1159 /* Init generic decoder params */
1160 if (ff->param.dir & PJMEDIA_DIR_DECODING) {
1161 AVCodecContext *ctx = ff->dec_ctx;
1162
1163 /* Width/height may be overriden by ffmpeg after first decoding. */
1164 ctx->width = ctx->coded_width = ff->param.dec_fmt.det.vid.size.w;
1165 ctx->height = ctx->coded_height = ff->param.dec_fmt.det.vid.size.h;
1166 ctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
1167 ctx->workaround_bugs = FF_BUG_AUTODETECT;
1168 ctx->opaque = ff;
1169 }
1170
1171 /* Override generic params or apply specific params before opening
1172 * the codec.
1173 */
1174 if (ff->desc->preopen) {
1175 status = (*ff->desc->preopen)(ff);
1176 if (status != PJ_SUCCESS)
1177 goto on_error;
1178 }
1179
1180 /* Open encoder */
1181 if (ff->param.dir & PJMEDIA_DIR_ENCODING) {
1182 int err;
1183
1184 pj_mutex_lock(ff_mutex);
1185 err = AVCODEC_OPEN(ff->enc_ctx, ff->enc);
1186 pj_mutex_unlock(ff_mutex);
1187 if (err < 0) {
1188 print_ffmpeg_err(err);
1189 status = PJMEDIA_CODEC_EFAILED;
1190 goto on_error;
1191 }
1192 enc_opened = PJ_TRUE;
1193 }
1194
1195 /* Open decoder */
1196 if (ff->param.dir & PJMEDIA_DIR_DECODING) {
1197 int err;
1198
1199 pj_mutex_lock(ff_mutex);
1200 err = AVCODEC_OPEN(ff->dec_ctx, ff->dec);
1201 pj_mutex_unlock(ff_mutex);
1202 if (err < 0) {
1203 print_ffmpeg_err(err);
1204 status = PJMEDIA_CODEC_EFAILED;
1205 goto on_error;
1206 }
1207 dec_opened = PJ_TRUE;
1208 }
1209
1210 /* Let the codec apply specific params after the codec opened */
1211 if (ff->desc->postopen) {
1212 status = (*ff->desc->postopen)(ff);
1213 if (status != PJ_SUCCESS)
1214 goto on_error;
1215 }
1216
1217 return PJ_SUCCESS;
1218
1219on_error:
1220 if (ff->enc_ctx) {
1221 if (enc_opened)
1222 avcodec_close(ff->enc_ctx);
1223 av_free(ff->enc_ctx);
1224 ff->enc_ctx = NULL;
1225 }
1226 if (ff->dec_ctx) {
1227 if (dec_opened)
1228 avcodec_close(ff->dec_ctx);
1229 av_free(ff->dec_ctx);
1230 ff->dec_ctx = NULL;
1231 }
1232 return status;
1233}
1234
1235/*
1236 * Open codec.
1237 */
1238static pj_status_t ffmpeg_codec_open( pjmedia_vid_codec *codec,
1239 pjmedia_vid_codec_param *attr )
1240{
1241 ffmpeg_private *ff;
1242 pj_status_t status;
1243 pj_mutex_t *ff_mutex;
1244
1245 PJ_ASSERT_RETURN(codec && attr, PJ_EINVAL);
1246 ff = (ffmpeg_private*)codec->codec_data;
1247
1248 pj_memcpy(&ff->param, attr, sizeof(*attr));
1249
1250 /* Normalize encoding MTU in codec param */
1251 if (attr->enc_mtu > PJMEDIA_MAX_VID_PAYLOAD_SIZE)
1252 attr->enc_mtu = PJMEDIA_MAX_VID_PAYLOAD_SIZE;
1253
1254 /* Open the codec */
1255 ff_mutex = ((struct ffmpeg_factory*)codec->factory)->mutex;
1256 status = open_ffmpeg_codec(ff, ff_mutex);
1257 if (status != PJ_SUCCESS)
1258 goto on_error;
1259
1260 /* Init format info and apply-param of decoder */
1261 ff->dec_vfi = pjmedia_get_video_format_info(NULL, ff->param.dec_fmt.id);
1262 if (!ff->dec_vfi) {
1263 status = PJ_EINVAL;
1264 goto on_error;
1265 }
1266 pj_bzero(&ff->dec_vafp, sizeof(ff->dec_vafp));
1267 ff->dec_vafp.size = ff->param.dec_fmt.det.vid.size;
1268 ff->dec_vafp.buffer = NULL;
1269 status = (*ff->dec_vfi->apply_fmt)(ff->dec_vfi, &ff->dec_vafp);
1270 if (status != PJ_SUCCESS) {
1271 goto on_error;
1272 }
1273
1274 /* Init format info and apply-param of encoder */
1275 ff->enc_vfi = pjmedia_get_video_format_info(NULL, ff->param.dec_fmt.id);
1276 if (!ff->enc_vfi) {
1277 status = PJ_EINVAL;
1278 goto on_error;
1279 }
1280 pj_bzero(&ff->enc_vafp, sizeof(ff->enc_vafp));
1281 ff->enc_vafp.size = ff->param.enc_fmt.det.vid.size;
1282 ff->enc_vafp.buffer = NULL;
1283 status = (*ff->enc_vfi->apply_fmt)(ff->enc_vfi, &ff->enc_vafp);
1284 if (status != PJ_SUCCESS) {
1285 goto on_error;
1286 }
1287
1288 /* Alloc buffers if needed */
1289 ff->whole = (ff->param.packing == PJMEDIA_VID_PACKING_WHOLE);
1290 if (!ff->whole) {
1291 ff->enc_buf_size = (unsigned)ff->enc_vafp.framebytes;
1292 ff->enc_buf = pj_pool_alloc(ff->pool, ff->enc_buf_size);
1293
1294 ff->dec_buf_size = (unsigned)ff->dec_vafp.framebytes;
1295 ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size);
1296 }
1297
1298 /* Update codec attributes, e.g: encoding format may be changed by
1299 * SDP fmtp negotiation.
1300 */
1301 pj_memcpy(attr, &ff->param, sizeof(*attr));
1302
1303 return PJ_SUCCESS;
1304
1305on_error:
1306 ffmpeg_codec_close(codec);
1307 return status;
1308}
1309
1310/*
1311 * Close codec.
1312 */
1313static pj_status_t ffmpeg_codec_close( pjmedia_vid_codec *codec )
1314{
1315 ffmpeg_private *ff;
1316 pj_mutex_t *ff_mutex;
1317
1318 PJ_ASSERT_RETURN(codec, PJ_EINVAL);
1319 ff = (ffmpeg_private*)codec->codec_data;
1320 ff_mutex = ((struct ffmpeg_factory*)codec->factory)->mutex;
1321
1322 pj_mutex_lock(ff_mutex);
1323 if (ff->enc_ctx) {
1324 avcodec_close(ff->enc_ctx);
1325 av_free(ff->enc_ctx);
1326 }
1327 if (ff->dec_ctx && ff->dec_ctx!=ff->enc_ctx) {
1328 avcodec_close(ff->dec_ctx);
1329 av_free(ff->dec_ctx);
1330 }
1331 ff->enc_ctx = NULL;
1332 ff->dec_ctx = NULL;
1333 pj_mutex_unlock(ff_mutex);
1334
1335 return PJ_SUCCESS;
1336}
1337
1338
1339/*
1340 * Modify codec settings.
1341 */
1342static pj_status_t ffmpeg_codec_modify( pjmedia_vid_codec *codec,
1343 const pjmedia_vid_codec_param *attr)
1344{
1345 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1346
1347 PJ_UNUSED_ARG(attr);
1348 PJ_UNUSED_ARG(ff);
1349
1350 return PJ_ENOTSUP;
1351}
1352
1353static pj_status_t ffmpeg_codec_get_param(pjmedia_vid_codec *codec,
1354 pjmedia_vid_codec_param *param)
1355{
1356 ffmpeg_private *ff;
1357
1358 PJ_ASSERT_RETURN(codec && param, PJ_EINVAL);
1359
1360 ff = (ffmpeg_private*)codec->codec_data;
1361 pj_memcpy(param, &ff->param, sizeof(*param));
1362
1363 return PJ_SUCCESS;
1364}
1365
1366
1367static pj_status_t ffmpeg_packetize ( pjmedia_vid_codec *codec,
1368 pj_uint8_t *bits,
1369 pj_size_t bits_len,
1370 unsigned *bits_pos,
1371 const pj_uint8_t **payload,
1372 pj_size_t *payload_len)
1373{
1374 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1375
1376 if (ff->desc->packetize) {
1377 return (*ff->desc->packetize)(ff, bits, bits_len, bits_pos,
1378 payload, payload_len);
1379 }
1380
1381 return PJ_ENOTSUP;
1382}
1383
1384static pj_status_t ffmpeg_unpacketize(pjmedia_vid_codec *codec,
1385 const pj_uint8_t *payload,
1386 pj_size_t payload_len,
1387 pj_uint8_t *bits,
1388 pj_size_t bits_len,
1389 unsigned *bits_pos)
1390{
1391 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1392
1393 if (ff->desc->unpacketize) {
1394 return (*ff->desc->unpacketize)(ff, payload, payload_len,
1395 bits, bits_len, bits_pos);
1396 }
1397
1398 return PJ_ENOTSUP;
1399}
1400
1401
1402/*
1403 * Encode frames.
1404 */
1405static pj_status_t ffmpeg_codec_encode_whole(pjmedia_vid_codec *codec,
1406 const pjmedia_vid_encode_opt *opt,
1407 const pjmedia_frame *input,
1408 unsigned output_buf_len,
1409 pjmedia_frame *output)
1410{
1411 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1412 pj_uint8_t *p = (pj_uint8_t*)input->buf;
1413 AVFrame avframe;
1414 AVPacket avpacket;
1415 int err, got_packet;
1416 //AVRational src_timebase;
1417 /* For some reasons (e.g: SSE/MMX usage), the avcodec_encode_video() must
1418 * have stack aligned to 16 bytes. Let's try to be safe by preparing the
1419 * 16-bytes aligned stack here, in case it's not managed by the ffmpeg.
1420 */
1421 PJ_ALIGN_DATA(pj_uint32_t i[4], 16);
1422
1423 if ((long)(pj_ssize_t)i & 0xF) {
1424 PJ_LOG(2,(THIS_FILE, "Stack alignment fails"));
1425 }
1426
1427 /* Check if encoder has been opened */
1428 PJ_ASSERT_RETURN(ff->enc_ctx, PJ_EINVALIDOP);
1429
1430 avcodec_get_frame_defaults(&avframe);
1431
1432 // Let ffmpeg manage the timestamps
1433 /*
1434 src_timebase.num = 1;
1435 src_timebase.den = ff->desc->info.clock_rate;
1436 avframe.pts = av_rescale_q(input->timestamp.u64, src_timebase,
1437 ff->enc_ctx->time_base);
1438 */
1439
1440 for (i[0] = 0; i[0] < ff->enc_vfi->plane_cnt; ++i[0]) {
1441 avframe.data[i[0]] = p;
1442 avframe.linesize[i[0]] = ff->enc_vafp.strides[i[0]];
1443 p += ff->enc_vafp.plane_bytes[i[0]];
1444 }
1445
1446 /* Force keyframe */
1447 if (opt && opt->force_keyframe) {
1448#if LIBAVCODEC_VER_AT_LEAST(53,20)
1449 avframe.pict_type = AV_PICTURE_TYPE_I;
1450#else
1451 avframe.pict_type = FF_I_TYPE;
1452#endif
1453 }
1454
1455 av_init_packet(&avpacket);
1456 avpacket.data = (pj_uint8_t*)output->buf;
1457 avpacket.size = output_buf_len;
1458
1459#if LIBAVCODEC_VER_AT_LEAST(54,15)
1460 err = avcodec_encode_video2(ff->enc_ctx, &avpacket, &avframe, &got_packet);
1461 if (!err && got_packet)
1462 err = avpacket.size;
1463#else
1464 PJ_UNUSED_ARG(got_packet);
1465 err = avcodec_encode_video(ff->enc_ctx, avpacket.data, avpacket.size, &avframe);
1466#endif
1467
1468 if (err < 0) {
1469 print_ffmpeg_err(err);
1470 return PJMEDIA_CODEC_EFAILED;
1471 } else {
1472 output->size = err;
1473 output->bit_info = 0;
1474 if (ff->enc_ctx->coded_frame->key_frame)
1475 output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME;
1476 }
1477
1478 return PJ_SUCCESS;
1479}
1480
1481static pj_status_t ffmpeg_codec_encode_begin(pjmedia_vid_codec *codec,
1482 const pjmedia_vid_encode_opt *opt,
1483 const pjmedia_frame *input,
1484 unsigned out_size,
1485 pjmedia_frame *output,
1486 pj_bool_t *has_more)
1487{
1488 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1489 pj_status_t status;
1490
1491 *has_more = PJ_FALSE;
1492
1493 if (ff->whole) {
1494 status = ffmpeg_codec_encode_whole(codec, opt, input, out_size,
1495 output);
1496 } else {
1497 pjmedia_frame whole_frm;
1498 const pj_uint8_t *payload;
1499 pj_size_t payload_len;
1500
1501 pj_bzero(&whole_frm, sizeof(whole_frm));
1502 whole_frm.buf = ff->enc_buf;
1503 whole_frm.size = ff->enc_buf_size;
1504 status = ffmpeg_codec_encode_whole(codec, opt, input,
1505 (unsigned)whole_frm.size,
1506 &whole_frm);
1507 if (status != PJ_SUCCESS)
1508 return status;
1509
1510 ff->enc_buf_is_keyframe = (whole_frm.bit_info &
1511 PJMEDIA_VID_FRM_KEYFRAME);
1512 ff->enc_frame_len = (unsigned)whole_frm.size;
1513 ff->enc_processed = 0;
1514 status = ffmpeg_packetize(codec, (pj_uint8_t*)whole_frm.buf,
1515 whole_frm.size, &ff->enc_processed,
1516 &payload, &payload_len);
1517 if (status != PJ_SUCCESS)
1518 return status;
1519
1520 if (out_size < payload_len)
1521 return PJMEDIA_CODEC_EFRMTOOSHORT;
1522
1523 output->type = PJMEDIA_FRAME_TYPE_VIDEO;
1524 pj_memcpy(output->buf, payload, payload_len);
1525 output->size = payload_len;
1526
1527 if (ff->enc_buf_is_keyframe)
1528 output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME;
1529
1530 *has_more = (ff->enc_processed < ff->enc_frame_len);
1531 }
1532
1533 return status;
1534}
1535
1536static pj_status_t ffmpeg_codec_encode_more(pjmedia_vid_codec *codec,
1537 unsigned out_size,
1538 pjmedia_frame *output,
1539 pj_bool_t *has_more)
1540{
1541 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1542 const pj_uint8_t *payload;
1543 pj_size_t payload_len;
1544 pj_status_t status;
1545
1546 *has_more = PJ_FALSE;
1547
1548 if (ff->enc_processed >= ff->enc_frame_len) {
1549 /* No more frame */
1550 return PJ_EEOF;
1551 }
1552
1553 status = ffmpeg_packetize(codec, (pj_uint8_t*)ff->enc_buf,
1554 ff->enc_frame_len, &ff->enc_processed,
1555 &payload, &payload_len);
1556 if (status != PJ_SUCCESS)
1557 return status;
1558
1559 if (out_size < payload_len)
1560 return PJMEDIA_CODEC_EFRMTOOSHORT;
1561
1562 output->type = PJMEDIA_FRAME_TYPE_VIDEO;
1563 pj_memcpy(output->buf, payload, payload_len);
1564 output->size = payload_len;
1565
1566 if (ff->enc_buf_is_keyframe)
1567 output->bit_info |= PJMEDIA_VID_FRM_KEYFRAME;
1568
1569 *has_more = (ff->enc_processed < ff->enc_frame_len);
1570
1571 return PJ_SUCCESS;
1572}
1573
1574
1575static pj_status_t check_decode_result(pjmedia_vid_codec *codec,
1576 const pj_timestamp *ts,
1577 pj_bool_t got_keyframe)
1578{
1579 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1580 pjmedia_video_apply_fmt_param *vafp = &ff->dec_vafp;
1581 pjmedia_event event;
1582
1583 /* Check for format change.
1584 * Decoder output format is set by libavcodec, in case it is different
1585 * to the configured param.
1586 */
1587 if (ff->dec_ctx->pix_fmt != ff->expected_dec_fmt ||
1588 ff->dec_ctx->width != (int)vafp->size.w ||
1589 ff->dec_ctx->height != (int)vafp->size.h)
1590 {
1591 pjmedia_format_id new_fmt_id;
1592 pj_status_t status;
1593
1594 /* Get current raw format id from ffmpeg decoder context */
1595 status = PixelFormat_to_pjmedia_format_id(ff->dec_ctx->pix_fmt,
1596 &new_fmt_id);
1597 if (status != PJ_SUCCESS)
1598 return status;
1599
1600 /* Update decoder format in param */
1601 ff->param.dec_fmt.id = new_fmt_id;
1602 ff->param.dec_fmt.det.vid.size.w = ff->dec_ctx->width;
1603 ff->param.dec_fmt.det.vid.size.h = ff->dec_ctx->height;
1604 ff->expected_dec_fmt = ff->dec_ctx->pix_fmt;
1605
1606 /* Re-init format info and apply-param of decoder */
1607 ff->dec_vfi = pjmedia_get_video_format_info(NULL, ff->param.dec_fmt.id);
1608 if (!ff->dec_vfi)
1609 return PJ_ENOTSUP;
1610 pj_bzero(&ff->dec_vafp, sizeof(ff->dec_vafp));
1611 ff->dec_vafp.size = ff->param.dec_fmt.det.vid.size;
1612 ff->dec_vafp.buffer = NULL;
1613 status = (*ff->dec_vfi->apply_fmt)(ff->dec_vfi, &ff->dec_vafp);
1614 if (status != PJ_SUCCESS)
1615 return status;
1616
1617 /* Realloc buffer if necessary */
1618 if (ff->dec_vafp.framebytes > ff->dec_buf_size) {
1619 PJ_LOG(5,(THIS_FILE, "Reallocating decoding buffer %u --> %u",
1620 (unsigned)ff->dec_buf_size,
1621 (unsigned)ff->dec_vafp.framebytes));
1622 ff->dec_buf_size = (unsigned)ff->dec_vafp.framebytes;
1623 ff->dec_buf = pj_pool_alloc(ff->pool, ff->dec_buf_size);
1624 }
1625
1626 /* Broadcast format changed event */
1627 pjmedia_event_init(&event, PJMEDIA_EVENT_FMT_CHANGED, ts, codec);
1628 event.data.fmt_changed.dir = PJMEDIA_DIR_DECODING;
1629 pj_memcpy(&event.data.fmt_changed.new_fmt, &ff->param.dec_fmt,
1630 sizeof(ff->param.dec_fmt));
1631 pjmedia_event_publish(NULL, codec, &event, 0);
1632 }
1633
1634 /* Check for missing/found keyframe */
1635 if (got_keyframe) {
1636 pj_get_timestamp(&ff->last_dec_keyframe_ts);
1637
1638 /* Broadcast keyframe event */
1639 pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_FOUND, ts, codec);
1640 pjmedia_event_publish(NULL, codec, &event, 0);
1641 } else if (ff->last_dec_keyframe_ts.u64 == 0) {
1642 /* Broadcast missing keyframe event */
1643 pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING, ts, codec);
1644 pjmedia_event_publish(NULL, codec, &event, 0);
1645 }
1646
1647 return PJ_SUCCESS;
1648}
1649
1650/*
1651 * Decode frame.
1652 */
1653static pj_status_t ffmpeg_codec_decode_whole(pjmedia_vid_codec *codec,
1654 const pjmedia_frame *input,
1655 unsigned output_buf_len,
1656 pjmedia_frame *output)
1657{
1658 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1659 AVFrame avframe;
1660 AVPacket avpacket;
1661 int err, got_picture;
1662
1663 /* Check if decoder has been opened */
1664 PJ_ASSERT_RETURN(ff->dec_ctx, PJ_EINVALIDOP);
1665
1666 /* Reset output frame bit info */
1667 output->bit_info = 0;
1668
1669 /* Validate output buffer size */
1670 // Do this validation later after getting decoding result, where the real
1671 // decoded size will be assured.
1672 //if (ff->dec_vafp.framebytes > output_buf_len)
1673 //return PJ_ETOOSMALL;
1674
1675 /* Init frame to receive the decoded data, the ffmpeg codec context will
1676 * automatically provide the decoded buffer (single buffer used for the
1677 * whole decoding session, and seems to be freed when the codec context
1678 * closed).
1679 */
1680 avcodec_get_frame_defaults(&avframe);
1681
1682 /* Init packet, the container of the encoded data */
1683 av_init_packet(&avpacket);
1684 avpacket.data = (pj_uint8_t*)input->buf;
1685 avpacket.size = (int)input->size;
1686
1687 /* ffmpeg warns:
1688 * - input buffer padding, at least FF_INPUT_BUFFER_PADDING_SIZE
1689 * - null terminated
1690 * Normally, encoded buffer is allocated more than needed, so lets just
1691 * bzero the input buffer end/pad, hope it will be just fine.
1692 */
1693 pj_bzero(avpacket.data+avpacket.size, FF_INPUT_BUFFER_PADDING_SIZE);
1694
1695 output->bit_info = 0;
1696 output->timestamp = input->timestamp;
1697
1698#if LIBAVCODEC_VER_AT_LEAST(52,72)
1699 //avpacket.flags = AV_PKT_FLAG_KEY;
1700#else
1701 avpacket.flags = 0;
1702#endif
1703
1704#if LIBAVCODEC_VER_AT_LEAST(52,72)
1705 err = avcodec_decode_video2(ff->dec_ctx, &avframe,
1706 &got_picture, &avpacket);
1707#else
1708 err = avcodec_decode_video(ff->dec_ctx, &avframe,
1709 &got_picture, avpacket.data, avpacket.size);
1710#endif
1711 if (err < 0) {
1712 pjmedia_event event;
1713
1714 output->type = PJMEDIA_FRAME_TYPE_NONE;
1715 output->size = 0;
1716 print_ffmpeg_err(err);
1717
1718 /* Broadcast missing keyframe event */
1719 pjmedia_event_init(&event, PJMEDIA_EVENT_KEYFRAME_MISSING,
1720 &input->timestamp, codec);
1721 pjmedia_event_publish(NULL, codec, &event, 0);
1722
1723 return PJMEDIA_CODEC_EBADBITSTREAM;
1724 } else if (got_picture) {
1725 pjmedia_video_apply_fmt_param *vafp = &ff->dec_vafp;
1726 pj_uint8_t *q = (pj_uint8_t*)output->buf;
1727 unsigned i;
1728 pj_status_t status;
1729
1730 /* Check decoding result, e.g: see if the format got changed,
1731 * keyframe found/missing.
1732 */
1733 status = check_decode_result(codec, &input->timestamp,
1734 avframe.key_frame);
1735 if (status != PJ_SUCCESS)
1736 return status;
1737
1738 /* Check provided buffer size */
1739 if (vafp->framebytes > output_buf_len)
1740 return PJ_ETOOSMALL;
1741
1742 /* Get the decoded data */
1743 for (i = 0; i < ff->dec_vfi->plane_cnt; ++i) {
1744 pj_uint8_t *p = avframe.data[i];
1745
1746 /* The decoded data may contain padding */
1747 if (avframe.linesize[i]!=vafp->strides[i]) {
1748 /* Padding exists, copy line by line */
1749 pj_uint8_t *q_end;
1750
1751 q_end = q+vafp->plane_bytes[i];
1752 while(q < q_end) {
1753 pj_memcpy(q, p, vafp->strides[i]);
1754 q += vafp->strides[i];
1755 p += avframe.linesize[i];
1756 }
1757 } else {
1758 /* No padding, copy the whole plane */
1759 pj_memcpy(q, p, vafp->plane_bytes[i]);
1760 q += vafp->plane_bytes[i];
1761 }
1762 }
1763
1764 output->type = PJMEDIA_FRAME_TYPE_VIDEO;
1765 output->size = vafp->framebytes;
1766 } else {
1767 output->type = PJMEDIA_FRAME_TYPE_NONE;
1768 output->size = 0;
1769 }
1770
1771 return PJ_SUCCESS;
1772}
1773
1774static pj_status_t ffmpeg_codec_decode( pjmedia_vid_codec *codec,
1775 pj_size_t pkt_count,
1776 pjmedia_frame packets[],
1777 unsigned out_size,
1778 pjmedia_frame *output)
1779{
1780 ffmpeg_private *ff = (ffmpeg_private*)codec->codec_data;
1781 pj_status_t status;
1782
1783 PJ_ASSERT_RETURN(codec && pkt_count > 0 && packets && output,
1784 PJ_EINVAL);
1785
1786 if (ff->whole) {
1787 pj_assert(pkt_count==1);
1788 return ffmpeg_codec_decode_whole(codec, &packets[0], out_size, output);
1789 } else {
1790 pjmedia_frame whole_frm;
1791 unsigned whole_len = 0;
1792 unsigned i;
1793
1794 for (i=0; i<pkt_count; ++i) {
1795 if (whole_len + packets[i].size > ff->dec_buf_size) {
1796 PJ_LOG(5,(THIS_FILE, "Decoding buffer overflow"));
1797 break;
1798 }
1799
1800 status = ffmpeg_unpacketize(codec, packets[i].buf, packets[i].size,
1801 ff->dec_buf, ff->dec_buf_size,
1802 &whole_len);
1803 if (status != PJ_SUCCESS) {
1804 PJ_PERROR(5,(THIS_FILE, status, "Unpacketize error"));
1805 continue;
1806 }
1807 }
1808
1809 whole_frm.buf = ff->dec_buf;
1810 whole_frm.size = whole_len;
1811 whole_frm.timestamp = output->timestamp = packets[i].timestamp;
1812 whole_frm.bit_info = 0;
1813
1814 return ffmpeg_codec_decode_whole(codec, &whole_frm, out_size, output);
1815 }
1816}
1817
1818
1819#ifdef _MSC_VER
1820# pragma comment( lib, "avcodec.lib")
1821#endif
1822
1823#endif /* PJMEDIA_HAS_FFMPEG_VID_CODEC */
1824