plug another panic when the gui cannot be started.
[asterisk/asterisk.git] / channels / console_video.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright 2007-2008, Marta Carbone, 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 /*
18  * Experimental support for video sessions. We use SDL for rendering, ffmpeg
19  * as the codec library for encoding and decoding, and Video4Linux and X11
20  * to generate the local video stream.
21  *
22  * If one of these pieces is not available, either at compile time or at
23  * runtime, we do our best to run without it. Of course, no codec library
24  * means we can only deal with raw data, no SDL means we cannot do rendering,
25  * no V4L or X11 means we cannot generate data (but in principle we could
26  * stream from or record to a file).
27  *
28  * We need a recent (2007.07.12 or newer) version of ffmpeg to avoid warnings.
29  * Older versions might give 'deprecated' messages during compilation,
30  * thus not compiling in AST_DEVMODE, or don't have swscale, in which case
31  * you can try to compile #defining OLD_FFMPEG here.
32  *
33  * $Revision$
34  */
35
36 //#define DROP_PACKETS 5       /* if set, drop this % of video packets */
37 //#define OLD_FFMPEG    1       /* set for old ffmpeg with no swscale */
38
39 #include "asterisk.h"
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/ioctl.h>
42 #include "asterisk/cli.h"
43 #include "asterisk/file.h"
44 #include "asterisk/channel.h"
45
46 #include "console_video.h"
47
48 /*
49 The code is structured as follows.
50
51 When a new console channel is created, we call console_video_start()
52 to initialize SDL, the source, and the encoder/ decoder for the
53 formats in use (XXX the latter two should be done later, once the
54 codec negotiation is complete).  Also, a thread is created to handle
55 the video source and generate frames.
56
57 While communication is on, the local source is generated by the
58 video thread, which wakes up periodically, generates frames and
59 enqueues them in chan->readq.  Incoming rtp frames are passed to
60 console_write_video(), decoded and passed to SDL for display.
61
62 For as unfortunate and confusing as it can be, we need to deal with a
63 number of different video representations (size, codec/pixel format,
64 codec parameters), as follows:
65
66  loc_src        is the data coming from the camera/X11/etc.
67         The format is typically constrained by the video source.
68
69  enc_in         is the input required by the encoder.
70         Typically constrained in size by the encoder type.
71
72  enc_out        is the bitstream transmitted over RTP.
73         Typically negotiated while the call is established.
74
75  loc_dpy        is the format used to display the local video source.
76         Depending on user preferences this can have the same size as
77         loc_src_fmt, or enc_in_fmt, or thumbnail size (e.g. PiP output)
78
79  dec_in         is the incoming RTP bitstream. Negotiated
80         during call establishment, it is not necessarily the same as
81         enc_in_fmt
82
83  dec_out        the output of the decoder.
84         The format is whatever the other side sends, and the
85         buffer is allocated by avcodec_decode_... so we only
86         copy the data here.
87
88  rem_dpy        the format used to display the remote stream
89
90  src_dpy        is the format used to display the local video source streams
91         The number of these fbuf_t is determined at run time, with dynamic allocation
92
93 We store the format info together with the buffer storing the data.
94 As a future optimization, a format/buffer may reference another one
95 if the formats are equivalent. This will save some unnecessary format
96 conversion.
97
98
99 In order to handle video you need to add to sip.conf (and presumably
100 iax.conf too) the following:
101
102         [general](+)
103                 videosupport=yes
104                 allow=h263      ; this or other video formats
105                 allow=h263p     ; this or other video formats
106
107  */
108
109 /*
110  * Codecs are absolutely necessary or we cannot do anything.
111  * SDL is optional (used for rendering only), so that we can still
112  * stream video withouth displaying it.
113  */
114 #if !defined(HAVE_VIDEO_CONSOLE) || !defined(HAVE_FFMPEG)
115 /* stubs if required pieces are missing */
116 int console_write_video(struct ast_channel *chan, struct ast_frame *f)
117 {
118         return 0;       /* writing video not supported */
119 }
120
121 int console_video_cli(struct video_desc *env, const char *var, int fd)
122 {
123         return 1;       /* nothing matched */
124 }
125
126 int console_video_config(struct video_desc **penv, const char *var, const char *val)
127 {
128         return 1;       /* no configuration */
129 }
130
131 void console_video_start(struct video_desc *env, struct ast_channel *owner)
132 {
133         ast_log(LOG_NOTICE, "voice only, console video support not present\n");
134 }
135
136 void console_video_uninit(struct video_desc *env)
137 {
138 }
139
140 int get_gui_startup(struct video_desc* env)
141 {
142         return 0; /* no gui here */
143 }
144
145 int console_video_formats = 0;
146
147 #else /* defined(HAVE_FFMPEG) && defined(HAVE_SDL) */
148
149 /*! The list of video formats we support. */
150 int console_video_formats = 
151         AST_FORMAT_H263_PLUS | AST_FORMAT_H263 |
152         AST_FORMAT_MP4_VIDEO | AST_FORMAT_H264 | AST_FORMAT_H261 ;
153
154
155
156 /* function to scale and encode buffers */
157 static void my_scale(struct fbuf_t *in, AVPicture *p_in,
158         struct fbuf_t *out, AVPicture *p_out);
159
160 /*
161  * this structure will be an entry in the table containing
162  * every device specified in the file oss.conf, it contains various infomation
163  * about the device
164  */
165 struct video_device {
166         char                    *name;          /* name of the device                   */
167         /* allocated dynamically (see fill_table function) */
168         struct grab_desc        *grabber;       /* the grabber for the device type      */
169         void                    *grabber_data;  /* device's private data structure      */
170         struct fbuf_t           *dev_buf;       /* buffer for incoming data             */
171         struct timeval          last_frame;     /* when we read the last frame ?        */
172         int                     status_index;   /* what is the status of the device (source) */
173         /* status index is set using the IS_ON, IS_PRIMARY and IS_SECONDARY costants */
174         /* status_index is the index of the status message in the src_msgs array in console_gui.c */
175 };
176
177 struct video_codec_desc;        /* forward declaration */
178 /*
179  * Descriptor of the local source, made of the following pieces:
180  *  + configuration info (geometry, device name, fps...). These are read
181  *    from the config file and copied here before calling video_out_init();
182  *  + the frame buffer (buf) and source pixel format, allocated at init time;
183  *  + the encoding and RTP info, including timestamps to generate
184  *    frames at the correct rate;
185  *  + source-specific info, i.e. fd for /dev/video, dpy-image for x11, etc,
186  *    filled in by grabber_open, part of source_specific information are in 
187  *    the device table (devices member), others are shared;
188  * NOTE: loc_src.data == NULL means the rest of the struct is invalid, and
189  *      the video source is not available.
190  */
191 struct video_out_desc {
192         /* video device support.
193          * videodevice and geometry are read from the config file.
194          * At the right time we try to open it and allocate a buffer.
195          * If we are successful, webcam_bufsize > 0 and we can read.
196          */
197         /* all the following is config file info copied from the parent */
198         int             fps;
199         int             bitrate;
200         int             qmin;
201
202         int sendvideo;
203
204         struct fbuf_t   loc_src_geometry;       /* local source geometry only (from config file) */
205         struct fbuf_t   enc_out;        /* encoder output buffer, allocated in video_out_init() */
206
207         struct video_codec_desc *enc;   /* encoder */
208         void            *enc_ctx;       /* encoding context */
209         AVCodec         *codec;
210         AVFrame         *enc_in_frame;  /* enc_in mapped into avcodec format. */
211                                         /* The initial part of AVFrame is an AVPicture */
212         int             mtu;
213         
214         /* Table of devices specified with "videodevice=" in oss.conf.
215          * Static size as we have a limited number of entries.
216          */
217         struct video_device     devices[MAX_VIDEO_SOURCES]; 
218         int                     device_num; /*number of devices in table*/
219         int                     device_primary; /*index of the actual primary device in the table*/
220         int                     device_secondary; /*index of the actual secondary device in the table*/
221
222         int                     picture_in_picture; /*Is the PiP mode activated? 0 = NO | 1 = YES*/
223
224         /* these are the coordinates of the picture inside the picture (visible if PiP mode is active) 
225         these coordinates are valid considering the containing buffer with cif geometry*/
226         int                     pip_x;
227         int                     pip_y;
228 };
229
230 /*
231  * The overall descriptor, with room for config info, video source and
232  * received data descriptors, SDL info, etc.
233  * This should be globally visible to all modules (grabber, vcodecs, gui)
234  * and contain all configurtion info.
235  */
236 struct video_desc {
237         char                    codec_name[64]; /* the codec we use */
238
239         int                     stayopen;       /* set if gui starts manually */
240         pthread_t               vthread;        /* video thread */
241         ast_mutex_t             dec_lock;       /* sync decoder and video thread */
242         int                     shutdown;       /* set to shutdown vthread */
243         struct ast_channel      *owner;         /* owner channel */
244
245
246         struct fbuf_t   enc_in;         /* encoder input buffer, allocated in video_out_init() */
247
248         char                    keypad_file[256];       /* image for the keypad */
249         char                    keypad_font[256];       /* font for the keypad */
250
251         char                    sdl_videodriver[256];
252
253         struct fbuf_t           rem_dpy;        /* display remote video, no buffer (it is in win[WIN_REMOTE].bmp) */
254         struct fbuf_t           loc_dpy;        /* display local source, no buffer (managed by SDL in bmp[1]) */
255
256         /* geometry of the thumbnails for all video sources. */
257         struct fbuf_t           src_dpy[MAX_VIDEO_SOURCES]; /* no buffer allocated here */
258
259         int frame_freeze;       /* flag to freeze the incoming frame */
260
261         /* local information for grabbers, codecs, gui */
262         struct gui_info         *gui;
263         struct video_dec_desc   *in;            /* remote video descriptor */
264         struct video_out_desc   out;            /* local video descriptor */
265 };
266
267 static AVPicture *fill_pict(struct fbuf_t *b, AVPicture *p);
268
269 void fbuf_free(struct fbuf_t *b)
270 {
271         struct fbuf_t x = *b;
272
273         if (b->data && b->size)
274                 ast_free(b->data);
275         bzero(b, sizeof(*b));
276         /* restore some fields */
277         b->w = x.w;
278         b->h = x.h;
279         b->pix_fmt = x.pix_fmt;
280 }
281
282 /* return the status of env->stayopen to chan_oss, as the latter
283  * does not have access to fields of struct video_desc
284  */
285 int get_gui_startup(struct video_desc* env)
286 {
287         return env ? env->stayopen : 0;
288 }
289
290 #if 0
291 /* helper function to print the amount of memory used by the process.
292  * Useful to track memory leaks, unfortunately this code is OS-specific
293  * so we keep it commented out.
294  */
295 static int
296 used_mem(const char *msg)
297 {
298         char in[128];
299
300         pid_t pid = getpid();
301         sprintf(in, "ps -o vsz= -o rss= %d", pid);
302         ast_log(LOG_WARNING, "used mem (vsize, rss) %s ", msg);
303         system(in);
304         return 0;
305 }
306 #endif
307         
308 #include "vcodecs.c"
309 #include "console_gui.c"
310
311 /*! \brief Try to open video sources, return 0 on success, 1 on error
312  * opens all video sources found in the oss.conf configuration files.
313  * Saves the grabber and the datas in the device table (in the devices field
314  * of the descriptor referenced by v).
315  * Initializes the device_primary and device_secondary
316  * fields of v with the first devices that was
317  * successfully opened.
318  *
319  * \param v = video out environment descriptor
320  *
321  * returns 0 on success, 1 on error 
322 */
323 static int grabber_open(struct video_out_desc *v)
324 {
325         struct grab_desc *g;
326         void *g_data;
327         int i, j;
328
329         /* for each device in the device table... */
330         for (i = 0; i < v->device_num; i++) {
331                 /* device already open */
332                 if (v->devices[i].grabber)
333                         continue;
334                 /* for each type of grabber supported... */
335                 for (j = 0; (g = console_grabbers[j]); j++) {
336                         /* the grabber is opened and the informations saved in the device table */
337                         g_data = g->open(v->devices[i].name, &v->loc_src_geometry, v->fps);
338                         if (!g_data)
339                                 continue;
340                         v->devices[i].grabber = g;
341                         v->devices[i].grabber_data = g_data;
342                         v->devices[i].status_index |= IS_ON;
343                 }
344         }
345         /* the first working device is selected as the primary one and the secondary one */
346         for (i = 0; i < v->device_num; i++) {
347                 if (!v->devices[i].grabber) 
348                         continue;
349                 v->device_primary = i;
350                 v->device_secondary = i;
351                 return 0; /* source found */
352         }
353         return 1; /* no source found */
354 }
355
356
357 /*! \brief complete a buffer from the specified local video source.
358  * Called by get_video_frames(), in turn called by the video thread.
359  *
360  * \param dev = video environment descriptor
361  * \param fps = frame per seconds, for every device
362  *
363  * returns:
364  * - NULL on falure
365  * - reference to the device buffer on success
366  */
367 static struct fbuf_t *grabber_read(struct video_device *dev, int fps)
368 {
369         struct timeval now = ast_tvnow();
370
371         if (dev->grabber == NULL) /* not initialized */
372                 return NULL;
373         
374         /* the last_frame field in this row of the device table (dev)
375         is always initialized, it is set during the parsing of the config
376         file, and never unset, function fill_device_table(). */
377         /* check if it is time to read */
378         if (ast_tvdiff_ms(now, dev->last_frame) < 1000/fps)
379                 return NULL; /* too early */
380         dev->last_frame = now; /* XXX actually, should correct for drift */
381         return dev->grabber->read(dev->grabber_data);
382 }
383
384 /*! \brief handler run when dragging with the left button on
385  * the local source window - the effect is to move the offset
386  * of the captured area.
387  */
388 static void grabber_move(struct video_device *dev, int dx, int dy)
389 {
390         if (dev->grabber && dev->grabber->move)
391                 dev->grabber->move(dev->grabber_data, dx, dy);
392 }
393
394 /*
395  * Map the codec name to the library. If not recognised, use a default.
396  * This is useful in the output path where we decide by name, presumably.
397  */
398 static struct video_codec_desc *map_config_video_format(char *name)
399 {
400         int i;
401
402         for (i = 0; supported_codecs[i]; i++)
403                 if (!strcasecmp(name, supported_codecs[i]->name))
404                         break;
405         if (supported_codecs[i] == NULL) {
406                 ast_log(LOG_WARNING, "Cannot find codec for '%s'\n", name);
407                 i = 0;
408                 strcpy(name, supported_codecs[i]->name);
409         }
410         ast_log(LOG_WARNING, "Using codec '%s'\n", name);
411         return supported_codecs[i];
412 }
413
414
415 /*! \brief uninitialize the descriptor for local video stream */
416 static int video_out_uninit(struct video_desc *env)
417 {
418         struct video_out_desc *v = &env->out;
419         int i; /* integer variable used as iterator */
420         
421         /* XXX this should be a codec callback */
422         if (v->enc_ctx) {
423                 AVCodecContext *enc_ctx = (AVCodecContext *)v->enc_ctx;
424                 avcodec_close(enc_ctx);
425                 av_free(enc_ctx);
426                 v->enc_ctx = NULL;
427         }
428         if (v->enc_in_frame) {
429                 av_free(v->enc_in_frame);
430                 v->enc_in_frame = NULL;
431         }
432         v->codec = NULL;        /* nothing to free, this is only a reference */
433         /* release the buffers */
434         fbuf_free(&env->enc_in);
435         fbuf_free(&v->enc_out);
436         /* close the grabbers */
437         for (i = 0; i < v->device_num; i++) {
438                 if (v->devices[i].grabber){
439                         v->devices[i].grabber_data =
440                                 v->devices[i].grabber->close(v->devices[i].grabber_data);
441                         v->devices[i].grabber = NULL;
442                         /* dev_buf is already freed by grabber->close() */
443                         v->devices[i].dev_buf = NULL;
444                 }
445                 v->devices[i].status_index = 0;
446         }
447         v->picture_in_picture = 0;
448         env->frame_freeze = 0;
449         return -1;
450 }
451
452 /*
453  * Initialize the encoder for the local source:
454  * - enc_ctx, codec, enc_in_frame are used by ffmpeg for encoding;
455  * - enc_out is used to store the encoded frame (to be sent)
456  * - mtu is used to determine the max size of video fragment
457  * NOTE: we enter here with the video source already open.
458  */
459 static int video_out_init(struct video_desc *env)
460 {
461         int codec;
462         int size;
463         struct fbuf_t *enc_in;
464         struct video_out_desc *v = &env->out;
465
466         v->enc_ctx              = NULL;
467         v->codec                = NULL;
468         v->enc_in_frame         = NULL;
469         v->enc_out.data         = NULL;
470
471         codec = map_video_format(v->enc->format, CM_WR);
472         v->codec = avcodec_find_encoder(codec);
473         if (!v->codec) {
474                 ast_log(LOG_WARNING, "Cannot find the encoder for format %d\n",
475                         codec);
476                 return -1;      /* error, but nothing to undo yet */
477         }
478
479         v->mtu = 1400;  /* set it early so the encoder can use it */
480
481         /* allocate the input buffer for encoding.
482          * ffmpeg only supports PIX_FMT_YUV420P for the encoding.
483          */
484         enc_in = &env->enc_in;
485         enc_in->pix_fmt = PIX_FMT_YUV420P;
486         enc_in->size = (enc_in->w * enc_in->h * 3)/2;
487         enc_in->data = ast_calloc(1, enc_in->size);
488         if (!enc_in->data) {
489                 ast_log(LOG_WARNING, "Cannot allocate encoder input buffer\n");
490                 return video_out_uninit(env);
491         }
492         /* construct an AVFrame that points into buf_in */
493         v->enc_in_frame = avcodec_alloc_frame();
494         if (!v->enc_in_frame) {
495                 ast_log(LOG_WARNING, "Unable to allocate the encoding video frame\n");
496                 return video_out_uninit(env);
497         }
498
499         /* parameters for PIX_FMT_YUV420P */
500         size = enc_in->w * enc_in->h;
501         v->enc_in_frame->data[0] = enc_in->data;
502         v->enc_in_frame->data[1] = v->enc_in_frame->data[0] + size;
503         v->enc_in_frame->data[2] = v->enc_in_frame->data[1] + size/4;
504         v->enc_in_frame->linesize[0] = enc_in->w;
505         v->enc_in_frame->linesize[1] = enc_in->w/2;
506         v->enc_in_frame->linesize[2] = enc_in->w/2;
507
508         /* now setup the parameters for the encoder.
509          * XXX should be codec-specific
510          */
511     {
512         AVCodecContext *enc_ctx = avcodec_alloc_context();
513         v->enc_ctx = enc_ctx;
514         enc_ctx->pix_fmt = enc_in->pix_fmt;
515         enc_ctx->width = enc_in->w;
516         enc_ctx->height = enc_in->h;
517         /* XXX rtp_callback ?
518          * rtp_mode so ffmpeg inserts as many start codes as possible.
519          */
520         enc_ctx->rtp_mode = 1;
521         enc_ctx->rtp_payload_size = v->mtu / 2; // mtu/2
522         enc_ctx->bit_rate = v->bitrate;
523         enc_ctx->bit_rate_tolerance = enc_ctx->bit_rate/2;
524         enc_ctx->qmin = v->qmin;        /* should be configured */
525         enc_ctx->time_base = (AVRational){1, v->fps};
526         enc_ctx->gop_size = v->fps*5; // emit I frame every 5 seconds
527
528         v->enc->enc_init(v->enc_ctx);
529  
530         if (avcodec_open(enc_ctx, v->codec) < 0) {
531                 ast_log(LOG_WARNING, "Unable to initialize the encoder %d\n",
532                         codec);
533                 av_free(enc_ctx);
534                 v->enc_ctx = NULL;
535                 return video_out_uninit(env);
536         }
537     }
538         /*
539          * Allocate enough for the encoded bitstream. As we are compressing,
540          * we hope that the output is never larger than the input size.
541          */
542         v->enc_out.data = ast_calloc(1, enc_in->size);
543         v->enc_out.size = enc_in->size;
544         v->enc_out.used = 0;
545
546         return 0;
547 }
548
549 /*! \brief possibly uninitialize the video console.
550  * Called at the end of a call, should reset the 'owner' field,
551  * then possibly terminate the video thread if the gui has
552  * not been started manually.
553  * In practice, signal the thread and give it a bit of time to
554  * complete, giving up if it gets stuck. Because uninit
555  * is called from hangup with the channel locked, and the thread
556  * uses the chan lock, we need to unlock here. This is unsafe,
557  * and we should really use refcounts for the channels.
558  */
559 void console_video_uninit(struct video_desc *env)
560 {
561         int i, t = 100; /* initial wait is shorter, than make it longer */
562         if (env->stayopen == 0) { /* gui opened by a call, do the shutdown */
563                 env->shutdown = 1;
564                 for (i=0; env->shutdown && i < 10; i++) {
565                         if (env->owner)
566                                 ast_channel_unlock(env->owner);
567                         usleep(t);
568                         t = 1000000;
569                         if (env->owner)
570                                 ast_channel_lock(env->owner);
571                 }
572                 env->vthread = NULL;
573         }
574         env->owner = NULL;      /* this is unconditional */
575 }
576
577 /*! fill an AVPicture from our fbuf info, as it is required by
578  * the image conversion routines in ffmpeg. Note that the pointers
579  * are recalculated if the fbuf has an offset (and so represents a picture in picture)
580  * XXX This depends on the format.
581  */
582 static AVPicture *fill_pict(struct fbuf_t *b, AVPicture *p)
583 {
584         /* provide defaults for commonly used formats */
585         int l4 = b->w * b->h/4; /* size of U or V frame */
586         int len = b->w;         /* Y linesize, bytes */
587         int luv = b->w/2;       /* U/V linesize, bytes */
588         int sample_size = 1;
589         
590         bzero(p, sizeof(*p));
591         switch (b->pix_fmt) {
592         case PIX_FMT_RGB555:
593         case PIX_FMT_RGB565:
594                 sample_size = 2;
595                 luv = 0;
596                 break;
597         case PIX_FMT_RGBA32:
598                 sample_size = 4;
599                 luv = 0;
600                 break;
601         case PIX_FMT_YUYV422:   /* Packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr */
602                 sample_size = 2;        /* all data in first plane, probably */
603                 luv = 0;
604                 break;
605         }
606         len *= sample_size;
607         
608         p->data[0] = b->data;
609         p->linesize[0] = len;
610         /* these are only valid for component images */
611         p->data[1] = luv ? b->data + 4*l4 : b->data+len;
612         p->data[2] = luv ? b->data + 5*l4 : b->data+len;
613         p->linesize[1] = luv;
614         p->linesize[2] = luv;
615         
616         /* add the offsets to the pointers previously calculated, 
617         it is necessary for the picture in picture mode */
618         p->data[0] += len*b->win_y + b->win_x*sample_size;
619         if (luv) { 
620                 p->data[1] += luv*(b->win_y/2) + (b->win_x/2) * sample_size;
621                 p->data[2] += luv*(b->win_y/2) + (b->win_x/2) * sample_size;
622         }
623         return p;
624 }
625
626 /*! convert/scale between an input and an output format.
627  * Old version of ffmpeg only have img_convert, which does not rescale.
628  * New versions use sws_scale which does both.
629  */
630 static void my_scale(struct fbuf_t *in, AVPicture *p_in,
631         struct fbuf_t *out, AVPicture *p_out)
632 {
633         AVPicture my_p_in, my_p_out;
634         int eff_w=out->w, eff_h=out->h;
635
636         if (p_in == NULL)
637                 p_in = fill_pict(in, &my_p_in);
638         if (p_out == NULL)
639                 p_out = fill_pict(out, &my_p_out);
640         
641         /*if win_w is different from zero then we must change 
642         the size of the scaled buffer (the position is already 
643         encoded into the out parameter)*/
644         if (out->win_w) { /* picture in picture enabled */
645                 eff_w=out->win_w;
646                 eff_h=out->win_h;
647         }
648 #ifdef OLD_FFMPEG
649         /* XXX img_convert is deprecated, and does not do rescaling, PiP not supported */
650         img_convert(p_out, out->pix_fmt,
651                 p_in, in->pix_fmt, in->w, in->h);
652 #else /* XXX replacement */
653     {
654         struct SwsContext *convert_ctx;
655         
656         convert_ctx = sws_getContext(in->w, in->h, in->pix_fmt,
657                 eff_w, eff_h, out->pix_fmt,
658                 SWS_BICUBIC, NULL, NULL, NULL);
659         if (convert_ctx == NULL) {
660                 ast_log(LOG_ERROR, "FFMPEG::convert_cmodel : swscale context initialization failed");
661                 return;
662         }
663         if (0)
664                 ast_log(LOG_WARNING, "in %d %dx%d out %d %dx%d\n",
665                         in->pix_fmt, in->w, in->h, out->pix_fmt, eff_w, eff_h);
666         sws_scale(convert_ctx,
667                 p_in->data, p_in->linesize,
668                 in->w, in->h, /* src slice */
669                 p_out->data, p_out->linesize);
670
671         sws_freeContext(convert_ctx);
672     }
673 #endif /* XXX replacement */
674 }
675
676 struct video_desc *get_video_desc(struct ast_channel *c);
677
678 /*
679  * This function is called (by asterisk) for each video packet
680  * coming from the network (the 'in' path) that needs to be processed.
681  * We need to reconstruct the entire video frame before we can decode it.
682  * After a video packet is received we have to:
683  * - extract the bitstream with pre_process_data()
684  * - append the bitstream to a buffer
685  * - if the fragment is the last (RTP Marker) we decode it with decode_video()
686  * - after the decoding is completed we display the decoded frame with show_frame()
687  */
688 int console_write_video(struct ast_channel *chan, struct ast_frame *f);
689 int console_write_video(struct ast_channel *chan, struct ast_frame *f)
690 {
691         struct video_desc *env = get_video_desc(chan);
692         struct video_dec_desc *v = env->in;
693
694         if (!env->gui)  /* no gui, no rendering */
695                 return 0;
696         if (v == NULL)
697                 env->in = v = dec_init(f->subclass & ~1);
698         if (v == NULL) {
699                 /* This is not fatal, but we won't have incoming video */
700                 ast_log(LOG_WARNING, "Cannot initialize input decoder\n");
701                 return 0;
702         }
703
704         if (v->dec_in_cur == NULL)      /* no buffer for incoming frames, drop */
705                 return 0;
706 #if defined(DROP_PACKETS) && DROP_PACKETS > 0
707         /* Simulate lost packets */
708         if ((random() % 10000) <= 100*DROP_PACKETS) {
709                 ast_log(LOG_NOTICE, "Packet lost [%d]\n", f->seqno);
710                 return 0;
711         }
712 #endif
713         if (v->discard) {
714                 /*
715                  * In discard mode, drop packets until we find one with
716                  * the RTP marker set (which is the end of frame).
717                  * Note that the RTP marker flag is sent as the LSB of the
718                  * subclass, which is a  bitmask of formats. The low bit is
719                  * normally used for audio so there is no interference.
720                  */
721                 if (f->subclass & 0x01) {
722                         v->dec_in_cur->used = 0;
723                         v->dec_in_cur->ebit = 0;
724                         v->next_seq = f->seqno + 1;     /* wrap at 16 bit */
725                         v->discard = 0;
726                         ast_log(LOG_WARNING, "out of discard mode, frame %d\n", f->seqno);
727                 }
728                 return 0;
729         }
730
731         /*
732          * Only in-order fragments will be accepted. Remember seqno
733          * has 16 bit so there is wraparound. Also, ideally we could
734          * accept a bit of reordering, but at the moment we don't.
735          */
736         if (v->next_seq != f->seqno) {
737                 ast_log(LOG_WARNING, "discarding frame out of order, %d %d\n",
738                         v->next_seq, f->seqno);
739                 v->discard = 1;
740                 return 0;
741         }
742         v->next_seq++;
743
744         if (f->data.ptr == NULL || f->datalen < 2) {
745                 ast_log(LOG_WARNING, "empty video frame, discard\n");
746                 return 0;
747         }
748         if (v->d_callbacks->dec_decap(v->dec_in_cur, f->data.ptr, f->datalen)) {
749                 ast_log(LOG_WARNING, "error in dec_decap, enter discard\n");
750                 v->discard = 1;
751         }
752         if (f->subclass & 0x01) {       // RTP Marker
753                 /* prepare to decode: advance the buffer so the video thread knows. */
754                 struct fbuf_t *tmp = v->dec_in_cur;     /* store current pointer */
755                 ast_mutex_lock(&env->dec_lock);
756                 if (++v->dec_in_cur == &v->dec_in[N_DEC_IN])    /* advance to next, circular */
757                         v->dec_in_cur = &v->dec_in[0];
758                 if (v->dec_in_dpy == NULL) {    /* were not displaying anything, so set it */
759                         v->dec_in_dpy = tmp;
760                 } else if (v->dec_in_dpy == v->dec_in_cur) { /* current slot is busy */
761                         v->dec_in_cur = NULL;
762                 }
763                 ast_mutex_unlock(&env->dec_lock);
764         }
765         return 0;
766 }
767
768
769 /*! \brief refreshes the buffers of all the device by calling the
770  * grabber_read on each device in the device table.
771  * it encodes the primary source buffer, if the picture in picture mode is
772  * enabled it encodes (in the buffer to split) the secondary source buffer too.
773  * The encoded buffer is splitted to build the local and the remote view.
774  * Return a list of ast_frame representing the video fragments.
775  * The head pointer is returned by the function, the tail pointer
776  * is returned as an argument.
777  *
778  * \param env = video environment descriptor
779  * \param tail = tail ponter (pratically a return value)
780  */
781 static struct ast_frame *get_video_frames(struct video_desc *env, struct ast_frame **tail)
782 {
783         struct video_out_desc *v = &env->out;
784         struct ast_frame *dummy;
785         struct fbuf_t *loc_src_primary = NULL, *p_read;
786         int i;
787         /* if no device was found in the config file */
788         if (!env->out.device_num)
789                 return NULL;
790         /* every time this function is called we refresh the buffers of every device,
791         updating the private device buffer in the device table */
792         for (i = 0; i < env->out.device_num; i++) {
793                 p_read = grabber_read(&env->out.devices[i], env->out.fps);
794                 /* it is used only if different from NULL, we mantain last good buffer otherwise */
795                 if (p_read)
796                         env->out.devices[i].dev_buf = p_read;
797         }
798         /* select the primary device buffer as the one to encode */
799         loc_src_primary = env->out.devices[env->out.device_primary].dev_buf;
800         /* loc_src_primary can be NULL if the device has been turned off during
801         execution of it is read too early */
802         if (loc_src_primary) {
803                 /* Scale the video for the encoder, then use it for local rendering
804                 so we will see the same as the remote party */
805                 my_scale(loc_src_primary, NULL, &env->enc_in, NULL);
806         }
807         if (env->out.picture_in_picture) { /* the picture in picture mode is enabled */
808                 struct fbuf_t *loc_src_secondary;
809                 /* reads from the secondary source */
810                 loc_src_secondary = env->out.devices[env->out.device_secondary].dev_buf;
811                 if (loc_src_secondary) {
812                         env->enc_in.win_x = env->out.pip_x;
813                         env->enc_in.win_y = env->out.pip_y;
814                         env->enc_in.win_w = env->enc_in.w/3;
815                         env->enc_in.win_h = env->enc_in.h/3;
816                         /* scales to the correct geometry and inserts in
817                         the enc_in buffer the picture in picture */
818                         my_scale(loc_src_secondary, NULL, &env->enc_in, NULL);
819                         /* returns to normal parameters (not picture in picture) */
820                         env->enc_in.win_x = 0;
821                         env->enc_in.win_y = 0;
822                         env->enc_in.win_w = 0;
823                         env->enc_in.win_h = 0;
824                 }
825                 else {
826                         /* loc_src_secondary can be NULL if the device has been turned off during
827                         execution of it is read too early */
828                         env->out.picture_in_picture = 0; /* disable picture in picture */
829                 }
830         }
831         show_frame(env, WIN_LOCAL); /* local rendering */
832         for (i = 0; i < env->out.device_num; i++) 
833                 show_frame(env, i+WIN_SRC1); /* rendering of every source device in thumbnails */
834         if (tail == NULL)
835                 tail = &dummy;
836         *tail = NULL;
837         /* if no reason for encoding, do not encode */
838         if (!env->owner || !loc_src_primary || !v->sendvideo)
839                 return NULL;
840         if (v->enc_out.data == NULL) {
841                 static volatile int a = 0;
842                 if (a++ < 2)
843                         ast_log(LOG_WARNING, "fail, no encoder output buffer\n");
844                 return NULL;
845         }
846         v->enc->enc_run(v);
847         return v->enc->enc_encap(&v->enc_out, v->mtu, tail);
848 }
849
850 /*
851  * Helper thread to periodically poll the video sources and enqueue the
852  * generated frames directed to the remote party to the channel's queue.
853  * Using a separate thread also helps because the encoding can be
854  * computationally expensive so we don't want to starve the main thread.
855  */
856 static void *video_thread(void *arg)
857 {
858         struct video_desc *env = arg;
859         int count = 0;
860         char save_display[128] = "";
861         int i; /* integer variable used as iterator */
862
863         /* if sdl_videodriver is set, override the environment. Also,
864          * if it contains 'console' override DISPLAY around the call to SDL_Init
865          * so we use the console as opposed to the x11 version of aalib
866          */
867         if (!ast_strlen_zero(env->sdl_videodriver)) { /* override */
868                 const char *s = getenv("DISPLAY");
869                 setenv("SDL_VIDEODRIVER", env->sdl_videodriver, 1);
870                 if (s && !strcasecmp(env->sdl_videodriver, "aalib-console")) {
871                         ast_copy_string(save_display, s, sizeof(save_display));
872                         unsetenv("DISPLAY");
873                 }
874         }
875         sdl_setup(env);
876         if (!ast_strlen_zero(save_display))
877                 setenv("DISPLAY", save_display, 1);
878
879         ast_mutex_init(&env->dec_lock); /* used to sync decoder and renderer */
880
881         if (grabber_open(&env->out)) {
882                 ast_log(LOG_WARNING, "cannot open local video source\n");
883         } 
884
885         if (env->out.device_num)
886                 env->out.devices[env->out.device_primary].status_index |= IS_PRIMARY | IS_SECONDARY;
887         
888         /* even if no device is connected, we must call video_out_init,
889          * as some of the data structures it initializes are
890          * used in get_video_frames()
891          */
892         video_out_init(env);
893
894         /* Writes intial status of the sources. */
895         if (env->gui) {
896             for (i = 0; i < env->out.device_num; i++) {
897                 print_message(env->gui->thumb_bd_array[i].board,
898                  src_msgs[env->out.devices[i].status_index]);
899             }
900         }
901
902         for (;;) {
903                 struct timeval t = { 0, 50000 };        /* XXX 20 times/sec */
904                 struct ast_frame *p, *f;
905                 struct ast_channel *chan;
906                 int fd;
907                 char *caption = NULL, buf[160];
908
909                 /* determine if video format changed */
910                 if (count++ % 10 == 0) {
911                         if (env->out.sendvideo && env->out.devices)
912                             sprintf(buf, "%s %s %dx%d @@ %dfps %dkbps",
913                                 env->out.devices[env->out.device_primary].name, env->codec_name,
914                                 env->enc_in.w, env->enc_in.h,
915                                 env->out.fps, env->out.bitrate/1000);
916                         else
917                             sprintf(buf, "hold");
918                         caption = buf;
919                 }
920
921                 /* manage keypad events */
922                 /* XXX here we should always check for events,
923                 * otherwise the drag will not work */ 
924                 if (env->gui)
925                         eventhandler(env, caption);
926  
927                 /* sleep for a while */
928                 ast_select(0, NULL, NULL, NULL, &t);
929
930             if (env->in) {
931                 struct video_dec_desc *v = env->in;
932                 
933                 /*
934                  * While there is something to display, call the decoder and free
935                  * the buffer, possibly enabling the receiver to store new data.
936                  */
937                 while (v->dec_in_dpy) {
938                         struct fbuf_t *tmp = v->dec_in_dpy;     /* store current pointer */
939
940                         /* decode the frame, but show it only if not frozen */
941                         if (v->d_callbacks->dec_run(v, tmp) && !env->frame_freeze)
942                                 show_frame(env, WIN_REMOTE);
943                         tmp->used = 0;  /* mark buffer as free */
944                         tmp->ebit = 0;
945                         ast_mutex_lock(&env->dec_lock);
946                         if (++v->dec_in_dpy == &v->dec_in[N_DEC_IN])    /* advance to next, circular */
947                                 v->dec_in_dpy = &v->dec_in[0];
948
949                         if (v->dec_in_cur == NULL)      /* receiver was idle, enable it... */
950                                 v->dec_in_cur = tmp;    /* using the slot just freed */
951                         else if (v->dec_in_dpy == v->dec_in_cur) /* this was the last slot */
952                                 v->dec_in_dpy = NULL;   /* nothing more to display */
953                         ast_mutex_unlock(&env->dec_lock);
954                 }
955             }
956
957                 if (env->shutdown)
958                         break;
959                 f = get_video_frames(env, &p);  /* read and display */
960                 if (!f)
961                         continue;
962                 chan = env->owner;
963                 if (chan == NULL) {
964                         /* drop the chain of frames, nobody uses them */
965                         while (f) {
966                                 struct ast_frame *g = AST_LIST_NEXT(f, frame_list);
967                                 ast_frfree(f);
968                                 f = g;
969                         }
970                         continue;
971                 }
972                 fd = chan->alertpipe[1];
973                 ast_channel_lock(chan);
974
975                 /* AST_LIST_INSERT_TAIL is only good for one frame, cannot use here */
976                 if (chan->readq.first == NULL) {
977                         chan->readq.first = f;
978                 } else {
979                         chan->readq.last->frame_list.next = f;
980                 }
981                 chan->readq.last = p;
982                 /*
983                  * more or less same as ast_queue_frame, but extra
984                  * write on the alertpipe to signal frames.
985                  */
986                 if (fd > -1) {
987                         int blah = 1, l = sizeof(blah);
988                         for (p = f; p; p = AST_LIST_NEXT(p, frame_list)) {
989                                 if (write(fd, &blah, l) != l)
990                                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d: %s!\n",
991                                             chan->name, f->frametype, f->subclass, strerror(errno));
992                         }
993                 }
994                 ast_channel_unlock(chan);
995         }
996         /* thread terminating, here could call the uninit */
997         /* uninitialize the local and remote video environments */
998         env->in = dec_uninit(env->in);
999         video_out_uninit(env);
1000
1001         if (env->gui)
1002                 env->gui = cleanup_sdl(env->gui, env->out.device_num);
1003         ast_mutex_destroy(&env->dec_lock);
1004         env->shutdown = 0;
1005         return NULL;
1006 }
1007
1008 static void copy_geometry(struct fbuf_t *src, struct fbuf_t *dst)
1009 {
1010         if (dst->w == 0)
1011                 dst->w = src->w;
1012         if (dst->h == 0)
1013                 dst->h = src->h;
1014 }
1015
1016 /*! initialize the video environment.
1017  * Apart from the formats (constant) used by sdl and the codec,
1018  * we use enc_in as the basic geometry.
1019  */
1020 static void init_env(struct video_desc *env)
1021 {
1022         struct fbuf_t *c = &(env->out.loc_src_geometry);                /* local source */
1023         struct fbuf_t *ei = &(env->enc_in);             /* encoder input */
1024         struct fbuf_t *ld = &(env->loc_dpy);    /* local display */
1025         struct fbuf_t *rd = &(env->rem_dpy);            /* remote display */
1026         int i; /* integer working as iterator */
1027
1028         c->pix_fmt = PIX_FMT_YUV420P;   /* default - camera format */
1029         ei->pix_fmt = PIX_FMT_YUV420P;  /* encoder input */
1030         if (ei->w == 0 || ei->h == 0) {
1031                 ei->w = 352;
1032                 ei->h = 288;
1033         }
1034         ld->pix_fmt = rd->pix_fmt = PIX_FMT_YUV420P; /* sdl format */
1035         /* inherit defaults */
1036         copy_geometry(ei, c);   /* camera inherits from encoder input */
1037         copy_geometry(ei, rd);  /* remote display inherits from encoder input */
1038         copy_geometry(rd, ld);  /* local display inherits from remote display */
1039
1040         /* fix the size of buffers for small windows */
1041         for (i = 0; i < env->out.device_num; i++) {
1042                 env->src_dpy[i].pix_fmt = PIX_FMT_YUV420P;
1043                 env->src_dpy[i].w = SRC_WIN_W;
1044                 env->src_dpy[i].h = SRC_WIN_H;
1045         }
1046         /* now we set the default coordinates for the picture in picture
1047         frames inside the env_in buffers, those can be changed by dragging the
1048         picture in picture with left click */
1049         env->out.pip_x = ei->w - ei->w/3;
1050         env->out.pip_y = ei->h - ei->h/3;
1051 }
1052
1053 /*!
1054  * The first call to the video code, called by oss_new() or similar.
1055  * Here we initialize the various components we use, namely SDL for display,
1056  * ffmpeg for encoding/decoding, and a local video source.
1057  * We do our best to progress even if some of the components are not
1058  * available.
1059  */
1060 void console_video_start(struct video_desc *env, struct ast_channel *owner)
1061 {
1062         ast_log(LOG_WARNING, "env %p chan %p\n", env, owner);
1063         if (env == NULL)        /* video not initialized */
1064                 return;
1065         env->owner = owner;     /* work even if no owner is specified */
1066         if (env->vthread)
1067                 return;         /* already initialized, nothing to do */
1068         init_env(env);
1069         env->out.enc = map_config_video_format(env->codec_name);
1070
1071         ast_log(LOG_WARNING, "start video out %s %dx%d\n",
1072                 env->codec_name, env->enc_in.w,  env->enc_in.h);
1073         /*
1074          * Register all codecs supported by the ffmpeg library.
1075          * We only need to do it once, but probably doesn't
1076          * harm to do it multiple times.
1077          */
1078         avcodec_init();
1079         avcodec_register_all();
1080         av_log_set_level(AV_LOG_ERROR); /* only report errors */
1081
1082         if (env->out.fps == 0) {
1083                 env->out.fps = 15;
1084                 ast_log(LOG_WARNING, "fps unset, forcing to %d\n", env->out.fps);
1085         }
1086         if (env->out.bitrate == 0) {
1087                 env->out.bitrate = 65000;
1088                 ast_log(LOG_WARNING, "bitrate unset, forcing to %d\n", env->out.bitrate);
1089         }
1090         /* XXX below probably can use ast_pthread_create_detace\hed() */
1091         ast_pthread_create_background(&env->vthread, NULL, video_thread, env);
1092         /* detach the thread to make sure memory is freed on termination */
1093         pthread_detach(env->vthread);
1094 }
1095
1096 /*
1097  * Parse a geometry string, accepting also common names for the formats.
1098  * Trick: if we have a leading > or < and a numeric geometry,
1099  * return the larger or smaller one.
1100  * E.g. <352x288 gives the smaller one, 320x240
1101  */
1102 static int video_geom(struct fbuf_t *b, const char *s)
1103 {
1104         int w = 0, h = 0;
1105
1106         static struct {
1107                 const char *s; int w; int h;
1108         } *fp, formats[] = {
1109                 {"16cif",       1408, 1152 },
1110                 {"xga",         1024, 768 },
1111                 {"4cif",        704, 576 },
1112                 {"vga",         640, 480 },
1113                 {"cif",         352, 288 },
1114                 {"qvga",        320, 240 },
1115                 {"qcif",        176, 144 },
1116                 {"sqcif",       128, 96 },
1117                 {NULL,          0, 0 },
1118         };
1119         if (*s == '<' || *s == '>')
1120                 sscanf(s+1,"%dx%d", &w, &h);
1121         for (fp = formats; fp->s; fp++) {
1122                 if (*s == '>') {        /* look for a larger one */
1123                         if (fp->w <= w) {
1124                                 if (fp > formats)
1125                                         fp--; /* back one step if possible */
1126                                 break;
1127                         }
1128                 } else if (*s == '<') { /* look for a smaller one */
1129                         if (fp->w < w)
1130                                 break;
1131                 } else if (!strcasecmp(s, fp->s)) { /* look for a string */
1132                         break;
1133                 }
1134         }
1135         if (*s == '<' && fp->s == NULL) /* smallest */
1136                 fp--;
1137         if (fp->s) {
1138                 b->w = fp->w;
1139                 b->h = fp->h;
1140         } else if (sscanf(s, "%dx%d", &b->w, &b->h) != 2) {
1141                 ast_log(LOG_WARNING, "Invalid video_size %s, using 352x288\n", s);
1142                 b->w = 352;
1143                 b->h = 288;
1144         }
1145         return 0;
1146 }
1147
1148
1149 /*! \brief add an entry to the video_device table,
1150  * ignoring duplicate names.
1151  * The table is a static array of 9 elements.
1152  * The last_frame field of each entry of the table is initialized to
1153  * the current time (we need a value inside this field, on stop of the
1154  * GUI the last_frame value is not changed, to avoid checking if it is 0 we
1155  * set the initial value on current time) XXX
1156  *
1157  * PARAMETERS:
1158  * \param devices_p = pointer to the table of devices
1159  * \param device_num_p = pointer to the number of devices
1160  * \param s = name of the new device to insert
1161  *
1162  * returns 0 on success, 1 on error
1163  */
1164 static int device_table_fill(struct video_device *devices, int *device_num_p, const char *s)
1165 {
1166         int i;
1167         struct video_device *p;
1168
1169         /* with the current implementation, we support a maximum of 9 devices.*/
1170         if (*device_num_p >= 9)
1171                 return 0; /* more devices will be ignored */
1172         /* ignore duplicate names */
1173         for (i = 0; i < *device_num_p; i++) {
1174                 if (!strcmp(devices[i].name, s))
1175                         return 0;
1176         }
1177         /* inserts the new video device */
1178         p = &devices[*device_num_p];
1179         /* XXX the string is allocated but NEVER deallocated,
1180         the good time to do that is when the module is unloaded, now we skip the problem */
1181         p->name = ast_strdup(s);                /* copy the name */
1182         /* other fields initially NULL */
1183         p->grabber = NULL;
1184         p->grabber_data = NULL;
1185         p->dev_buf = NULL;
1186         p->last_frame = ast_tvnow();
1187         p->status_index = 0;
1188         (*device_num_p)++;                      /* one device added */
1189         return 0;
1190 }
1191
1192 /* extend ast_cli with video commands. Called by console_video_config */
1193 int console_video_cli(struct video_desc *env, const char *var, int fd)
1194 {
1195         if (env == NULL)
1196                 return 1;       /* unrecognised */
1197
1198         if (!strcasecmp(var, "videodevice")) {
1199                 ast_cli(fd, "videodevice is [%s]\n", env->out.devices[env->out.device_primary].name);
1200         } else if (!strcasecmp(var, "videocodec")) {
1201                 ast_cli(fd, "videocodec is [%s]\n", env->codec_name);
1202         } else if (!strcasecmp(var, "sendvideo")) {
1203                 ast_cli(fd, "sendvideo is [%s]\n", env->out.sendvideo ? "on" : "off");
1204         } else if (!strcasecmp(var, "video_size")) {
1205                 int in_w = 0, in_h = 0;
1206                 if (env->in) {
1207                         in_w = env->in->dec_out.w;
1208                         in_h = env->in->dec_out.h;
1209                 }
1210                 ast_cli(fd, "sizes: video %dx%d camera %dx%d local %dx%d remote %dx%d in %dx%d\n",
1211                         env->enc_in.w, env->enc_in.h,
1212                         env->out.loc_src_geometry.w, env->out.loc_src_geometry.h,
1213                         env->loc_dpy.w, env->loc_dpy.h,
1214                         env->rem_dpy.w, env->rem_dpy.h,
1215                         in_w, in_h);
1216         } else if (!strcasecmp(var, "bitrate")) {
1217                 ast_cli(fd, "bitrate is [%d]\n", env->out.bitrate);
1218         } else if (!strcasecmp(var, "qmin")) {
1219                 ast_cli(fd, "qmin is [%d]\n", env->out.qmin);
1220         } else if (!strcasecmp(var, "fps")) {
1221                 ast_cli(fd, "fps is [%d]\n", env->out.fps);
1222         } else if (!strcasecmp(var, "startgui")) {
1223                 env->stayopen = 1;
1224                 console_video_start(env, NULL);
1225         } else if (!strcasecmp(var, "stopgui") && env->stayopen != 0) {
1226                 env->stayopen = 0;
1227                 if (env->gui && env->owner)
1228                         ast_cli_command(-1, "console hangup");
1229                 else /* not in a call */
1230                         console_video_uninit(env);
1231         } else {
1232                 return 1;       /* unrecognised */
1233         }
1234         return 0;       /* recognised */
1235 }
1236
1237 /*! parse config command for video support. */
1238 int console_video_config(struct video_desc **penv,
1239         const char *var, const char *val)
1240 {
1241         struct video_desc *env;
1242
1243         if (penv == NULL) {
1244                 ast_log(LOG_WARNING, "bad argument penv=NULL\n");
1245                 return 1;       /* error */
1246         }
1247         /* allocate the video descriptor first time we get here */
1248         env = *penv;
1249         if (env == NULL) {
1250                 env = *penv = ast_calloc(1, sizeof(struct video_desc));
1251                 if (env == NULL) {
1252                         ast_log(LOG_WARNING, "fail to allocate video_desc\n");
1253                         return 1;       /* error */
1254                 
1255                 }
1256                 /* set default values - 0's are already there */
1257                 env->out.device_primary = 0;
1258                 env->out.device_secondary = 0;
1259                 env->out.fps = 5;
1260                 env->out.bitrate = 65000;
1261                 env->out.sendvideo = 1;
1262                 env->out.qmin = 3;
1263                 env->out.device_num = 0;
1264         }
1265         CV_START(var, val);
1266         CV_F("videodevice", device_table_fill(env->out.devices, &env->out.device_num, val));
1267         CV_BOOL("sendvideo", env->out.sendvideo);
1268         CV_F("video_size", video_geom(&env->enc_in, val));
1269         CV_F("camera_size", video_geom(&env->out.loc_src_geometry, val));
1270         CV_F("local_size", video_geom(&env->loc_dpy, val));
1271         CV_F("remote_size", video_geom(&env->rem_dpy, val));
1272         CV_STR("keypad", env->keypad_file);
1273         CV_F("region", keypad_cfg_read(env->gui, val));
1274         CV_UINT("startgui", env->stayopen);     /* enable gui at startup */
1275         CV_STR("keypad_font", env->keypad_font);
1276         CV_STR("sdl_videodriver", env->sdl_videodriver);
1277         CV_UINT("fps", env->out.fps);
1278         CV_UINT("bitrate", env->out.bitrate);
1279         CV_UINT("qmin", env->out.qmin);
1280         CV_STR("videocodec", env->codec_name);
1281         return 1;       /* nothing found */
1282
1283         CV_END;         /* the 'nothing found' case */
1284         return 0;               /* found something */
1285 }
1286
1287 #endif  /* video support */