vcodecs.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright 2007-2008, Sergio Fadda, Luigi Rizzo
  5. *
  6. * See http://www.asterisk.org for more information about
  7. * the Asterisk project. Please do not directly contact
  8. * any of the maintainers of this project for assistance;
  9. * the project provides a web site, mailing lists and IRC
  10. * channels for your use.
  11. *
  12. * This program is free software, distributed under the terms of
  13. * the GNU General Public License Version 2. See the LICENSE file
  14. * at the top of the source tree.
  15. */
  16. /*
  17. * Video codecs support for console_video.c
  18. * $Revision$
  19. */
  20. #include "asterisk.h"
  21. #include "console_video.h"
  22. #include "asterisk/frame.h"
  23. #include "asterisk/utils.h" /* ast_calloc() */
  24. struct video_out_desc;
  25. struct video_dec_desc;
  26. struct fbuf_t;
  27. /*
  28. * Each codec is defined by a number of callbacks
  29. */
  30. /*! \brief initialize the encoder */
  31. typedef int (*encoder_init_f)(AVCodecContext *v);
  32. /*! \brief actually call the encoder */
  33. typedef int (*encoder_encode_f)(struct video_out_desc *v);
  34. /*! \brief encapsulate the bistream in RTP frames */
  35. typedef struct ast_frame *(*encoder_encap_f)(struct fbuf_t *, int mtu,
  36. struct ast_frame **tail);
  37. /*! \brief inizialize the decoder */
  38. typedef int (*decoder_init_f)(AVCodecContext *enc_ctx);
  39. /*! \brief extract the bitstream from RTP frames and store in the fbuf.
  40. * return 0 if ok, 1 on error
  41. */
  42. typedef int (*decoder_decap_f)(struct fbuf_t *b, uint8_t *data, int len);
  43. /*! \brief actually call the decoder */
  44. typedef int (*decoder_decode_f)(struct video_dec_desc *v, struct fbuf_t *b);
  45. struct video_codec_desc {
  46. const char *name; /* format name */
  47. int format; /* AST_FORMAT_* */
  48. encoder_init_f enc_init;
  49. encoder_encap_f enc_encap;
  50. encoder_encode_f enc_run;
  51. decoder_init_f dec_init;
  52. decoder_decap_f dec_decap;
  53. decoder_decode_f dec_run;
  54. };
  55. /*
  56. * Descriptor for the incoming stream, with multiple buffers for the bitstream
  57. * extracted from the RTP packets, RTP reassembly info, and a frame buffer
  58. * for the decoded frame (buf).
  59. * The descriptor is allocated as the first frame comes in.
  60. *
  61. * Incoming payload is stored in one of the dec_in[] buffers, which are
  62. * emptied by the video thread. These buffers are organized in a circular
  63. * queue, with dec_in_cur being the buffer in use by the incoming stream,
  64. * and dec_in_dpy is the one being displayed. When the pointers need to
  65. * be changed, we synchronize the access to them with dec_lock.
  66. * When the list is full dec_in_cur = NULL (we cannot store new data),
  67. * when the list is empty dec_in_dpy = NULL (we cannot display frames).
  68. */
  69. struct video_dec_desc {
  70. struct video_codec_desc *d_callbacks; /* decoder callbacks */
  71. AVCodecContext *dec_ctx; /* information about the codec in the stream */
  72. AVCodec *codec; /* reference to the codec */
  73. AVFrame *d_frame; /* place to store the decoded frame */
  74. AVCodecParserContext *parser;
  75. uint16_t next_seq; /* must be 16 bit */
  76. int discard; /* flag for discard status */
  77. #define N_DEC_IN 3 /* number of incoming buffers */
  78. struct fbuf_t *dec_in_cur; /* buffer being filled in */
  79. struct fbuf_t *dec_in_dpy; /* buffer to display */
  80. struct fbuf_t dec_in[N_DEC_IN]; /* incoming bitstream, allocated/extended in fbuf_append() */
  81. struct fbuf_t dec_out; /* decoded frame, no buffer (data is in AVFrame) */
  82. };
  83. #ifdef debugging_only
  84. /* some debugging code to check the bitstream:
  85. * declare a bit buffer, initialize it, and fetch data from it.
  86. */
  87. struct bitbuf {
  88. const uint8_t *base;
  89. int bitsize; /* total size in bits */
  90. int ofs; /* next bit to read */
  91. };
  92. static struct bitbuf bitbuf_init(const uint8_t *base, int bitsize, int start_ofs)
  93. {
  94. struct bitbuf a;
  95. a.base = base;
  96. a.bitsize = bitsize;
  97. a.ofs = start_ofs;
  98. return a;
  99. }
  100. static int bitbuf_left(struct bitbuf *b)
  101. {
  102. return b->bitsize - b->ofs;
  103. }
  104. static uint32_t getbits(struct bitbuf *b, int n)
  105. {
  106. int i, ofs;
  107. const uint8_t *d;
  108. uint8_t mask;
  109. uint32_t retval = 0;
  110. if (n> 31) {
  111. ast_log(LOG_WARNING, "too many bits %d, max 32\n", n);
  112. return 0;
  113. }
  114. if (n + b->ofs > b->bitsize) {
  115. ast_log(LOG_WARNING, "bitbuf overflow %d of %d\n", n + b->ofs, b->bitsize);
  116. n = b->bitsize - b->ofs;
  117. }
  118. ofs = 7 - b->ofs % 8; /* start from msb */
  119. mask = 1 << ofs;
  120. d = b->base + b->ofs / 8; /* current byte */
  121. for (i=0 ; i < n; i++) {
  122. retval += retval + (*d & mask ? 1 : 0); /* shift in new byte */
  123. b->ofs++;
  124. mask >>= 1;
  125. if (mask == 0) {
  126. d++;
  127. mask = 0x80;
  128. }
  129. }
  130. return retval;
  131. }
  132. static void check_h261(struct fbuf_t *b)
  133. {
  134. struct bitbuf a = bitbuf_init(b->data, b->used * 8, 0);
  135. uint32_t x, y;
  136. x = getbits(&a, 20); /* PSC, 0000 0000 0000 0001 0000 */
  137. if (x != 0x10) {
  138. ast_log(LOG_WARNING, "bad PSC 0x%x\n", x);
  139. return;
  140. }
  141. x = getbits(&a, 5); /* temporal reference */
  142. y = getbits(&a, 6); /* ptype */
  143. if (0)
  144. ast_log(LOG_WARNING, "size %d TR %d PTY spl %d doc %d freeze %d %sCIF hi %d\n",
  145. b->used,
  146. x,
  147. (y & 0x20) ? 1 : 0,
  148. (y & 0x10) ? 1 : 0,
  149. (y & 0x8) ? 1 : 0,
  150. (y & 0x4) ? "" : "Q",
  151. (y & 0x2) ? 1:0);
  152. while ( (x = getbits(&a, 1)) == 1)
  153. ast_log(LOG_WARNING, "PSPARE 0x%x\n", getbits(&a, 8));
  154. // ast_log(LOG_WARNING, "PSPARE 0 - start GOB LAYER\n");
  155. while ( (x = bitbuf_left(&a)) > 0) {
  156. // ast_log(LOG_WARNING, "GBSC %d bits left\n", x);
  157. x = getbits(&a, 16); /* GBSC 0000 0000 0000 0001 */
  158. if (x != 0x1) {
  159. ast_log(LOG_WARNING, "bad GBSC 0x%x\n", x);
  160. break;
  161. }
  162. x = getbits(&a, 4); /* group number */
  163. y = getbits(&a, 5); /* gquant */
  164. if (x == 0) {
  165. ast_log(LOG_WARNING, " bad GN %d\n", x);
  166. break;
  167. }
  168. while ( (x = getbits(&a, 1)) == 1)
  169. ast_log(LOG_WARNING, "GSPARE 0x%x\n", getbits(&a, 8));
  170. while ( (x = bitbuf_left(&a)) > 0) { /* MB layer */
  171. break;
  172. }
  173. }
  174. }
  175. void dump_buf(struct fbuf_t *b);
  176. void dump_buf(struct fbuf_t *b)
  177. {
  178. int i, x, last2lines;
  179. char buf[80];
  180. last2lines = (b->used - 16) & ~0xf;
  181. ast_log(LOG_WARNING, "buf size %d of %d\n", b->used, b->size);
  182. for (i = 0; i < b->used; i++) {
  183. x = i & 0xf;
  184. if ( x == 0) { /* new line */
  185. if (i != 0)
  186. ast_log(LOG_WARNING, "%s\n", buf);
  187. memset(buf, '\0', sizeof(buf));
  188. sprintf(buf, "%04x: ", i);
  189. }
  190. sprintf(buf + 6 + x*3, "%02x ", b->data[i]);
  191. if (i > 31 && i < last2lines)
  192. i = last2lines - 1;
  193. }
  194. if (buf[0])
  195. ast_log(LOG_WARNING, "%s\n", buf);
  196. }
  197. #endif /* debugging_only */
  198. /*!
  199. * Build an ast_frame for a given chunk of data, and link it into
  200. * the queue, with possibly 'head' bytes at the beginning to
  201. * fill in some fields later.
  202. */
  203. static struct ast_frame *create_video_frame(uint8_t *start, uint8_t *end,
  204. int format, int head, struct ast_frame *prev)
  205. {
  206. int len = end-start;
  207. uint8_t *data;
  208. struct ast_frame *f;
  209. data = ast_calloc(1, len+head);
  210. f = ast_calloc(1, sizeof(*f));
  211. if (f == NULL || data == NULL) {
  212. ast_log(LOG_WARNING, "--- frame error f %p data %p len %d format %d\n",
  213. f, data, len, format);
  214. if (f)
  215. ast_free(f);
  216. if (data)
  217. ast_free(data);
  218. return NULL;
  219. }
  220. memcpy(data+head, start, len);
  221. f->data.ptr = data;
  222. f->mallocd = AST_MALLOCD_DATA | AST_MALLOCD_HDR;
  223. //f->has_timing_info = 1;
  224. //f->ts = ast_tvdiff_ms(ast_tvnow(), out->ts);
  225. f->datalen = len+head;
  226. f->frametype = AST_FRAME_VIDEO;
  227. f->subclass = format;
  228. f->samples = 0;
  229. f->offset = 0;
  230. f->src = "Console";
  231. f->delivery.tv_sec = 0;
  232. f->delivery.tv_usec = 0;
  233. f->seqno = 0;
  234. AST_LIST_NEXT(f, frame_list) = NULL;
  235. if (prev)
  236. AST_LIST_NEXT(prev, frame_list) = f;
  237. return f;
  238. }
  239. /*
  240. * Append a chunk of data to a buffer taking care of bit alignment
  241. * Return 0 on success, != 0 on failure
  242. */
  243. static int fbuf_append(struct fbuf_t *b, uint8_t *src, int len,
  244. int sbit, int ebit)
  245. {
  246. /*
  247. * Allocate buffer. ffmpeg wants an extra FF_INPUT_BUFFER_PADDING_SIZE,
  248. * and also wants 0 as a buffer terminator to prevent trouble.
  249. */
  250. int need = len + FF_INPUT_BUFFER_PADDING_SIZE;
  251. int i;
  252. uint8_t *dst, mask;
  253. if (b->data == NULL) {
  254. b->size = need;
  255. b->used = 0;
  256. b->ebit = 0;
  257. b->data = ast_calloc(1, b->size);
  258. } else if (b->used + need > b->size) {
  259. b->size = b->used + need;
  260. b->data = ast_realloc(b->data, b->size);
  261. }
  262. if (b->data == NULL) {
  263. ast_log(LOG_WARNING, "alloc failure for %d, discard\n",
  264. b->size);
  265. return 1;
  266. }
  267. if (b->used == 0 && b->ebit != 0) {
  268. ast_log(LOG_WARNING, "ebit not reset at start\n");
  269. b->ebit = 0;
  270. }
  271. dst = b->data + b->used;
  272. i = b->ebit + sbit; /* bits to ignore around */
  273. if (i == 0) { /* easy case, just append */
  274. /* do everything in the common block */
  275. } else if (i == 8) { /* easy too, just handle the overlap byte */
  276. mask = (1 << b->ebit) - 1;
  277. /* update the last byte in the buffer */
  278. dst[-1] &= ~mask; /* clear bits to ignore */
  279. dst[-1] |= (*src & mask); /* append new bits */
  280. src += 1; /* skip and prepare for common block */
  281. len --;
  282. } else { /* must shift the new block, not done yet */
  283. ast_log(LOG_WARNING, "must handle shift %d %d at %d\n",
  284. b->ebit, sbit, b->used);
  285. return 1;
  286. }
  287. memcpy(dst, src, len);
  288. b->used += len;
  289. b->ebit = ebit;
  290. b->data[b->used] = 0; /* padding */
  291. return 0;
  292. }
  293. /*
  294. * Here starts the glue code for the various supported video codecs.
  295. * For each of them, we need to provide routines for initialization,
  296. * calling the encoder, encapsulating the bitstream in ast_frames,
  297. * extracting payload from ast_frames, and calling the decoder.
  298. */
  299. /*--- h263+ support --- */
  300. /*! \brief initialization of h263p */
  301. static int h263p_enc_init(AVCodecContext *enc_ctx)
  302. {
  303. /* modes supported are
  304. - Unrestricted Motion Vector (annex D)
  305. - Advanced Prediction (annex F)
  306. - Advanced Intra Coding (annex I)
  307. - Deblocking Filter (annex J)
  308. - Slice Structure (annex K)
  309. - Alternative Inter VLC (annex S)
  310. - Modified Quantization (annex T)
  311. */
  312. enc_ctx->flags |=CODEC_FLAG_H263P_UMV; /* annex D */
  313. enc_ctx->flags |=CODEC_FLAG_AC_PRED; /* annex f ? */
  314. enc_ctx->flags |=CODEC_FLAG_H263P_SLICE_STRUCT; /* annex k */
  315. enc_ctx->flags |= CODEC_FLAG_H263P_AIC; /* annex I */
  316. return 0;
  317. }
  318. /*
  319. * Create RTP/H.263 fragments to avoid IP fragmentation. We fragment on a
  320. * PSC or a GBSC, but if we don't find a suitable place just break somewhere.
  321. * Everything is byte-aligned.
  322. */
  323. static struct ast_frame *h263p_encap(struct fbuf_t *b, int mtu,
  324. struct ast_frame **tail)
  325. {
  326. struct ast_frame *cur = NULL, *first = NULL;
  327. uint8_t *d = b->data;
  328. int len = b->used;
  329. int l = len; /* size of the current fragment. If 0, must look for a psc */
  330. for (;len > 0; len -= l, d += l) {
  331. uint8_t *data;
  332. struct ast_frame *f;
  333. int i, h;
  334. if (len >= 3 && d[0] == 0 && d[1] == 0 && d[2] >= 0x80) {
  335. /* we are starting a new block, so look for a PSC. */
  336. for (i = 3; i < len - 3; i++) {
  337. if (d[i] == 0 && d[i+1] == 0 && d[i+2] >= 0x80) {
  338. l = i;
  339. break;
  340. }
  341. }
  342. }
  343. if (l > mtu || l > len) { /* psc not found, split */
  344. l = MIN(len, mtu);
  345. }
  346. if (l < 1 || l > mtu) {
  347. ast_log(LOG_WARNING, "--- frame error l %d\n", l);
  348. break;
  349. }
  350. if (d[0] == 0 && d[1] == 0) { /* we start with a psc */
  351. h = 0;
  352. } else { /* no psc, create a header */
  353. h = 2;
  354. }
  355. f = create_video_frame(d, d+l, AST_FORMAT_H263_PLUS, h, cur);
  356. if (!f)
  357. break;
  358. data = f->data.ptr;
  359. if (h == 0) { /* we start with a psc */
  360. data[0] |= 0x04; // set P == 1, and we are done
  361. } else { /* no psc, create a header */
  362. data[0] = data[1] = 0; // P == 0
  363. }
  364. if (!cur)
  365. first = f;
  366. cur = f;
  367. }
  368. if (cur)
  369. cur->subclass |= 1; // RTP Marker
  370. *tail = cur; /* end of the list */
  371. return first;
  372. }
  373. /*! \brief extract the bitstreem from the RTP payload.
  374. * This is format dependent.
  375. * For h263+, the format is defined in RFC 2429
  376. * and basically has a fixed 2-byte header as follows:
  377. * 5 bits RR reserved, shall be 0
  378. * 1 bit P indicate a start/end condition,
  379. * in which case the payload should be prepended
  380. * by two zero-valued bytes.
  381. * 1 bit V there is an additional VRC header after this header
  382. * 6 bits PLEN length in bytes of extra picture header
  383. * 3 bits PEBIT how many bits to be ignored in the last byte
  384. *
  385. * XXX the code below is not complete.
  386. */
  387. static int h263p_decap(struct fbuf_t *b, uint8_t *data, int len)
  388. {
  389. int PLEN;
  390. if (len < 2) {
  391. ast_log(LOG_WARNING, "invalid framesize %d\n", len);
  392. return 1;
  393. }
  394. PLEN = ( (data[0] & 1) << 5 ) | ( (data[1] & 0xf8) >> 3);
  395. if (PLEN > 0) {
  396. data += PLEN;
  397. len -= PLEN;
  398. }
  399. if (data[0] & 4) /* bit P */
  400. data[0] = data[1] = 0;
  401. else {
  402. data += 2;
  403. len -= 2;
  404. }
  405. return fbuf_append(b, data, len, 0, 0); /* ignore trail bits */
  406. }
  407. /*
  408. * generic encoder, used by the various protocols supported here.
  409. * We assume that the buffer is empty at the beginning.
  410. */
  411. static int ffmpeg_encode(struct video_out_desc *v)
  412. {
  413. struct fbuf_t *b = &v->enc_out;
  414. int i;
  415. b->used = avcodec_encode_video(v->enc_ctx, b->data, b->size, v->enc_in_frame);
  416. i = avcodec_encode_video(v->enc_ctx, b->data + b->used, b->size - b->used, NULL); /* delayed frames ? */
  417. if (i > 0) {
  418. ast_log(LOG_WARNING, "have %d more bytes\n", i);
  419. b->used += i;
  420. }
  421. return 0;
  422. }
  423. /*
  424. * Generic decoder, which is used by h263p, h263 and h261 as it simply
  425. * invokes ffmpeg's decoder.
  426. * av_parser_parse should merge a randomly chopped up stream into
  427. * proper frames. After that, if we have a valid frame, we decode it
  428. * until the entire frame is processed.
  429. */
  430. static int ffmpeg_decode(struct video_dec_desc *v, struct fbuf_t *b)
  431. {
  432. uint8_t *src = b->data;
  433. int srclen = b->used;
  434. int full_frame = 0;
  435. if (srclen == 0) /* no data */
  436. return 0;
  437. while (srclen) {
  438. uint8_t *data;
  439. int datalen, ret;
  440. int len = av_parser_parse(v->parser, v->dec_ctx, &data, &datalen, src, srclen, 0, 0);
  441. src += len;
  442. srclen -= len;
  443. /* The parser might return something it cannot decode, so it skips
  444. * the block returning no data
  445. */
  446. if (data == NULL || datalen == 0)
  447. continue;
  448. ret = avcodec_decode_video(v->dec_ctx, v->d_frame, &full_frame, data, datalen);
  449. if (full_frame == 1) /* full frame */
  450. break;
  451. if (ret < 0) {
  452. ast_log(LOG_NOTICE, "Error decoding\n");
  453. break;
  454. }
  455. }
  456. if (srclen != 0) /* update b with leftover data */
  457. memmove(b->data, src, srclen);
  458. b->used = srclen;
  459. b->ebit = 0;
  460. return full_frame;
  461. }
  462. static struct video_codec_desc h263p_codec = {
  463. .name = "h263p",
  464. .format = AST_FORMAT_H263_PLUS,
  465. .enc_init = h263p_enc_init,
  466. .enc_encap = h263p_encap,
  467. .enc_run = ffmpeg_encode,
  468. .dec_init = NULL,
  469. .dec_decap = h263p_decap,
  470. .dec_run = ffmpeg_decode
  471. };
  472. /*--- Plain h263 support --------*/
  473. static int h263_enc_init(AVCodecContext *enc_ctx)
  474. {
  475. /* XXX check whether these are supported */
  476. enc_ctx->flags |= CODEC_FLAG_H263P_UMV;
  477. enc_ctx->flags |= CODEC_FLAG_H263P_AIC;
  478. enc_ctx->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
  479. enc_ctx->flags |= CODEC_FLAG_AC_PRED;
  480. return 0;
  481. }
  482. /*
  483. * h263 encapsulation is specified in RFC2190. There are three modes
  484. * defined (A, B, C), with 4, 8 and 12 bytes of header, respectively.
  485. * The header is made as follows
  486. * 0.....................|.......................|.............|....31
  487. * F:1 P:1 SBIT:3 EBIT:3 SRC:3 I:1 U:1 S:1 A:1 R:4 DBQ:2 TRB:3 TR:8
  488. * FP = 0- mode A, (only one word of header)
  489. * FP = 10 mode B, and also means this is an I or P frame
  490. * FP = 11 mode C, and also means this is a PB frame.
  491. * SBIT, EBIT nuber of bits to ignore at beginning (msbits) and end (lsbits)
  492. * SRC bits 6,7,8 from the h263 PTYPE field
  493. * I = 0 intra-coded, 1 = inter-coded (bit 9 from PTYPE)
  494. * U = 1 for Unrestricted Motion Vector (bit 10 from PTYPE)
  495. * S = 1 for Syntax Based Arith coding (bit 11 from PTYPE)
  496. * A = 1 for Advanced Prediction (bit 12 from PTYPE)
  497. * R = reserved, must be 0
  498. * DBQ = differential quantization, DBQUANT from h263, 0 unless we are using
  499. * PB frames
  500. * TRB = temporal reference for bframes, also 0 unless this is a PB frame
  501. * TR = temporal reference for P frames, also 0 unless PB frame.
  502. *
  503. * Mode B and mode C description omitted.
  504. *
  505. * An RTP frame can start with a PSC 0000 0000 0000 0000 1000 0
  506. * or with a GBSC, which also has the first 17 bits as a PSC.
  507. * Note - PSC are byte-aligned, GOB not necessarily. PSC start with
  508. * PSC:22 0000 0000 0000 0000 1000 00 picture start code
  509. * TR:8 .... .... temporal reference
  510. * PTYPE:13 or more ptype...
  511. * If we don't fragment a GOB SBIT and EBIT = 0.
  512. * reference, 8 bit)
  513. *
  514. * The assumption below is that we start with a PSC.
  515. */
  516. static struct ast_frame *h263_encap(struct fbuf_t *b, int mtu,
  517. struct ast_frame **tail)
  518. {
  519. uint8_t *d = b->data;
  520. int start = 0, i, len = b->used;
  521. struct ast_frame *f, *cur = NULL, *first = NULL;
  522. const int pheader_len = 4; /* Use RFC-2190 Mode A */
  523. uint8_t h263_hdr[12]; /* worst case, room for a type c header */
  524. uint8_t *h = h263_hdr; /* shorthand */
  525. #define H263_MIN_LEN 6
  526. if (len < H263_MIN_LEN) /* unreasonably small */
  527. return NULL;
  528. memset(h263_hdr, '\0', sizeof(h263_hdr));
  529. /* Now set the header bytes. Only type A by now,
  530. * and h[0] = h[2] = h[3] = 0 by default.
  531. * PTYPE starts 30 bits in the picture, so the first useful
  532. * bit for us is bit 36 i.e. within d[4] (0 is the msbit).
  533. * SRC = d[4] & 0x1c goes into data[1] & 0xe0
  534. * I = d[4] & 0x02 goes into data[1] & 0x10
  535. * U = d[4] & 0x01 goes into data[1] & 0x08
  536. * S = d[5] & 0x80 goes into data[1] & 0x04
  537. * A = d[5] & 0x40 goes into data[1] & 0x02
  538. * R = 0 goes into data[1] & 0x01
  539. * Optimizing it, we have
  540. */
  541. h[1] = ( (d[4] & 0x1f) << 3 ) | /* SRC, I, U */
  542. ( (d[5] & 0xc0) >> 5 ); /* S, A, R */
  543. /* now look for the next PSC or GOB header. First try to hit
  544. * a '0' byte then look around for the 0000 0000 0000 0000 1 pattern
  545. * which is both in the PSC and the GBSC.
  546. */
  547. for (i = H263_MIN_LEN, start = 0; start < len; start = i, i += 3) {
  548. //ast_log(LOG_WARNING, "search at %d of %d/%d\n", i, start, len);
  549. for (; i < len ; i++) {
  550. uint8_t x, rpos, lpos;
  551. int rpos_i; /* index corresponding to rpos */
  552. if (d[i] != 0) /* cannot be in a GBSC */
  553. continue;
  554. if (i > len - 1)
  555. break;
  556. x = d[i+1];
  557. if (x == 0) /* next is equally good */
  558. continue;
  559. /* see if around us we can make 16 '0' bits for the GBSC.
  560. * Look for the first bit set on the right, and then
  561. * see if we have enough 0 on the left.
  562. * We are guaranteed to end before rpos == 0
  563. */
  564. for (rpos = 0x80, rpos_i = 8; rpos; rpos >>= 1, rpos_i--)
  565. if (x & rpos) /* found the '1' bit in GBSC */
  566. break;
  567. x = d[i-1]; /* now look behind */
  568. for (lpos = rpos; lpos ; lpos >>= 1)
  569. if (x & lpos) /* too early, not a GBSC */
  570. break;
  571. if (lpos) /* as i said... */
  572. continue;
  573. /* now we have a GBSC starting somewhere in d[i-1],
  574. * but it might be not byte-aligned
  575. */
  576. if (rpos == 0x80) { /* lucky case */
  577. i = i - 1;
  578. } else { /* XXX to be completed */
  579. ast_log(LOG_WARNING, "unaligned GBSC 0x%x %d\n",
  580. rpos, rpos_i);
  581. }
  582. break;
  583. }
  584. /* This frame is up to offset i (not inclusive).
  585. * We do not split it yet even if larger than MTU.
  586. */
  587. f = create_video_frame(d + start, d+i, AST_FORMAT_H263,
  588. pheader_len, cur);
  589. if (!f)
  590. break;
  591. memmove(f->data.ptr, h, 4); /* copy the h263 header */
  592. /* XXX to do: if not aligned, fix sbit and ebit,
  593. * then move i back by 1 for the next frame
  594. */
  595. if (!cur)
  596. first = f;
  597. cur = f;
  598. }
  599. if (cur)
  600. cur->subclass |= 1; // RTP Marker
  601. *tail = cur;
  602. return first;
  603. }
  604. /* XXX We only drop the header here, but maybe we need more. */
  605. static int h263_decap(struct fbuf_t *b, uint8_t *data, int len)
  606. {
  607. if (len < 4) {
  608. ast_log(LOG_WARNING, "invalid framesize %d\n", len);
  609. return 1; /* error */
  610. }
  611. if ( (data[0] & 0x80) == 0) {
  612. len -= 4;
  613. data += 4;
  614. } else {
  615. ast_log(LOG_WARNING, "unsupported mode 0x%x\n",
  616. data[0]);
  617. return 1;
  618. }
  619. return fbuf_append(b, data, len, 0, 0); /* XXX no bit alignment support yet */
  620. }
  621. static struct video_codec_desc h263_codec = {
  622. .name = "h263",
  623. .format = AST_FORMAT_H263,
  624. .enc_init = h263_enc_init,
  625. .enc_encap = h263_encap,
  626. .enc_run = ffmpeg_encode,
  627. .dec_init = NULL,
  628. .dec_decap = h263_decap,
  629. .dec_run = ffmpeg_decode
  630. };
  631. /*---- h261 support -----*/
  632. static int h261_enc_init(AVCodecContext *enc_ctx)
  633. {
  634. /* It is important to set rtp_payload_size = 0, otherwise
  635. * ffmpeg in h261 mode will produce output that it cannot parse.
  636. * Also try to send I frames more frequently than with other codecs.
  637. */
  638. enc_ctx->rtp_payload_size = 0; /* important - ffmpeg fails otherwise */
  639. return 0;
  640. }
  641. /*
  642. * The encapsulation of H261 is defined in RFC4587 which obsoletes RFC2032
  643. * The bitstream is preceded by a 32-bit header word:
  644. * SBIT:3 EBIT:3 I:1 V:1 GOBN:4 MBAP:5 QUANT:5 HMVD:5 VMVD:5
  645. * SBIT and EBIT are the bits to be ignored at beginning and end,
  646. * I=1 if the stream has only INTRA frames - cannot change during the stream.
  647. * V=0 if motion vector is not used. Cannot change.
  648. * GOBN is the GOB number in effect at the start of packet, 0 if we
  649. * start with a GOB header
  650. * QUANT is the quantizer in effect, 0 if we start with GOB header
  651. * HMVD reference horizontal motion vector. 10000 is forbidden
  652. * VMVD reference vertical motion vector, as above.
  653. * Packetization should occur at GOB boundaries, and if not possible
  654. * with MacroBlock fragmentation. However it is likely that blocks
  655. * are not bit-aligned so we must take care of this.
  656. */
  657. static struct ast_frame *h261_encap(struct fbuf_t *b, int mtu,
  658. struct ast_frame **tail)
  659. {
  660. uint8_t *d = b->data;
  661. int start = 0, i, len = b->used;
  662. struct ast_frame *f, *cur = NULL, *first = NULL;
  663. const int pheader_len = 4;
  664. uint8_t h261_hdr[4];
  665. uint8_t *h = h261_hdr; /* shorthand */
  666. int sbit = 0, ebit = 0;
  667. #define H261_MIN_LEN 10
  668. if (len < H261_MIN_LEN) /* unreasonably small */
  669. return NULL;
  670. memset(h261_hdr, '\0', sizeof(h261_hdr));
  671. /* Similar to the code in h263_encap, but the marker there is longer.
  672. * Start a few bytes within the bitstream to avoid hitting the marker
  673. * twice. Note we might access the buffer at len, but this is ok because
  674. * the caller has it oversized.
  675. */
  676. for (i = H261_MIN_LEN, start = 0; start < len - 1; start = i, i += 4) {
  677. #if 0 /* test - disable packetization */
  678. i = len; /* wrong... */
  679. #else
  680. int found = 0, found_ebit = 0; /* last GBSC position found */
  681. for (; i < len ; i++) {
  682. uint8_t x, rpos, lpos;
  683. if (d[i] != 0) /* cannot be in a GBSC */
  684. continue;
  685. x = d[i+1];
  686. if (x == 0) /* next is equally good */
  687. continue;
  688. /* See if around us we find 15 '0' bits for the GBSC.
  689. * Look for the first bit set on the right, and then
  690. * see if we have enough 0 on the left.
  691. * We are guaranteed to end before rpos == 0
  692. */
  693. for (rpos = 0x80, ebit = 7; rpos; ebit--, rpos >>= 1)
  694. if (x & rpos) /* found the '1' bit in GBSC */
  695. break;
  696. x = d[i-1]; /* now look behind */
  697. for (lpos = (rpos >> 1); lpos ; lpos >>= 1)
  698. if (x & lpos) /* too early, not a GBSC */
  699. break;
  700. if (lpos) /* as i said... */
  701. continue;
  702. /* now we have a GBSC starting somewhere in d[i-1],
  703. * but it might be not byte-aligned. Just remember it.
  704. */
  705. if (i - start > mtu) /* too large, stop now */
  706. break;
  707. found_ebit = ebit;
  708. found = i;
  709. i += 4; /* continue forward */
  710. }
  711. if (i >= len) { /* trim if we went too forward */
  712. i = len;
  713. ebit = 0; /* hopefully... should ask the bitstream ? */
  714. }
  715. if (i - start > mtu && found) {
  716. /* use the previous GBSC, hope is within the mtu */
  717. i = found;
  718. ebit = found_ebit;
  719. }
  720. #endif /* test */
  721. if (i - start < 4) /* XXX too short ? */
  722. continue;
  723. /* This frame is up to offset i (not inclusive).
  724. * We do not split it yet even if larger than MTU.
  725. */
  726. f = create_video_frame(d + start, d+i, AST_FORMAT_H261,
  727. pheader_len, cur);
  728. if (!f)
  729. break;
  730. /* recompute header with I=0, V=1 */
  731. h[0] = ( (sbit & 7) << 5 ) | ( (ebit & 7) << 2 ) | 1;
  732. memmove(f->data.ptr, h, 4); /* copy the h261 header */
  733. if (ebit) /* not aligned, restart from previous byte */
  734. i--;
  735. sbit = (8 - ebit) & 7;
  736. ebit = 0;
  737. if (!cur)
  738. first = f;
  739. cur = f;
  740. }
  741. if (cur)
  742. cur->subclass |= 1; // RTP Marker
  743. *tail = cur;
  744. return first;
  745. }
  746. /*
  747. * Pieces might be unaligned so we really need to put them together.
  748. */
  749. static int h261_decap(struct fbuf_t *b, uint8_t *data, int len)
  750. {
  751. int ebit, sbit;
  752. if (len < 8) {
  753. ast_log(LOG_WARNING, "invalid framesize %d\n", len);
  754. return 1;
  755. }
  756. sbit = (data[0] >> 5) & 7;
  757. ebit = (data[0] >> 2) & 7;
  758. len -= 4;
  759. data += 4;
  760. return fbuf_append(b, data, len, sbit, ebit);
  761. }
  762. static struct video_codec_desc h261_codec = {
  763. .name = "h261",
  764. .format = AST_FORMAT_H261,
  765. .enc_init = h261_enc_init,
  766. .enc_encap = h261_encap,
  767. .enc_run = ffmpeg_encode,
  768. .dec_init = NULL,
  769. .dec_decap = h261_decap,
  770. .dec_run = ffmpeg_decode
  771. };
  772. /* mpeg4 support */
  773. static int mpeg4_enc_init(AVCodecContext *enc_ctx)
  774. {
  775. #if 0
  776. //enc_ctx->flags |= CODEC_FLAG_LOW_DELAY; /*don't use b frames ?*/
  777. enc_ctx->flags |= CODEC_FLAG_AC_PRED;
  778. enc_ctx->flags |= CODEC_FLAG_H263P_UMV;
  779. enc_ctx->flags |= CODEC_FLAG_QPEL;
  780. enc_ctx->flags |= CODEC_FLAG_4MV;
  781. enc_ctx->flags |= CODEC_FLAG_GMC;
  782. enc_ctx->flags |= CODEC_FLAG_LOOP_FILTER;
  783. enc_ctx->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
  784. #endif
  785. enc_ctx->rtp_payload_size = 0; /* important - ffmpeg fails otherwise */
  786. return 0;
  787. }
  788. /* simplistic encapsulation - just split frames in mtu-size units */
  789. static struct ast_frame *mpeg4_encap(struct fbuf_t *b, int mtu,
  790. struct ast_frame **tail)
  791. {
  792. struct ast_frame *f, *cur = NULL, *first = NULL;
  793. uint8_t *d = b->data;
  794. uint8_t *end = d + b->used;
  795. int len;
  796. for (;d < end; d += len, cur = f) {
  797. len = MIN(mtu, end - d);
  798. f = create_video_frame(d, d + len, AST_FORMAT_MP4_VIDEO, 0, cur);
  799. if (!f)
  800. break;
  801. if (!first)
  802. first = f;
  803. }
  804. if (cur)
  805. cur->subclass |= 1;
  806. *tail = cur;
  807. return first;
  808. }
  809. static int mpeg4_decap(struct fbuf_t *b, uint8_t *data, int len)
  810. {
  811. return fbuf_append(b, data, len, 0, 0);
  812. }
  813. static int mpeg4_decode(struct video_dec_desc *v, struct fbuf_t *b)
  814. {
  815. int full_frame = 0, datalen = b->used;
  816. int ret = avcodec_decode_video(v->dec_ctx, v->d_frame, &full_frame,
  817. b->data, datalen);
  818. if (ret < 0) {
  819. ast_log(LOG_NOTICE, "Error decoding\n");
  820. ret = datalen; /* assume we used everything. */
  821. }
  822. datalen -= ret;
  823. if (datalen > 0) /* update b with leftover bytes */
  824. memmove(b->data, b->data + ret, datalen);
  825. b->used = datalen;
  826. b->ebit = 0;
  827. return full_frame;
  828. }
  829. static struct video_codec_desc mpeg4_codec = {
  830. .name = "mpeg4",
  831. .format = AST_FORMAT_MP4_VIDEO,
  832. .enc_init = mpeg4_enc_init,
  833. .enc_encap = mpeg4_encap,
  834. .enc_run = ffmpeg_encode,
  835. .dec_init = NULL,
  836. .dec_decap = mpeg4_decap,
  837. .dec_run = mpeg4_decode
  838. };
  839. static int h264_enc_init(AVCodecContext *enc_ctx)
  840. {
  841. enc_ctx->flags |= CODEC_FLAG_TRUNCATED;
  842. //enc_ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
  843. //enc_ctx->flags2 |= CODEC_FLAG2_FASTPSKIP;
  844. /* TODO: Maybe we need to add some other flags */
  845. enc_ctx->rtp_mode = 0;
  846. enc_ctx->rtp_payload_size = 0;
  847. enc_ctx->bit_rate_tolerance = enc_ctx->bit_rate;
  848. return 0;
  849. }
  850. static int h264_dec_init(AVCodecContext *dec_ctx)
  851. {
  852. dec_ctx->flags |= CODEC_FLAG_TRUNCATED;
  853. return 0;
  854. }
  855. /*
  856. * The structure of a generic H.264 stream is:
  857. * - 0..n 0-byte(s), unused, optional. one zero-byte is always present
  858. * in the first NAL before the start code prefix.
  859. * - start code prefix (3 bytes): 0x000001
  860. * (the first bytestream has a
  861. * like these 0x00000001!)
  862. * - NAL header byte ( F[1] | NRI[2] | Type[5] ) where type != 0
  863. * - byte-stream
  864. * - 0..n 0-byte(s) (padding, unused).
  865. * Segmentation in RTP only needs to be done on start code prefixes.
  866. * If fragments are too long... we don't support it yet.
  867. * - encapsulate (or fragment) the byte-stream (with NAL header included)
  868. */
  869. static struct ast_frame *h264_encap(struct fbuf_t *b, int mtu,
  870. struct ast_frame **tail)
  871. {
  872. struct ast_frame *f = NULL, *cur = NULL, *first = NULL;
  873. uint8_t *d, *start = b->data;
  874. uint8_t *end = start + b->used;
  875. /* Search the first start code prefix - ITU-T H.264 sec. B.2,
  876. * and move start right after that, on the NAL header byte.
  877. */
  878. #define HAVE_NAL(x) (x[-4] == 0 && x[-3] == 0 && x[-2] == 0 && x[-1] == 1)
  879. for (start += 4; start < end; start++) {
  880. int ty = start[0] & 0x1f;
  881. if (HAVE_NAL(start) && ty != 0 && ty != 31)
  882. break;
  883. }
  884. /* if not found, or too short, we just skip the next loop and are done. */
  885. /* Here follows the main loop to create frames. Search subsequent start
  886. * codes, and then possibly fragment the unit into smaller fragments.
  887. */
  888. for (;start < end - 4; start = d) {
  889. int size; /* size of current block */
  890. uint8_t hdr[2]; /* add-on header when fragmenting */
  891. int ty = 0;
  892. /* now search next nal */
  893. for (d = start + 4; d < end; d++) {
  894. ty = d[0] & 0x1f;
  895. if (HAVE_NAL(d))
  896. break; /* found NAL */
  897. }
  898. /* have a block to send. d past the start code unless we overflow */
  899. if (d >= end) { /* NAL not found */
  900. d = end + 4;
  901. } else if (ty == 0 || ty == 31) { /* found but invalid type, skip */
  902. ast_log(LOG_WARNING, "skip invalid nal type %d at %d of %d\n",
  903. ty, d - (uint8_t *)b->data, b->used);
  904. continue;
  905. }
  906. size = d - start - 4; /* don't count the end */
  907. if (size < mtu) { // test - don't fragment
  908. // Single NAL Unit
  909. f = create_video_frame(start, d - 4, AST_FORMAT_H264, 0, cur);
  910. if (!f)
  911. break;
  912. if (!first)
  913. first = f;
  914. cur = f;
  915. continue;
  916. }
  917. // Fragmented Unit (Mode A: no DON, very weak)
  918. hdr[0] = (*start & 0xe0) | 28; /* mark as a fragmentation unit */
  919. hdr[1] = (*start++ & 0x1f) | 0x80 ; /* keep type and set START bit */
  920. size--; /* skip the NAL header */
  921. while (size) {
  922. uint8_t *data;
  923. int frag_size = MIN(size, mtu);
  924. f = create_video_frame(start, start+frag_size, AST_FORMAT_H264, 2, cur);
  925. if (!f)
  926. break;
  927. size -= frag_size; /* skip this data block */
  928. start += frag_size;
  929. data = f->data.ptr;
  930. data[0] = hdr[0];
  931. data[1] = hdr[1] | (size == 0 ? 0x40 : 0); /* end bit if we are done */
  932. hdr[1] &= ~0x80; /* clear start bit for subsequent frames */
  933. if (!first)
  934. first = f;
  935. cur = f;
  936. }
  937. }
  938. if (cur)
  939. cur->subclass |= 1; // RTP Marker
  940. *tail = cur;
  941. return first;
  942. }
  943. static int h264_decap(struct fbuf_t *b, uint8_t *data, int len)
  944. {
  945. /* Start Code Prefix (Annex B in specification) */
  946. uint8_t scp[] = { 0x00, 0x00, 0x00, 0x01 };
  947. int retval = 0;
  948. int type, ofs = 0;
  949. if (len < 2) {
  950. ast_log(LOG_WARNING, "--- invalid len %d\n", len);
  951. return 1;
  952. }
  953. /* first of all, check if the packet has F == 0 */
  954. if (data[0] & 0x80) {
  955. ast_log(LOG_WARNING, "--- forbidden packet; nal: %02x\n",
  956. data[0]);
  957. return 1;
  958. }
  959. type = data[0] & 0x1f;
  960. switch (type) {
  961. case 0:
  962. case 31:
  963. ast_log(LOG_WARNING, "--- invalid type: %d\n", type);
  964. return 1;
  965. case 24:
  966. case 25:
  967. case 26:
  968. case 27:
  969. case 29:
  970. ast_log(LOG_WARNING, "--- encapsulation not supported : %d\n", type);
  971. return 1;
  972. case 28: /* FU-A Unit */
  973. if (data[1] & 0x80) { // S == 1, import F and NRI from next
  974. data[1] &= 0x1f; /* preserve type */
  975. data[1] |= (data[0] & 0xe0); /* import F & NRI */
  976. retval = fbuf_append(b, scp, sizeof(scp), 0, 0);
  977. ofs = 1;
  978. } else {
  979. ofs = 2;
  980. }
  981. break;
  982. default: /* From 1 to 23 (Single NAL Unit) */
  983. retval = fbuf_append(b, scp, sizeof(scp), 0, 0);
  984. }
  985. if (!retval)
  986. retval = fbuf_append(b, data + ofs, len - ofs, 0, 0);
  987. if (retval)
  988. ast_log(LOG_WARNING, "result %d\n", retval);
  989. return retval;
  990. }
  991. static struct video_codec_desc h264_codec = {
  992. .name = "h264",
  993. .format = AST_FORMAT_H264,
  994. .enc_init = h264_enc_init,
  995. .enc_encap = h264_encap,
  996. .enc_run = ffmpeg_encode,
  997. .dec_init = h264_dec_init,
  998. .dec_decap = h264_decap,
  999. .dec_run = ffmpeg_decode
  1000. };
  1001. /*
  1002. * Table of translation between asterisk and ffmpeg formats.
  1003. * We need also a field for read and write (encoding and decoding), because
  1004. * e.g. H263+ uses different codec IDs in ffmpeg when encoding or decoding.
  1005. */
  1006. struct _cm { /* map ffmpeg codec types to asterisk formats */
  1007. uint32_t ast_format; /* 0 is a terminator */
  1008. enum CodecID codec;
  1009. enum { CM_RD = 1, CM_WR = 2, CM_RDWR = 3 } rw; /* read or write or both ? */
  1010. //struct video_codec_desc *codec_desc;
  1011. };
  1012. static const struct _cm video_formats[] = {
  1013. { AST_FORMAT_H263_PLUS, CODEC_ID_H263, CM_RD }, /* incoming H263P ? */
  1014. { AST_FORMAT_H263_PLUS, CODEC_ID_H263P, CM_WR },
  1015. { AST_FORMAT_H263, CODEC_ID_H263, CM_RD },
  1016. { AST_FORMAT_H263, CODEC_ID_H263, CM_WR },
  1017. { AST_FORMAT_H261, CODEC_ID_H261, CM_RDWR },
  1018. { AST_FORMAT_H264, CODEC_ID_H264, CM_RDWR },
  1019. { AST_FORMAT_MP4_VIDEO, CODEC_ID_MPEG4, CM_RDWR },
  1020. { 0, 0, 0 },
  1021. };
  1022. /*! \brief map an asterisk format into an ffmpeg one */
  1023. static enum CodecID map_video_format(uint32_t ast_format, int rw)
  1024. {
  1025. struct _cm *i;
  1026. for (i = video_formats; i->ast_format != 0; i++)
  1027. if (ast_format & i->ast_format && rw & i->rw && rw & i->rw)
  1028. return i->codec;
  1029. return CODEC_ID_NONE;
  1030. }
  1031. /* pointers to supported codecs. We assume the first one to be non null. */
  1032. static const struct video_codec_desc *supported_codecs[] = {
  1033. &h263p_codec,
  1034. &h264_codec,
  1035. &h263_codec,
  1036. &h261_codec,
  1037. &mpeg4_codec,
  1038. NULL
  1039. };
  1040. /*
  1041. * Map the AST_FORMAT to the library. If not recognised, fail.
  1042. * This is useful in the input path where we get frames.
  1043. */
  1044. static struct video_codec_desc *map_video_codec(int fmt)
  1045. {
  1046. int i;
  1047. for (i = 0; supported_codecs[i]; i++)
  1048. if (fmt == supported_codecs[i]->format) {
  1049. ast_log(LOG_WARNING, "using %s for format 0x%x\n",
  1050. supported_codecs[i]->name, fmt);
  1051. return supported_codecs[i];
  1052. }
  1053. return NULL;
  1054. }
  1055. /*! \brief uninitialize the descriptor for remote video stream */
  1056. static struct video_dec_desc *dec_uninit(struct video_dec_desc *v)
  1057. {
  1058. int i;
  1059. if (v == NULL) /* not initialized yet */
  1060. return NULL;
  1061. if (v->parser) {
  1062. av_parser_close(v->parser);
  1063. v->parser = NULL;
  1064. }
  1065. if (v->dec_ctx) {
  1066. avcodec_close(v->dec_ctx);
  1067. av_free(v->dec_ctx);
  1068. v->dec_ctx = NULL;
  1069. }
  1070. if (v->d_frame) {
  1071. av_free(v->d_frame);
  1072. v->d_frame = NULL;
  1073. }
  1074. v->codec = NULL; /* only a reference */
  1075. v->d_callbacks = NULL; /* forget the decoder */
  1076. v->discard = 1; /* start in discard mode */
  1077. for (i = 0; i < N_DEC_IN; i++)
  1078. fbuf_free(&v->dec_in[i]);
  1079. fbuf_free(&v->dec_out);
  1080. ast_free(v);
  1081. return NULL; /* error, in case someone cares */
  1082. }
  1083. /*
  1084. * initialize ffmpeg resources used for decoding frames from the network.
  1085. */
  1086. static struct video_dec_desc *dec_init(uint32_t the_ast_format)
  1087. {
  1088. enum CodecID codec;
  1089. struct video_dec_desc *v = ast_calloc(1, sizeof(*v));
  1090. if (v == NULL)
  1091. return NULL;
  1092. v->discard = 1;
  1093. v->d_callbacks = map_video_codec(the_ast_format);
  1094. if (v->d_callbacks == NULL) {
  1095. ast_log(LOG_WARNING, "cannot find video codec, drop input 0x%x\n", the_ast_format);
  1096. return dec_uninit(v);
  1097. }
  1098. codec = map_video_format(v->d_callbacks->format, CM_RD);
  1099. v->codec = avcodec_find_decoder(codec);
  1100. if (!v->codec) {
  1101. ast_log(LOG_WARNING, "Unable to find the decoder for format %d\n", codec);
  1102. return dec_uninit(v);
  1103. }
  1104. /*
  1105. * Initialize the codec context.
  1106. */
  1107. v->dec_ctx = avcodec_alloc_context();
  1108. if (!v->dec_ctx) {
  1109. ast_log(LOG_WARNING, "Cannot allocate the decoder context\n");
  1110. return dec_uninit(v);
  1111. }
  1112. /* XXX call dec_init() ? */
  1113. if (avcodec_open(v->dec_ctx, v->codec) < 0) {
  1114. ast_log(LOG_WARNING, "Cannot open the decoder context\n");
  1115. av_free(v->dec_ctx);
  1116. v->dec_ctx = NULL;
  1117. return dec_uninit(v);
  1118. }
  1119. v->parser = av_parser_init(codec);
  1120. if (!v->parser) {
  1121. ast_log(LOG_WARNING, "Cannot initialize the decoder parser\n");
  1122. return dec_uninit(v);
  1123. }
  1124. v->d_frame = avcodec_alloc_frame();
  1125. if (!v->d_frame) {
  1126. ast_log(LOG_WARNING, "Cannot allocate decoding video frame\n");
  1127. return dec_uninit(v);
  1128. }
  1129. v->dec_in_cur = &v->dec_in[0]; /* buffer for incoming frames */
  1130. v->dec_in_dpy = NULL; /* nothing to display */
  1131. return v; /* ok */
  1132. }
  1133. /*------ end codec specific code -----*/