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