8a52ae0487e55f13037d0d64f191d8f69517092d
[libam7xxx.git] / examples / am7xxx-play.c
1 /*
2  * am7xxx-play - play stuff on an am7xxx device (e.g. Acer C110, PicoPix 1020)
3  *
4  * Copyright (C) 2012  Antonio Ospite <ospite@studenti.unina.it>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * @example examples/am7xxx-play.c
22  * am7xxx-play uses libavdevice, libavformat, libavcodec and libswscale to
23  * decode the input, encode it to jpeg and display it with libam7xxx.
24  */
25
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <string.h>
29 #include <signal.h>
30 #include <getopt.h>
31
32 #include <libavdevice/avdevice.h>
33 #include <libavformat/avformat.h>
34 #include <libswscale/swscale.h>
35
36 #include <am7xxx.h>
37
38 static unsigned int run = 1;
39
40 struct video_input_ctx {
41         AVFormatContext *format_ctx;
42         AVCodecContext  *codec_ctx;
43         int video_stream_index;
44 };
45
46 static int video_input_init(struct video_input_ctx *input_ctx,
47                             const char *input_format_string,
48                             const char *input_path,
49                             AVDictionary **input_options)
50 {
51         AVInputFormat *input_format = NULL;
52         AVFormatContext *input_format_ctx;
53         AVCodecContext *input_codec_ctx;
54         AVCodec *input_codec;
55         int video_index;
56         unsigned int i;
57         int ret;
58
59         avdevice_register_all();
60         avcodec_register_all();
61         av_register_all();
62
63         if (input_format_string) {
64                 /* find the desired input format */
65                 input_format = av_find_input_format(input_format_string);
66                 if (input_format == NULL) {
67                         fprintf(stderr, "cannot find input format\n");
68                         ret = -ENODEV;
69                         goto out;
70                 }
71         }
72
73         if (input_path == NULL) {
74                 fprintf(stderr, "input_path must not be NULL!\n");
75                 ret = -EINVAL;
76                 goto out;
77         }
78
79         /* open the input format/device */
80         input_format_ctx = NULL;
81         ret = avformat_open_input(&input_format_ctx,
82                                   input_path,
83                                   input_format,
84                                   input_options);
85         if (ret < 0) {
86                 fprintf(stderr, "cannot open input format/device\n");
87                 goto out;
88         }
89
90         /* get information on the input stream (e.g. format, bitrate, framerate) */
91         ret = avformat_find_stream_info(input_format_ctx, NULL);
92         if (ret < 0) {
93                 fprintf(stderr, "cannot get information on the stream\n");
94                 goto cleanup;
95         }
96
97         /* dump what was found */
98         av_dump_format(input_format_ctx, 0, input_path, 0);
99
100         /* look for the first video_stream */
101         video_index = -1;
102         for (i = 0; i < input_format_ctx->nb_streams; i++)
103                 if (input_format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
104                         video_index = i;
105                         break;
106                 }
107         if (video_index == -1) {
108                 fprintf(stderr, "cannot find any video streams\n");
109                 ret = -ENOTSUP;
110                 goto cleanup;
111         }
112
113         /* get a pointer to the codec context for the video stream */
114         input_codec_ctx = input_format_ctx->streams[video_index]->codec;
115         if (input_codec_ctx == NULL) {
116                 fprintf(stderr, "input codec context is not valid\n");
117                 ret = -ENOTSUP;
118                 goto cleanup;
119         }
120
121         /* find the decoder for the video stream */
122         input_codec = avcodec_find_decoder(input_codec_ctx->codec_id);
123         if (input_codec == NULL) {
124                 fprintf(stderr, "input_codec is NULL!\n");
125                 ret = -ENOTSUP;
126                 goto cleanup;
127         }
128
129         /* open the decoder */
130         ret = avcodec_open2(input_codec_ctx, input_codec, NULL);
131         if (ret < 0) {
132                 fprintf(stderr, "cannot open input codec\n");
133                 ret = -ENOTSUP;
134                 goto cleanup;
135         }
136
137         input_ctx->format_ctx = input_format_ctx;
138         input_ctx->codec_ctx = input_codec_ctx;
139         input_ctx->video_stream_index = video_index;
140
141         ret = 0;
142         goto out;
143
144 cleanup:
145         avformat_close_input(&input_format_ctx);
146 out:
147         av_dict_free(input_options);
148         *input_options = NULL;
149         return ret;
150 }
151
152
153 struct video_output_ctx {
154         AVCodecContext  *codec_ctx;
155         int raw_output;
156 };
157
158 static int video_output_init(struct video_output_ctx *output_ctx,
159                              struct video_input_ctx *input_ctx,
160                              unsigned int upscale,
161                              unsigned int quality,
162                              am7xxx_image_format image_format,
163                              am7xxx_device *dev)
164 {
165         AVCodecContext *output_codec_ctx;
166         AVCodec *output_codec;
167         unsigned int new_output_width;
168         unsigned int new_output_height;
169         int ret;
170
171         if (input_ctx == NULL) {
172                 fprintf(stderr, "input_ctx must not be NULL!\n");
173                 ret = -EINVAL;
174                 goto out;
175         }
176
177         /* create the encoder context */
178         output_codec_ctx = avcodec_alloc_context3(NULL);
179         if (output_codec_ctx == NULL) {
180                 fprintf(stderr, "cannot allocate output codec context!\n");
181                 ret = -ENOMEM;
182                 goto out;
183         }
184
185         /* Calculate the new output dimension so the original picture is shown
186          * in its entirety */
187         ret = am7xxx_calc_scaled_image_dimensions(dev,
188                                                   upscale,
189                                                   (input_ctx->codec_ctx)->width,
190                                                   (input_ctx->codec_ctx)->height,
191                                                   &new_output_width,
192                                                   &new_output_height);
193         if (ret < 0) {
194                 fprintf(stderr, "cannot calculate output dimension\n");
195                 goto cleanup;
196         }
197
198         /* put sample parameters */
199         output_codec_ctx->bit_rate   = (input_ctx->codec_ctx)->bit_rate;
200         output_codec_ctx->width      = new_output_width;
201         output_codec_ctx->height     = new_output_height;
202         output_codec_ctx->time_base.num  =
203                 (input_ctx->format_ctx)->streams[input_ctx->video_stream_index]->time_base.num;
204         output_codec_ctx->time_base.den  =
205                 (input_ctx->format_ctx)->streams[input_ctx->video_stream_index]->time_base.den;
206
207         /* When the raw format is requested we don't actually need to setup
208          * and open a decoder
209          */
210         if (image_format == AM7XXX_IMAGE_FORMAT_NV12) {
211                 fprintf(stdout, "using raw output format\n");
212                 output_codec_ctx->pix_fmt    = PIX_FMT_NV12;
213                 output_ctx->codec_ctx = output_codec_ctx;
214                 output_ctx->raw_output = 1;
215                 ret = 0;
216                 goto out;
217         }
218
219         output_codec_ctx->pix_fmt    = PIX_FMT_YUVJ420P;
220         output_codec_ctx->codec_id   = CODEC_ID_MJPEG;
221         output_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
222
223         /* Set quality and other VBR settings */
224
225         /* @note: 'quality' is expected to be between 1 and 100, but a value
226          * between 0 to 99 has to be passed when calculating qmin and qmax.
227          * This way qmin and qmax will cover the range 1-FF_QUALITY_SCALE, and
228          * in particular they won't be 0, this is needed because they are used
229          * as divisor somewhere in the encoding process */
230         output_codec_ctx->qmin       = output_codec_ctx->qmax = ((100 - (quality - 1)) * FF_QUALITY_SCALE) / 100;
231         output_codec_ctx->mb_lmin    = output_codec_ctx->lmin = output_codec_ctx->qmin * FF_QP2LAMBDA;
232         output_codec_ctx->mb_lmax    = output_codec_ctx->lmax = output_codec_ctx->qmax * FF_QP2LAMBDA;
233         output_codec_ctx->flags      |= CODEC_FLAG_QSCALE;
234         output_codec_ctx->global_quality = output_codec_ctx->qmin * FF_QP2LAMBDA;
235
236         /* find the encoder */
237         output_codec = avcodec_find_encoder(output_codec_ctx->codec_id);
238         if (output_codec == NULL) {
239                 fprintf(stderr, "cannot find output codec!\n");
240                 ret = -ENOTSUP;
241                 goto cleanup;
242         }
243
244         /* open the codec */
245         ret = avcodec_open2(output_codec_ctx, output_codec, NULL);
246         if (ret < 0) {
247                 fprintf(stderr, "could not open output codec!\n");
248                 goto cleanup;
249         }
250
251         output_ctx->codec_ctx = output_codec_ctx;
252         output_ctx->raw_output = 0;
253
254         ret = 0;
255         goto out;
256
257 cleanup:
258         avcodec_close(output_codec_ctx);
259         av_free(output_codec_ctx);
260 out:
261         return ret;
262 }
263
264
265 static int am7xxx_play(const char *input_format_string,
266                        AVDictionary **input_options,
267                        const char *input_path,
268                        unsigned int rescale_method,
269                        unsigned int upscale,
270                        unsigned int quality,
271                        am7xxx_image_format image_format,
272                        am7xxx_device *dev)
273 {
274         struct video_input_ctx input_ctx;
275         struct video_output_ctx output_ctx;
276         AVFrame *picture_raw;
277         AVFrame *picture_scaled;
278         int out_buf_size;
279         uint8_t *out_buf;
280         int out_picture_size;
281         struct SwsContext *sw_scale_ctx;
282         AVPacket packet;
283         int got_picture;
284         int ret = 0;
285
286         ret = video_input_init(&input_ctx, input_format_string, input_path, input_options);
287         if (ret < 0) {
288                 fprintf(stderr, "cannot initialize input\n");
289                 goto out;
290         }
291
292         ret = video_output_init(&output_ctx, &input_ctx, upscale, quality, image_format, dev);
293         if (ret < 0) {
294                 fprintf(stderr, "cannot initialize input\n");
295                 goto cleanup_input;
296         }
297
298         /* allocate an input frame */
299         picture_raw = avcodec_alloc_frame();
300         if (picture_raw == NULL) {
301                 fprintf(stderr, "cannot allocate the raw picture frame!\n");
302                 ret = -ENOMEM;
303                 goto cleanup_output;
304         }
305
306         /* allocate output frame */
307         picture_scaled = avcodec_alloc_frame();
308         if (picture_scaled == NULL) {
309                 fprintf(stderr, "cannot allocate the scaled picture!\n");
310                 ret = -ENOMEM;
311                 goto cleanup_picture_raw;
312         }
313
314         /* calculate the bytes needed for the output image and create buffer for the output image */
315         out_buf_size = avpicture_get_size((output_ctx.codec_ctx)->pix_fmt,
316                                           (output_ctx.codec_ctx)->width,
317                                           (output_ctx.codec_ctx)->height);
318         out_buf = av_malloc(out_buf_size * sizeof(uint8_t));
319         if (out_buf == NULL) {
320                 fprintf(stderr, "cannot allocate output data buffer!\n");
321                 ret = -ENOMEM;
322                 goto cleanup_picture_scaled;
323         }
324
325         /* assign appropriate parts of buffer to image planes in picture_scaled */
326         avpicture_fill((AVPicture *)picture_scaled,
327                        out_buf,
328                        (output_ctx.codec_ctx)->pix_fmt,
329                        (output_ctx.codec_ctx)->width,
330                        (output_ctx.codec_ctx)->height);
331
332         sw_scale_ctx = sws_getCachedContext(NULL,
333                                             (input_ctx.codec_ctx)->width,
334                                             (input_ctx.codec_ctx)->height,
335                                             (input_ctx.codec_ctx)->pix_fmt,
336                                             (output_ctx.codec_ctx)->width,
337                                             (output_ctx.codec_ctx)->height,
338                                             (output_ctx.codec_ctx)->pix_fmt,
339                                             rescale_method,
340                                             NULL, NULL, NULL);
341         if (sw_scale_ctx == NULL) {
342                 fprintf(stderr, "cannot set up the rescaling context!\n");
343                 ret = -EINVAL;
344                 goto cleanup_out_buf;
345         }
346
347         while (run) {
348                 /* read packet */
349                 ret = av_read_frame(input_ctx.format_ctx, &packet);
350                 if (ret < 0) {
351                         if (ret == (int)AVERROR_EOF || input_ctx.format_ctx->pb->eof_reached)
352                                 ret = 0;
353                         else
354                                 fprintf(stderr, "av_read_frame failed, EOF?\n");
355                         run = 0;
356                         goto end_while;
357                 }
358
359                 if (packet.stream_index != input_ctx.video_stream_index) {
360                         /* that is more or less a "continue", but there is
361                          * still the packet to free */
362                         goto end_while;
363                 }
364
365                 /* decode */
366                 got_picture = 0;
367                 ret = avcodec_decode_video2(input_ctx.codec_ctx, picture_raw, &got_picture, &packet);
368                 if (ret < 0) {
369                         fprintf(stderr, "cannot decode video\n");
370                         run = 0;
371                         goto end_while;
372                 }
373
374                 /* if we get the complete frame */
375                 if (got_picture) {
376                         /* convert it to YUV */
377                         sws_scale(sw_scale_ctx,
378                                   (const uint8_t * const*)picture_raw->data,
379                                   picture_raw->linesize,
380                                   0,
381                                   (input_ctx.codec_ctx)->height,
382                                   picture_scaled->data,
383                                   picture_scaled->linesize);
384
385                         if (output_ctx.raw_output) {
386                                 out_picture_size = out_buf_size;
387                         } else {
388                                 picture_scaled->quality = (output_ctx.codec_ctx)->global_quality;
389                                 /* TODO: switch to avcodec_encode_video2() eventually */
390                                 out_picture_size = avcodec_encode_video(output_ctx.codec_ctx,
391                                                                         out_buf,
392                                                                         out_buf_size,
393                                                                         picture_scaled);
394                                 if (out_picture_size < 0) {
395                                         fprintf(stderr, "cannot encode video\n");
396                                         ret = out_picture_size;
397                                         run = 0;
398                                         goto end_while;
399                                 }
400                         }
401
402 #ifdef DEBUG
403                         char filename[NAME_MAX];
404                         FILE *file;
405                         if (!output_ctx.raw_output)
406                                 snprintf(filename, NAME_MAX, "out_q%03d.jpg", quality);
407                         else
408                                 snprintf(filename, NAME_MAX, "out.raw");
409                         file = fopen(filename, "wb");
410                         fwrite(out_buf, 1, out_picture_size, file);
411                         fclose(file);
412 #endif
413
414                         ret = am7xxx_send_image(dev,
415                                                 image_format,
416                                                 (output_ctx.codec_ctx)->width,
417                                                 (output_ctx.codec_ctx)->height,
418                                                 out_buf,
419                                                 out_picture_size);
420                         if (ret < 0) {
421                                 perror("am7xxx_send_image");
422                                 run = 0;
423                                 goto end_while;
424                         }
425                 }
426 end_while:
427                 av_free_packet(&packet);
428         }
429
430         sws_freeContext(sw_scale_ctx);
431 cleanup_out_buf:
432         av_free(out_buf);
433 cleanup_picture_scaled:
434         av_free(picture_scaled);
435 cleanup_picture_raw:
436         av_free(picture_raw);
437
438 cleanup_output:
439         /* av_free is needed as well,
440          * see http://libav.org/doxygen/master/avcodec_8h.html#a5d7440cd7ea195bd0b14f21a00ef36dd
441          */
442         avcodec_close(output_ctx.codec_ctx);
443         av_free(output_ctx.codec_ctx);
444
445 cleanup_input:
446         avcodec_close(input_ctx.codec_ctx);
447         avformat_close_input(&(input_ctx.format_ctx));
448
449 out:
450         return ret;
451 }
452
453 #ifdef HAVE_XCB
454 #include <xcb/xcb.h>
455 static int x_get_screen_dimensions(const char *displayname, int *width, int *height)
456 {
457         int i, screen_number;
458         xcb_connection_t *connection;
459         const xcb_setup_t *setup;
460         xcb_screen_iterator_t iter;
461
462         connection = xcb_connect(displayname, &screen_number);
463         if (xcb_connection_has_error(connection)) {
464                 fprintf(stderr, "Cannot open a connection to %s\n", displayname);
465                 return -EINVAL;
466         }
467
468         setup = xcb_get_setup(connection);
469         if (setup == NULL) {
470                 fprintf(stderr, "Cannot get setup for %s\n", displayname);
471                 xcb_disconnect(connection);
472                 return -EINVAL;
473         }
474
475         iter = xcb_setup_roots_iterator(setup);
476         for (i = 0; i < screen_number; ++i) {
477                 xcb_screen_next(&iter);
478         }
479
480         xcb_screen_t *screen = iter.data;
481
482         *width = screen->width_in_pixels;
483         *height = screen->height_in_pixels;
484
485         xcb_disconnect(connection);
486
487         return 0;
488 }
489
490 static char *get_x_screen_size(const char *input_path)
491 {
492         int len;
493         int width;
494         int height;
495         char *screen_size;
496         int ret;
497
498         ret = x_get_screen_dimensions(input_path, &width, &height);
499         if (ret < 0) {
500                 fprintf(stderr, "Cannot get screen dimensions for %s\n", input_path);
501                 return NULL;
502         }
503
504         len = snprintf(NULL, 0, "%dx%d", width, height);
505
506         screen_size = malloc((len + 1) * sizeof(char));
507         if (screen_size == NULL) {
508                 perror("malloc");
509                 return NULL;
510         }
511
512         len = snprintf(screen_size, len + 1, "%dx%d", width, height);
513         if (len < 0) {
514                 free(screen_size);
515                 screen_size = NULL;
516                 return NULL;
517         }
518         return screen_size;
519 }
520 #else
521 static char *get_x_screen_size(const char *input_path)
522 {
523         (void) input_path;
524         fprintf(stderr, "%s: fallback implementation\n", __func__);
525         return strdup("vga");
526 }
527 #endif
528
529 static void unset_run(int signo)
530 {
531         (void) signo;
532         run = 0;
533 }
534
535 static int set_signal_handler(void (*signal_handler)(int))
536 {
537         struct sigaction new_action;
538         struct sigaction old_action;
539         int ret = 0;
540
541         new_action.sa_handler = signal_handler;
542         sigemptyset(&new_action.sa_mask);
543         new_action.sa_flags = 0;
544
545         ret = sigaction(SIGINT, NULL, &old_action);
546         if (ret < 0) {
547                 perror("sigaction on old_action");
548                 goto out;
549         }
550
551         if (old_action.sa_handler != SIG_IGN) {
552                 ret = sigaction(SIGINT, &new_action, NULL);
553                 if (ret < 0) {
554                         perror("sigaction on new_action");
555                         goto out;
556                 }
557         }
558
559 out:
560         return ret;
561 }
562
563 static void usage(char *name)
564 {
565         printf("usage: %s [OPTIONS]\n\n", name);
566         printf("OPTIONS:\n");
567         printf("\t-f <input format>\tthe input device format\n");
568         printf("\t-i <input path>\t\tthe input path\n");
569         printf("\t-o <options>\t\ta comma separated list of input format options\n");
570         printf("\t\t\t\tEXAMPLE:\n");
571         printf("\t\t\t\t\t-o draw_mouse=1,framerate=100,video_size=800x480\n");
572         printf("\t-s <scaling method>\tthe rescaling method (see swscale.h)\n");
573         printf("\t-u \t\t\tupscale the image if smaller than the display dimensions\n");
574         printf("\t-F <format>\t\tthe image format to use (default is JPEG)\n");
575         printf("\t\t\t\tSUPPORTED FORMATS:\n");
576         printf("\t\t\t\t\t1 - JPEG\n");
577         printf("\t\t\t\t\t2 - NV12\n");
578         printf("\t-q <quality>\t\tquality of jpeg sent to the device, between 1 and 100\n");
579         printf("\t-l <log level>\t\tthe verbosity level of libam7xxx output (0-5)\n");
580         printf("\t-p <power level>\tpower level of device, between %x (off) and %x (maximum)\n", AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
581         printf("\t\t\t\tWARNING: Level 2 and greater require the master AND\n\t\t\t\t\t the slave connector to be plugged in.\n");
582         printf("\t-h \t\t\tthis help message\n");
583         printf("\n\nEXAMPLES OF USE:\n");
584         printf("\t%s -f x11grab -i :0.0 -o video_size=800x480\n", name);
585         printf("\t%s -f fbdev -i /dev/fb0\n", name);
586         printf("\t%s -f video4linux2 -i /dev/video0 -o video_size=320x240,frame_rate=100 -u -q 90\n", name);
587         printf("\t%s -i http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v\n", name);
588 }
589
590 int main(int argc, char *argv[])
591 {
592         int ret;
593         int opt;
594         char *subopts;
595         char *subopts_saved;
596         char *subopt;
597         char *input_format_string = NULL;
598         AVDictionary *options = NULL;
599         char *input_path = NULL;
600         unsigned int rescale_method = SWS_BICUBIC;
601         unsigned int upscale = 0;
602         unsigned int quality = 95;
603         int log_level = AM7XXX_LOG_INFO;
604         am7xxx_power_mode power_mode = AM7XXX_POWER_LOW;
605         int format = AM7XXX_IMAGE_FORMAT_JPEG;
606         am7xxx_context *ctx;
607         am7xxx_device *dev;
608
609         while ((opt = getopt(argc, argv, "f:i:o:s:uF:q:l:p:h")) != -1) {
610                 switch (opt) {
611                 case 'f':
612                         input_format_string = strdup(optarg);
613                         break;
614                 case 'i':
615                         input_path = strdup(optarg);
616                         break;
617                 case 'o':
618                         /*
619                          * parse suboptions, the expected format is something
620                          * like:
621                          *   draw_mouse=1,framerate=100,video_size=800x480
622                          */
623                         subopts = subopts_saved = strdup(optarg);
624                         while((subopt = strtok_r(subopts, ",", &subopts))) {
625                                 char *subopt_name = strtok_r(subopt, "=", &subopt);
626                                 char *subopt_value = strtok_r(NULL, "", &subopt);
627                                 if (subopt_value == NULL) {
628                                         fprintf(stderr, "invalid suboption: %s\n", subopt_name);
629                                         continue;
630                                 }
631                                 av_dict_set(&options, subopt_name, subopt_value, 0);
632                         }
633                         free(subopts_saved);
634                         break;
635                 case 's':
636                         rescale_method = atoi(optarg);
637                         switch(rescale_method) {
638                         case SWS_FAST_BILINEAR:
639                         case SWS_BILINEAR:
640                         case SWS_BICUBIC:
641                         case SWS_X:
642                         case SWS_POINT:
643                         case SWS_AREA:
644                         case SWS_BICUBLIN:
645                         case SWS_GAUSS:
646                         case SWS_SINC:
647                         case SWS_LANCZOS:
648                         case SWS_SPLINE:
649                                 break;
650                         default:
651                                 fprintf(stderr, "Unsupported rescale method\n");
652                                 ret = -EINVAL;
653                                 goto out;
654                         }
655                         break;
656                 case 'u':
657                         upscale = 1;
658                         break;
659                 case 'F':
660                         format = atoi(optarg);
661                         switch(format) {
662                         case AM7XXX_IMAGE_FORMAT_JPEG:
663                                 fprintf(stdout, "JPEG format\n");
664                                 break;
665                         case AM7XXX_IMAGE_FORMAT_NV12:
666                                 fprintf(stdout, "NV12 format\n");
667                                 break;
668                         default:
669                                 fprintf(stderr, "Unsupported format\n");
670                                 ret = -EINVAL;
671                                 goto out;
672                         }
673                         break;
674                 case 'q':
675                         quality = atoi(optarg);
676                         if (quality < 1 || quality > 100) {
677                                 fprintf(stderr, "Invalid quality value, must be between 1 and 100\n");
678                                 ret = -EINVAL;
679                                 goto out;
680                         }
681                         break;
682                 case 'l':
683                         log_level = atoi(optarg);
684                         if (log_level < AM7XXX_LOG_FATAL || log_level > AM7XXX_LOG_TRACE) {
685                                 fprintf(stderr, "Unsupported log level, falling back to AM7XXX_LOG_ERROR\n");
686                                 log_level = AM7XXX_LOG_ERROR;
687                         }
688                         break;
689                 case 'p':
690                         power_mode = atoi(optarg);
691                         switch(power_mode) {
692                         case AM7XXX_POWER_OFF:
693                         case AM7XXX_POWER_LOW:
694                         case AM7XXX_POWER_MIDDLE:
695                         case AM7XXX_POWER_HIGH:
696                         case AM7XXX_POWER_TURBO:
697                                 fprintf(stdout, "Power mode: %x\n", power_mode);
698                                 break;
699                         default:
700                                 fprintf(stderr, "Invalid power mode value, must be between %x and %x\n", AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
701                                 ret = -EINVAL;
702                                 goto out;
703                         }
704                         break;
705                 case 'h':
706                         usage(argv[0]);
707                         ret = 0;
708                         goto out;
709                         break;
710                 default: /* '?' */
711                         usage(argv[0]);
712                         ret = -EINVAL;
713                         goto out;
714                 }
715         }
716
717         if (input_path == NULL) {
718                 fprintf(stderr, "The -i option must always be passed\n");
719                 ret = -EINVAL;
720                 goto out;
721         }
722
723         /*
724          * When the input format is 'x11grab' set some useful fallback options
725          * if not supplied by the user, in particular grab full screen
726          */
727         if (input_format_string && strcmp(input_format_string, "x11grab") == 0) {
728                 char *video_size;
729
730                 video_size = get_x_screen_size(input_path);
731
732                 if (!av_dict_get(options, "video_size", NULL, 0))
733                         av_dict_set(&options, "video_size", video_size, 0);
734
735                 if (!av_dict_get(options, "framerate", NULL, 0))
736                         av_dict_set(&options, "framerate", "60", 0);
737
738                 if (!av_dict_get(options, "draw_mouse", NULL, 0))
739                         av_dict_set(&options, "draw_mouse",  "1", 0);
740
741                 free(video_size);
742         }
743
744         ret = set_signal_handler(unset_run);
745         if (ret < 0) {
746                 perror("sigaction");
747                 goto out;
748         }
749
750         ret = am7xxx_init(&ctx);
751         if (ret < 0) {
752                 perror("am7xxx_init");
753                 goto out;
754         }
755
756         am7xxx_set_log_level(ctx, log_level);
757
758         ret = am7xxx_open_device(ctx, &dev, 0);
759         if (ret < 0) {
760                 perror("am7xxx_open_device");
761                 goto cleanup;
762         }
763
764         ret = am7xxx_set_power_mode(dev, power_mode);
765         if (ret < 0) {
766                 perror("am7xxx_set_power_mode");
767                 goto cleanup;
768         }
769
770         ret = am7xxx_play(input_format_string,
771                           &options,
772                           input_path,
773                           rescale_method,
774                           upscale,
775                           quality,
776                           format,
777                           dev);
778         if (ret < 0) {
779                 fprintf(stderr, "am7xxx_play failed\n");
780                 goto cleanup;
781         }
782
783 cleanup:
784         am7xxx_shutdown(ctx);
785 out:
786         av_dict_free(&options);
787         free(input_path);
788         free(input_format_string);
789         return ret;
790 }