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.

1698 lines
53KB

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