You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1798 lines
56KB

  1. /*
  2. * MPEG1/2 mux/demux
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library 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 GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. */
  19. #include "avformat.h"
  20. #include "bitstream.h"
  21. #define MAX_PAYLOAD_SIZE 4096
  22. //#define DEBUG_SEEK
  23. #undef NDEBUG
  24. #include <assert.h>
  25. typedef struct PacketDesc {
  26. int64_t pts;
  27. int64_t dts;
  28. int size;
  29. int unwritten_size;
  30. int flags;
  31. struct PacketDesc *next;
  32. } PacketDesc;
  33. typedef struct {
  34. FifoBuffer fifo;
  35. uint8_t id;
  36. int max_buffer_size; /* in bytes */
  37. int buffer_index;
  38. PacketDesc *predecode_packet;
  39. PacketDesc *premux_packet;
  40. PacketDesc **next_packet;
  41. int packet_number;
  42. uint8_t lpcm_header[3];
  43. int lpcm_align;
  44. uint8_t *fifo_iframe_ptr;
  45. int align_iframe;
  46. int64_t vobu_start_pts;
  47. } StreamInfo;
  48. typedef struct {
  49. int packet_size; /* required packet size */
  50. int packet_number;
  51. int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
  52. int system_header_freq;
  53. int system_header_size;
  54. int mux_rate; /* bitrate in units of 50 bytes/s */
  55. /* stream info */
  56. int audio_bound;
  57. int video_bound;
  58. int is_mpeg2;
  59. int is_vcd;
  60. int is_svcd;
  61. int is_dvd;
  62. int64_t last_scr; /* current system clock */
  63. double vcd_padding_bitrate; //FIXME floats
  64. int64_t vcd_padding_bytes_written;
  65. } MpegMuxContext;
  66. #define PACK_START_CODE ((unsigned int)0x000001ba)
  67. #define SYSTEM_HEADER_START_CODE ((unsigned int)0x000001bb)
  68. #define SEQUENCE_END_CODE ((unsigned int)0x000001b7)
  69. #define PACKET_START_CODE_MASK ((unsigned int)0xffffff00)
  70. #define PACKET_START_CODE_PREFIX ((unsigned int)0x00000100)
  71. #define ISO_11172_END_CODE ((unsigned int)0x000001b9)
  72. /* mpeg2 */
  73. #define PROGRAM_STREAM_MAP 0x1bc
  74. #define PRIVATE_STREAM_1 0x1bd
  75. #define PADDING_STREAM 0x1be
  76. #define PRIVATE_STREAM_2 0x1bf
  77. #define AUDIO_ID 0xc0
  78. #define VIDEO_ID 0xe0
  79. #define AC3_ID 0x80
  80. #define DTS_ID 0x8a
  81. #define LPCM_ID 0xa0
  82. #define SUB_ID 0x20
  83. #define STREAM_TYPE_VIDEO_MPEG1 0x01
  84. #define STREAM_TYPE_VIDEO_MPEG2 0x02
  85. #define STREAM_TYPE_AUDIO_MPEG1 0x03
  86. #define STREAM_TYPE_AUDIO_MPEG2 0x04
  87. #define STREAM_TYPE_PRIVATE_SECTION 0x05
  88. #define STREAM_TYPE_PRIVATE_DATA 0x06
  89. #define STREAM_TYPE_AUDIO_AAC 0x0f
  90. #define STREAM_TYPE_VIDEO_MPEG4 0x10
  91. #define STREAM_TYPE_VIDEO_H264 0x1b
  92. #define STREAM_TYPE_AUDIO_AC3 0x81
  93. #define STREAM_TYPE_AUDIO_DTS 0x8a
  94. static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
  95. #ifdef CONFIG_MUXERS
  96. static AVOutputFormat mpeg1system_mux;
  97. static AVOutputFormat mpeg1vcd_mux;
  98. static AVOutputFormat mpeg2vob_mux;
  99. static AVOutputFormat mpeg2svcd_mux;
  100. static AVOutputFormat mpeg2dvd_mux;
  101. static int put_pack_header(AVFormatContext *ctx,
  102. uint8_t *buf, int64_t timestamp)
  103. {
  104. MpegMuxContext *s = ctx->priv_data;
  105. PutBitContext pb;
  106. init_put_bits(&pb, buf, 128);
  107. put_bits(&pb, 32, PACK_START_CODE);
  108. if (s->is_mpeg2) {
  109. put_bits(&pb, 2, 0x1);
  110. } else {
  111. put_bits(&pb, 4, 0x2);
  112. }
  113. put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
  114. put_bits(&pb, 1, 1);
  115. put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
  116. put_bits(&pb, 1, 1);
  117. put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
  118. put_bits(&pb, 1, 1);
  119. if (s->is_mpeg2) {
  120. /* clock extension */
  121. put_bits(&pb, 9, 0);
  122. }
  123. put_bits(&pb, 1, 1);
  124. put_bits(&pb, 22, s->mux_rate);
  125. put_bits(&pb, 1, 1);
  126. if (s->is_mpeg2) {
  127. put_bits(&pb, 1, 1);
  128. put_bits(&pb, 5, 0x1f); /* reserved */
  129. put_bits(&pb, 3, 0); /* stuffing length */
  130. }
  131. flush_put_bits(&pb);
  132. return pbBufPtr(&pb) - pb.buf;
  133. }
  134. static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
  135. {
  136. MpegMuxContext *s = ctx->priv_data;
  137. int size, i, private_stream_coded, id;
  138. PutBitContext pb;
  139. init_put_bits(&pb, buf, 128);
  140. put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
  141. put_bits(&pb, 16, 0);
  142. put_bits(&pb, 1, 1);
  143. put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
  144. put_bits(&pb, 1, 1); /* marker */
  145. if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
  146. /* This header applies only to the video stream (see VCD standard p. IV-7)*/
  147. put_bits(&pb, 6, 0);
  148. } else
  149. put_bits(&pb, 6, s->audio_bound);
  150. if (s->is_vcd) {
  151. /* see VCD standard, p. IV-7*/
  152. put_bits(&pb, 1, 0);
  153. put_bits(&pb, 1, 1);
  154. } else {
  155. put_bits(&pb, 1, 0); /* variable bitrate*/
  156. put_bits(&pb, 1, 0); /* non constrainted bit stream */
  157. }
  158. if (s->is_vcd || s->is_dvd) {
  159. /* see VCD standard p IV-7 */
  160. put_bits(&pb, 1, 1); /* audio locked */
  161. put_bits(&pb, 1, 1); /* video locked */
  162. } else {
  163. put_bits(&pb, 1, 0); /* audio locked */
  164. put_bits(&pb, 1, 0); /* video locked */
  165. }
  166. put_bits(&pb, 1, 1); /* marker */
  167. if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
  168. /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
  169. put_bits(&pb, 5, 0);
  170. } else
  171. put_bits(&pb, 5, s->video_bound);
  172. if (s->is_dvd) {
  173. put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
  174. put_bits(&pb, 7, 0x7f); /* reserved byte */
  175. } else
  176. put_bits(&pb, 8, 0xff); /* reserved byte */
  177. /* DVD-Video Stream_bound entries
  178. id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
  179. id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0)
  180. id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
  181. id (0xBF) private stream 2, NAV packs, set to 2x1024. */
  182. if (s->is_dvd) {
  183. int P_STD_max_video = 0;
  184. int P_STD_max_mpeg_audio = 0;
  185. int P_STD_max_mpeg_PS1 = 0;
  186. for(i=0;i<ctx->nb_streams;i++) {
  187. StreamInfo *stream = ctx->streams[i]->priv_data;
  188. id = stream->id;
  189. if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
  190. P_STD_max_mpeg_PS1 = stream->max_buffer_size;
  191. } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
  192. P_STD_max_mpeg_audio = stream->max_buffer_size;
  193. } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
  194. P_STD_max_video = stream->max_buffer_size;
  195. }
  196. }
  197. /* video */
  198. put_bits(&pb, 8, 0xb9); /* stream ID */
  199. put_bits(&pb, 2, 3);
  200. put_bits(&pb, 1, 1);
  201. put_bits(&pb, 13, P_STD_max_video / 1024);
  202. /* audio */
  203. if (P_STD_max_mpeg_audio == 0)
  204. P_STD_max_mpeg_audio = 4096;
  205. put_bits(&pb, 8, 0xb8); /* stream ID */
  206. put_bits(&pb, 2, 3);
  207. put_bits(&pb, 1, 0);
  208. put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
  209. /* private stream 1 */
  210. put_bits(&pb, 8, 0xbd); /* stream ID */
  211. put_bits(&pb, 2, 3);
  212. put_bits(&pb, 1, 0);
  213. put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
  214. /* private stream 2 */
  215. put_bits(&pb, 8, 0xbf); /* stream ID */
  216. put_bits(&pb, 2, 3);
  217. put_bits(&pb, 1, 1);
  218. put_bits(&pb, 13, 2);
  219. }
  220. else {
  221. /* audio stream info */
  222. private_stream_coded = 0;
  223. for(i=0;i<ctx->nb_streams;i++) {
  224. StreamInfo *stream = ctx->streams[i]->priv_data;
  225. /* For VCDs, only include the stream info for the stream
  226. that the pack which contains this system belongs to.
  227. (see VCD standard p. IV-7) */
  228. if ( !s->is_vcd || stream->id==only_for_stream_id
  229. || only_for_stream_id==0) {
  230. id = stream->id;
  231. if (id < 0xc0) {
  232. /* special case for private streams (AC3 use that) */
  233. if (private_stream_coded)
  234. continue;
  235. private_stream_coded = 1;
  236. id = 0xbd;
  237. }
  238. put_bits(&pb, 8, id); /* stream ID */
  239. put_bits(&pb, 2, 3);
  240. if (id < 0xe0) {
  241. /* audio */
  242. put_bits(&pb, 1, 0);
  243. put_bits(&pb, 13, stream->max_buffer_size / 128);
  244. } else {
  245. /* video */
  246. put_bits(&pb, 1, 1);
  247. put_bits(&pb, 13, stream->max_buffer_size / 1024);
  248. }
  249. }
  250. }
  251. }
  252. flush_put_bits(&pb);
  253. size = pbBufPtr(&pb) - pb.buf;
  254. /* patch packet size */
  255. buf[4] = (size - 6) >> 8;
  256. buf[5] = (size - 6) & 0xff;
  257. return size;
  258. }
  259. static int get_system_header_size(AVFormatContext *ctx)
  260. {
  261. int buf_index, i, private_stream_coded;
  262. StreamInfo *stream;
  263. MpegMuxContext *s = ctx->priv_data;
  264. if (s->is_dvd)
  265. return 18; // DVD-Video system headers are 18 bytes fixed length.
  266. buf_index = 12;
  267. private_stream_coded = 0;
  268. for(i=0;i<ctx->nb_streams;i++) {
  269. stream = ctx->streams[i]->priv_data;
  270. if (stream->id < 0xc0) {
  271. if (private_stream_coded)
  272. continue;
  273. private_stream_coded = 1;
  274. }
  275. buf_index += 3;
  276. }
  277. return buf_index;
  278. }
  279. static int mpeg_mux_init(AVFormatContext *ctx)
  280. {
  281. MpegMuxContext *s = ctx->priv_data;
  282. int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
  283. AVStream *st;
  284. StreamInfo *stream;
  285. int audio_bitrate;
  286. int video_bitrate;
  287. s->packet_number = 0;
  288. s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
  289. s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
  290. s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux || ctx->oformat == &mpeg2dvd_mux);
  291. s->is_dvd = (ctx->oformat == &mpeg2dvd_mux);
  292. if(ctx->packet_size)
  293. s->packet_size = ctx->packet_size;
  294. else
  295. s->packet_size = 2048;
  296. s->vcd_padding_bytes_written = 0;
  297. s->vcd_padding_bitrate=0;
  298. s->audio_bound = 0;
  299. s->video_bound = 0;
  300. mpa_id = AUDIO_ID;
  301. ac3_id = AC3_ID;
  302. dts_id = DTS_ID;
  303. mpv_id = VIDEO_ID;
  304. mps_id = SUB_ID;
  305. lpcm_id = LPCM_ID;
  306. for(i=0;i<ctx->nb_streams;i++) {
  307. st = ctx->streams[i];
  308. stream = av_mallocz(sizeof(StreamInfo));
  309. if (!stream)
  310. goto fail;
  311. st->priv_data = stream;
  312. av_set_pts_info(st, 64, 1, 90000);
  313. switch(st->codec->codec_type) {
  314. case CODEC_TYPE_AUDIO:
  315. if (st->codec->codec_id == CODEC_ID_AC3) {
  316. stream->id = ac3_id++;
  317. } else if (st->codec->codec_id == CODEC_ID_DTS) {
  318. stream->id = dts_id++;
  319. } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
  320. stream->id = lpcm_id++;
  321. for(j = 0; j < 4; j++) {
  322. if (lpcm_freq_tab[j] == st->codec->sample_rate)
  323. break;
  324. }
  325. if (j == 4)
  326. goto fail;
  327. if (st->codec->channels > 8)
  328. return -1;
  329. stream->lpcm_header[0] = 0x0c;
  330. stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
  331. stream->lpcm_header[2] = 0x80;
  332. stream->lpcm_align = st->codec->channels * 2;
  333. } else {
  334. stream->id = mpa_id++;
  335. }
  336. /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
  337. Right now it is also used for everything else.*/
  338. stream->max_buffer_size = 4 * 1024;
  339. s->audio_bound++;
  340. break;
  341. case CODEC_TYPE_VIDEO:
  342. stream->id = mpv_id++;
  343. if (st->codec->rc_buffer_size)
  344. stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
  345. else
  346. stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
  347. #if 0
  348. /* see VCD standard, p. IV-7*/
  349. stream->max_buffer_size = 46 * 1024;
  350. else
  351. /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
  352. Right now it is also used for everything else.*/
  353. stream->max_buffer_size = 230 * 1024;
  354. #endif
  355. s->video_bound++;
  356. break;
  357. case CODEC_TYPE_SUBTITLE:
  358. stream->id = mps_id++;
  359. stream->max_buffer_size = 16 * 1024;
  360. break;
  361. default:
  362. return -1;
  363. }
  364. fifo_init(&stream->fifo, 16);
  365. }
  366. bitrate = 0;
  367. audio_bitrate = 0;
  368. video_bitrate = 0;
  369. for(i=0;i<ctx->nb_streams;i++) {
  370. int codec_rate;
  371. st = ctx->streams[i];
  372. stream = (StreamInfo*) st->priv_data;
  373. if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
  374. codec_rate= st->codec->rc_max_rate;
  375. else
  376. codec_rate= st->codec->bit_rate;
  377. if(!codec_rate)
  378. codec_rate= (1<<21)*8*50/ctx->nb_streams;
  379. bitrate += codec_rate;
  380. if (stream->id==AUDIO_ID)
  381. audio_bitrate += codec_rate;
  382. else if (stream->id==VIDEO_ID)
  383. video_bitrate += codec_rate;
  384. }
  385. if(ctx->mux_rate){
  386. s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
  387. } else {
  388. /* we increase slightly the bitrate to take into account the
  389. headers. XXX: compute it exactly */
  390. bitrate += bitrate*5/100;
  391. bitrate += 10000;
  392. s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
  393. }
  394. if (s->is_vcd) {
  395. double overhead_rate;
  396. /* The VCD standard mandates that the mux_rate field is 3528
  397. (see standard p. IV-6).
  398. The value is actually "wrong", i.e. if you calculate
  399. it using the normal formula and the 75 sectors per second transfer
  400. rate you get a different value because the real pack size is 2324,
  401. not 2352. But the standard explicitly specifies that the mux_rate
  402. field in the header must have this value.*/
  403. // s->mux_rate=2352 * 75 / 50; /* = 3528*/
  404. /* The VCD standard states that the muxed stream must be
  405. exactly 75 packs / second (the data rate of a single speed cdrom).
  406. Since the video bitrate (probably 1150000 bits/sec) will be below
  407. the theoretical maximum we have to add some padding packets
  408. to make up for the lower data rate.
  409. (cf. VCD standard p. IV-6 )*/
  410. /* Add the header overhead to the data rate.
  411. 2279 data bytes per audio pack, 2294 data bytes per video pack*/
  412. overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
  413. overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
  414. overhead_rate *= 8;
  415. /* Add padding so that the full bitrate is 2324*75 bytes/sec */
  416. s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
  417. }
  418. if (s->is_vcd || s->is_mpeg2)
  419. /* every packet */
  420. s->pack_header_freq = 1;
  421. else
  422. /* every 2 seconds */
  423. s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
  424. /* the above seems to make pack_header_freq zero sometimes */
  425. if (s->pack_header_freq == 0)
  426. s->pack_header_freq = 1;
  427. if (s->is_mpeg2)
  428. /* every 200 packets. Need to look at the spec. */
  429. s->system_header_freq = s->pack_header_freq * 40;
  430. else if (s->is_vcd)
  431. /* the standard mandates that there are only two system headers
  432. in the whole file: one in the first packet of each stream.
  433. (see standard p. IV-7 and IV-8) */
  434. s->system_header_freq = 0x7fffffff;
  435. else
  436. s->system_header_freq = s->pack_header_freq * 5;
  437. for(i=0;i<ctx->nb_streams;i++) {
  438. stream = ctx->streams[i]->priv_data;
  439. stream->packet_number = 0;
  440. }
  441. s->system_header_size = get_system_header_size(ctx);
  442. s->last_scr = 0;
  443. return 0;
  444. fail:
  445. for(i=0;i<ctx->nb_streams;i++) {
  446. av_free(ctx->streams[i]->priv_data);
  447. }
  448. return -ENOMEM;
  449. }
  450. static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
  451. {
  452. put_byte(pb,
  453. (id << 4) |
  454. (((timestamp >> 30) & 0x07) << 1) |
  455. 1);
  456. put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
  457. put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
  458. }
  459. /* return the number of padding bytes that should be inserted into
  460. the multiplexed stream.*/
  461. static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
  462. {
  463. MpegMuxContext *s = ctx->priv_data;
  464. int pad_bytes = 0;
  465. if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
  466. {
  467. int64_t full_pad_bytes;
  468. full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
  469. pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
  470. if (pad_bytes<0)
  471. /* might happen if we have already padded to a later timestamp. This
  472. can occur if another stream has already advanced further.*/
  473. pad_bytes=0;
  474. }
  475. return pad_bytes;
  476. }
  477. #if 0 /* unused, remove? */
  478. /* return the exact available payload size for the next packet for
  479. stream 'stream_index'. 'pts' and 'dts' are only used to know if
  480. timestamps are needed in the packet header. */
  481. static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
  482. int64_t pts, int64_t dts)
  483. {
  484. MpegMuxContext *s = ctx->priv_data;
  485. int buf_index;
  486. StreamInfo *stream;
  487. stream = ctx->streams[stream_index]->priv_data;
  488. buf_index = 0;
  489. if (((s->packet_number % s->pack_header_freq) == 0)) {
  490. /* pack header size */
  491. if (s->is_mpeg2)
  492. buf_index += 14;
  493. else
  494. buf_index += 12;
  495. if (s->is_vcd) {
  496. /* there is exactly one system header for each stream in a VCD MPEG,
  497. One in the very first video packet and one in the very first
  498. audio packet (see VCD standard p. IV-7 and IV-8).*/
  499. if (stream->packet_number==0)
  500. /* The system headers refer only to the stream they occur in,
  501. so they have a constant size.*/
  502. buf_index += 15;
  503. } else {
  504. if ((s->packet_number % s->system_header_freq) == 0)
  505. buf_index += s->system_header_size;
  506. }
  507. }
  508. if ((s->is_vcd && stream->packet_number==0)
  509. || (s->is_svcd && s->packet_number==0))
  510. /* the first pack of each stream contains only the pack header,
  511. the system header and some padding (see VCD standard p. IV-6)
  512. Add the padding size, so that the actual payload becomes 0.*/
  513. buf_index += s->packet_size - buf_index;
  514. else {
  515. /* packet header size */
  516. buf_index += 6;
  517. if (s->is_mpeg2) {
  518. buf_index += 3;
  519. if (stream->packet_number==0)
  520. buf_index += 3; /* PES extension */
  521. buf_index += 1; /* obligatory stuffing byte */
  522. }
  523. if (pts != AV_NOPTS_VALUE) {
  524. if (dts != pts)
  525. buf_index += 5 + 5;
  526. else
  527. buf_index += 5;
  528. } else {
  529. if (!s->is_mpeg2)
  530. buf_index++;
  531. }
  532. if (stream->id < 0xc0) {
  533. /* AC3/LPCM private data header */
  534. buf_index += 4;
  535. if (stream->id >= 0xa0) {
  536. int n;
  537. buf_index += 3;
  538. /* NOTE: we round the payload size to an integer number of
  539. LPCM samples */
  540. n = (s->packet_size - buf_index) % stream->lpcm_align;
  541. if (n)
  542. buf_index += (stream->lpcm_align - n);
  543. }
  544. }
  545. if (s->is_vcd && stream->id == AUDIO_ID)
  546. /* The VCD standard demands that 20 zero bytes follow
  547. each audio packet (see standard p. IV-8).*/
  548. buf_index+=20;
  549. }
  550. return s->packet_size - buf_index;
  551. }
  552. #endif
  553. /* Write an MPEG padding packet header. */
  554. static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
  555. {
  556. MpegMuxContext *s = ctx->priv_data;
  557. int i;
  558. put_be32(pb, PADDING_STREAM);
  559. put_be16(pb, packet_bytes - 6);
  560. if (!s->is_mpeg2) {
  561. put_byte(pb, 0x0f);
  562. packet_bytes -= 7;
  563. } else
  564. packet_bytes -= 6;
  565. for(i=0;i<packet_bytes;i++)
  566. put_byte(pb, 0xff);
  567. }
  568. static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
  569. int nb_frames=0;
  570. PacketDesc *pkt_desc= stream->premux_packet;
  571. while(len>0){
  572. if(pkt_desc->size == pkt_desc->unwritten_size)
  573. nb_frames++;
  574. len -= pkt_desc->unwritten_size;
  575. pkt_desc= pkt_desc->next;
  576. }
  577. return nb_frames;
  578. }
  579. /* flush the packet on stream stream_index */
  580. static int flush_packet(AVFormatContext *ctx, int stream_index,
  581. int64_t pts, int64_t dts, int64_t scr, int trailer_size)
  582. {
  583. MpegMuxContext *s = ctx->priv_data;
  584. StreamInfo *stream = ctx->streams[stream_index]->priv_data;
  585. uint8_t *buf_ptr;
  586. int size, payload_size, startcode, id, stuffing_size, i, header_len;
  587. int packet_size;
  588. uint8_t buffer[128];
  589. int zero_trail_bytes = 0;
  590. int pad_packet_bytes = 0;
  591. int pes_flags;
  592. int general_pack = 0; /*"general" pack without data specific to one stream?*/
  593. int nb_frames;
  594. id = stream->id;
  595. #if 0
  596. printf("packet ID=%2x PTS=%0.3f\n",
  597. id, pts / 90000.0);
  598. #endif
  599. buf_ptr = buffer;
  600. if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
  601. /* output pack and systems header if needed */
  602. size = put_pack_header(ctx, buf_ptr, scr);
  603. buf_ptr += size;
  604. s->last_scr= scr;
  605. if (s->is_vcd) {
  606. /* there is exactly one system header for each stream in a VCD MPEG,
  607. One in the very first video packet and one in the very first
  608. audio packet (see VCD standard p. IV-7 and IV-8).*/
  609. if (stream->packet_number==0) {
  610. size = put_system_header(ctx, buf_ptr, id);
  611. buf_ptr += size;
  612. }
  613. } else if (s->is_dvd) {
  614. if (stream->align_iframe || s->packet_number == 0){
  615. int bytes_to_iframe;
  616. int PES_bytes_to_fill;
  617. if (stream->fifo_iframe_ptr >= stream->fifo.rptr) {
  618. bytes_to_iframe = stream->fifo_iframe_ptr - stream->fifo.rptr;
  619. } else {
  620. bytes_to_iframe = (stream->fifo.end - stream->fifo.rptr) + (stream->fifo_iframe_ptr - stream->fifo.buffer);
  621. }
  622. PES_bytes_to_fill = s->packet_size - size - 10;
  623. if (pts != AV_NOPTS_VALUE) {
  624. if (dts != pts)
  625. PES_bytes_to_fill -= 5 + 5;
  626. else
  627. PES_bytes_to_fill -= 5;
  628. }
  629. if (bytes_to_iframe == 0 || s->packet_number == 0) {
  630. size = put_system_header(ctx, buf_ptr, 0);
  631. buf_ptr += size;
  632. size = buf_ptr - buffer;
  633. put_buffer(&ctx->pb, buffer, size);
  634. put_be32(&ctx->pb, PRIVATE_STREAM_2);
  635. put_be16(&ctx->pb, 0x03d4); // length
  636. put_byte(&ctx->pb, 0x00); // substream ID, 00=PCI
  637. for (i = 0; i < 979; i++)
  638. put_byte(&ctx->pb, 0x00);
  639. put_be32(&ctx->pb, PRIVATE_STREAM_2);
  640. put_be16(&ctx->pb, 0x03fa); // length
  641. put_byte(&ctx->pb, 0x01); // substream ID, 01=DSI
  642. for (i = 0; i < 1017; i++)
  643. put_byte(&ctx->pb, 0x00);
  644. memset(buffer, 0, 128);
  645. buf_ptr = buffer;
  646. s->packet_number++;
  647. stream->align_iframe = 0;
  648. scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
  649. size = put_pack_header(ctx, buf_ptr, scr);
  650. s->last_scr= scr;
  651. buf_ptr += size;
  652. /* GOP Start */
  653. } else if (bytes_to_iframe < PES_bytes_to_fill) {
  654. pad_packet_bytes = PES_bytes_to_fill - bytes_to_iframe;
  655. }
  656. }
  657. } else {
  658. if ((s->packet_number % s->system_header_freq) == 0) {
  659. size = put_system_header(ctx, buf_ptr, 0);
  660. buf_ptr += size;
  661. }
  662. }
  663. }
  664. size = buf_ptr - buffer;
  665. put_buffer(&ctx->pb, buffer, size);
  666. packet_size = s->packet_size - size;
  667. if (s->is_vcd && id == AUDIO_ID)
  668. /* The VCD standard demands that 20 zero bytes follow
  669. each audio pack (see standard p. IV-8).*/
  670. zero_trail_bytes += 20;
  671. if ((s->is_vcd && stream->packet_number==0)
  672. || (s->is_svcd && s->packet_number==0)) {
  673. /* for VCD the first pack of each stream contains only the pack header,
  674. the system header and lots of padding (see VCD standard p. IV-6).
  675. In the case of an audio pack, 20 zero bytes are also added at
  676. the end.*/
  677. /* For SVCD we fill the very first pack to increase compatibility with
  678. some DVD players. Not mandated by the standard.*/
  679. if (s->is_svcd)
  680. general_pack = 1; /* the system header refers to both streams and no stream data*/
  681. pad_packet_bytes = packet_size - zero_trail_bytes;
  682. }
  683. packet_size -= pad_packet_bytes + zero_trail_bytes;
  684. if (packet_size > 0) {
  685. /* packet header size */
  686. packet_size -= 6;
  687. /* packet header */
  688. if (s->is_mpeg2) {
  689. header_len = 3;
  690. if (stream->packet_number==0)
  691. header_len += 3; /* PES extension */
  692. header_len += 1; /* obligatory stuffing byte */
  693. } else {
  694. header_len = 0;
  695. }
  696. if (pts != AV_NOPTS_VALUE) {
  697. if (dts != pts)
  698. header_len += 5 + 5;
  699. else
  700. header_len += 5;
  701. } else {
  702. if (!s->is_mpeg2)
  703. header_len++;
  704. }
  705. payload_size = packet_size - header_len;
  706. if (id < 0xc0) {
  707. startcode = PRIVATE_STREAM_1;
  708. payload_size -= 1;
  709. if (id >= 0x40) {
  710. payload_size -= 3;
  711. if (id >= 0xa0)
  712. payload_size -= 3;
  713. }
  714. } else {
  715. startcode = 0x100 + id;
  716. }
  717. stuffing_size = payload_size - fifo_size(&stream->fifo, stream->fifo.rptr);
  718. // first byte doesnt fit -> reset pts/dts + stuffing
  719. if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
  720. int timestamp_len=0;
  721. if(dts != pts)
  722. timestamp_len += 5;
  723. if(pts != AV_NOPTS_VALUE)
  724. timestamp_len += s->is_mpeg2 ? 5 : 4;
  725. pts=dts= AV_NOPTS_VALUE;
  726. header_len -= timestamp_len;
  727. if (s->is_dvd && stream->align_iframe) {
  728. pad_packet_bytes += timestamp_len;
  729. packet_size -= timestamp_len;
  730. } else {
  731. payload_size += timestamp_len;
  732. }
  733. stuffing_size += timestamp_len;
  734. if(payload_size > trailer_size)
  735. stuffing_size += payload_size - trailer_size;
  736. }
  737. if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
  738. packet_size += pad_packet_bytes;
  739. payload_size += pad_packet_bytes; // undo the previous adjustment
  740. if (stuffing_size < 0) {
  741. stuffing_size = pad_packet_bytes;
  742. } else {
  743. stuffing_size += pad_packet_bytes;
  744. }
  745. pad_packet_bytes = 0;
  746. }
  747. if (stuffing_size < 0)
  748. stuffing_size = 0;
  749. if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
  750. pad_packet_bytes += stuffing_size;
  751. packet_size -= stuffing_size;
  752. payload_size -= stuffing_size;
  753. stuffing_size = 0;
  754. }
  755. nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
  756. put_be32(&ctx->pb, startcode);
  757. put_be16(&ctx->pb, packet_size);
  758. if (!s->is_mpeg2)
  759. for(i=0;i<stuffing_size;i++)
  760. put_byte(&ctx->pb, 0xff);
  761. if (s->is_mpeg2) {
  762. put_byte(&ctx->pb, 0x80); /* mpeg2 id */
  763. pes_flags=0;
  764. if (pts != AV_NOPTS_VALUE) {
  765. pes_flags |= 0x80;
  766. if (dts != pts)
  767. pes_flags |= 0x40;
  768. }
  769. /* Both the MPEG-2 and the SVCD standards demand that the
  770. P-STD_buffer_size field be included in the first packet of
  771. every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
  772. and MPEG-2 standard 2.7.7) */
  773. if (stream->packet_number == 0)
  774. pes_flags |= 0x01;
  775. put_byte(&ctx->pb, pes_flags); /* flags */
  776. put_byte(&ctx->pb, header_len - 3 + stuffing_size);
  777. if (pes_flags & 0x80) /*write pts*/
  778. put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
  779. if (pes_flags & 0x40) /*write dts*/
  780. put_timestamp(&ctx->pb, 0x01, dts);
  781. if (pes_flags & 0x01) { /*write pes extension*/
  782. put_byte(&ctx->pb, 0x10); /* flags */
  783. /* P-STD buffer info */
  784. if (id == AUDIO_ID)
  785. put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
  786. else
  787. put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
  788. }
  789. } else {
  790. if (pts != AV_NOPTS_VALUE) {
  791. if (dts != pts) {
  792. put_timestamp(&ctx->pb, 0x03, pts);
  793. put_timestamp(&ctx->pb, 0x01, dts);
  794. } else {
  795. put_timestamp(&ctx->pb, 0x02, pts);
  796. }
  797. } else {
  798. put_byte(&ctx->pb, 0x0f);
  799. }
  800. }
  801. if (s->is_mpeg2) {
  802. /* special stuffing byte that is always written
  803. to prevent accidental generation of start codes. */
  804. put_byte(&ctx->pb, 0xff);
  805. for(i=0;i<stuffing_size;i++)
  806. put_byte(&ctx->pb, 0xff);
  807. }
  808. if (startcode == PRIVATE_STREAM_1) {
  809. put_byte(&ctx->pb, id);
  810. if (id >= 0xa0) {
  811. /* LPCM (XXX: check nb_frames) */
  812. put_byte(&ctx->pb, 7);
  813. put_be16(&ctx->pb, 4); /* skip 3 header bytes */
  814. put_byte(&ctx->pb, stream->lpcm_header[0]);
  815. put_byte(&ctx->pb, stream->lpcm_header[1]);
  816. put_byte(&ctx->pb, stream->lpcm_header[2]);
  817. } else if (id >= 0x40) {
  818. /* AC3 */
  819. put_byte(&ctx->pb, nb_frames);
  820. put_be16(&ctx->pb, trailer_size+1);
  821. }
  822. }
  823. /* output data */
  824. if(put_fifo(&ctx->pb, &stream->fifo, payload_size - stuffing_size, &stream->fifo.rptr) < 0)
  825. return -1;
  826. }else{
  827. payload_size=
  828. stuffing_size= 0;
  829. }
  830. if (pad_packet_bytes > 0)
  831. put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);
  832. for(i=0;i<zero_trail_bytes;i++)
  833. put_byte(&ctx->pb, 0x00);
  834. put_flush_packet(&ctx->pb);
  835. s->packet_number++;
  836. /* only increase the stream packet number if this pack actually contains
  837. something that is specific to this stream! I.e. a dedicated header
  838. or some data.*/
  839. if (!general_pack)
  840. stream->packet_number++;
  841. return payload_size - stuffing_size;
  842. }
  843. static void put_vcd_padding_sector(AVFormatContext *ctx)
  844. {
  845. /* There are two ways to do this padding: writing a sector/pack
  846. of 0 values, or writing an MPEG padding pack. Both seem to
  847. work with most decoders, BUT the VCD standard only allows a 0-sector
  848. (see standard p. IV-4, IV-5).
  849. So a 0-sector it is...*/
  850. MpegMuxContext *s = ctx->priv_data;
  851. int i;
  852. for(i=0;i<s->packet_size;i++)
  853. put_byte(&ctx->pb, 0);
  854. s->vcd_padding_bytes_written += s->packet_size;
  855. put_flush_packet(&ctx->pb);
  856. /* increasing the packet number is correct. The SCR of the following packs
  857. is calculated from the packet_number and it has to include the padding
  858. sector (it represents the sector index, not the MPEG pack index)
  859. (see VCD standard p. IV-6)*/
  860. s->packet_number++;
  861. }
  862. #if 0 /* unused, remove? */
  863. static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
  864. {
  865. MpegMuxContext *s = ctx->priv_data;
  866. int64_t scr;
  867. /* Since the data delivery rate is constant, SCR is computed
  868. using the formula C + i * 1200 where C is the start constant
  869. and i is the pack index.
  870. It is recommended that SCR 0 is at the beginning of the VCD front
  871. margin (a sequence of empty Form 2 sectors on the CD).
  872. It is recommended that the front margin is 30 sectors long, so
  873. we use C = 30*1200 = 36000
  874. (Note that even if the front margin is not 30 sectors the file
  875. will still be correct according to the standard. It just won't have
  876. the "recommended" value).*/
  877. scr = 36000 + s->packet_number * 1200;
  878. return scr;
  879. }
  880. #endif
  881. static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
  882. // MpegMuxContext *s = ctx->priv_data;
  883. int i;
  884. for(i=0; i<ctx->nb_streams; i++){
  885. AVStream *st = ctx->streams[i];
  886. StreamInfo *stream = st->priv_data;
  887. PacketDesc *pkt_desc= stream->predecode_packet;
  888. while(pkt_desc && scr > pkt_desc->dts){ //FIXME > vs >=
  889. if(stream->buffer_index < pkt_desc->size ||
  890. stream->predecode_packet == stream->premux_packet){
  891. av_log(ctx, AV_LOG_ERROR, "buffer underflow\n");
  892. break;
  893. }
  894. stream->buffer_index -= pkt_desc->size;
  895. stream->predecode_packet= pkt_desc->next;
  896. av_freep(&pkt_desc);
  897. }
  898. }
  899. return 0;
  900. }
  901. static int output_packet(AVFormatContext *ctx, int flush){
  902. MpegMuxContext *s = ctx->priv_data;
  903. AVStream *st;
  904. StreamInfo *stream;
  905. int i, avail_space, es_size, trailer_size;
  906. int best_i= -1;
  907. int best_score= INT_MIN;
  908. int ignore_constraints=0;
  909. int64_t scr= s->last_scr;
  910. PacketDesc *timestamp_packet;
  911. const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
  912. retry:
  913. for(i=0; i<ctx->nb_streams; i++){
  914. AVStream *st = ctx->streams[i];
  915. StreamInfo *stream = st->priv_data;
  916. const int avail_data= fifo_size(&stream->fifo, stream->fifo.rptr);
  917. const int space= stream->max_buffer_size - stream->buffer_index;
  918. int rel_space= 1024*space / stream->max_buffer_size;
  919. PacketDesc *next_pkt= stream->premux_packet;
  920. /* for subtitle, a single PES packet must be generated,
  921. so we flush after every single subtitle packet */
  922. if(s->packet_size > avail_data && !flush
  923. && st->codec->codec_type != CODEC_TYPE_SUBTITLE)
  924. return 0;
  925. if(avail_data==0)
  926. continue;
  927. assert(avail_data>0);
  928. if(space < s->packet_size && !ignore_constraints)
  929. continue;
  930. if(next_pkt && next_pkt->dts - scr > max_delay)
  931. continue;
  932. if(rel_space > best_score){
  933. best_score= rel_space;
  934. best_i = i;
  935. avail_space= space;
  936. }
  937. }
  938. if(best_i < 0){
  939. int64_t best_dts= INT64_MAX;
  940. for(i=0; i<ctx->nb_streams; i++){
  941. AVStream *st = ctx->streams[i];
  942. StreamInfo *stream = st->priv_data;
  943. PacketDesc *pkt_desc= stream->predecode_packet;
  944. if(pkt_desc && pkt_desc->dts < best_dts)
  945. best_dts= pkt_desc->dts;
  946. }
  947. #if 0
  948. av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n",
  949. scr/90000.0, best_dts/90000.0);
  950. #endif
  951. if(best_dts == INT64_MAX)
  952. return 0;
  953. if(scr >= best_dts+1 && !ignore_constraints){
  954. av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
  955. ignore_constraints= 1;
  956. }
  957. scr= FFMAX(best_dts+1, scr);
  958. if(remove_decoded_packets(ctx, scr) < 0)
  959. return -1;
  960. goto retry;
  961. }
  962. assert(best_i >= 0);
  963. st = ctx->streams[best_i];
  964. stream = st->priv_data;
  965. assert(fifo_size(&stream->fifo, stream->fifo.rptr) > 0);
  966. assert(avail_space >= s->packet_size || ignore_constraints);
  967. timestamp_packet= stream->premux_packet;
  968. if(timestamp_packet->unwritten_size == timestamp_packet->size){
  969. trailer_size= 0;
  970. }else{
  971. trailer_size= timestamp_packet->unwritten_size;
  972. timestamp_packet= timestamp_packet->next;
  973. }
  974. if(timestamp_packet){
  975. //av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f scr:%f stream:%d\n", timestamp_packet->dts/90000.0, timestamp_packet->pts/90000.0, scr/90000.0, best_i);
  976. es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
  977. }else{
  978. assert(fifo_size(&stream->fifo, stream->fifo.rptr) == trailer_size);
  979. es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
  980. }
  981. if (s->is_vcd) {
  982. /* Write one or more padding sectors, if necessary, to reach
  983. the constant overall bitrate.*/
  984. int vcd_pad_bytes;
  985. while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
  986. put_vcd_padding_sector(ctx);
  987. s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
  988. }
  989. }
  990. stream->buffer_index += es_size;
  991. s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
  992. while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
  993. es_size -= stream->premux_packet->unwritten_size;
  994. stream->premux_packet= stream->premux_packet->next;
  995. }
  996. if(es_size)
  997. stream->premux_packet->unwritten_size -= es_size;
  998. if(remove_decoded_packets(ctx, s->last_scr) < 0)
  999. return -1;
  1000. return 1;
  1001. }
  1002. static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
  1003. {
  1004. MpegMuxContext *s = ctx->priv_data;
  1005. int stream_index= pkt->stream_index;
  1006. int size= pkt->size;
  1007. uint8_t *buf= pkt->data;
  1008. AVStream *st = ctx->streams[stream_index];
  1009. StreamInfo *stream = st->priv_data;
  1010. int64_t pts, dts;
  1011. PacketDesc *pkt_desc;
  1012. const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
  1013. const int is_iframe = st->codec->codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
  1014. pts= pkt->pts;
  1015. dts= pkt->dts;
  1016. if(pts != AV_NOPTS_VALUE) pts += preload;
  1017. if(dts != AV_NOPTS_VALUE) dts += preload;
  1018. //av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
  1019. if (!stream->premux_packet)
  1020. stream->next_packet = &stream->premux_packet;
  1021. *stream->next_packet=
  1022. pkt_desc= av_mallocz(sizeof(PacketDesc));
  1023. pkt_desc->pts= pts;
  1024. pkt_desc->dts= dts;
  1025. pkt_desc->unwritten_size=
  1026. pkt_desc->size= size;
  1027. if(!stream->predecode_packet)
  1028. stream->predecode_packet= pkt_desc;
  1029. stream->next_packet= &pkt_desc->next;
  1030. fifo_realloc(&stream->fifo, fifo_size(&stream->fifo, NULL) + size + 1);
  1031. if (s->is_dvd){
  1032. if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
  1033. stream->fifo_iframe_ptr = stream->fifo.wptr;
  1034. stream->align_iframe = 1;
  1035. stream->vobu_start_pts = pts;
  1036. } else {
  1037. stream->align_iframe = 0;
  1038. }
  1039. }
  1040. fifo_write(&stream->fifo, buf, size, &stream->fifo.wptr);
  1041. for(;;){
  1042. int ret= output_packet(ctx, 0);
  1043. if(ret<=0)
  1044. return ret;
  1045. }
  1046. }
  1047. static int mpeg_mux_end(AVFormatContext *ctx)
  1048. {
  1049. // MpegMuxContext *s = ctx->priv_data;
  1050. StreamInfo *stream;
  1051. int i;
  1052. for(;;){
  1053. int ret= output_packet(ctx, 1);
  1054. if(ret<0)
  1055. return ret;
  1056. else if(ret==0)
  1057. break;
  1058. }
  1059. /* End header according to MPEG1 systems standard. We do not write
  1060. it as it is usually not needed by decoders and because it
  1061. complicates MPEG stream concatenation. */
  1062. //put_be32(&ctx->pb, ISO_11172_END_CODE);
  1063. //put_flush_packet(&ctx->pb);
  1064. for(i=0;i<ctx->nb_streams;i++) {
  1065. stream = ctx->streams[i]->priv_data;
  1066. assert(fifo_size(&stream->fifo, stream->fifo.rptr) == 0);
  1067. fifo_free(&stream->fifo);
  1068. }
  1069. return 0;
  1070. }
  1071. #endif //CONFIG_MUXERS
  1072. /*********************************************/
  1073. /* demux code */
  1074. #define MAX_SYNC_SIZE 100000
  1075. static int mpegps_probe(AVProbeData *p)
  1076. {
  1077. uint32_t code= -1;
  1078. int sys=0, pspack=0, priv1=0, vid=0;
  1079. int i;
  1080. for(i=0; i<p->buf_size; i++){
  1081. code = (code<<8) + p->buf[i];
  1082. if ((code & 0xffffff00) == 0x100) {
  1083. switch(code){
  1084. case SYSTEM_HEADER_START_CODE: sys++; break;
  1085. case PRIVATE_STREAM_1: priv1++; break;
  1086. case PACK_START_CODE: pspack++; break;
  1087. case (VIDEO_ID + 0x100): vid++; break;
  1088. }
  1089. }
  1090. }
  1091. if(sys && sys*9 <= pspack*10)
  1092. return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
  1093. if((priv1 || vid) && (priv1+vid)*9 <= pspack*10)
  1094. return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
  1095. return 0;
  1096. }
  1097. typedef struct MpegDemuxContext {
  1098. int header_state;
  1099. unsigned char psm_es_type[256];
  1100. } MpegDemuxContext;
  1101. static int mpegps_read_header(AVFormatContext *s,
  1102. AVFormatParameters *ap)
  1103. {
  1104. MpegDemuxContext *m = s->priv_data;
  1105. m->header_state = 0xff;
  1106. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1107. /* no need to do more */
  1108. return 0;
  1109. }
  1110. static int64_t get_pts(ByteIOContext *pb, int c)
  1111. {
  1112. int64_t pts;
  1113. int val;
  1114. if (c < 0)
  1115. c = get_byte(pb);
  1116. pts = (int64_t)((c >> 1) & 0x07) << 30;
  1117. val = get_be16(pb);
  1118. pts |= (int64_t)(val >> 1) << 15;
  1119. val = get_be16(pb);
  1120. pts |= (int64_t)(val >> 1);
  1121. return pts;
  1122. }
  1123. static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
  1124. uint32_t *header_state)
  1125. {
  1126. unsigned int state, v;
  1127. int val, n;
  1128. state = *header_state;
  1129. n = *size_ptr;
  1130. while (n > 0) {
  1131. if (url_feof(pb))
  1132. break;
  1133. v = get_byte(pb);
  1134. n--;
  1135. if (state == 0x000001) {
  1136. state = ((state << 8) | v) & 0xffffff;
  1137. val = state;
  1138. goto found;
  1139. }
  1140. state = ((state << 8) | v) & 0xffffff;
  1141. }
  1142. val = -1;
  1143. found:
  1144. *header_state = state;
  1145. *size_ptr = n;
  1146. return val;
  1147. }
  1148. #if 0 /* unused, remove? */
  1149. /* XXX: optimize */
  1150. static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
  1151. {
  1152. int64_t pos, pos_start;
  1153. int max_size, start_code;
  1154. max_size = *size_ptr;
  1155. pos_start = url_ftell(pb);
  1156. /* in order to go faster, we fill the buffer */
  1157. pos = pos_start - 16386;
  1158. if (pos < 0)
  1159. pos = 0;
  1160. url_fseek(pb, pos, SEEK_SET);
  1161. get_byte(pb);
  1162. pos = pos_start;
  1163. for(;;) {
  1164. pos--;
  1165. if (pos < 0 || (pos_start - pos) >= max_size) {
  1166. start_code = -1;
  1167. goto the_end;
  1168. }
  1169. url_fseek(pb, pos, SEEK_SET);
  1170. start_code = get_be32(pb);
  1171. if ((start_code & 0xffffff00) == 0x100)
  1172. break;
  1173. }
  1174. the_end:
  1175. *size_ptr = pos_start - pos;
  1176. return start_code;
  1177. }
  1178. #endif
  1179. /**
  1180. * Extracts stream types from a program stream map
  1181. * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
  1182. *
  1183. * @return number of bytes occupied by PSM in the bitstream
  1184. */
  1185. static long mpegps_psm_parse(MpegDemuxContext *m, ByteIOContext *pb)
  1186. {
  1187. int psm_length, ps_info_length, es_map_length;
  1188. psm_length = get_be16(pb);
  1189. get_byte(pb);
  1190. get_byte(pb);
  1191. ps_info_length = get_be16(pb);
  1192. /* skip program_stream_info */
  1193. url_fskip(pb, ps_info_length);
  1194. es_map_length = get_be16(pb);
  1195. /* at least one es available? */
  1196. while (es_map_length >= 4){
  1197. unsigned char type = get_byte(pb);
  1198. unsigned char es_id = get_byte(pb);
  1199. uint16_t es_info_length = get_be16(pb);
  1200. /* remember mapping from stream id to stream type */
  1201. m->psm_es_type[es_id] = type;
  1202. /* skip program_stream_info */
  1203. url_fskip(pb, es_info_length);
  1204. es_map_length -= 4 + es_info_length;
  1205. }
  1206. get_be32(pb); /* crc32 */
  1207. return 2 + psm_length;
  1208. }
  1209. /* read the next PES header. Return its position in ppos
  1210. (if not NULL), and its start code, pts and dts.
  1211. */
  1212. static int mpegps_read_pes_header(AVFormatContext *s,
  1213. int64_t *ppos, int *pstart_code,
  1214. int64_t *ppts, int64_t *pdts)
  1215. {
  1216. MpegDemuxContext *m = s->priv_data;
  1217. int len, size, startcode, c, flags, header_len;
  1218. int64_t pts, dts, last_pos;
  1219. last_pos = -1;
  1220. redo:
  1221. /* next start code (should be immediately after) */
  1222. m->header_state = 0xff;
  1223. size = MAX_SYNC_SIZE;
  1224. startcode = find_next_start_code(&s->pb, &size, &m->header_state);
  1225. //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
  1226. if (startcode < 0)
  1227. return AVERROR_IO;
  1228. if (startcode == PACK_START_CODE)
  1229. goto redo;
  1230. if (startcode == SYSTEM_HEADER_START_CODE)
  1231. goto redo;
  1232. if (startcode == PADDING_STREAM ||
  1233. startcode == PRIVATE_STREAM_2) {
  1234. /* skip them */
  1235. len = get_be16(&s->pb);
  1236. url_fskip(&s->pb, len);
  1237. goto redo;
  1238. }
  1239. if (startcode == PROGRAM_STREAM_MAP) {
  1240. mpegps_psm_parse(m, &s->pb);
  1241. goto redo;
  1242. }
  1243. /* find matching stream */
  1244. if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
  1245. (startcode >= 0x1e0 && startcode <= 0x1ef) ||
  1246. (startcode == 0x1bd)))
  1247. goto redo;
  1248. if (ppos) {
  1249. *ppos = url_ftell(&s->pb) - 4;
  1250. }
  1251. len = get_be16(&s->pb);
  1252. pts = AV_NOPTS_VALUE;
  1253. dts = AV_NOPTS_VALUE;
  1254. /* stuffing */
  1255. for(;;) {
  1256. if (len < 1)
  1257. goto redo;
  1258. c = get_byte(&s->pb);
  1259. len--;
  1260. /* XXX: for mpeg1, should test only bit 7 */
  1261. if (c != 0xff)
  1262. break;
  1263. }
  1264. if ((c & 0xc0) == 0x40) {
  1265. /* buffer scale & size */
  1266. if (len < 2)
  1267. goto redo;
  1268. get_byte(&s->pb);
  1269. c = get_byte(&s->pb);
  1270. len -= 2;
  1271. }
  1272. if ((c & 0xf0) == 0x20) {
  1273. if (len < 4)
  1274. goto redo;
  1275. dts = pts = get_pts(&s->pb, c);
  1276. len -= 4;
  1277. } else if ((c & 0xf0) == 0x30) {
  1278. if (len < 9)
  1279. goto redo;
  1280. pts = get_pts(&s->pb, c);
  1281. dts = get_pts(&s->pb, -1);
  1282. len -= 9;
  1283. } else if ((c & 0xc0) == 0x80) {
  1284. /* mpeg 2 PES */
  1285. if ((c & 0x30) != 0) {
  1286. /* Encrypted multiplex not handled */
  1287. goto redo;
  1288. }
  1289. flags = get_byte(&s->pb);
  1290. header_len = get_byte(&s->pb);
  1291. len -= 2;
  1292. if (header_len > len)
  1293. goto redo;
  1294. if ((flags & 0xc0) == 0x80) {
  1295. dts = pts = get_pts(&s->pb, -1);
  1296. if (header_len < 5)
  1297. goto redo;
  1298. header_len -= 5;
  1299. len -= 5;
  1300. } if ((flags & 0xc0) == 0xc0) {
  1301. pts = get_pts(&s->pb, -1);
  1302. dts = get_pts(&s->pb, -1);
  1303. if (header_len < 10)
  1304. goto redo;
  1305. header_len -= 10;
  1306. len -= 10;
  1307. }
  1308. len -= header_len;
  1309. while (header_len > 0) {
  1310. get_byte(&s->pb);
  1311. header_len--;
  1312. }
  1313. }
  1314. else if( c!= 0xf )
  1315. goto redo;
  1316. if (startcode == PRIVATE_STREAM_1 && !m->psm_es_type[startcode & 0xff]) {
  1317. if (len < 1)
  1318. goto redo;
  1319. startcode = get_byte(&s->pb);
  1320. len--;
  1321. if (startcode >= 0x80 && startcode <= 0xbf) {
  1322. /* audio: skip header */
  1323. if (len < 3)
  1324. goto redo;
  1325. get_byte(&s->pb);
  1326. get_byte(&s->pb);
  1327. get_byte(&s->pb);
  1328. len -= 3;
  1329. }
  1330. }
  1331. if(dts != AV_NOPTS_VALUE && ppos){
  1332. int i;
  1333. for(i=0; i<s->nb_streams; i++){
  1334. if(startcode == s->streams[i]->id) {
  1335. av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
  1336. }
  1337. }
  1338. }
  1339. *pstart_code = startcode;
  1340. *ppts = pts;
  1341. *pdts = dts;
  1342. return len;
  1343. }
  1344. static int mpegps_read_packet(AVFormatContext *s,
  1345. AVPacket *pkt)
  1346. {
  1347. MpegDemuxContext *m = s->priv_data;
  1348. AVStream *st;
  1349. int len, startcode, i, type, codec_id = 0, es_type;
  1350. int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
  1351. redo:
  1352. len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
  1353. if (len < 0)
  1354. return len;
  1355. /* now find stream */
  1356. for(i=0;i<s->nb_streams;i++) {
  1357. st = s->streams[i];
  1358. if (st->id == startcode)
  1359. goto found;
  1360. }
  1361. es_type = m->psm_es_type[startcode & 0xff];
  1362. if(es_type > 0){
  1363. if(es_type == STREAM_TYPE_VIDEO_MPEG1){
  1364. codec_id = CODEC_ID_MPEG2VIDEO;
  1365. type = CODEC_TYPE_VIDEO;
  1366. } else if(es_type == STREAM_TYPE_VIDEO_MPEG2){
  1367. codec_id = CODEC_ID_MPEG2VIDEO;
  1368. type = CODEC_TYPE_VIDEO;
  1369. } else if(es_type == STREAM_TYPE_AUDIO_MPEG1 ||
  1370. es_type == STREAM_TYPE_AUDIO_MPEG2){
  1371. codec_id = CODEC_ID_MP3;
  1372. type = CODEC_TYPE_AUDIO;
  1373. } else if(es_type == STREAM_TYPE_AUDIO_AAC){
  1374. codec_id = CODEC_ID_AAC;
  1375. type = CODEC_TYPE_AUDIO;
  1376. } else if(es_type == STREAM_TYPE_VIDEO_MPEG4){
  1377. codec_id = CODEC_ID_MPEG4;
  1378. type = CODEC_TYPE_VIDEO;
  1379. } else if(es_type == STREAM_TYPE_VIDEO_H264){
  1380. codec_id = CODEC_ID_H264;
  1381. type = CODEC_TYPE_VIDEO;
  1382. } else if(es_type == STREAM_TYPE_AUDIO_AC3){
  1383. codec_id = CODEC_ID_AC3;
  1384. type = CODEC_TYPE_AUDIO;
  1385. } else {
  1386. goto skip;
  1387. }
  1388. } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
  1389. type = CODEC_TYPE_VIDEO;
  1390. codec_id = CODEC_ID_MPEG2VIDEO;
  1391. } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
  1392. type = CODEC_TYPE_AUDIO;
  1393. codec_id = CODEC_ID_MP2;
  1394. } else if (startcode >= 0x80 && startcode <= 0x87) {
  1395. type = CODEC_TYPE_AUDIO;
  1396. codec_id = CODEC_ID_AC3;
  1397. } else if (startcode >= 0x88 && startcode <= 0x9f) {
  1398. type = CODEC_TYPE_AUDIO;
  1399. codec_id = CODEC_ID_DTS;
  1400. } else if (startcode >= 0xa0 && startcode <= 0xbf) {
  1401. type = CODEC_TYPE_AUDIO;
  1402. codec_id = CODEC_ID_PCM_S16BE;
  1403. } else if (startcode >= 0x20 && startcode <= 0x3f) {
  1404. type = CODEC_TYPE_SUBTITLE;
  1405. codec_id = CODEC_ID_DVD_SUBTITLE;
  1406. } else {
  1407. skip:
  1408. /* skip packet */
  1409. url_fskip(&s->pb, len);
  1410. goto redo;
  1411. }
  1412. /* no stream found: add a new stream */
  1413. st = av_new_stream(s, startcode);
  1414. if (!st)
  1415. goto skip;
  1416. st->codec->codec_type = type;
  1417. st->codec->codec_id = codec_id;
  1418. if (codec_id != CODEC_ID_PCM_S16BE)
  1419. st->need_parsing = 1;
  1420. found:
  1421. if(st->discard >= AVDISCARD_ALL)
  1422. goto skip;
  1423. if (startcode >= 0xa0 && startcode <= 0xbf) {
  1424. int b1, freq;
  1425. /* for LPCM, we just skip the header and consider it is raw
  1426. audio data */
  1427. if (len <= 3)
  1428. goto skip;
  1429. get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
  1430. b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
  1431. get_byte(&s->pb); /* dynamic range control (0x80 = off) */
  1432. len -= 3;
  1433. freq = (b1 >> 4) & 3;
  1434. st->codec->sample_rate = lpcm_freq_tab[freq];
  1435. st->codec->channels = 1 + (b1 & 7);
  1436. st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * 2;
  1437. }
  1438. av_new_packet(pkt, len);
  1439. get_buffer(&s->pb, pkt->data, pkt->size);
  1440. pkt->pts = pts;
  1441. pkt->dts = dts;
  1442. pkt->stream_index = st->index;
  1443. #if 0
  1444. av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f size=%d\n",
  1445. pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0, pkt->size);
  1446. #endif
  1447. return 0;
  1448. }
  1449. static int mpegps_read_close(AVFormatContext *s)
  1450. {
  1451. return 0;
  1452. }
  1453. static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
  1454. int64_t *ppos, int64_t pos_limit)
  1455. {
  1456. int len, startcode;
  1457. int64_t pos, pts, dts;
  1458. pos = *ppos;
  1459. #ifdef DEBUG_SEEK
  1460. printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
  1461. #endif
  1462. url_fseek(&s->pb, pos, SEEK_SET);
  1463. for(;;) {
  1464. len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
  1465. if (len < 0) {
  1466. #ifdef DEBUG_SEEK
  1467. printf("none (ret=%d)\n", len);
  1468. #endif
  1469. return AV_NOPTS_VALUE;
  1470. }
  1471. if (startcode == s->streams[stream_index]->id &&
  1472. dts != AV_NOPTS_VALUE) {
  1473. break;
  1474. }
  1475. url_fskip(&s->pb, len);
  1476. }
  1477. #ifdef DEBUG_SEEK
  1478. printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
  1479. #endif
  1480. *ppos = pos;
  1481. return dts;
  1482. }
  1483. #ifdef CONFIG_MUXERS
  1484. static AVOutputFormat mpeg1system_mux = {
  1485. "mpeg",
  1486. "MPEG1 System format",
  1487. "video/mpeg",
  1488. "mpg,mpeg",
  1489. sizeof(MpegMuxContext),
  1490. CODEC_ID_MP2,
  1491. CODEC_ID_MPEG1VIDEO,
  1492. mpeg_mux_init,
  1493. mpeg_mux_write_packet,
  1494. mpeg_mux_end,
  1495. };
  1496. static AVOutputFormat mpeg1vcd_mux = {
  1497. "vcd",
  1498. "MPEG1 System format (VCD)",
  1499. "video/mpeg",
  1500. NULL,
  1501. sizeof(MpegMuxContext),
  1502. CODEC_ID_MP2,
  1503. CODEC_ID_MPEG1VIDEO,
  1504. mpeg_mux_init,
  1505. mpeg_mux_write_packet,
  1506. mpeg_mux_end,
  1507. };
  1508. static AVOutputFormat mpeg2vob_mux = {
  1509. "vob",
  1510. "MPEG2 PS format (VOB)",
  1511. "video/mpeg",
  1512. "vob",
  1513. sizeof(MpegMuxContext),
  1514. CODEC_ID_MP2,
  1515. CODEC_ID_MPEG2VIDEO,
  1516. mpeg_mux_init,
  1517. mpeg_mux_write_packet,
  1518. mpeg_mux_end,
  1519. };
  1520. /* Same as mpeg2vob_mux except that the pack size is 2324 */
  1521. static AVOutputFormat mpeg2svcd_mux = {
  1522. "svcd",
  1523. "MPEG2 PS format (VOB)",
  1524. "video/mpeg",
  1525. "vob",
  1526. sizeof(MpegMuxContext),
  1527. CODEC_ID_MP2,
  1528. CODEC_ID_MPEG2VIDEO,
  1529. mpeg_mux_init,
  1530. mpeg_mux_write_packet,
  1531. mpeg_mux_end,
  1532. };
  1533. /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
  1534. static AVOutputFormat mpeg2dvd_mux = {
  1535. "dvd",
  1536. "MPEG2 PS format (DVD VOB)",
  1537. "video/mpeg",
  1538. "dvd",
  1539. sizeof(MpegMuxContext),
  1540. CODEC_ID_MP2,
  1541. CODEC_ID_MPEG2VIDEO,
  1542. mpeg_mux_init,
  1543. mpeg_mux_write_packet,
  1544. mpeg_mux_end,
  1545. };
  1546. #endif //CONFIG_MUXERS
  1547. AVInputFormat mpegps_demux = {
  1548. "mpeg",
  1549. "MPEG PS format",
  1550. sizeof(MpegDemuxContext),
  1551. mpegps_probe,
  1552. mpegps_read_header,
  1553. mpegps_read_packet,
  1554. mpegps_read_close,
  1555. NULL, //mpegps_read_seek,
  1556. mpegps_read_dts,
  1557. .flags = AVFMT_SHOW_IDS,
  1558. };
  1559. int mpegps_init(void)
  1560. {
  1561. #ifdef CONFIG_MUXERS
  1562. av_register_output_format(&mpeg1system_mux);
  1563. av_register_output_format(&mpeg1vcd_mux);
  1564. av_register_output_format(&mpeg2vob_mux);
  1565. av_register_output_format(&mpeg2svcd_mux);
  1566. av_register_output_format(&mpeg2dvd_mux);
  1567. #endif //CONFIG_MUXERS
  1568. av_register_input_format(&mpegps_demux);
  1569. return 0;
  1570. }