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