vcodecs.c 35 KB

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