• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

libavformat/rtpdec.c

Go to the documentation of this file.
00001 /*
00002  * RTP input format
00003  * Copyright (c) 2002 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 /* needed for gethostname() */
00023 #define _XOPEN_SOURCE 600
00024 
00025 #include "libavcodec/bitstream.h"
00026 #include "avformat.h"
00027 #include "mpegts.h"
00028 
00029 #include <unistd.h>
00030 #include "network.h"
00031 
00032 #include "rtpdec.h"
00033 #include "rtp_h264.h"
00034 
00035 //#define DEBUG
00036 
00037 /* TODO: - add RTCP statistics reporting (should be optional).
00038 
00039          - add support for h263/mpeg4 packetized output : IDEA: send a
00040          buffer to 'rtp_write_packet' contains all the packets for ONE
00041          frame. Each packet should have a four byte header containing
00042          the length in big endian format (same trick as
00043          'url_open_dyn_packet_buf')
00044 */
00045 
00046 /* statistics functions */
00047 RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
00048 
00049 static RTPDynamicProtocolHandler mp4v_es_handler= {"MP4V-ES", CODEC_TYPE_VIDEO, CODEC_ID_MPEG4};
00050 static RTPDynamicProtocolHandler mpeg4_generic_handler= {"mpeg4-generic", CODEC_TYPE_AUDIO, CODEC_ID_AAC};
00051 
00052 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
00053 {
00054     handler->next= RTPFirstDynamicPayloadHandler;
00055     RTPFirstDynamicPayloadHandler= handler;
00056 }
00057 
00058 void av_register_rtp_dynamic_payload_handlers(void)
00059 {
00060     ff_register_dynamic_payload_handler(&mp4v_es_handler);
00061     ff_register_dynamic_payload_handler(&mpeg4_generic_handler);
00062     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
00063 }
00064 
00065 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
00066 {
00067     if (buf[1] != 200)
00068         return -1;
00069     s->last_rtcp_ntp_time = AV_RB64(buf + 8);
00070     if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
00071         s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
00072     s->last_rtcp_timestamp = AV_RB32(buf + 16);
00073     return 0;
00074 }
00075 
00076 #define RTP_SEQ_MOD (1<<16)
00077 
00081 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
00082 {
00083     memset(s, 0, sizeof(RTPStatistics));
00084     s->max_seq= base_sequence;
00085     s->probation= 1;
00086 }
00087 
00091 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
00092 {
00093     s->max_seq= seq;
00094     s->cycles= 0;
00095     s->base_seq= seq -1;
00096     s->bad_seq= RTP_SEQ_MOD + 1;
00097     s->received= 0;
00098     s->expected_prior= 0;
00099     s->received_prior= 0;
00100     s->jitter= 0;
00101     s->transit= 0;
00102 }
00103 
00107 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
00108 {
00109     uint16_t udelta= seq - s->max_seq;
00110     const int MAX_DROPOUT= 3000;
00111     const int MAX_MISORDER = 100;
00112     const int MIN_SEQUENTIAL = 2;
00113 
00114     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
00115     if(s->probation)
00116     {
00117         if(seq==s->max_seq + 1) {
00118             s->probation--;
00119             s->max_seq= seq;
00120             if(s->probation==0) {
00121                 rtp_init_sequence(s, seq);
00122                 s->received++;
00123                 return 1;
00124             }
00125         } else {
00126             s->probation= MIN_SEQUENTIAL - 1;
00127             s->max_seq = seq;
00128         }
00129     } else if (udelta < MAX_DROPOUT) {
00130         // in order, with permissible gap
00131         if(seq < s->max_seq) {
00132             //sequence number wrapped; count antother 64k cycles
00133             s->cycles += RTP_SEQ_MOD;
00134         }
00135         s->max_seq= seq;
00136     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
00137         // sequence made a large jump...
00138         if(seq==s->bad_seq) {
00139             // two sequential packets-- assume that the other side restarted without telling us; just resync.
00140             rtp_init_sequence(s, seq);
00141         } else {
00142             s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
00143             return 0;
00144         }
00145     } else {
00146         // duplicate or reordered packet...
00147     }
00148     s->received++;
00149     return 1;
00150 }
00151 
00152 #if 0
00153 
00158 static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
00159 {
00160     uint32_t transit= arrival_timestamp - sent_timestamp;
00161     int d;
00162     s->transit= transit;
00163     d= FFABS(transit - s->transit);
00164     s->jitter += d - ((s->jitter + 8)>>4);
00165 }
00166 #endif
00167 
00168 int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
00169 {
00170     ByteIOContext *pb;
00171     uint8_t *buf;
00172     int len;
00173     int rtcp_bytes;
00174     RTPStatistics *stats= &s->statistics;
00175     uint32_t lost;
00176     uint32_t extended_max;
00177     uint32_t expected_interval;
00178     uint32_t received_interval;
00179     uint32_t lost_interval;
00180     uint32_t expected;
00181     uint32_t fraction;
00182     uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
00183 
00184     if (!s->rtp_ctx || (count < 1))
00185         return -1;
00186 
00187     /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
00188     /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
00189     s->octet_count += count;
00190     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
00191         RTCP_TX_RATIO_DEN;
00192     rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
00193     if (rtcp_bytes < 28)
00194         return -1;
00195     s->last_octet_count = s->octet_count;
00196 
00197     if (url_open_dyn_buf(&pb) < 0)
00198         return -1;
00199 
00200     // Receiver Report
00201     put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
00202     put_byte(pb, 201);
00203     put_be16(pb, 7); /* length in words - 1 */
00204     put_be32(pb, s->ssrc); // our own SSRC
00205     put_be32(pb, s->ssrc); // XXX: should be the server's here!
00206     // some placeholders we should really fill...
00207     // RFC 1889/p64
00208     extended_max= stats->cycles + stats->max_seq;
00209     expected= extended_max - stats->base_seq + 1;
00210     lost= expected - stats->received;
00211     lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
00212     expected_interval= expected - stats->expected_prior;
00213     stats->expected_prior= expected;
00214     received_interval= stats->received - stats->received_prior;
00215     stats->received_prior= stats->received;
00216     lost_interval= expected_interval - received_interval;
00217     if (expected_interval==0 || lost_interval<=0) fraction= 0;
00218     else fraction = (lost_interval<<8)/expected_interval;
00219 
00220     fraction= (fraction<<24) | lost;
00221 
00222     put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
00223     put_be32(pb, extended_max); /* max sequence received */
00224     put_be32(pb, stats->jitter>>4); /* jitter */
00225 
00226     if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
00227     {
00228         put_be32(pb, 0); /* last SR timestamp */
00229         put_be32(pb, 0); /* delay since last SR */
00230     } else {
00231         uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
00232         uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
00233 
00234         put_be32(pb, middle_32_bits); /* last SR timestamp */
00235         put_be32(pb, delay_since_last); /* delay since last SR */
00236     }
00237 
00238     // CNAME
00239     put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
00240     put_byte(pb, 202);
00241     len = strlen(s->hostname);
00242     put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
00243     put_be32(pb, s->ssrc);
00244     put_byte(pb, 0x01);
00245     put_byte(pb, len);
00246     put_buffer(pb, s->hostname, len);
00247     // padding
00248     for (len = (6 + len) % 4; len % 4; len++) {
00249         put_byte(pb, 0);
00250     }
00251 
00252     put_flush_packet(pb);
00253     len = url_close_dyn_buf(pb, &buf);
00254     if ((len > 0) && buf) {
00255         int result;
00256         dprintf(s->ic, "sending %d bytes of RR\n", len);
00257         result= url_write(s->rtp_ctx, buf, len);
00258         dprintf(s->ic, "result from url_write: %d\n", result);
00259         av_free(buf);
00260     }
00261     return 0;
00262 }
00263 
00270 RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, RTPPayloadData *rtp_payload_data)
00271 {
00272     RTPDemuxContext *s;
00273 
00274     s = av_mallocz(sizeof(RTPDemuxContext));
00275     if (!s)
00276         return NULL;
00277     s->payload_type = payload_type;
00278     s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
00279     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
00280     s->ic = s1;
00281     s->st = st;
00282     s->rtp_payload_data = rtp_payload_data;
00283     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
00284     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
00285         s->ts = mpegts_parse_open(s->ic);
00286         if (s->ts == NULL) {
00287             av_free(s);
00288             return NULL;
00289         }
00290     } else {
00291         av_set_pts_info(st, 32, 1, 90000);
00292         switch(st->codec->codec_id) {
00293         case CODEC_ID_MPEG1VIDEO:
00294         case CODEC_ID_MPEG2VIDEO:
00295         case CODEC_ID_MP2:
00296         case CODEC_ID_MP3:
00297         case CODEC_ID_MPEG4:
00298         case CODEC_ID_H264:
00299             st->need_parsing = AVSTREAM_PARSE_FULL;
00300             break;
00301         default:
00302             if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
00303                 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
00304             }
00305             break;
00306         }
00307     }
00308     // needed to send back RTCP RR in RTSP sessions
00309     s->rtp_ctx = rtpc;
00310     gethostname(s->hostname, sizeof(s->hostname));
00311     return s;
00312 }
00313 
00314 void
00315 rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
00316                                RTPDynamicProtocolHandler *handler)
00317 {
00318     s->dynamic_protocol_context = ctx;
00319     s->parse_packet = handler->parse_packet;
00320 }
00321 
00322 static int rtp_parse_mp4_au(RTPDemuxContext *s, const uint8_t *buf)
00323 {
00324     int au_headers_length, au_header_size, i;
00325     GetBitContext getbitcontext;
00326     RTPPayloadData *infos;
00327 
00328     infos = s->rtp_payload_data;
00329 
00330     if (infos == NULL)
00331         return -1;
00332 
00333     /* decode the first 2 bytes where the AUHeader sections are stored
00334        length in bits */
00335     au_headers_length = AV_RB16(buf);
00336 
00337     if (au_headers_length > RTP_MAX_PACKET_LENGTH)
00338       return -1;
00339 
00340     infos->au_headers_length_bytes = (au_headers_length + 7) / 8;
00341 
00342     /* skip AU headers length section (2 bytes) */
00343     buf += 2;
00344 
00345     init_get_bits(&getbitcontext, buf, infos->au_headers_length_bytes * 8);
00346 
00347     /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */
00348     au_header_size = infos->sizelength + infos->indexlength;
00349     if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))
00350         return -1;
00351 
00352     infos->nb_au_headers = au_headers_length / au_header_size;
00353     infos->au_headers = av_malloc(sizeof(struct AUHeaders) * infos->nb_au_headers);
00354 
00355     /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)
00356        In my test, the FAAD decoder does not behave correctly when sending each AU one by one
00357        but does when sending the whole as one big packet...  */
00358     infos->au_headers[0].size = 0;
00359     infos->au_headers[0].index = 0;
00360     for (i = 0; i < infos->nb_au_headers; ++i) {
00361         infos->au_headers[0].size += get_bits_long(&getbitcontext, infos->sizelength);
00362         infos->au_headers[0].index = get_bits_long(&getbitcontext, infos->indexlength);
00363     }
00364 
00365     infos->nb_au_headers = 1;
00366 
00367     return 0;
00368 }
00369 
00373 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
00374 {
00375     if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {
00376         int64_t addend;
00377         int delta_timestamp;
00378 
00379         /* compute pts from timestamp with received ntp_time */
00380         delta_timestamp = timestamp - s->last_rtcp_timestamp;
00381         /* convert to the PTS timebase */
00382         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
00383         pkt->pts = addend + delta_timestamp;
00384     }
00385     pkt->stream_index = s->st->index;
00386 }
00387 
00397 int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
00398                      const uint8_t *buf, int len)
00399 {
00400     unsigned int ssrc, h;
00401     int payload_type, seq, ret, flags = 0;
00402     AVStream *st;
00403     uint32_t timestamp;
00404     int rv= 0;
00405 
00406     if (!buf) {
00407         /* return the next packets, if any */
00408         if(s->st && s->parse_packet) {
00409             timestamp= 0; 
00410             rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
00411                                 s->st, pkt, &timestamp, NULL, 0, flags);
00412             finalize_packet(s, pkt, timestamp);
00413             return rv;
00414         } else {
00415             // TODO: Move to a dynamic packet handler (like above)
00416             if (s->read_buf_index >= s->read_buf_size)
00417                 return -1;
00418             ret = mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
00419                                       s->read_buf_size - s->read_buf_index);
00420             if (ret < 0)
00421                 return -1;
00422             s->read_buf_index += ret;
00423             if (s->read_buf_index < s->read_buf_size)
00424                 return 1;
00425             else
00426                 return 0;
00427         }
00428     }
00429 
00430     if (len < 12)
00431         return -1;
00432 
00433     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
00434         return -1;
00435     if (buf[1] >= 200 && buf[1] <= 204) {
00436         rtcp_parse_packet(s, buf, len);
00437         return -1;
00438     }
00439     payload_type = buf[1] & 0x7f;
00440     if (buf[1] & 0x80)
00441         flags |= RTP_FLAG_MARKER;
00442     seq  = AV_RB16(buf + 2);
00443     timestamp = AV_RB32(buf + 4);
00444     ssrc = AV_RB32(buf + 8);
00445     /* store the ssrc in the RTPDemuxContext */
00446     s->ssrc = ssrc;
00447 
00448     /* NOTE: we can handle only one payload type */
00449     if (s->payload_type != payload_type)
00450         return -1;
00451 
00452     st = s->st;
00453     // only do something with this if all the rtp checks pass...
00454     if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
00455     {
00456         av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
00457                payload_type, seq, ((s->seq + 1) & 0xffff));
00458         return -1;
00459     }
00460 
00461     s->seq = seq;
00462     len -= 12;
00463     buf += 12;
00464 
00465     if (!st) {
00466         /* specific MPEG2TS demux support */
00467         ret = mpegts_parse_packet(s->ts, pkt, buf, len);
00468         if (ret < 0)
00469             return -1;
00470         if (ret < len) {
00471             s->read_buf_size = len - ret;
00472             memcpy(s->buf, buf + ret, s->read_buf_size);
00473             s->read_buf_index = 0;
00474             return 1;
00475         }
00476     } else if (s->parse_packet) {
00477         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
00478                              s->st, pkt, &timestamp, buf, len, flags);
00479     } else {
00480         // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
00481         switch(st->codec->codec_id) {
00482         case CODEC_ID_MP2:
00483             /* better than nothing: skip mpeg audio RTP header */
00484             if (len <= 4)
00485                 return -1;
00486             h = AV_RB32(buf);
00487             len -= 4;
00488             buf += 4;
00489             av_new_packet(pkt, len);
00490             memcpy(pkt->data, buf, len);
00491             break;
00492         case CODEC_ID_MPEG1VIDEO:
00493         case CODEC_ID_MPEG2VIDEO:
00494             /* better than nothing: skip mpeg video RTP header */
00495             if (len <= 4)
00496                 return -1;
00497             h = AV_RB32(buf);
00498             buf += 4;
00499             len -= 4;
00500             if (h & (1 << 26)) {
00501                 /* mpeg2 */
00502                 if (len <= 4)
00503                     return -1;
00504                 buf += 4;
00505                 len -= 4;
00506             }
00507             av_new_packet(pkt, len);
00508             memcpy(pkt->data, buf, len);
00509             break;
00510             // moved from below, verbatim.  this is because this section handles packets, and the lower switch handles
00511             // timestamps.
00512             // TODO: Put this into a dynamic packet handler...
00513         case CODEC_ID_AAC:
00514             if (rtp_parse_mp4_au(s, buf))
00515                 return -1;
00516             {
00517                 RTPPayloadData *infos = s->rtp_payload_data;
00518                 if (infos == NULL)
00519                     return -1;
00520                 buf += infos->au_headers_length_bytes + 2;
00521                 len -= infos->au_headers_length_bytes + 2;
00522 
00523                 /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define
00524                     one au_header */
00525                 av_new_packet(pkt, infos->au_headers[0].size);
00526                 memcpy(pkt->data, buf, infos->au_headers[0].size);
00527                 buf += infos->au_headers[0].size;
00528                 len -= infos->au_headers[0].size;
00529             }
00530             s->read_buf_size = len;
00531             rv= 0;
00532             break;
00533         default:
00534             av_new_packet(pkt, len);
00535             memcpy(pkt->data, buf, len);
00536             break;
00537         }
00538 
00539         // now perform timestamp things....
00540         finalize_packet(s, pkt, timestamp);
00541     }
00542     return rv;
00543 }
00544 
00545 void rtp_parse_close(RTPDemuxContext *s)
00546 {
00547     // TODO: fold this into the protocol specific data fields.
00548     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
00549         mpegts_parse_close(s->ts);
00550     }
00551     av_free(s);
00552 }

Generated on Sat Feb 16 2013 09:23:15 for ffmpeg by  doxygen 1.7.1