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

libavformat/mpegtsenc.c

Go to the documentation of this file.
00001 /*
00002  * MPEG2 transport stream (aka DVB) muxer
00003  * Copyright (c) 2003 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 #include "libavutil/bswap.h"
00023 #include "libavutil/crc.h"
00024 #include "libavutil/dict.h"
00025 #include "libavutil/opt.h"
00026 #include "libavutil/avassert.h"
00027 #include "libavcodec/mpegvideo.h"
00028 #include "avformat.h"
00029 #include "internal.h"
00030 #include "mpegts.h"
00031 #include "adts.h"
00032 
00033 #define PCR_TIME_BASE 27000000
00034 
00035 /* write DVB SI sections */
00036 
00037 /*********************************************/
00038 /* mpegts section writer */
00039 
00040 typedef struct MpegTSSection {
00041     int pid;
00042     int cc;
00043     void (*write_packet)(struct MpegTSSection *s, const uint8_t *packet);
00044     void *opaque;
00045 } MpegTSSection;
00046 
00047 typedef struct MpegTSService {
00048     MpegTSSection pmt; /* MPEG2 pmt table context */
00049     int sid;           /* service ID */
00050     char *name;
00051     char *provider_name;
00052     int pcr_pid;
00053     int pcr_packet_count;
00054     int pcr_packet_period;
00055 } MpegTSService;
00056 
00057 typedef struct MpegTSWrite {
00058     const AVClass *av_class;
00059     MpegTSSection pat; /* MPEG2 pat table */
00060     MpegTSSection sdt; /* MPEG2 sdt table context */
00061     MpegTSService **services;
00062     int sdt_packet_count;
00063     int sdt_packet_period;
00064     int pat_packet_count;
00065     int pat_packet_period;
00066     int nb_services;
00067     int onid;
00068     int tsid;
00069     int64_t first_pcr;
00070     int mux_rate; 
00071 
00072     int transport_stream_id;
00073     int original_network_id;
00074     int service_id;
00075 
00076     int pmt_start_pid;
00077     int start_pid;
00078 } MpegTSWrite;
00079 
00080 static const AVOption options[] = {
00081     { "mpegts_transport_stream_id", "Set transport_stream_id field.",
00082       offsetof(MpegTSWrite, transport_stream_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
00083     { "mpegts_original_network_id", "Set original_network_id field.",
00084       offsetof(MpegTSWrite, original_network_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
00085     { "mpegts_service_id", "Set service_id field.",
00086       offsetof(MpegTSWrite, service_id), FF_OPT_TYPE_INT, {.dbl = 0x0001 }, 0x0001, 0xffff, AV_OPT_FLAG_ENCODING_PARAM},
00087     { "mpegts_pmt_start_pid", "Set the first pid of the PMT.",
00088       offsetof(MpegTSWrite, pmt_start_pid), FF_OPT_TYPE_INT, {.dbl = 0x1000 }, 0x0010, 0x1f00, AV_OPT_FLAG_ENCODING_PARAM},
00089     { "mpegts_start_pid", "Set the first pid.",
00090       offsetof(MpegTSWrite, start_pid), FF_OPT_TYPE_INT, {.dbl = 0x0100 }, 0x0100, 0x0f00, AV_OPT_FLAG_ENCODING_PARAM},
00091     { NULL },
00092 };
00093 
00094 static const AVClass mpegts_muxer_class = {
00095     .class_name     = "MPEGTS muxer",
00096     .item_name      = av_default_item_name,
00097     .option         = options,
00098     .version        = LIBAVUTIL_VERSION_INT,
00099 };
00100 
00101 /* NOTE: 4 bytes must be left at the end for the crc32 */
00102 static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)
00103 {
00104     unsigned int crc;
00105     unsigned char packet[TS_PACKET_SIZE];
00106     const unsigned char *buf_ptr;
00107     unsigned char *q;
00108     int first, b, len1, left;
00109 
00110     crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, buf, len - 4));
00111     buf[len - 4] = (crc >> 24) & 0xff;
00112     buf[len - 3] = (crc >> 16) & 0xff;
00113     buf[len - 2] = (crc >> 8) & 0xff;
00114     buf[len - 1] = (crc) & 0xff;
00115 
00116     /* send each packet */
00117     buf_ptr = buf;
00118     while (len > 0) {
00119         first = (buf == buf_ptr);
00120         q = packet;
00121         *q++ = 0x47;
00122         b = (s->pid >> 8);
00123         if (first)
00124             b |= 0x40;
00125         *q++ = b;
00126         *q++ = s->pid;
00127         s->cc = (s->cc + 1) & 0xf;
00128         *q++ = 0x10 | s->cc;
00129         if (first)
00130             *q++ = 0; /* 0 offset */
00131         len1 = TS_PACKET_SIZE - (q - packet);
00132         if (len1 > len)
00133             len1 = len;
00134         memcpy(q, buf_ptr, len1);
00135         q += len1;
00136         /* add known padding data */
00137         left = TS_PACKET_SIZE - (q - packet);
00138         if (left > 0)
00139             memset(q, 0xff, left);
00140 
00141         s->write_packet(s, packet);
00142 
00143         buf_ptr += len1;
00144         len -= len1;
00145     }
00146 }
00147 
00148 static inline void put16(uint8_t **q_ptr, int val)
00149 {
00150     uint8_t *q;
00151     q = *q_ptr;
00152     *q++ = val >> 8;
00153     *q++ = val;
00154     *q_ptr = q;
00155 }
00156 
00157 static int mpegts_write_section1(MpegTSSection *s, int tid, int id,
00158                           int version, int sec_num, int last_sec_num,
00159                           uint8_t *buf, int len)
00160 {
00161     uint8_t section[1024], *q;
00162     unsigned int tot_len;
00163     /* reserved_future_use field must be set to 1 for SDT */
00164     unsigned int flags = tid == SDT_TID ? 0xf000 : 0xb000;
00165 
00166     tot_len = 3 + 5 + len + 4;
00167     /* check if not too big */
00168     if (tot_len > 1024)
00169         return -1;
00170 
00171     q = section;
00172     *q++ = tid;
00173     put16(&q, flags | (len + 5 + 4)); /* 5 byte header + 4 byte CRC */
00174     put16(&q, id);
00175     *q++ = 0xc1 | (version << 1); /* current_next_indicator = 1 */
00176     *q++ = sec_num;
00177     *q++ = last_sec_num;
00178     memcpy(q, buf, len);
00179 
00180     mpegts_write_section(s, section, tot_len);
00181     return 0;
00182 }
00183 
00184 /*********************************************/
00185 /* mpegts writer */
00186 
00187 #define DEFAULT_PROVIDER_NAME   "FFmpeg"
00188 #define DEFAULT_SERVICE_NAME    "Service01"
00189 
00190 /* a PES packet header is generated every DEFAULT_PES_HEADER_FREQ packets */
00191 #define DEFAULT_PES_HEADER_FREQ 16
00192 #define DEFAULT_PES_PAYLOAD_SIZE ((DEFAULT_PES_HEADER_FREQ - 1) * 184 + 170)
00193 
00194 /* we retransmit the SI info at this rate */
00195 #define SDT_RETRANS_TIME 500
00196 #define PAT_RETRANS_TIME 100
00197 #define PCR_RETRANS_TIME 20
00198 
00199 typedef struct MpegTSWriteStream {
00200     struct MpegTSService *service;
00201     int pid; /* stream associated pid */
00202     int cc;
00203     int payload_index;
00204     int first_pts_check; 
00205     int64_t payload_pts;
00206     int64_t payload_dts;
00207     uint8_t payload[DEFAULT_PES_PAYLOAD_SIZE];
00208     ADTSContext *adts;
00209 } MpegTSWriteStream;
00210 
00211 static void mpegts_write_pat(AVFormatContext *s)
00212 {
00213     MpegTSWrite *ts = s->priv_data;
00214     MpegTSService *service;
00215     uint8_t data[1012], *q;
00216     int i;
00217 
00218     q = data;
00219     for(i = 0; i < ts->nb_services; i++) {
00220         service = ts->services[i];
00221         put16(&q, service->sid);
00222         put16(&q, 0xe000 | service->pmt.pid);
00223     }
00224     mpegts_write_section1(&ts->pat, PAT_TID, ts->tsid, 0, 0, 0,
00225                           data, q - data);
00226 }
00227 
00228 static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)
00229 {
00230     //    MpegTSWrite *ts = s->priv_data;
00231     uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;
00232     int val, stream_type, i;
00233 
00234     q = data;
00235     put16(&q, 0xe000 | service->pcr_pid);
00236 
00237     program_info_length_ptr = q;
00238     q += 2; /* patched after */
00239 
00240     /* put program info here */
00241 
00242     val = 0xf000 | (q - program_info_length_ptr - 2);
00243     program_info_length_ptr[0] = val >> 8;
00244     program_info_length_ptr[1] = val;
00245 
00246     for(i = 0; i < s->nb_streams; i++) {
00247         AVStream *st = s->streams[i];
00248         MpegTSWriteStream *ts_st = st->priv_data;
00249         AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
00250         switch(st->codec->codec_id) {
00251         case CODEC_ID_MPEG1VIDEO:
00252         case CODEC_ID_MPEG2VIDEO:
00253             stream_type = STREAM_TYPE_VIDEO_MPEG2;
00254             break;
00255         case CODEC_ID_MPEG4:
00256             stream_type = STREAM_TYPE_VIDEO_MPEG4;
00257             break;
00258         case CODEC_ID_H264:
00259             stream_type = STREAM_TYPE_VIDEO_H264;
00260             break;
00261         case CODEC_ID_DIRAC:
00262             stream_type = STREAM_TYPE_VIDEO_DIRAC;
00263             break;
00264         case CODEC_ID_MP2:
00265         case CODEC_ID_MP3:
00266             stream_type = STREAM_TYPE_AUDIO_MPEG1;
00267             break;
00268         case CODEC_ID_AAC:
00269             stream_type = STREAM_TYPE_AUDIO_AAC;
00270             break;
00271         case CODEC_ID_AAC_LATM:
00272             stream_type = STREAM_TYPE_AUDIO_AAC_LATM;
00273             break;
00274         case CODEC_ID_AC3:
00275             stream_type = STREAM_TYPE_AUDIO_AC3;
00276             break;
00277         default:
00278             stream_type = STREAM_TYPE_PRIVATE_DATA;
00279             break;
00280         }
00281         *q++ = stream_type;
00282         put16(&q, 0xe000 | ts_st->pid);
00283         desc_length_ptr = q;
00284         q += 2; /* patched after */
00285 
00286         /* write optional descriptors here */
00287         switch(st->codec->codec_type) {
00288         case AVMEDIA_TYPE_AUDIO:
00289             if (lang) {
00290                 char *p;
00291                 char *next = lang->value;
00292                 uint8_t *len_ptr;
00293 
00294                 *q++ = 0x0a; /* ISO 639 language descriptor */
00295                 len_ptr = q++;
00296                 *len_ptr = 0;
00297 
00298                 for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {
00299                     next = strchr(p, ',');
00300                     if (strlen(p) != 3 && (!next || next != p + 3))
00301                         continue; /* not a 3-letter code */
00302 
00303                     *q++ = *p++;
00304                     *q++ = *p++;
00305                     *q++ = *p++;
00306 
00307                 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
00308                     *q++ = 0x01;
00309                 else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
00310                     *q++ = 0x02;
00311                 else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
00312                     *q++ = 0x03;
00313                 else
00314                     *q++ = 0; /* undefined type */
00315 
00316                     *len_ptr += 4;
00317                 }
00318 
00319                 if (*len_ptr == 0)
00320                     q -= 2; /* no language codes were written */
00321             }
00322             break;
00323         case AVMEDIA_TYPE_SUBTITLE:
00324             {
00325                 const char *language;
00326                 language = lang && strlen(lang->value)==3 ? lang->value : "eng";
00327                 *q++ = 0x59;
00328                 *q++ = 8;
00329                 *q++ = language[0];
00330                 *q++ = language[1];
00331                 *q++ = language[2];
00332                 *q++ = 0x10; /* normal subtitles (0x20 = if hearing pb) */
00333                 if(st->codec->extradata_size == 4) {
00334                     memcpy(q, st->codec->extradata, 4);
00335                     q += 4;
00336                 } else {
00337                     put16(&q, 1); /* page id */
00338                     put16(&q, 1); /* ancillary page id */
00339                 }
00340             }
00341             break;
00342         case AVMEDIA_TYPE_VIDEO:
00343             if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {
00344                 *q++ = 0x05; /*MPEG-2 registration descriptor*/
00345                 *q++ = 4;
00346                 *q++ = 'd';
00347                 *q++ = 'r';
00348                 *q++ = 'a';
00349                 *q++ = 'c';
00350             }
00351             break;
00352         }
00353 
00354         val = 0xf000 | (q - desc_length_ptr - 2);
00355         desc_length_ptr[0] = val >> 8;
00356         desc_length_ptr[1] = val;
00357     }
00358     mpegts_write_section1(&service->pmt, PMT_TID, service->sid, 0, 0, 0,
00359                           data, q - data);
00360 }
00361 
00362 /* NOTE: str == NULL is accepted for an empty string */
00363 static void putstr8(uint8_t **q_ptr, const char *str)
00364 {
00365     uint8_t *q;
00366     int len;
00367 
00368     q = *q_ptr;
00369     if (!str)
00370         len = 0;
00371     else
00372         len = strlen(str);
00373     *q++ = len;
00374     memcpy(q, str, len);
00375     q += len;
00376     *q_ptr = q;
00377 }
00378 
00379 static void mpegts_write_sdt(AVFormatContext *s)
00380 {
00381     MpegTSWrite *ts = s->priv_data;
00382     MpegTSService *service;
00383     uint8_t data[1012], *q, *desc_list_len_ptr, *desc_len_ptr;
00384     int i, running_status, free_ca_mode, val;
00385 
00386     q = data;
00387     put16(&q, ts->onid);
00388     *q++ = 0xff;
00389     for(i = 0; i < ts->nb_services; i++) {
00390         service = ts->services[i];
00391         put16(&q, service->sid);
00392         *q++ = 0xfc | 0x00; /* currently no EIT info */
00393         desc_list_len_ptr = q;
00394         q += 2;
00395         running_status = 4; /* running */
00396         free_ca_mode = 0;
00397 
00398         /* write only one descriptor for the service name and provider */
00399         *q++ = 0x48;
00400         desc_len_ptr = q;
00401         q++;
00402         *q++ = 0x01; /* digital television service */
00403         putstr8(&q, service->provider_name);
00404         putstr8(&q, service->name);
00405         desc_len_ptr[0] = q - desc_len_ptr - 1;
00406 
00407         /* fill descriptor length */
00408         val = (running_status << 13) | (free_ca_mode << 12) |
00409             (q - desc_list_len_ptr - 2);
00410         desc_list_len_ptr[0] = val >> 8;
00411         desc_list_len_ptr[1] = val;
00412     }
00413     mpegts_write_section1(&ts->sdt, SDT_TID, ts->tsid, 0, 0, 0,
00414                           data, q - data);
00415 }
00416 
00417 static MpegTSService *mpegts_add_service(MpegTSWrite *ts,
00418                                          int sid,
00419                                          const char *provider_name,
00420                                          const char *name)
00421 {
00422     MpegTSService *service;
00423 
00424     service = av_mallocz(sizeof(MpegTSService));
00425     if (!service)
00426         return NULL;
00427     service->pmt.pid = ts->pmt_start_pid + ts->nb_services;
00428     service->sid = sid;
00429     service->provider_name = av_strdup(provider_name);
00430     service->name = av_strdup(name);
00431     service->pcr_pid = 0x1fff;
00432     dynarray_add(&ts->services, &ts->nb_services, service);
00433     return service;
00434 }
00435 
00436 static void section_write_packet(MpegTSSection *s, const uint8_t *packet)
00437 {
00438     AVFormatContext *ctx = s->opaque;
00439     avio_write(ctx->pb, packet, TS_PACKET_SIZE);
00440 }
00441 
00442 static int mpegts_write_header(AVFormatContext *s)
00443 {
00444     MpegTSWrite *ts = s->priv_data;
00445     MpegTSWriteStream *ts_st;
00446     MpegTSService *service;
00447     AVStream *st, *pcr_st = NULL;
00448     AVDictionaryEntry *title, *provider;
00449     int i, j;
00450     const char *service_name;
00451     const char *provider_name;
00452     int *pids;
00453 
00454     ts->tsid = ts->transport_stream_id;
00455     ts->onid = ts->original_network_id;
00456     /* allocate a single DVB service */
00457     title = av_dict_get(s->metadata, "service_name", NULL, 0);
00458     if (!title)
00459         title = av_dict_get(s->metadata, "title", NULL, 0);
00460     service_name = title ? title->value : DEFAULT_SERVICE_NAME;
00461     provider = av_dict_get(s->metadata, "service_provider", NULL, 0);
00462     provider_name = provider ? provider->value : DEFAULT_PROVIDER_NAME;
00463     service = mpegts_add_service(ts, ts->service_id, provider_name, service_name);
00464     service->pmt.write_packet = section_write_packet;
00465     service->pmt.opaque = s;
00466     service->pmt.cc = 15;
00467 
00468     ts->pat.pid = PAT_PID;
00469     ts->pat.cc = 15; // Initialize at 15 so that it wraps and be equal to 0 for the first packet we write
00470     ts->pat.write_packet = section_write_packet;
00471     ts->pat.opaque = s;
00472 
00473     ts->sdt.pid = SDT_PID;
00474     ts->sdt.cc = 15;
00475     ts->sdt.write_packet = section_write_packet;
00476     ts->sdt.opaque = s;
00477 
00478     pids = av_malloc(s->nb_streams * sizeof(*pids));
00479     if (!pids)
00480         return AVERROR(ENOMEM);
00481 
00482     /* assign pids to each stream */
00483     for(i = 0;i < s->nb_streams; i++) {
00484         st = s->streams[i];
00485         av_set_pts_info(st, 33, 1, 90000);
00486         ts_st = av_mallocz(sizeof(MpegTSWriteStream));
00487         if (!ts_st)
00488             goto fail;
00489         st->priv_data = ts_st;
00490         ts_st->service = service;
00491         /* MPEG pid values < 16 are reserved. Applications which set st->id in
00492          * this range are assigned a calculated pid. */
00493         if (st->id < 16) {
00494             ts_st->pid = ts->start_pid + i;
00495         } else if (st->id < 0x1FFF) {
00496             ts_st->pid = st->id;
00497         } else {
00498             av_log(s, AV_LOG_ERROR, "Invalid stream id %d, must be less than 8191\n", st->id);
00499             goto fail;
00500         }
00501         if (ts_st->pid == service->pmt.pid) {
00502             av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
00503             goto fail;
00504         }
00505         for (j = 0; j < i; j++)
00506             if (pids[j] == ts_st->pid) {
00507                 av_log(s, AV_LOG_ERROR, "Duplicate stream id %d\n", ts_st->pid);
00508                 goto fail;
00509             }
00510         pids[i] = ts_st->pid;
00511         ts_st->payload_pts = AV_NOPTS_VALUE;
00512         ts_st->payload_dts = AV_NOPTS_VALUE;
00513         ts_st->first_pts_check = 1;
00514         ts_st->cc = 15;
00515         /* update PCR pid by using the first video stream */
00516         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
00517             service->pcr_pid == 0x1fff) {
00518             service->pcr_pid = ts_st->pid;
00519             pcr_st = st;
00520         }
00521         if (st->codec->codec_id == CODEC_ID_AAC &&
00522             st->codec->extradata_size > 0) {
00523             ts_st->adts = av_mallocz(sizeof(*ts_st->adts));
00524             if (!ts_st->adts)
00525                 return AVERROR(ENOMEM);
00526             if (ff_adts_decode_extradata(s, ts_st->adts, st->codec->extradata,
00527                                          st->codec->extradata_size) < 0)
00528                 return -1;
00529         }
00530     }
00531 
00532     av_free(pids);
00533 
00534     /* if no video stream, use the first stream as PCR */
00535     if (service->pcr_pid == 0x1fff && s->nb_streams > 0) {
00536         pcr_st = s->streams[0];
00537         ts_st = pcr_st->priv_data;
00538         service->pcr_pid = ts_st->pid;
00539     }
00540 
00541     ts->mux_rate = s->mux_rate ? s->mux_rate : 1;
00542 
00543     if (ts->mux_rate > 1) {
00544         service->pcr_packet_period = (ts->mux_rate * PCR_RETRANS_TIME) /
00545             (TS_PACKET_SIZE * 8 * 1000);
00546         ts->sdt_packet_period      = (ts->mux_rate * SDT_RETRANS_TIME) /
00547             (TS_PACKET_SIZE * 8 * 1000);
00548         ts->pat_packet_period      = (ts->mux_rate * PAT_RETRANS_TIME) /
00549             (TS_PACKET_SIZE * 8 * 1000);
00550 
00551         ts->first_pcr = av_rescale(s->max_delay, PCR_TIME_BASE, AV_TIME_BASE);
00552     } else {
00553         /* Arbitrary values, PAT/PMT could be written on key frames */
00554         ts->sdt_packet_period = 200;
00555         ts->pat_packet_period = 40;
00556         if (pcr_st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00557             if (!pcr_st->codec->frame_size) {
00558                 av_log(s, AV_LOG_WARNING, "frame size not set\n");
00559                 service->pcr_packet_period =
00560                     pcr_st->codec->sample_rate/(10*512);
00561             } else {
00562                 service->pcr_packet_period =
00563                     pcr_st->codec->sample_rate/(10*pcr_st->codec->frame_size);
00564             }
00565         } else {
00566             // max delta PCR 0.1s
00567             service->pcr_packet_period =
00568                 pcr_st->codec->time_base.den/(10*pcr_st->codec->time_base.num);
00569         }
00570     }
00571 
00572     // output a PCR as soon as possible
00573     service->pcr_packet_count = service->pcr_packet_period;
00574     ts->pat_packet_count = ts->pat_packet_period-1;
00575     ts->sdt_packet_count = ts->sdt_packet_period-1;
00576 
00577     if (ts->mux_rate == 1)
00578         av_log(s, AV_LOG_INFO, "muxrate VBR, ");
00579     else
00580         av_log(s, AV_LOG_INFO, "muxrate %d, ", ts->mux_rate);
00581     av_log(s, AV_LOG_INFO, "pcr every %d pkts, "
00582            "sdt every %d, pat/pmt every %d pkts\n",
00583            service->pcr_packet_period,
00584            ts->sdt_packet_period, ts->pat_packet_period);
00585 
00586     avio_flush(s->pb);
00587 
00588     return 0;
00589 
00590  fail:
00591     av_free(pids);
00592     for(i = 0;i < s->nb_streams; i++) {
00593         st = s->streams[i];
00594         av_freep(&st->priv_data);
00595     }
00596     return -1;
00597 }
00598 
00599 /* send SDT, PAT and PMT tables regulary */
00600 static void retransmit_si_info(AVFormatContext *s)
00601 {
00602     MpegTSWrite *ts = s->priv_data;
00603     int i;
00604 
00605     if (++ts->sdt_packet_count == ts->sdt_packet_period) {
00606         ts->sdt_packet_count = 0;
00607         mpegts_write_sdt(s);
00608     }
00609     if (++ts->pat_packet_count == ts->pat_packet_period) {
00610         ts->pat_packet_count = 0;
00611         mpegts_write_pat(s);
00612         for(i = 0; i < ts->nb_services; i++) {
00613             mpegts_write_pmt(s, ts->services[i]);
00614         }
00615     }
00616 }
00617 
00618 static int64_t get_pcr(const MpegTSWrite *ts, AVIOContext *pb)
00619 {
00620     return av_rescale(avio_tell(pb) + 11, 8 * PCR_TIME_BASE, ts->mux_rate) +
00621            ts->first_pcr;
00622 }
00623 
00624 static uint8_t* write_pcr_bits(uint8_t *buf, int64_t pcr)
00625 {
00626     int64_t pcr_low = pcr % 300, pcr_high = pcr / 300;
00627 
00628     *buf++ = pcr_high >> 25;
00629     *buf++ = pcr_high >> 17;
00630     *buf++ = pcr_high >> 9;
00631     *buf++ = pcr_high >> 1;
00632     *buf++ = pcr_high << 7 | pcr_low >> 8 | 0x7e;
00633     *buf++ = pcr_low;
00634 
00635     return buf;
00636 }
00637 
00638 /* Write a single null transport stream packet */
00639 static void mpegts_insert_null_packet(AVFormatContext *s)
00640 {
00641     uint8_t *q;
00642     uint8_t buf[TS_PACKET_SIZE];
00643 
00644     q = buf;
00645     *q++ = 0x47;
00646     *q++ = 0x00 | 0x1f;
00647     *q++ = 0xff;
00648     *q++ = 0x10;
00649     memset(q, 0x0FF, TS_PACKET_SIZE - (q - buf));
00650     avio_write(s->pb, buf, TS_PACKET_SIZE);
00651 }
00652 
00653 /* Write a single transport stream packet with a PCR and no payload */
00654 static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)
00655 {
00656     MpegTSWrite *ts = s->priv_data;
00657     MpegTSWriteStream *ts_st = st->priv_data;
00658     uint8_t *q;
00659     uint8_t buf[TS_PACKET_SIZE];
00660 
00661     q = buf;
00662     *q++ = 0x47;
00663     *q++ = ts_st->pid >> 8;
00664     *q++ = ts_st->pid;
00665     *q++ = 0x20 | ts_st->cc;   /* Adaptation only */
00666     /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */
00667     *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */
00668     *q++ = 0x10;               /* Adaptation flags: PCR present */
00669 
00670     /* PCR coded into 6 bytes */
00671     q = write_pcr_bits(q, get_pcr(ts, s->pb));
00672 
00673     /* stuffing bytes */
00674     memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));
00675     avio_write(s->pb, buf, TS_PACKET_SIZE);
00676 }
00677 
00678 static void write_pts(uint8_t *q, int fourbits, int64_t pts)
00679 {
00680     int val;
00681 
00682     val = fourbits << 4 | (((pts >> 30) & 0x07) << 1) | 1;
00683     *q++ = val;
00684     val = (((pts >> 15) & 0x7fff) << 1) | 1;
00685     *q++ = val >> 8;
00686     *q++ = val;
00687     val = (((pts) & 0x7fff) << 1) | 1;
00688     *q++ = val >> 8;
00689     *q++ = val;
00690 }
00691 
00692 /* Add a pes header to the front of payload, and segment into an integer number of
00693  * ts packets. The final ts packet is padded using an over-sized adaptation header
00694  * to exactly fill the last ts packet.
00695  * NOTE: 'payload' contains a complete PES payload.
00696  */
00697 static void mpegts_write_pes(AVFormatContext *s, AVStream *st,
00698                              const uint8_t *payload, int payload_size,
00699                              int64_t pts, int64_t dts)
00700 {
00701     MpegTSWriteStream *ts_st = st->priv_data;
00702     MpegTSWrite *ts = s->priv_data;
00703     uint8_t buf[TS_PACKET_SIZE];
00704     uint8_t *q;
00705     int val, is_start, len, header_len, write_pcr, private_code, flags;
00706     int afc_len, stuffing_len;
00707     int64_t pcr = -1; /* avoid warning */
00708     int64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE);
00709 
00710     is_start = 1;
00711     while (payload_size > 0) {
00712         retransmit_si_info(s);
00713 
00714         write_pcr = 0;
00715         if (ts_st->pid == ts_st->service->pcr_pid) {
00716             if (ts->mux_rate > 1 || is_start) // VBR pcr period is based on frames
00717                 ts_st->service->pcr_packet_count++;
00718             if (ts_st->service->pcr_packet_count >=
00719                 ts_st->service->pcr_packet_period) {
00720                 ts_st->service->pcr_packet_count = 0;
00721                 write_pcr = 1;
00722             }
00723         }
00724 
00725         if (ts->mux_rate > 1 && dts != AV_NOPTS_VALUE &&
00726             (dts - get_pcr(ts, s->pb)/300) > delay) {
00727             /* pcr insert gets priority over null packet insert */
00728             if (write_pcr)
00729                 mpegts_insert_pcr_only(s, st);
00730             else
00731                 mpegts_insert_null_packet(s);
00732             continue; /* recalculate write_pcr and possibly retransmit si_info */
00733         }
00734 
00735         /* prepare packet header */
00736         q = buf;
00737         *q++ = 0x47;
00738         val = (ts_st->pid >> 8);
00739         if (is_start)
00740             val |= 0x40;
00741         *q++ = val;
00742         *q++ = ts_st->pid;
00743         ts_st->cc = (ts_st->cc + 1) & 0xf;
00744         *q++ = 0x10 | ts_st->cc | (write_pcr ? 0x20 : 0);
00745         if (write_pcr) {
00746             // add 11, pcr references the last byte of program clock reference base
00747             if (ts->mux_rate > 1)
00748                 pcr = get_pcr(ts, s->pb);
00749             else
00750                 pcr = (dts - delay)*300;
00751             if (dts != AV_NOPTS_VALUE && dts < pcr / 300)
00752                 av_log(s, AV_LOG_WARNING, "dts < pcr, TS is invalid\n");
00753             *q++ = 7; /* AFC length */
00754             *q++ = 0x10; /* flags: PCR present */
00755             q = write_pcr_bits(q, pcr);
00756         }
00757         if (is_start) {
00758             int pes_extension = 0;
00759             /* write PES header */
00760             *q++ = 0x00;
00761             *q++ = 0x00;
00762             *q++ = 0x01;
00763             private_code = 0;
00764             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00765                 if (st->codec->codec_id == CODEC_ID_DIRAC) {
00766                     *q++ = 0xfd;
00767                 } else
00768                     *q++ = 0xe0;
00769             } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
00770                        (st->codec->codec_id == CODEC_ID_MP2 ||
00771                         st->codec->codec_id == CODEC_ID_MP3 ||
00772                         st->codec->codec_id == CODEC_ID_AAC)) {
00773                 *q++ = 0xc0;
00774             } else {
00775                 *q++ = 0xbd;
00776                 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
00777                     private_code = 0x20;
00778                 }
00779             }
00780             header_len = 0;
00781             flags = 0;
00782             if (pts != AV_NOPTS_VALUE) {
00783                 header_len += 5;
00784                 flags |= 0x80;
00785             }
00786             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
00787                 header_len += 5;
00788                 flags |= 0x40;
00789             }
00790             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
00791                 st->codec->codec_id == CODEC_ID_DIRAC) {
00792                 /* set PES_extension_flag */
00793                 pes_extension = 1;
00794                 flags |= 0x01;
00795 
00796                 /*
00797                 * One byte for PES2 extension flag +
00798                 * one byte for extension length +
00799                 * one byte for extension id
00800                 */
00801                 header_len += 3;
00802             }
00803             len = payload_size + header_len + 3;
00804             if (private_code != 0)
00805                 len++;
00806             if (len > 0xffff)
00807                 len = 0;
00808             *q++ = len >> 8;
00809             *q++ = len;
00810             val = 0x80;
00811             /* data alignment indicator is required for subtitle data */
00812             if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
00813                 val |= 0x04;
00814             *q++ = val;
00815             *q++ = flags;
00816             *q++ = header_len;
00817             if (pts != AV_NOPTS_VALUE) {
00818                 write_pts(q, flags >> 6, pts);
00819                 q += 5;
00820             }
00821             if (dts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE && dts != pts) {
00822                 write_pts(q, 1, dts);
00823                 q += 5;
00824             }
00825             if (pes_extension && st->codec->codec_id == CODEC_ID_DIRAC) {
00826                 flags = 0x01;  /* set PES_extension_flag_2 */
00827                 *q++ = flags;
00828                 *q++ = 0x80 | 0x01;  /* marker bit + extension length */
00829                 /*
00830                 * Set the stream id extension flag bit to 0 and
00831                 * write the extended stream id
00832                 */
00833                 *q++ = 0x00 | 0x60;
00834             }
00835             if (private_code != 0)
00836                 *q++ = private_code;
00837             is_start = 0;
00838         }
00839         /* header size */
00840         header_len = q - buf;
00841         /* data len */
00842         len = TS_PACKET_SIZE - header_len;
00843         if (len > payload_size)
00844             len = payload_size;
00845         stuffing_len = TS_PACKET_SIZE - header_len - len;
00846         if (stuffing_len > 0) {
00847             /* add stuffing with AFC */
00848             if (buf[3] & 0x20) {
00849                 /* stuffing already present: increase its size */
00850                 afc_len = buf[4] + 1;
00851                 memmove(buf + 4 + afc_len + stuffing_len,
00852                         buf + 4 + afc_len,
00853                         header_len - (4 + afc_len));
00854                 buf[4] += stuffing_len;
00855                 memset(buf + 4 + afc_len, 0xff, stuffing_len);
00856             } else {
00857                 /* add stuffing */
00858                 memmove(buf + 4 + stuffing_len, buf + 4, header_len - 4);
00859                 buf[3] |= 0x20;
00860                 buf[4] = stuffing_len - 1;
00861                 if (stuffing_len >= 2) {
00862                     buf[5] = 0x00;
00863                     memset(buf + 6, 0xff, stuffing_len - 2);
00864                 }
00865             }
00866         }
00867         memcpy(buf + TS_PACKET_SIZE - len, payload, len);
00868         payload += len;
00869         payload_size -= len;
00870         avio_write(s->pb, buf, TS_PACKET_SIZE);
00871     }
00872     avio_flush(s->pb);
00873 }
00874 
00875 static int mpegts_write_packet(AVFormatContext *s, AVPacket *pkt)
00876 {
00877     AVStream *st = s->streams[pkt->stream_index];
00878     int size = pkt->size;
00879     uint8_t *buf= pkt->data;
00880     uint8_t *data= NULL;
00881     MpegTSWriteStream *ts_st = st->priv_data;
00882     const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE)*2;
00883     int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;
00884 
00885     if (pkt->pts != AV_NOPTS_VALUE)
00886         pts = pkt->pts + delay;
00887     if (pkt->dts != AV_NOPTS_VALUE)
00888         dts = pkt->dts + delay;
00889 
00890     if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {
00891         av_log(s, AV_LOG_ERROR, "first pts value must set\n");
00892         return -1;
00893     }
00894     ts_st->first_pts_check = 0;
00895 
00896     if (st->codec->codec_id == CODEC_ID_H264) {
00897         const uint8_t *p = buf, *buf_end = p+size;
00898         uint32_t state = -1;
00899 
00900         if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {
00901             av_log(s, AV_LOG_ERROR, "h264 bitstream malformated, "
00902                    "no startcode found, use -vbsf h264_mp4toannexb\n");
00903             return -1;
00904         }
00905 
00906         do {
00907             p = ff_find_start_code(p, buf_end, &state);
00908             //av_log(s, AV_LOG_INFO, "nal %d\n", state & 0x1f);
00909         } while (p < buf_end && (state & 0x1f) != 9 &&
00910                  (state & 0x1f) != 5 && (state & 0x1f) != 1);
00911 
00912         if ((state & 0x1f) != 9) { // AUD NAL
00913             data = av_malloc(pkt->size+6);
00914             if (!data)
00915                 return -1;
00916             memcpy(data+6, pkt->data, pkt->size);
00917             AV_WB32(data, 0x00000001);
00918             data[4] = 0x09;
00919             data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit
00920             buf  = data;
00921             size = pkt->size+6;
00922         }
00923     } else if (st->codec->codec_id == CODEC_ID_AAC) {
00924         if (pkt->size < 2)
00925             return -1;
00926         if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {
00927             ADTSContext *adts = ts_st->adts;
00928             int new_size;
00929             if (!adts) {
00930                 av_log(s, AV_LOG_ERROR, "aac bitstream not in adts format "
00931                        "and extradata missing\n");
00932                 return -1;
00933             }
00934             new_size = ADTS_HEADER_SIZE+adts->pce_size+pkt->size;
00935             if ((unsigned)new_size >= INT_MAX)
00936                 return -1;
00937             data = av_malloc(new_size);
00938             if (!data)
00939                 return AVERROR(ENOMEM);
00940             ff_adts_write_frame_header(adts, data, pkt->size, adts->pce_size);
00941             if (adts->pce_size) {
00942                 memcpy(data+ADTS_HEADER_SIZE, adts->pce_data, adts->pce_size);
00943                 adts->pce_size = 0;
00944             }
00945             memcpy(data+ADTS_HEADER_SIZE+adts->pce_size, pkt->data, pkt->size);
00946             buf = data;
00947             size = new_size;
00948         }
00949     }
00950 
00951     if (ts_st->payload_index && ts_st->payload_index + size > DEFAULT_PES_PAYLOAD_SIZE) {
00952         mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
00953                          ts_st->payload_pts, ts_st->payload_dts);
00954         ts_st->payload_index = 0;
00955     }
00956 
00957     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO || size > DEFAULT_PES_PAYLOAD_SIZE) {
00958         av_assert0(!ts_st->payload_index);
00959         // for video and subtitle, write a single pes packet
00960         mpegts_write_pes(s, st, buf, size, pts, dts);
00961         av_free(data);
00962         return 0;
00963     }
00964 
00965     if (!ts_st->payload_index) {
00966         ts_st->payload_pts = pts;
00967         ts_st->payload_dts = dts;
00968     }
00969 
00970     memcpy(ts_st->payload + ts_st->payload_index, buf, size);
00971     ts_st->payload_index += size;
00972 
00973     av_free(data);
00974 
00975     return 0;
00976 }
00977 
00978 static int mpegts_write_end(AVFormatContext *s)
00979 {
00980     MpegTSWrite *ts = s->priv_data;
00981     MpegTSWriteStream *ts_st;
00982     MpegTSService *service;
00983     AVStream *st;
00984     int i;
00985 
00986     /* flush current packets */
00987     for(i = 0; i < s->nb_streams; i++) {
00988         st = s->streams[i];
00989         ts_st = st->priv_data;
00990         if (ts_st->payload_index > 0) {
00991             mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,
00992                              ts_st->payload_pts, ts_st->payload_dts);
00993         }
00994         av_freep(&ts_st->adts);
00995     }
00996     avio_flush(s->pb);
00997 
00998     for(i = 0; i < ts->nb_services; i++) {
00999         service = ts->services[i];
01000         av_freep(&service->provider_name);
01001         av_freep(&service->name);
01002         av_free(service);
01003     }
01004     av_free(ts->services);
01005 
01006     return 0;
01007 }
01008 
01009 AVOutputFormat ff_mpegts_muxer = {
01010     "mpegts",
01011     NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
01012     "video/x-mpegts",
01013     "ts,m2t",
01014     sizeof(MpegTSWrite),
01015     CODEC_ID_MP2,
01016     CODEC_ID_MPEG2VIDEO,
01017     mpegts_write_header,
01018     mpegts_write_packet,
01019     mpegts_write_end,
01020     .priv_class = &mpegts_muxer_class,
01021 };

Generated on Wed Apr 11 2012 07:31:36 for FFmpeg by  doxygen 1.7.1