1
/* $Id: vid_stream.c 4197 2012-07-05 07:26:29Z nanang $ */
3
* Copyright (C) 2011 Teluu Inc. (http://www.teluu.com)
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.
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.
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
19
#include <pjmedia/vid_stream.h>
20
#include <pjmedia/errno.h>
21
#include <pjmedia/event.h>
22
#include <pjmedia/rtp.h>
23
#include <pjmedia/rtcp.h>
24
#include <pjmedia/jbuf.h>
25
#include <pjmedia/stream_common.h>
27
#include <pj/assert.h>
28
#include <pj/compat/socket.h>
30
#include <pj/ioqueue.h>
35
#include <pj/sock_select.h>
36
#include <pj/string.h> /* memcpy() */
39
#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
42
#define THIS_FILE "vid_stream.c"
44
#define LOGERR_(expr) stream_perror expr
45
#define TRC_(expr) PJ_LOG(5,expr)
46
#define SIGNATURE PJMEDIA_SIG_PORT_VID_STREAM
50
/* Tracing jitter buffer operations in a stream session to a CSV file.
51
* The trace will contain JB operation timestamp, frame info, RTP info, and
52
* the JB state right after the operation.
54
#define TRACE_JB 0 /* Enable/disable trace. */
55
#define TRACE_JB_PATH_PREFIX "" /* Optional path/prefix
56
for the CSV filename. */
58
# include <pj/file_io.h>
59
# define TRACE_JB_INVALID_FD ((pj_oshandle_t)-1)
60
# define TRACE_JB_OPENED(s) (s->trace_jb_fd != TRACE_JB_INVALID_FD)
63
#ifndef PJMEDIA_VSTREAM_SIZE
64
# define PJMEDIA_VSTREAM_SIZE 1000
67
#ifndef PJMEDIA_VSTREAM_INC
68
# define PJMEDIA_VSTREAM_INC 1000
71
/* Due to network MTU limitation, a picture bitstream may be splitted into
72
* several chunks for RTP delivery. The chunk number may vary depend on the
73
* picture resolution and MTU. This constant specifies the minimum chunk
74
* number to be allocated to store a picture bitstream in decoding direction.
76
#define MIN_CHUNKS_PER_FRM 30
78
/* Video stream keep-alive feature is currently disabled. */
79
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA != 0
80
# undef PJMEDIA_STREAM_ENABLE_KA
81
# define PJMEDIA_STREAM_ENABLE_KA 0
88
typedef struct pjmedia_vid_channel
90
pjmedia_vid_stream *stream; /**< Parent stream. */
91
pjmedia_dir dir; /**< Channel direction. */
92
pjmedia_port port; /**< Port interface. */
93
unsigned pt; /**< Payload type. */
94
pj_bool_t paused; /**< Paused?. */
95
void *buf; /**< Output buffer. */
96
unsigned buf_size; /**< Size of output buffer. */
97
pjmedia_rtp_session rtp; /**< RTP session. */
98
} pjmedia_vid_channel;
102
* This structure describes media stream.
103
* A media stream is bidirectional media transmission between two endpoints.
104
* It consists of two channels, i.e. encoding and decoding channels.
105
* A media stream corresponds to a single "m=" line in a SDP session
108
struct pjmedia_vid_stream
110
pj_pool_t *own_pool; /**< Internal pool. */
111
pjmedia_endpt *endpt; /**< Media endpoint. */
112
pjmedia_vid_codec_mgr *codec_mgr; /**< Codec manager. */
113
pjmedia_vid_stream_info info; /**< Stream info. */
115
pjmedia_vid_channel *enc; /**< Encoding channel. */
116
pjmedia_vid_channel *dec; /**< Decoding channel. */
118
pjmedia_dir dir; /**< Stream direction. */
119
void *user_data; /**< User data. */
120
pj_str_t name; /**< Stream name */
121
pj_str_t cname; /**< SDES CNAME */
123
pjmedia_transport *transport; /**< Stream transport. */
124
unsigned send_err_cnt; /**< Send error count. */
126
pj_mutex_t *jb_mutex;
127
pjmedia_jbuf *jb; /**< Jitter buffer. */
128
char jb_last_frm; /**< Last frame type from jb */
129
unsigned jb_last_frm_cnt;/**< Last JB frame type counter*/
131
pjmedia_rtcp_session rtcp; /**< RTCP for incoming RTP. */
132
pj_uint32_t rtcp_last_tx; /**< RTCP tx time in timestamp */
133
pj_uint32_t rtcp_interval; /**< Interval, in timestamp. */
134
pj_bool_t initial_rr; /**< Initial RTCP RR sent */
135
pj_bool_t rtcp_sdes_bye_disabled;/**< Send RTCP SDES/BYE?*/
136
void *out_rtcp_pkt; /**< Outgoing RTCP packet. */
137
unsigned out_rtcp_pkt_size;
138
/**< Outgoing RTCP packet size. */
140
unsigned dec_max_size; /**< Size of decoded/raw picture*/
141
pjmedia_ratio dec_max_fps; /**< Max fps of decoding dir. */
142
pjmedia_frame dec_frame; /**< Current decoded frame. */
143
pjmedia_event fmt_event; /**< Buffered fmt_changed event
145
pjmedia_event miss_keyframe_event;
146
/**< Buffered missing keyframe
147
event for delayed republish*/
149
unsigned frame_size; /**< Size of encoded base frame.*/
150
unsigned frame_ts_len; /**< Frame length in timestamp. */
152
unsigned rx_frame_cnt; /**< # of array in rx_frames */
153
pjmedia_frame *rx_frames; /**< Temp. buffer for incoming
156
pj_bool_t force_keyframe;/**< Forced to encode keyframe? */
158
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0
159
pj_bool_t use_ka; /**< Stream keep-alive with non-
160
codec-VAD mechanism is
162
pj_timestamp last_frm_ts_sent; /**< Timestamp of last sending
167
pj_oshandle_t trace_jb_fd; /**< Jitter tracing file handle.*/
168
char *trace_jb_buf; /**< Jitter tracing buffer. */
171
pjmedia_vid_codec *codec; /**< Codec instance being used. */
172
pj_uint32_t last_dec_ts; /**< Last decoded timestamp. */
173
int last_dec_seq; /**< Last decoded sequence. */
176
pj_timestamp ts_freq; /**< Timestamp frequency. */
179
unsigned rc_total_sleep;
180
unsigned rc_total_pkt;
181
unsigned rc_total_img;
182
pj_timestamp tx_start;
188
static pj_status_t decode_frame(pjmedia_vid_stream *stream,
189
pjmedia_frame *frame);
194
static void stream_perror(const char *sender, const char *title,
197
char errmsg[PJ_ERR_MSG_SIZE];
199
pj_strerror(status, errmsg, sizeof(errmsg));
200
PJ_LOG(4,(sender, "%s: %s [err:%d]", title, errmsg, status));
204
static pj_status_t send_rtcp(pjmedia_vid_stream *stream,
211
PJ_INLINE(int) trace_jb_print_timestamp(char **buf, pj_ssize_t len)
214
pj_parsed_time ptime;
220
pj_gettimeofday(&now);
221
pj_time_decode(&now, &ptime);
222
p += pj_utoa_pad(ptime.hour, p, 2, '0');
224
p += pj_utoa_pad(ptime.min, p, 2, '0');
226
p += pj_utoa_pad(ptime.sec, p, 2, '0');
228
p += pj_utoa_pad(ptime.msec, p, 3, '0');
236
PJ_INLINE(int) trace_jb_print_state(pjmedia_vid_stream *stream,
237
char **buf, pj_ssize_t len)
240
char *endp = *buf + len;
241
pjmedia_jb_state state;
243
pjmedia_jbuf_get_state(stream->jb, &state);
245
len = pj_ansi_snprintf(p, endp-p, "%d, %d, %d",
246
state.size, state.burst, state.prefetch);
247
if ((len < 0) || (len >= endp-p))
255
static void trace_jb_get(pjmedia_vid_stream *stream, pjmedia_jb_frame_type ft,
258
char *p = stream->trace_jb_buf;
259
char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE;
263
if (!TRACE_JB_OPENED(stream))
266
/* Print timestamp. */
267
if (trace_jb_print_timestamp(&p, endp-p))
268
goto on_insuff_buffer;
270
/* Print frame type and size */
272
case PJMEDIA_JB_MISSING_FRAME:
275
case PJMEDIA_JB_NORMAL_FRAME:
278
case PJMEDIA_JB_ZERO_PREFETCH_FRAME:
281
case PJMEDIA_JB_ZERO_EMPTY_FRAME:
289
/* Print operation, size, frame count, frame type */
290
len = pj_ansi_snprintf(p, endp-p, "GET,%d,1,%s,,,,", fsize, ft_st);
291
if ((len < 0) || (len >= endp-p))
292
goto on_insuff_buffer;
296
if (trace_jb_print_state(stream, &p, endp-p))
297
goto on_insuff_buffer;
299
/* Print end of line */
301
goto on_insuff_buffer;
304
/* Write and flush */
305
len = p - stream->trace_jb_buf;
306
pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len);
307
pj_file_flush(stream->trace_jb_fd);
311
pj_assert(!"Trace buffer too small, check PJ_LOG_MAX_SIZE!");
314
static void trace_jb_put(pjmedia_vid_stream *stream,
315
const pjmedia_rtp_hdr *hdr,
316
unsigned payloadlen, unsigned frame_cnt)
318
char *p = stream->trace_jb_buf;
319
char *endp = stream->trace_jb_buf + PJ_LOG_MAX_SIZE;
322
if (!TRACE_JB_OPENED(stream))
325
/* Print timestamp. */
326
if (trace_jb_print_timestamp(&p, endp-p))
327
goto on_insuff_buffer;
329
/* Print operation, size, frame count, RTP info */
330
len = pj_ansi_snprintf(p, endp-p,
331
"PUT,%d,%d,,%d,%d,%d,",
332
payloadlen, frame_cnt,
333
pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), hdr->m);
334
if ((len < 0) || (len >= endp-p))
335
goto on_insuff_buffer;
339
if (trace_jb_print_state(stream, &p, endp-p))
340
goto on_insuff_buffer;
342
/* Print end of line */
344
goto on_insuff_buffer;
347
/* Write and flush */
348
len = p - stream->trace_jb_buf;
349
pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len);
350
pj_file_flush(stream->trace_jb_fd);
354
pj_assert(!"Trace buffer too small, check PJ_LOG_MAX_SIZE!");
357
#endif /* TRACE_JB */
359
static void dump_port_info(const pjmedia_vid_channel *chan,
360
const char *event_name)
362
const pjmedia_port_info *pi = &chan->port.info;
365
PJ_LOG(5, (pi->name.ptr,
366
" %s format %s: %dx%d %s%s %d/%d(~%d)fps",
367
(chan->dir==PJMEDIA_DIR_DECODING? "Decoding":"Encoding"),
369
pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h,
370
pjmedia_fourcc_name(pi->fmt.id, fourcc_name),
371
(chan->dir==PJMEDIA_DIR_ENCODING?"->":"<-"),
372
pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum,
373
pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum));
377
* Handle events from stream components.
379
static pj_status_t stream_event_cb(pjmedia_event *event,
382
pjmedia_vid_stream *stream = (pjmedia_vid_stream*)user_data;
384
if (event->epub == stream->codec) {
385
/* This is codec event */
386
switch (event->type) {
387
case PJMEDIA_EVENT_FMT_CHANGED:
388
/* Copy the event to avoid deadlock if we publish the event
389
* now. This happens because fmt_event may trigger restart
390
* while we're still holding the jb_mutex.
392
pj_memcpy(&stream->fmt_event, event, sizeof(*event));
395
case PJMEDIA_EVENT_KEYFRAME_MISSING:
396
/* Republish this event later from get_frame(). */
397
pj_memcpy(&stream->miss_keyframe_event, event, sizeof(*event));
405
return pjmedia_event_publish(NULL, stream, event, 0);
408
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA != 0
410
* Send keep-alive packet using non-codec frame.
412
static void send_keep_alive_packet(pjmedia_vid_stream *stream)
414
#if PJMEDIA_STREAM_ENABLE_KA == PJMEDIA_STREAM_KA_EMPTY_RTP
416
/* Keep-alive packet is empty RTP */
417
pjmedia_vid_channel *channel = stream->enc;
422
TRC_((channel->port.info.name.ptr,
423
"Sending keep-alive (RTCP and empty RTP)"));
426
status = pjmedia_rtp_encode_rtp( &stream->enc->rtp,
432
pj_assert(status == PJ_SUCCESS);
434
pj_memcpy(stream->enc->buf, pkt, pkt_len);
435
pjmedia_transport_send_rtp(stream->transport, stream->enc->buf,
439
send_rtcp(stream, PJ_TRUE, PJ_FALSE);
441
#elif PJMEDIA_STREAM_ENABLE_KA == PJMEDIA_STREAM_KA_USER
443
/* Keep-alive packet is defined in PJMEDIA_STREAM_KA_USER_PKT */
444
pjmedia_vid_channel *channel = stream->enc;
446
const pj_str_t str_ka = PJMEDIA_STREAM_KA_USER_PKT;
448
TRC_((channel->port.info.name.ptr,
449
"Sending keep-alive (custom RTP/RTCP packets)"));
451
/* Send to RTP port */
452
pj_memcpy(stream->enc->buf, str_ka.ptr, str_ka.slen);
453
pkt_len = str_ka.slen;
454
pjmedia_transport_send_rtp(stream->transport, stream->enc->buf,
457
/* Send to RTCP port */
458
pjmedia_transport_send_rtcp(stream->transport, stream->enc->buf,
463
PJ_UNUSED_ARG(stream);
467
#endif /* defined(PJMEDIA_STREAM_ENABLE_KA) */
470
static pj_status_t send_rtcp(pjmedia_vid_stream *stream,
479
/* Build RTCP RR/SR packet */
480
pjmedia_rtcp_build_rtcp(&stream->rtcp, &sr_rr_pkt, &len);
482
if (with_sdes || with_bye) {
483
pkt = (pj_uint8_t*) stream->out_rtcp_pkt;
484
pj_memcpy(pkt, sr_rr_pkt, len);
485
max_len = stream->out_rtcp_pkt_size;
487
pkt = (pj_uint8_t*)sr_rr_pkt;
491
/* Build RTCP SDES packet */
493
pjmedia_rtcp_sdes sdes;
496
pj_bzero(&sdes, sizeof(sdes));
497
sdes.cname = stream->cname;
498
sdes_len = max_len - len;
499
status = pjmedia_rtcp_build_rtcp_sdes(&stream->rtcp, pkt+len,
501
if (status != PJ_SUCCESS) {
502
PJ_PERROR(4,(stream->name.ptr, status,
503
"Error generating RTCP SDES"));
509
/* Build RTCP BYE packet */
513
bye_len = max_len - len;
514
status = pjmedia_rtcp_build_rtcp_bye(&stream->rtcp, pkt+len,
516
if (status != PJ_SUCCESS) {
517
PJ_PERROR(4,(stream->name.ptr, status,
518
"Error generating RTCP BYE"));
525
status = pjmedia_transport_send_rtcp(stream->transport, pkt, len);
534
* This function is can be called by either put_frame() or get_frame(),
535
* to transmit periodic RTCP SR/RR report.
537
static void check_tx_rtcp(pjmedia_vid_stream *stream, pj_uint32_t timestamp)
539
/* Note that timestamp may represent local or remote timestamp,
540
* depending on whether this function is called from put_frame()
545
if (stream->rtcp_last_tx == 0) {
547
stream->rtcp_last_tx = timestamp;
549
} else if (timestamp - stream->rtcp_last_tx >= stream->rtcp_interval) {
552
status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled, PJ_FALSE);
553
if (status != PJ_SUCCESS) {
554
PJ_PERROR(4,(stream->name.ptr, status,
555
"Error sending RTCP"));
558
stream->rtcp_last_tx = timestamp;
564
static void dump_bin(const char *buf, unsigned len)
568
PJ_LOG(3,(THIS_FILE, "begin dump"));
569
for (i=0; i<len; ++i) {
572
unsigned val = buf[i] & 0xFF;
575
for (j=0; j<8; ++j) {
576
if (val & (1 << (7-j)))
582
PJ_LOG(3,(THIS_FILE, "%2d %s [%d]", i, bits, val));
584
PJ_LOG(3,(THIS_FILE, "end dump"));
590
* This callback is called by stream transport on receipt of packets
593
static void on_rx_rtp( void *data,
595
pj_ssize_t bytes_read)
598
pjmedia_vid_stream *stream = (pjmedia_vid_stream*) data;
599
pjmedia_vid_channel *channel = stream->dec;
600
const pjmedia_rtp_hdr *hdr;
603
pjmedia_rtp_status seq_st;
605
pj_bool_t pkt_discarded = PJ_FALSE;
607
/* Check for errors */
608
if (bytes_read < 0) {
609
LOGERR_((channel->port.info.name.ptr, "RTP recv() error", -bytes_read));
613
/* Ignore keep-alive packets */
614
if (bytes_read < (pj_ssize_t) sizeof(pjmedia_rtp_hdr))
617
/* Update RTP and RTCP session. */
618
status = pjmedia_rtp_decode_rtp(&channel->rtp, pkt, bytes_read,
619
&hdr, &payload, &payloadlen);
620
if (status != PJ_SUCCESS) {
621
LOGERR_((channel->port.info.name.ptr, "RTP decode error", status));
622
stream->rtcp.stat.rx.discard++;
626
/* Ignore the packet if decoder is paused */
630
/* Update RTP session (also checks if RTP session can accept
631
* the incoming packet.
633
pjmedia_rtp_session_update2(&channel->rtp, hdr, &seq_st, PJ_TRUE);
634
if (seq_st.status.value) {
635
TRC_ ((channel->port.info.name.ptr,
636
"RTP status: badpt=%d, badssrc=%d, dup=%d, "
637
"outorder=%d, probation=%d, restart=%d",
638
seq_st.status.flag.badpt,
639
seq_st.status.flag.badssrc,
640
seq_st.status.flag.dup,
641
seq_st.status.flag.outorder,
642
seq_st.status.flag.probation,
643
seq_st.status.flag.restart));
645
if (seq_st.status.flag.badpt) {
646
PJ_LOG(4,(channel->port.info.name.ptr,
647
"Bad RTP pt %d (expecting %d)",
648
hdr->pt, channel->rtp.out_pt));
651
if (seq_st.status.flag.badssrc) {
652
PJ_LOG(4,(channel->port.info.name.ptr,
653
"Changed RTP peer SSRC %d (previously %d)",
654
channel->rtp.peer_ssrc, stream->rtcp.peer_ssrc));
655
stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc;
661
/* Skip bad RTP packet */
662
if (seq_st.status.flag.bad) {
663
pkt_discarded = PJ_TRUE;
667
/* Ignore if payloadlen is zero */
668
if (payloadlen == 0) {
669
pkt_discarded = PJ_TRUE;
673
pj_mutex_lock( stream->jb_mutex );
675
/* Quickly see if there may be a full picture in the jitter buffer, and
676
* decode them if so. More thorough check will be done in decode_frame().
678
if ((pj_ntohl(hdr->ts) != stream->dec_frame.timestamp.u32.lo) || hdr->m) {
679
if (PJMEDIA_VID_STREAM_SKIP_PACKETS_TO_REDUCE_LATENCY) {
680
/* Always decode whenever we have picture in jb and
681
* overwrite already decoded picture if necessary
683
pj_size_t old_size = stream->dec_frame.size;
685
stream->dec_frame.size = stream->dec_max_size;
686
if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) {
687
stream->dec_frame.size = old_size;
690
/* Only decode if we don't already have decoded one,
691
* unless the jb is full.
693
pj_bool_t can_decode = PJ_FALSE;
695
if (pjmedia_jbuf_is_full(stream->jb)) {
696
can_decode = PJ_TRUE;
698
else if (stream->dec_frame.size == 0) {
699
can_decode = PJ_TRUE;
703
stream->dec_frame.size = stream->dec_max_size;
704
if (decode_frame(stream, &stream->dec_frame) != PJ_SUCCESS) {
705
stream->dec_frame.size = 0;
711
/* Put "good" packet to jitter buffer, or reset the jitter buffer
712
* when RTP session is restarted.
714
if (seq_st.status.flag.restart) {
715
status = pjmedia_jbuf_reset(stream->jb);
716
PJ_LOG(4,(channel->port.info.name.ptr, "Jitter buffer reset"));
718
/* Just put the payload into jitter buffer */
719
pjmedia_jbuf_put_frame3(stream->jb, payload, payloadlen, 0,
720
pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), NULL);
723
trace_jb_put(stream, hdr, payloadlen, count);
727
pj_mutex_unlock( stream->jb_mutex );
730
/* Check if now is the time to transmit RTCP SR/RR report.
731
* We only do this when stream direction is "decoding only",
732
* because otherwise check_tx_rtcp() will be handled by put_frame()
734
if (stream->dir == PJMEDIA_DIR_DECODING) {
735
check_tx_rtcp(stream, pj_ntohl(hdr->ts));
739
LOGERR_((channel->port.info.name.ptr, "Jitter buffer put() error",
741
pkt_discarded = PJ_TRUE;
746
/* Update RTCP session */
747
if (stream->rtcp.peer_ssrc == 0)
748
stream->rtcp.peer_ssrc = channel->rtp.peer_ssrc;
750
pjmedia_rtcp_rx_rtp2(&stream->rtcp, pj_ntohs(hdr->seq),
751
pj_ntohl(hdr->ts), payloadlen, pkt_discarded);
753
/* Send RTCP RR and SDES after we receive some RTP packets */
754
if (stream->rtcp.received >= 10 && !stream->initial_rr) {
755
status = send_rtcp(stream, !stream->rtcp_sdes_bye_disabled,
757
if (status != PJ_SUCCESS) {
758
PJ_PERROR(4,(stream->name.ptr, status,
759
"Error sending initial RTCP RR"));
761
stream->initial_rr = PJ_TRUE;
768
* This callback is called by stream transport on receipt of packets
769
* in the RTCP socket.
771
static void on_rx_rtcp( void *data,
773
pj_ssize_t bytes_read)
775
pjmedia_vid_stream *stream = (pjmedia_vid_stream*) data;
777
/* Check for errors */
778
if (bytes_read < 0) {
779
LOGERR_((stream->cname.ptr, "RTCP recv() error",
784
pjmedia_rtcp_rx_rtcp(&stream->rtcp, pkt, bytes_read);
787
static pj_status_t put_frame(pjmedia_port *port,
788
pjmedia_frame *frame)
790
pjmedia_vid_stream *stream = (pjmedia_vid_stream*) port->port_data.pdata;
791
pjmedia_vid_channel *channel = stream->enc;
792
pj_status_t status = 0;
793
pjmedia_frame frame_out;
797
pj_bool_t has_more_data = PJ_FALSE;
798
pj_size_t total_sent = 0;
799
pjmedia_vid_encode_opt enc_opt;
800
unsigned pkt_cnt = 0;
801
pj_timestamp initial_time;
803
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA != 0
804
/* If the interval since last sending packet is greater than
805
* PJMEDIA_STREAM_KA_INTERVAL, send keep-alive packet.
809
pj_uint32_t dtx_duration;
811
dtx_duration = pj_timestamp_diff32(&stream->last_frm_ts_sent,
813
/* Video stream keep-alive feature is currently disabled. */
816
PJMEDIA_STREAM_KA_INTERVAL *
817
PJMEDIA_PIA_SRATE(&channel->port.info))
819
send_keep_alive_packet(stream);
820
stream->last_frm_ts_sent = frame->timestamp;
826
/* Don't do anything if stream is paused */
827
if (channel->paused) {
831
/* Get frame length in timestamp unit */
832
rtp_ts_len = stream->frame_ts_len;
834
/* Init frame_out buffer. */
835
frame_out.buf = ((char*)channel->buf) + sizeof(pjmedia_rtp_hdr);
838
/* Init encoding option */
839
pj_bzero(&enc_opt, sizeof(enc_opt));
840
if (stream->force_keyframe) {
841
/* Force encoder to generate keyframe */
842
enc_opt.force_keyframe = PJ_TRUE;
843
stream->force_keyframe = PJ_FALSE;
844
TRC_((channel->port.info.name.ptr,
845
"Forcing encoder to generate keyframe"));
849
status = pjmedia_vid_codec_encode_begin(stream->codec, &enc_opt, frame,
851
sizeof(pjmedia_rtp_hdr),
854
if (status != PJ_SUCCESS) {
855
LOGERR_((channel->port.info.name.ptr,
856
"Codec encode_begin() error", status));
858
/* Update RTP timestamp */
859
pjmedia_rtp_encode_rtp(&channel->rtp, channel->pt, 1, 0,
860
rtp_ts_len, (const void**)&rtphdr,
865
pj_get_timestamp(&initial_time);
867
/* Loop while we have frame to send */
869
status = pjmedia_rtp_encode_rtp(&channel->rtp,
871
(has_more_data == PJ_FALSE ? 1 : 0),
874
(const void**)&rtphdr,
876
if (status != PJ_SUCCESS) {
877
LOGERR_((channel->port.info.name.ptr,
878
"RTP encode_rtp() error", status));
882
// Copy RTP header to the beginning of packet
883
pj_memcpy(channel->buf, rtphdr, sizeof(pjmedia_rtp_hdr));
885
// Send the RTP packet to the transport.
886
status = pjmedia_transport_send_rtp(stream->transport,
889
sizeof(pjmedia_rtp_hdr));
890
if (status != PJ_SUCCESS) {
891
enum { COUNT_TO_REPORT = 20 };
892
if (stream->send_err_cnt++ == 0) {
893
LOGERR_((channel->port.info.name.ptr,
894
"Transport send_rtp() error",
897
if (stream->send_err_cnt > COUNT_TO_REPORT)
898
stream->send_err_cnt = 0;
899
/* Ignore this error */
902
pjmedia_rtcp_tx_rtp(&stream->rtcp, frame_out.size);
903
total_sent += frame_out.size;
909
/* Next packets use same timestamp */
915
status = pjmedia_vid_codec_encode_more(stream->codec,
917
sizeof(pjmedia_rtp_hdr),
920
if (status != PJ_SUCCESS) {
921
LOGERR_((channel->port.info.name.ptr,
922
"Codec encode_more() error", status));
923
/* Ignore this error (?) */
927
/* Send rate control */
928
if (stream->info.rc_cfg.method==PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING)
930
pj_timestamp now, next_send_ts, total_send_ts;
932
total_send_ts.u64 = total_sent * stream->ts_freq.u64 * 8 /
933
stream->info.rc_cfg.bandwidth;
934
next_send_ts = initial_time;
935
pj_add_timestamp(&next_send_ts, &total_send_ts);
937
pj_get_timestamp(&now);
938
if (pj_cmp_timestamp(&now, &next_send_ts) < 0) {
940
ms_sleep = pj_elapsed_msec(&now, &next_send_ts);
945
pj_thread_sleep(ms_sleep);
951
/* Trace log for rate control */
953
pj_timestamp end_time;
954
unsigned total_sleep;
956
pj_get_timestamp(&end_time);
957
total_sleep = pj_elapsed_msec(&initial_time, &end_time);
958
PJ_LOG(5, (stream->name.ptr, "total pkt=%d size=%d sleep=%d",
959
pkt_cnt, total_sent, total_sleep));
961
if (stream->tx_start.u64 == 0)
962
stream->tx_start = initial_time;
963
stream->tx_end = end_time;
964
stream->rc_total_pkt += pkt_cnt;
965
stream->rc_total_sleep += total_sleep;
966
stream->rc_total_img++;
970
/* Check if now is the time to transmit RTCP SR/RR report.
971
* We only do this when stream direction is not "decoding only", because
972
* when it is, check_tx_rtcp() will be handled by get_frame().
974
if (stream->dir != PJMEDIA_DIR_DECODING) {
975
check_tx_rtcp(stream, pj_ntohl(channel->rtp.out_hdr.ts));
978
/* Do nothing if we have nothing to transmit */
979
if (total_sent == 0) {
984
stream->rtcp.stat.rtp_tx_last_ts = pj_ntohl(stream->enc->rtp.out_hdr.ts);
985
stream->rtcp.stat.rtp_tx_last_seq = pj_ntohs(stream->enc->rtp.out_hdr.seq);
987
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0
988
/* Update timestamp of last sending packet. */
989
stream->last_frm_ts_sent = frame->timestamp;
995
/* Decode one image from jitter buffer */
996
static pj_status_t decode_frame(pjmedia_vid_stream *stream,
997
pjmedia_frame *frame)
999
pjmedia_vid_channel *channel = stream->dec;
1000
pj_uint32_t last_ts = 0;
1001
int frm_first_seq = 0, frm_last_seq = 0;
1002
pj_bool_t got_frame = PJ_FALSE;
1006
/* Repeat get payload from the jitter buffer until all payloads with same
1007
* timestamp are collected.
1010
/* Check if we got a decodable frame */
1011
for (cnt=0; ; ++cnt) {
1016
/* Peek frame from jitter buffer. */
1017
pjmedia_jbuf_peek_frame(stream->jb, cnt, NULL, NULL,
1018
&ptype, NULL, &ts, &seq);
1019
if (ptype == PJMEDIA_JB_NORMAL_FRAME) {
1022
frm_first_seq = seq;
1024
if (ts != last_ts) {
1025
got_frame = PJ_TRUE;
1029
} else if (ptype == PJMEDIA_JB_ZERO_EMPTY_FRAME) {
1030
/* No more packet in the jitter buffer */
1038
/* Generate frame bitstream from the payload */
1039
if (cnt > stream->rx_frame_cnt) {
1040
PJ_LOG(1,(channel->port.info.name.ptr,
1041
"Discarding %u frames because array is full!",
1042
cnt - stream->rx_frame_cnt));
1043
pjmedia_jbuf_remove_frame(stream->jb, cnt - stream->rx_frame_cnt);
1044
cnt = stream->rx_frame_cnt;
1047
for (i = 0; i < cnt; ++i) {
1050
stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_VIDEO;
1051
stream->rx_frames[i].timestamp.u64 = last_ts;
1052
stream->rx_frames[i].bit_info = 0;
1054
/* We use jbuf_peek_frame() as it will returns the pointer of
1055
* the payload (no buffer and memcpy needed), just as we need.
1057
pjmedia_jbuf_peek_frame(stream->jb, i,
1058
(const void**)&stream->rx_frames[i].buf,
1059
&stream->rx_frames[i].size, &ptype,
1062
if (ptype != PJMEDIA_JB_NORMAL_FRAME) {
1063
/* Packet lost, must set payload to NULL and keep going */
1064
stream->rx_frames[i].buf = NULL;
1065
stream->rx_frames[i].size = 0;
1066
stream->rx_frames[i].type = PJMEDIA_FRAME_TYPE_NONE;
1072
status = pjmedia_vid_codec_decode(stream->codec, cnt,
1074
frame->size, frame);
1075
if (status != PJ_SUCCESS) {
1076
LOGERR_((channel->port.info.name.ptr, "codec decode() error",
1078
frame->type = PJMEDIA_FRAME_TYPE_NONE;
1082
pjmedia_jbuf_remove_frame(stream->jb, cnt);
1085
/* Learn remote frame rate after successful decoding */
1086
if (frame->type == PJMEDIA_FRAME_TYPE_VIDEO && frame->size)
1088
/* Only check remote frame rate when timestamp is not wrapping and
1089
* sequence is increased by 1.
1091
if (last_ts > stream->last_dec_ts &&
1092
frm_first_seq - stream->last_dec_seq == 1)
1094
pj_uint32_t ts_diff;
1095
pjmedia_video_format_detail *vfd;
1097
ts_diff = last_ts - stream->last_dec_ts;
1098
vfd = pjmedia_format_get_video_format_detail(
1099
&channel->port.info.fmt, PJ_TRUE);
1100
if (stream->info.codec_info.clock_rate * vfd->fps.denum !=
1101
vfd->fps.num * ts_diff)
1103
/* Frame rate changed, update decoding port info */
1104
if (stream->info.codec_info.clock_rate % ts_diff == 0) {
1105
vfd->fps.num = stream->info.codec_info.clock_rate/ts_diff;
1108
vfd->fps.num = stream->info.codec_info.clock_rate;
1109
vfd->fps.denum = ts_diff;
1112
/* Update stream info */
1113
stream->info.codec_param->dec_fmt.det.vid.fps = vfd->fps;
1115
/* Publish PJMEDIA_EVENT_FMT_CHANGED event if frame rate
1116
* increased and not exceeding 100fps.
1118
if (vfd->fps.num/vfd->fps.denum <= 100 &&
1119
vfd->fps.num * stream->dec_max_fps.denum >
1120
stream->dec_max_fps.num * vfd->fps.denum)
1122
pjmedia_event *event = &stream->fmt_event;
1124
/* Update max fps of decoding dir */
1125
stream->dec_max_fps = vfd->fps;
1127
/* Use the buffered format changed event:
1128
* - just update the framerate if there is pending event,
1129
* - otherwise, init the whole event.
1131
if (stream->fmt_event.type != PJMEDIA_EVENT_NONE) {
1132
event->data.fmt_changed.new_fmt.det.vid.fps = vfd->fps;
1134
pjmedia_event_init(event, PJMEDIA_EVENT_FMT_CHANGED,
1135
&frame->timestamp, stream);
1136
event->data.fmt_changed.dir = PJMEDIA_DIR_DECODING;
1137
pj_memcpy(&event->data.fmt_changed.new_fmt,
1138
&stream->info.codec_param->dec_fmt,
1139
sizeof(pjmedia_format));
1145
/* Update last frame seq and timestamp */
1146
stream->last_dec_seq = frm_last_seq;
1147
stream->last_dec_ts = last_ts;
1150
return got_frame ? PJ_SUCCESS : PJ_ENOTFOUND;
1154
static pj_status_t get_frame(pjmedia_port *port,
1155
pjmedia_frame *frame)
1157
pjmedia_vid_stream *stream = (pjmedia_vid_stream*) port->port_data.pdata;
1158
pjmedia_vid_channel *channel = stream->dec;
1160
/* Return no frame is channel is paused */
1161
if (channel->paused) {
1162
frame->type = PJMEDIA_FRAME_TYPE_NONE;
1167
/* Report pending events. Do not publish the event while holding the
1168
* jb_mutex as that would lead to deadlock. It should be safe to
1169
* operate on fmt_event without the mutex because format change normally
1170
* would only occur once during the start of the media.
1172
if (stream->fmt_event.type != PJMEDIA_EVENT_NONE) {
1173
pjmedia_event_fmt_changed_data *fmt_chg_data;
1175
fmt_chg_data = &stream->fmt_event.data.fmt_changed;
1177
/* Update stream info and decoding channel port info */
1178
if (fmt_chg_data->dir == PJMEDIA_DIR_DECODING) {
1179
pjmedia_format_copy(&stream->info.codec_param->dec_fmt,
1180
&fmt_chg_data->new_fmt);
1181
pjmedia_format_copy(&stream->dec->port.info.fmt,
1182
&fmt_chg_data->new_fmt);
1184
/* Override the framerate to be 1.5x higher in the event
1187
fmt_chg_data->new_fmt.det.vid.fps.num *= 3;
1188
fmt_chg_data->new_fmt.det.vid.fps.num /= 2;
1190
pjmedia_format_copy(&stream->info.codec_param->enc_fmt,
1191
&fmt_chg_data->new_fmt);
1192
pjmedia_format_copy(&stream->enc->port.info.fmt,
1193
&fmt_chg_data->new_fmt);
1196
dump_port_info(fmt_chg_data->dir==PJMEDIA_DIR_DECODING ?
1197
stream->dec : stream->enc,
1200
pjmedia_event_publish(NULL, port, &stream->fmt_event, 0);
1202
stream->fmt_event.type = PJMEDIA_EVENT_NONE;
1205
if (stream->miss_keyframe_event.type != PJMEDIA_EVENT_NONE) {
1206
pjmedia_event_publish(NULL, port, &stream->miss_keyframe_event,
1207
PJMEDIA_EVENT_PUBLISH_POST_EVENT);
1208
stream->miss_keyframe_event.type = PJMEDIA_EVENT_NONE;
1211
pj_mutex_lock( stream->jb_mutex );
1213
if (stream->dec_frame.size == 0) {
1214
/* Don't have frame in buffer, try to decode one */
1215
if (decode_frame(stream, frame) != PJ_SUCCESS) {
1216
frame->type = PJMEDIA_FRAME_TYPE_NONE;
1220
if (frame->size < stream->dec_frame.size) {
1221
PJ_LOG(4,(stream->dec->port.info.name.ptr,
1222
"Error: not enough buffer for decoded frame "
1223
"(supplied=%d, required=%d)",
1224
(int)frame->size, (int)stream->dec_frame.size));
1225
frame->type = PJMEDIA_FRAME_TYPE_NONE;
1228
frame->type = stream->dec_frame.type;
1229
frame->timestamp = stream->dec_frame.timestamp;
1230
frame->size = stream->dec_frame.size;
1231
pj_memcpy(frame->buf, stream->dec_frame.buf, frame->size);
1234
stream->dec_frame.size = 0;
1237
pj_mutex_unlock( stream->jb_mutex );
1243
* Create media channel.
1245
static pj_status_t create_channel( pj_pool_t *pool,
1246
pjmedia_vid_stream *stream,
1249
const pjmedia_vid_stream_info *info,
1250
pjmedia_vid_channel **p_channel)
1253
pjmedia_vid_channel *channel;
1255
unsigned min_out_pkt_size;
1257
const char *type_name;
1258
pjmedia_format *fmt;
1259
char fourcc_name[5];
1260
pjmedia_port_info *pi;
1262
pj_assert(info->type == PJMEDIA_TYPE_VIDEO);
1263
pj_assert(dir == PJMEDIA_DIR_DECODING || dir == PJMEDIA_DIR_ENCODING);
1265
/* Allocate memory for channel descriptor */
1266
channel = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_channel);
1267
PJ_ASSERT_RETURN(channel != NULL, PJ_ENOMEM);
1270
if (dir==PJMEDIA_DIR_DECODING) {
1271
type_name = "vstdec";
1272
fmt = &info->codec_param->dec_fmt;
1274
type_name = "vstenc";
1275
fmt = &info->codec_param->enc_fmt;
1277
name.ptr = (char*) pj_pool_alloc(pool, M);
1278
name.slen = pj_ansi_snprintf(name.ptr, M, "%s%p", type_name, stream);
1279
pi = &channel->port.info;
1281
/* Init channel info. */
1282
channel->stream = stream;
1284
channel->paused = 1;
1287
/* Allocate buffer for outgoing packet. */
1288
if (dir == PJMEDIA_DIR_ENCODING) {
1289
channel->buf_size = sizeof(pjmedia_rtp_hdr) + stream->frame_size;
1291
/* It should big enough to hold (minimally) RTCP SR with an SDES. */
1292
min_out_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) +
1293
sizeof(pjmedia_rtcp_common) +
1294
(4 + stream->cname.slen) +
1297
if (channel->buf_size < min_out_pkt_size)
1298
channel->buf_size = min_out_pkt_size;
1300
channel->buf = pj_pool_alloc(pool, channel->buf_size);
1301
PJ_ASSERT_RETURN(channel->buf != NULL, PJ_ENOMEM);
1304
/* Create RTP and RTCP sessions: */
1305
if (info->rtp_seq_ts_set == 0) {
1306
status = pjmedia_rtp_session_init(&channel->rtp, pt, info->ssrc);
1308
pjmedia_rtp_session_setting settings;
1310
settings.flags = (pj_uint8_t)((info->rtp_seq_ts_set << 2) | 3);
1311
settings.default_pt = pt;
1312
settings.sender_ssrc = info->ssrc;
1313
settings.seq = info->rtp_seq;
1314
settings.ts = info->rtp_ts;
1315
status = pjmedia_rtp_session_init2(&channel->rtp, settings);
1317
if (status != PJ_SUCCESS)
1321
pjmedia_port_info_init2(pi, &name, SIGNATURE, dir, fmt);
1322
if (dir == PJMEDIA_DIR_DECODING) {
1323
channel->port.get_frame = &get_frame;
1325
pi->fmt.id = info->codec_param->dec_fmt.id;
1326
channel->port.put_frame = &put_frame;
1330
channel->port.port_data.pdata = stream;
1332
PJ_LOG(5, (name.ptr,
1333
"%s channel created %dx%d %s%s%.*s %d/%d(~%d)fps",
1334
(dir==PJMEDIA_DIR_ENCODING?"Encoding":"Decoding"),
1335
pi->fmt.det.vid.size.w, pi->fmt.det.vid.size.h,
1336
pjmedia_fourcc_name(pi->fmt.id, fourcc_name),
1337
(dir==PJMEDIA_DIR_ENCODING?"->":"<-"),
1338
info->codec_info.encoding_name.slen,
1339
info->codec_info.encoding_name.ptr,
1340
pi->fmt.det.vid.fps.num, pi->fmt.det.vid.fps.denum,
1341
pi->fmt.det.vid.fps.num/pi->fmt.det.vid.fps.denum));
1344
*p_channel = channel;
1352
PJ_DEF(pj_status_t) pjmedia_vid_stream_create(
1353
pjmedia_endpt *endpt,
1355
pjmedia_vid_stream_info *info,
1356
pjmedia_transport *tp,
1358
pjmedia_vid_stream **p_stream)
1361
pj_pool_t *own_pool = NULL;
1362
pjmedia_vid_stream *stream;
1363
unsigned jb_init, jb_max, jb_min_pre, jb_max_pre;
1364
int frm_ptime, chunks_per_frm;
1365
pjmedia_video_format_detail *vfd_enc, *vfd_dec;
1370
own_pool = pjmedia_endpt_create_pool( endpt, "vstrm%p",
1371
PJMEDIA_VSTREAM_SIZE,
1372
PJMEDIA_VSTREAM_INC);
1373
PJ_ASSERT_RETURN(own_pool != NULL, PJ_ENOMEM);
1377
/* Allocate stream */
1378
stream = PJ_POOL_ZALLOC_T(pool, pjmedia_vid_stream);
1379
PJ_ASSERT_RETURN(stream != NULL, PJ_ENOMEM);
1380
stream->own_pool = own_pool;
1382
/* Get codec manager */
1383
stream->codec_mgr = pjmedia_vid_codec_mgr_instance();
1384
PJ_ASSERT_RETURN(stream->codec_mgr, PJMEDIA_CODEC_EFAILED);
1386
/* Init stream/port name */
1387
stream->name.ptr = (char*) pj_pool_alloc(pool, M);
1388
stream->name.slen = pj_ansi_snprintf(stream->name.ptr, M,
1391
/* Create and initialize codec: */
1392
status = pjmedia_vid_codec_mgr_alloc_codec(stream->codec_mgr,
1395
if (status != PJ_SUCCESS)
1398
/* Get codec param: */
1399
if (!info->codec_param) {
1400
pjmedia_vid_codec_param def_param;
1402
status = pjmedia_vid_codec_mgr_get_default_param(stream->codec_mgr,
1405
if (status != PJ_SUCCESS)
1408
info->codec_param = pjmedia_vid_codec_param_clone(pool, &def_param);
1409
pj_assert(info->codec_param);
1412
/* Init codec param and adjust MTU */
1413
info->codec_param->dir = info->dir;
1414
info->codec_param->enc_mtu -= (sizeof(pjmedia_rtp_hdr) +
1415
PJMEDIA_STREAM_RESV_PAYLOAD_LEN);
1416
if (info->codec_param->enc_mtu > PJMEDIA_MAX_MTU)
1417
info->codec_param->enc_mtu = PJMEDIA_MAX_MTU;
1419
/* Packet size estimation for decoding direction */
1420
vfd_enc = pjmedia_format_get_video_format_detail(
1421
&info->codec_param->enc_fmt, PJ_TRUE);
1422
vfd_dec = pjmedia_format_get_video_format_detail(
1423
&info->codec_param->dec_fmt, PJ_TRUE);
1426
stream->endpt = endpt;
1427
stream->dir = info->dir;
1428
stream->user_data = user_data;
1429
stream->rtcp_interval = (PJMEDIA_RTCP_INTERVAL-500 + (pj_rand()%1000)) *
1430
info->codec_info.clock_rate / 1000;
1431
stream->rtcp_sdes_bye_disabled = info->rtcp_sdes_bye_disabled;
1433
stream->jb_last_frm = PJMEDIA_JB_NORMAL_FRAME;
1435
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0
1436
stream->use_ka = info->use_ka;
1439
/* Build random RTCP CNAME. CNAME has user@host format */
1440
stream->cname.ptr = p = (char*) pj_pool_alloc(pool, 20);
1441
pj_create_random_string(p, 5);
1443
*p++ = '@'; *p++ = 'p'; *p++ = 'j';
1444
pj_create_random_string(p, 6);
1446
*p++ = '.'; *p++ = 'o'; *p++ = 'r'; *p++ = 'g';
1447
stream->cname.slen = p - stream->cname.ptr;
1450
/* Create mutex to protect jitter buffer: */
1452
status = pj_mutex_create_simple(pool, NULL, &stream->jb_mutex);
1453
if (status != PJ_SUCCESS)
1456
/* Init and open the codec. */
1457
status = pjmedia_vid_codec_init(stream->codec, pool);
1458
if (status != PJ_SUCCESS)
1460
status = pjmedia_vid_codec_open(stream->codec, info->codec_param);
1461
if (status != PJ_SUCCESS)
1464
/* Subscribe to codec events */
1465
pjmedia_event_subscribe(NULL, &stream_event_cb, stream,
1468
/* Estimate the maximum frame size */
1469
stream->frame_size = vfd_enc->size.w * vfd_enc->size.h * 4;
1472
stream->frame_size = vfd_enc->max_bps/8 * vfd_enc->fps.denum /
1475
/* As the maximum frame_size is not represented directly by maximum bps
1476
* (which includes intra and predicted frames), let's increase the
1477
* frame size value for safety.
1479
stream->frame_size <<= 4;
1482
/* Validate the frame size */
1483
if (stream->frame_size == 0 ||
1484
stream->frame_size > PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE)
1486
stream->frame_size = PJMEDIA_MAX_VIDEO_ENC_FRAME_SIZE;
1489
/* Get frame length in timestamp unit */
1490
stream->frame_ts_len = info->codec_info.clock_rate *
1491
vfd_enc->fps.denum / vfd_enc->fps.num;
1493
/* Initialize send rate states */
1494
pj_get_timestamp_freq(&stream->ts_freq);
1495
if (info->rc_cfg.bandwidth == 0)
1496
info->rc_cfg.bandwidth = vfd_enc->max_bps;
1498
/* For simple blocking, need to have bandwidth large enough, otherwise
1499
* we can slow down the transmission too much
1501
if (info->rc_cfg.method==PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING &&
1502
info->rc_cfg.bandwidth < vfd_enc->avg_bps * 3)
1504
info->rc_cfg.bandwidth = vfd_enc->avg_bps * 3;
1507
/* Override the initial framerate in the decoding direction. This initial
1508
* value will be used by the renderer to configure its clock, and setting
1509
* it to a bit higher value can avoid the possibility of high latency
1510
* caused by clock drift (remote encoder clock runs slightly faster than
1511
* local renderer clock) or video setup lag. Note that the actual framerate
1512
* will be continuously calculated based on the incoming RTP timestamps.
1514
vfd_dec->fps.num = vfd_dec->fps.num * 3 / 2;
1515
stream->dec_max_fps = vfd_dec->fps;
1517
/* Create decoder channel */
1518
status = create_channel( pool, stream, PJMEDIA_DIR_DECODING,
1519
info->rx_pt, info, &stream->dec);
1520
if (status != PJ_SUCCESS)
1523
/* Create encoder channel */
1524
status = create_channel( pool, stream, PJMEDIA_DIR_ENCODING,
1525
info->tx_pt, info, &stream->enc);
1526
if (status != PJ_SUCCESS)
1529
/* Create temporary buffer for immediate decoding */
1530
stream->dec_max_size = vfd_dec->size.w * vfd_dec->size.h * 4;
1531
stream->dec_frame.buf = pj_pool_alloc(pool, stream->dec_max_size);
1533
/* Init jitter buffer parameters: */
1534
frm_ptime = 1000 * vfd_enc->fps.denum / vfd_enc->fps.num;
1535
chunks_per_frm = stream->frame_size / PJMEDIA_MAX_MRU;
1536
if (chunks_per_frm < MIN_CHUNKS_PER_FRM)
1537
chunks_per_frm = MIN_CHUNKS_PER_FRM;
1539
/* JB max count, default 500ms */
1540
if (info->jb_max >= frm_ptime)
1541
jb_max = info->jb_max * chunks_per_frm / frm_ptime;
1543
jb_max = 500 * chunks_per_frm / frm_ptime;
1545
/* JB min prefetch, default 1 frame */
1546
if (info->jb_min_pre >= frm_ptime)
1547
jb_min_pre = info->jb_min_pre * chunks_per_frm / frm_ptime;
1551
/* JB max prefetch, default 4/5 JB max count */
1552
if (info->jb_max_pre >= frm_ptime)
1553
jb_max_pre = info->jb_max_pre * chunks_per_frm / frm_ptime;
1555
jb_max_pre = jb_max * 4 / 5;
1557
/* JB init prefetch, default 0 */
1558
if (info->jb_init >= frm_ptime)
1559
jb_init = info->jb_init * chunks_per_frm / frm_ptime;
1563
/* Allocate array for temporary storage for assembly of incoming
1564
* frames. Add more just in case.
1566
stream->rx_frame_cnt = chunks_per_frm * 2;
1567
stream->rx_frames = pj_pool_calloc(pool, stream->rx_frame_cnt,
1568
sizeof(stream->rx_frames[0]));
1570
/* Create jitter buffer */
1571
status = pjmedia_jbuf_create(pool, &stream->dec->port.info.name,
1573
1000 * vfd_enc->fps.denum / vfd_enc->fps.num,
1574
jb_max, &stream->jb);
1575
if (status != PJ_SUCCESS)
1579
/* Set up jitter buffer */
1580
pjmedia_jbuf_set_adaptive(stream->jb, jb_init, jb_min_pre, jb_max_pre);
1581
pjmedia_jbuf_set_discard(stream->jb, PJMEDIA_JB_DISCARD_NONE);
1583
/* Init RTCP session: */
1585
pjmedia_rtcp_session_setting rtcp_setting;
1587
pjmedia_rtcp_session_setting_default(&rtcp_setting);
1588
rtcp_setting.name = stream->name.ptr;
1589
rtcp_setting.ssrc = info->ssrc;
1590
rtcp_setting.rtp_ts_base = pj_ntohl(stream->enc->rtp.out_hdr.ts);
1591
rtcp_setting.clock_rate = info->codec_info.clock_rate;
1592
rtcp_setting.samples_per_frame = 1;
1594
pjmedia_rtcp_init2(&stream->rtcp, &rtcp_setting);
1597
/* Allocate outgoing RTCP buffer, should be enough to hold SR/RR, SDES,
1600
stream->out_rtcp_pkt_size = sizeof(pjmedia_rtcp_sr_pkt) +
1601
sizeof(pjmedia_rtcp_common) +
1602
(4 + stream->cname.slen) +
1604
if (stream->out_rtcp_pkt_size > PJMEDIA_MAX_MTU)
1605
stream->out_rtcp_pkt_size = PJMEDIA_MAX_MTU;
1607
stream->out_rtcp_pkt = pj_pool_alloc(pool, stream->out_rtcp_pkt_size);
1609
/* Only attach transport when stream is ready. */
1610
status = pjmedia_transport_attach(tp, stream, &info->rem_addr,
1612
pj_sockaddr_get_len(&info->rem_addr),
1613
&on_rx_rtp, &on_rx_rtcp);
1614
if (status != PJ_SUCCESS)
1617
stream->transport = tp;
1619
/* Send RTCP SDES */
1620
if (!stream->rtcp_sdes_bye_disabled) {
1621
pjmedia_vid_stream_send_rtcp_sdes(stream);
1624
#if defined(PJMEDIA_STREAM_ENABLE_KA) && PJMEDIA_STREAM_ENABLE_KA!=0
1625
/* NAT hole punching by sending KA packet via RTP transport. */
1627
send_keep_alive_packet(stream);
1632
char trace_name[PJ_MAXPATH];
1635
pj_ansi_snprintf(trace_name, sizeof(trace_name),
1636
TRACE_JB_PATH_PREFIX "%s.csv",
1637
channel->port.info.name.ptr);
1638
status = pj_file_open(pool, trace_name, PJ_O_RDWR,
1639
&stream->trace_jb_fd);
1640
if (status != PJ_SUCCESS) {
1641
stream->trace_jb_fd = TRACE_JB_INVALID_FD;
1642
PJ_LOG(3,(THIS_FILE, "Failed creating RTP trace file '%s'",
1645
stream->trace_jb_buf = (char*)pj_pool_alloc(pool, PJ_LOG_MAX_SIZE);
1647
/* Print column header */
1648
len = pj_ansi_snprintf(stream->trace_jb_buf, PJ_LOG_MAX_SIZE,
1649
"Time, Operation, Size, Frame Count, "
1650
"Frame type, RTP Seq, RTP TS, RTP M, "
1651
"JB size, JB burst level, JB prefetch\n");
1652
pj_file_write(stream->trace_jb_fd, stream->trace_jb_buf, &len);
1653
pj_file_flush(stream->trace_jb_fd);
1658
/* Save the stream info */
1659
pj_memcpy(&stream->info, info, sizeof(*info));
1660
stream->info.codec_param = pjmedia_vid_codec_param_clone(
1661
pool, info->codec_param);
1666
PJ_LOG(5,(THIS_FILE, "Video stream %s created", stream->name.ptr));
1675
PJ_DEF(pj_status_t) pjmedia_vid_stream_destroy( pjmedia_vid_stream *stream )
1677
PJ_ASSERT_RETURN(stream != NULL, PJ_EINVAL);
1681
unsigned total_time;
1683
total_time = pj_elapsed_msec(&stream->tx_start, &stream->tx_end);
1684
PJ_LOG(5, (stream->name.ptr,
1685
"RC stat: pkt_cnt=%.2f/image, sleep=%.2fms/s, fps=%.2f",
1686
stream->rc_total_pkt*1.0/stream->rc_total_img,
1687
stream->rc_total_sleep*1000.0/total_time,
1688
stream->rc_total_img*1000.0/total_time));
1692
/* Send RTCP BYE (also SDES) */
1693
if (!stream->rtcp_sdes_bye_disabled) {
1694
send_rtcp(stream, PJ_TRUE, PJ_TRUE);
1697
/* Detach from transport
1698
* MUST NOT hold stream mutex while detaching from transport, as
1699
* it may cause deadlock. See ticket #460 for the details.
1701
if (stream->transport) {
1702
pjmedia_transport_detach(stream->transport, stream);
1703
stream->transport = NULL;
1706
/* This function may be called when stream is partly initialized. */
1707
if (stream->jb_mutex)
1708
pj_mutex_lock(stream->jb_mutex);
1712
if (stream->codec) {
1713
pjmedia_event_unsubscribe(NULL, &stream_event_cb, stream,
1715
pjmedia_vid_codec_close(stream->codec);
1716
pjmedia_vid_codec_mgr_dealloc_codec(stream->codec_mgr, stream->codec);
1717
stream->codec = NULL;
1722
if (stream->jb_mutex) {
1723
pj_mutex_destroy(stream->jb_mutex);
1724
stream->jb_mutex = NULL;
1727
/* Destroy jitter buffer */
1729
pjmedia_jbuf_destroy(stream->jb);
1734
if (TRACE_JB_OPENED(stream)) {
1735
pj_file_close(stream->trace_jb_fd);
1736
stream->trace_jb_fd = TRACE_JB_INVALID_FD;
1740
if (stream->own_pool) {
1741
pj_pool_t *pool = stream->own_pool;
1742
stream->own_pool = NULL;
1743
pj_pool_release(pool);
1751
* Get the port interface.
1753
PJ_DEF(pj_status_t) pjmedia_vid_stream_get_port(pjmedia_vid_stream *stream,
1755
pjmedia_port **p_port )
1757
PJ_ASSERT_RETURN(dir==PJMEDIA_DIR_ENCODING || dir==PJMEDIA_DIR_DECODING,
1760
if (dir == PJMEDIA_DIR_ENCODING)
1761
*p_port = &stream->enc->port;
1763
*p_port = &stream->dec->port;
1770
* Get the transport object
1772
PJ_DEF(pjmedia_transport*) pjmedia_vid_stream_get_transport(
1773
pjmedia_vid_stream *st)
1775
return st->transport;
1780
* Get stream statistics.
1782
PJ_DEF(pj_status_t) pjmedia_vid_stream_get_stat(
1783
const pjmedia_vid_stream *stream,
1784
pjmedia_rtcp_stat *stat)
1786
PJ_ASSERT_RETURN(stream && stat, PJ_EINVAL);
1788
pj_memcpy(stat, &stream->rtcp.stat, sizeof(pjmedia_rtcp_stat));
1794
* Reset the stream statistics in the middle of a stream session.
1796
PJ_DEF(pj_status_t) pjmedia_vid_stream_reset_stat(pjmedia_vid_stream *stream)
1798
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1800
pjmedia_rtcp_init_stat(&stream->rtcp.stat);
1807
* Get jitter buffer state.
1809
PJ_DEF(pj_status_t) pjmedia_vid_stream_get_stat_jbuf(
1810
const pjmedia_vid_stream *stream,
1811
pjmedia_jb_state *state)
1813
PJ_ASSERT_RETURN(stream && state, PJ_EINVAL);
1814
return pjmedia_jbuf_get_state(stream->jb, state);
1819
* Get the stream info.
1821
PJ_DEF(pj_status_t) pjmedia_vid_stream_get_info(
1822
const pjmedia_vid_stream *stream,
1823
pjmedia_vid_stream_info *info)
1825
PJ_ASSERT_RETURN(stream && info, PJ_EINVAL);
1826
pj_memcpy(info, &stream->info, sizeof(*info));
1834
PJ_DEF(pj_status_t) pjmedia_vid_stream_start(pjmedia_vid_stream *stream)
1837
PJ_ASSERT_RETURN(stream && stream->enc && stream->dec, PJ_EINVALIDOP);
1839
if (stream->enc && (stream->dir & PJMEDIA_DIR_ENCODING)) {
1840
stream->enc->paused = 0;
1841
//pjmedia_snd_stream_start(stream->enc->snd_stream);
1842
PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream started"));
1844
PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused"));
1847
if (stream->dec && (stream->dir & PJMEDIA_DIR_DECODING)) {
1848
stream->dec->paused = 0;
1849
//pjmedia_snd_stream_start(stream->dec->snd_stream);
1850
PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream started"));
1852
PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused"));
1862
PJ_DEF(pj_bool_t) pjmedia_vid_stream_is_running(pjmedia_vid_stream *stream,
1865
pj_bool_t is_running = PJ_TRUE;
1867
PJ_ASSERT_RETURN(stream, PJ_FALSE);
1869
if (dir & PJMEDIA_DIR_ENCODING) {
1870
is_running &= (stream->enc && !stream->enc->paused);
1873
if (dir & PJMEDIA_DIR_DECODING) {
1874
is_running &= (stream->dec && !stream->dec->paused);
1883
PJ_DEF(pj_status_t) pjmedia_vid_stream_pause(pjmedia_vid_stream *stream,
1886
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1888
if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) {
1889
stream->enc->paused = 1;
1890
PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream paused"));
1893
if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) {
1894
stream->dec->paused = 1;
1896
/* Also reset jitter buffer */
1897
pj_mutex_lock( stream->jb_mutex );
1898
pjmedia_jbuf_reset(stream->jb);
1899
pj_mutex_unlock( stream->jb_mutex );
1901
PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream paused"));
1911
PJ_DEF(pj_status_t) pjmedia_vid_stream_resume(pjmedia_vid_stream *stream,
1914
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1916
if ((dir & PJMEDIA_DIR_ENCODING) && stream->enc) {
1917
stream->enc->paused = 0;
1918
PJ_LOG(4,(stream->enc->port.info.name.ptr, "Encoder stream resumed"));
1921
if ((dir & PJMEDIA_DIR_DECODING) && stream->dec) {
1922
stream->dec->paused = 0;
1923
PJ_LOG(4,(stream->dec->port.info.name.ptr, "Decoder stream resumed"));
1931
* Force stream to send video keyframe.
1933
PJ_DEF(pj_status_t) pjmedia_vid_stream_send_keyframe(
1934
pjmedia_vid_stream *stream)
1936
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1938
if (!pjmedia_vid_stream_is_running(stream, PJMEDIA_DIR_ENCODING))
1939
return PJ_EINVALIDOP;
1941
stream->force_keyframe = PJ_TRUE;
1950
PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_sdes(
1951
pjmedia_vid_stream *stream)
1953
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1955
return send_rtcp(stream, PJ_TRUE, PJ_FALSE);
1962
PJ_DEF(pj_status_t) pjmedia_vid_stream_send_rtcp_bye(
1963
pjmedia_vid_stream *stream)
1965
PJ_ASSERT_RETURN(stream, PJ_EINVAL);
1967
if (stream->enc && stream->transport) {
1968
return send_rtcp(stream, PJ_TRUE, PJ_TRUE);
1976
* Initialize the video stream rate control with default settings.
1979
pjmedia_vid_stream_rc_config_default(pjmedia_vid_stream_rc_config *cfg)
1981
pj_bzero(cfg, sizeof(*cfg));
1982
cfg->method = PJMEDIA_VID_STREAM_RC_SIMPLE_BLOCKING;
1986
#endif /* PJMEDIA_HAS_VIDEO */