88d398ae5b6dc11da6d4bede9c79c1b5933a206d
[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_free_context(&output_codec_ctx);
270 out:
271         return ret;
272 }
273
274
275 static int am7xxx_play(const char *input_format_string,
276                        AVDictionary **input_options,
277                        const char *input_path,
278                        unsigned int rescale_method,
279                        unsigned int upscale,
280                        unsigned int quality,
281                        am7xxx_image_format image_format,
282                        am7xxx_device *dev,
283                        int dump_frame)
284 {
285         struct video_input_ctx input_ctx;
286         struct video_output_ctx output_ctx;
287         AVFrame *picture_raw;
288         AVFrame *picture_scaled;
289         int out_buf_size;
290         uint8_t *out_buf;
291         int out_picture_size;
292         uint8_t *out_picture;
293         struct SwsContext *sw_scale_ctx;
294         AVPacket in_packet;
295         AVPacket out_packet;
296         int got_picture;
297         int got_packet;
298         int ret;
299
300         ret = video_input_init(&input_ctx, input_format_string, input_path, input_options);
301         if (ret < 0) {
302                 fprintf(stderr, "cannot initialize input\n");
303                 goto out;
304         }
305
306         ret = video_output_init(&output_ctx, &input_ctx, upscale, quality, image_format, dev);
307         if (ret < 0) {
308                 fprintf(stderr, "cannot initialize input\n");
309                 goto cleanup_input;
310         }
311
312         /* allocate an input frame */
313         picture_raw = av_frame_alloc();
314         if (picture_raw == NULL) {
315                 fprintf(stderr, "cannot allocate the raw picture frame!\n");
316                 ret = -ENOMEM;
317                 goto cleanup_output;
318         }
319
320         /* allocate output frame */
321         picture_scaled = av_frame_alloc();
322         if (picture_scaled == NULL) {
323                 fprintf(stderr, "cannot allocate the scaled picture!\n");
324                 ret = -ENOMEM;
325                 goto cleanup_picture_raw;
326         }
327         picture_scaled->format = (output_ctx.codec_ctx)->pix_fmt;
328         picture_scaled->width = (output_ctx.codec_ctx)->width;
329         picture_scaled->height = (output_ctx.codec_ctx)->height;
330
331         /* calculate the bytes needed for the output image and create buffer for the output image */
332         out_buf_size = av_image_get_buffer_size((output_ctx.codec_ctx)->pix_fmt,
333                                                 (output_ctx.codec_ctx)->width,
334                                                 (output_ctx.codec_ctx)->height,
335                                                 1);
336         out_buf = av_malloc(out_buf_size * sizeof(uint8_t));
337         if (out_buf == NULL) {
338                 fprintf(stderr, "cannot allocate output data buffer!\n");
339                 ret = -ENOMEM;
340                 goto cleanup_picture_scaled;
341         }
342
343         /* assign appropriate parts of buffer to image planes in picture_scaled */
344         av_image_fill_arrays(picture_scaled->data,
345                              picture_scaled->linesize,
346                              out_buf,
347                              (output_ctx.codec_ctx)->pix_fmt,
348                              (output_ctx.codec_ctx)->width,
349                              (output_ctx.codec_ctx)->height,
350                              1);
351
352         sw_scale_ctx = sws_getCachedContext(NULL,
353                                             (input_ctx.codec_ctx)->width,
354                                             (input_ctx.codec_ctx)->height,
355                                             (input_ctx.codec_ctx)->pix_fmt,
356                                             (output_ctx.codec_ctx)->width,
357                                             (output_ctx.codec_ctx)->height,
358                                             (output_ctx.codec_ctx)->pix_fmt,
359                                             rescale_method,
360                                             NULL, NULL, NULL);
361         if (sw_scale_ctx == NULL) {
362                 fprintf(stderr, "cannot set up the rescaling context!\n");
363                 ret = -EINVAL;
364                 goto cleanup_out_buf;
365         }
366
367         got_packet = 0;
368         while (run) {
369                 /* read packet */
370                 ret = av_read_frame(input_ctx.format_ctx, &in_packet);
371                 if (ret < 0) {
372                         if (ret == (int)AVERROR_EOF || input_ctx.format_ctx->pb->eof_reached)
373                                 ret = 0;
374                         else
375                                 fprintf(stderr, "av_read_frame failed, EOF?\n");
376                         run = 0;
377                         goto end_while;
378                 }
379
380                 if (in_packet.stream_index != input_ctx.video_stream_index) {
381                         /* that is more or less a "continue", but there is
382                          * still the packet to free */
383                         goto end_while;
384                 }
385
386                 /* decode */
387                 got_picture = 0;
388                 ret = avcodec_decode_video2(input_ctx.codec_ctx, picture_raw, &got_picture, &in_packet);
389                 if (ret < 0) {
390                         fprintf(stderr, "cannot decode video\n");
391                         run = 0;
392                         goto end_while;
393                 }
394
395                 /* if we got the complete frame */
396                 if (got_picture) {
397                         /* 
398                          * Rescaling the picture also changes its pixel format
399                          * to the raw format supported by the projector if
400                          * this was set in video_output_init()
401                          */
402                         sws_scale(sw_scale_ctx,
403                                   (const uint8_t * const *)picture_raw->data,
404                                   picture_raw->linesize,
405                                   0,
406                                   (input_ctx.codec_ctx)->height,
407                                   picture_scaled->data,
408                                   picture_scaled->linesize);
409
410                         if (output_ctx.raw_output) {
411                                 out_picture = out_buf;
412                                 out_picture_size = out_buf_size;
413                         } else {
414                                 picture_scaled->quality = (output_ctx.codec_ctx)->global_quality;
415                                 av_init_packet(&out_packet);
416                                 out_packet.data = NULL;
417                                 out_packet.size = 0;
418                                 got_packet = 0;
419                                 ret = avcodec_encode_video2(output_ctx.codec_ctx,
420                                                             &out_packet,
421                                                             picture_scaled,
422                                                             &got_packet);
423                                 if (ret < 0 || !got_packet) {
424                                         fprintf(stderr, "cannot encode video\n");
425                                         run = 0;
426                                         goto end_while;
427                                 }
428
429                                 out_picture = out_packet.data;
430                                 out_picture_size = out_packet.size;
431                         }
432
433 #ifdef DEBUG
434                         if (dump_frame) {
435                                 char filename[NAME_MAX];
436                                 FILE *file;
437                                 if (!output_ctx.raw_output)
438                                         snprintf(filename, NAME_MAX, "out_q%03d.jpg", quality);
439                                 else
440                                         snprintf(filename, NAME_MAX, "out.raw");
441                                 file = fopen(filename, "wb");
442                                 fwrite(out_picture, 1, out_picture_size, file);
443                                 fclose(file);
444                         }
445 #else
446                         (void) dump_frame;
447 #endif
448
449                         ret = am7xxx_send_image_async(dev,
450                                                       image_format,
451                                                       (output_ctx.codec_ctx)->width,
452                                                       (output_ctx.codec_ctx)->height,
453                                                       out_picture,
454                                                       out_picture_size);
455                         if (ret < 0) {
456                                 perror("am7xxx_send_image_async");
457                                 run = 0;
458                                 goto end_while;
459                         }
460                 }
461 end_while:
462                 if (!output_ctx.raw_output && got_packet)
463                         av_packet_unref(&out_packet);
464                 av_packet_unref(&in_packet);
465         }
466
467         sws_freeContext(sw_scale_ctx);
468 cleanup_out_buf:
469         av_free(out_buf);
470 cleanup_picture_scaled:
471         av_frame_free(&picture_scaled);
472 cleanup_picture_raw:
473         av_frame_free(&picture_raw);
474
475 cleanup_output:
476         /* Freeing the codec context is needed as well,
477          * see https://libav.org/documentation/doxygen/master/group__lavc__core.html#gaf4daa92361efb3523ef5afeb0b54077f
478          */
479         avcodec_close(output_ctx.codec_ctx);
480         avcodec_free_context(&(output_ctx.codec_ctx));
481
482 cleanup_input:
483         avcodec_close(input_ctx.codec_ctx);
484         avcodec_free_context(&(input_ctx.codec_ctx));
485         avformat_close_input(&(input_ctx.format_ctx));
486
487 out:
488         return ret;
489 }
490
491 #ifdef HAVE_XCB
492 #include <xcb/xcb.h>
493 static int x_get_screen_dimensions(const char *displayname, int *width, int *height)
494 {
495         int i, screen_number;
496         xcb_connection_t *connection;
497         const xcb_setup_t *setup;
498         xcb_screen_iterator_t iter;
499
500         connection = xcb_connect(displayname, &screen_number);
501         if (xcb_connection_has_error(connection)) {
502                 fprintf(stderr, "Cannot open a connection to %s\n", displayname);
503                 return -EINVAL;
504         }
505
506         setup = xcb_get_setup(connection);
507         if (setup == NULL) {
508                 fprintf(stderr, "Cannot get setup for %s\n", displayname);
509                 xcb_disconnect(connection);
510                 return -EINVAL;
511         }
512
513         iter = xcb_setup_roots_iterator(setup);
514         for (i = 0; i < screen_number; ++i) {
515                 xcb_screen_next(&iter);
516         }
517
518         xcb_screen_t *screen = iter.data;
519
520         *width = screen->width_in_pixels;
521         *height = screen->height_in_pixels;
522
523         xcb_disconnect(connection);
524
525         return 0;
526 }
527
528 static char *get_x_screen_size(const char *input_path)
529 {
530         int len;
531         int width;
532         int height;
533         char *screen_size;
534         int ret;
535
536         ret = x_get_screen_dimensions(input_path, &width, &height);
537         if (ret < 0) {
538                 fprintf(stderr, "Cannot get screen dimensions for %s\n", input_path);
539                 return NULL;
540         }
541
542         len = snprintf(NULL, 0, "%dx%d", width, height);
543
544         screen_size = malloc((len + 1) * sizeof(char));
545         if (screen_size == NULL) {
546                 perror("malloc");
547                 return NULL;
548         }
549
550         len = snprintf(screen_size, len + 1, "%dx%d", width, height);
551         if (len < 0) {
552                 free(screen_size);
553                 screen_size = NULL;
554                 return NULL;
555         }
556         return screen_size;
557 }
558 #else
559 static char *get_x_screen_size(const char *input_path)
560 {
561         (void) input_path;
562         fprintf(stderr, "%s: fallback implementation, assuming a vga screen\n", __func__);
563         return strdup("vga");
564 }
565 #endif
566
567 static void unset_run(int signo)
568 {
569         (void) signo;
570         run = 0;
571 }
572
573 #ifdef HAVE_SIGACTION
574 static int set_signal_handler(void (*signal_handler)(int))
575 {
576         struct sigaction new_action;
577         struct sigaction old_action;
578         int ret;
579
580         new_action.sa_handler = signal_handler;
581         sigemptyset(&new_action.sa_mask);
582         new_action.sa_flags = 0;
583
584         ret = sigaction(SIGINT, NULL, &old_action);
585         if (ret < 0) {
586                 perror("sigaction on old_action");
587                 goto out;
588         }
589
590         if (old_action.sa_handler != SIG_IGN) {
591                 ret = sigaction(SIGINT, &new_action, NULL);
592                 if (ret < 0) {
593                         perror("sigaction on new_action");
594                         goto out;
595                 }
596         }
597
598 out:
599         return ret;
600 }
601 #else
602 static int set_signal_handler(void (*signal_handler)(int))
603 {
604         (void)signal_handler;
605         fprintf(stderr, "set_signal_handler() not implemented, sigaction not available\n");
606         return 0;
607 }
608 #endif
609
610
611 static void usage(char *name)
612 {
613         printf("usage: %s [OPTIONS]\n\n", name);
614         printf("OPTIONS:\n");
615         printf("\t-d <index>\t\tthe device index (default is 0)\n");
616 #ifdef DEBUG
617         printf("\t-D \t\t\tdump the last frame to a file (only active in DEBUG mode)\n");
618 #endif
619         printf("\t-f <input format>\tthe input device format\n");
620         printf("\t-i <input path>\t\tthe input path\n");
621         printf("\t-o <options>\t\ta comma separated list of input format options\n");
622         printf("\t\t\t\tEXAMPLE:\n");
623         printf("\t\t\t\t\t-o draw_mouse=1,framerate=100,video_size=800x480\n");
624         printf("\t-s <scaling method>\tthe rescaling method (see swscale.h)\n");
625         printf("\t-u \t\t\tupscale the image if smaller than the display dimensions\n");
626         printf("\t-F <format>\t\tthe image format to use (default is JPEG)\n");
627         printf("\t\t\t\tSUPPORTED FORMATS:\n");
628         printf("\t\t\t\t\t1 - JPEG\n");
629         printf("\t\t\t\t\t2 - NV12\n");
630         printf("\t-q <quality>\t\tquality of jpeg sent to the device, between 1 and 100\n");
631         printf("\t-l <log level>\t\tthe verbosity level of libam7xxx output (0-5)\n");
632         printf("\t-p <power mode>\t\tthe power mode of device, between %d (off) and %d (turbo)\n",
633                AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
634         printf("\t\t\t\tWARNING: Level 2 and greater require the master AND\n");
635         printf("\t\t\t\t         the slave connector to be plugged in.\n");
636         printf("\t-z <zoom mode>\t\tthe display zoom mode, between %d (original) and %d (tele)\n",
637                AM7XXX_ZOOM_ORIGINAL, AM7XXX_ZOOM_TELE);
638         printf("\t-h \t\t\tthis help message\n");
639         printf("\n\nEXAMPLES OF USE:\n");
640         printf("\t%s -f x11grab -i :0.0 -o video_size=800x480\n", name);
641         printf("\t%s -f fbdev -i /dev/fb0\n", name);
642         printf("\t%s -f video4linux2 -i /dev/video0 -o video_size=320x240,frame_rate=100 -u -q 90\n", name);
643         printf("\t%s -i http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v\n", name);
644 }
645
646 int main(int argc, char *argv[])
647 {
648         int ret;
649         int opt;
650         char *subopts;
651         char *subopts_saved;
652         char *subopt;
653         char *input_format_string = NULL;
654         AVDictionary *options = NULL;
655         char *input_path = NULL;
656         unsigned int rescale_method = SWS_BICUBIC;
657         unsigned int upscale = 0;
658         unsigned int quality = 95;
659         int log_level = AM7XXX_LOG_INFO;
660         int device_index = 0;
661         int power_mode = AM7XXX_POWER_LOW;
662         int zoom = AM7XXX_ZOOM_ORIGINAL;
663         int format = AM7XXX_IMAGE_FORMAT_JPEG;
664         am7xxx_context *ctx;
665         am7xxx_device *dev;
666         int dump_frame = 0;
667
668         while ((opt = getopt(argc, argv, "d:Df:i:o:s:uF:q:l:p:z:h")) != -1) {
669                 switch (opt) {
670                 case 'd':
671                         device_index = atoi(optarg);
672                         if (device_index < 0) {
673                                 fprintf(stderr, "Unsupported device index\n");
674                                 ret = -EINVAL;
675                                 goto out;
676                         }
677                         break;
678                 case 'D':
679                         dump_frame = 1;
680 #ifndef DEBUG
681                         fprintf(stderr, "Warning: the -D option is only active in DEBUG mode.\n");
682 #endif
683                         break;
684                 case 'f':
685                         input_format_string = strdup(optarg);
686                         break;
687                 case 'i':
688                         input_path = strdup(optarg);
689                         break;
690                 case 'o':
691 #ifdef HAVE_STRTOK_R
692                         /*
693                          * parse suboptions, the expected format is something
694                          * like:
695                          *   draw_mouse=1,framerate=100,video_size=800x480
696                          */
697                         subopts = subopts_saved = strdup(optarg);
698                         while ((subopt = strtok_r(subopts, ",", &subopts))) {
699                                 char *subopt_name = strtok_r(subopt, "=", &subopt);
700                                 char *subopt_value = strtok_r(NULL, "", &subopt);
701                                 if (subopt_value == NULL) {
702                                         fprintf(stderr, "invalid suboption: %s\n", subopt_name);
703                                         continue;
704                                 }
705                                 av_dict_set(&options, subopt_name, subopt_value, 0);
706                         }
707                         free(subopts_saved);
708 #else
709                         fprintf(stderr, "Option '-o' not implemented\n");
710 #endif
711                         break;
712                 case 's':
713                         rescale_method = atoi(optarg);
714                         switch(rescale_method) {
715                         case SWS_FAST_BILINEAR:
716                         case SWS_BILINEAR:
717                         case SWS_BICUBIC:
718                         case SWS_X:
719                         case SWS_POINT:
720                         case SWS_AREA:
721                         case SWS_BICUBLIN:
722                         case SWS_GAUSS:
723                         case SWS_SINC:
724                         case SWS_LANCZOS:
725                         case SWS_SPLINE:
726                                 break;
727                         default:
728                                 fprintf(stderr, "Unsupported rescale method\n");
729                                 ret = -EINVAL;
730                                 goto out;
731                         }
732                         break;
733                 case 'u':
734                         upscale = 1;
735                         break;
736                 case 'F':
737                         format = atoi(optarg);
738                         switch(format) {
739                         case AM7XXX_IMAGE_FORMAT_JPEG:
740                                 fprintf(stdout, "JPEG format\n");
741                                 break;
742                         case AM7XXX_IMAGE_FORMAT_NV12:
743                                 fprintf(stdout, "NV12 format\n");
744                                 break;
745                         default:
746                                 fprintf(stderr, "Unsupported format\n");
747                                 ret = -EINVAL;
748                                 goto out;
749                         }
750                         break;
751                 case 'q':
752                         quality = atoi(optarg);
753                         if (quality < 1 || quality > 100) {
754                                 fprintf(stderr, "Invalid quality value, must be between 1 and 100\n");
755                                 ret = -EINVAL;
756                                 goto out;
757                         }
758                         break;
759                 case 'l':
760                         log_level = atoi(optarg);
761                         if (log_level < AM7XXX_LOG_FATAL || log_level > AM7XXX_LOG_TRACE) {
762                                 fprintf(stderr, "Unsupported log level, falling back to AM7XXX_LOG_ERROR\n");
763                                 log_level = AM7XXX_LOG_ERROR;
764                         }
765                         break;
766                 case 'p':
767                         power_mode = atoi(optarg);
768                         switch(power_mode) {
769                         case AM7XXX_POWER_OFF:
770                         case AM7XXX_POWER_LOW:
771                         case AM7XXX_POWER_MIDDLE:
772                         case AM7XXX_POWER_HIGH:
773                         case AM7XXX_POWER_TURBO:
774                                 fprintf(stdout, "Power mode: %d\n", power_mode);
775                                 break;
776                         default:
777                                 fprintf(stderr, "Invalid power mode value, must be between %d and %d\n",
778                                         AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
779                                 ret = -EINVAL;
780                                 goto out;
781                         }
782                         break;
783                 case 'z':
784                         zoom = atoi(optarg);
785                         switch(zoom) {
786                         case AM7XXX_ZOOM_ORIGINAL:
787                         case AM7XXX_ZOOM_H:
788                         case AM7XXX_ZOOM_H_V:
789                         case AM7XXX_ZOOM_TEST:
790                         case AM7XXX_ZOOM_TELE:
791                                 fprintf(stdout, "Zoom: %d\n", zoom);
792                                 break;
793                         default:
794                                 fprintf(stderr, "Invalid zoom mode value, must be between %d and %d\n",
795                                         AM7XXX_ZOOM_ORIGINAL, AM7XXX_ZOOM_TELE);
796                                 ret = -EINVAL;
797                                 goto out;
798                         }
799                         break;
800                 case 'h':
801                         usage(argv[0]);
802                         ret = 0;
803                         goto out;
804                 default: /* '?' */
805                         usage(argv[0]);
806                         ret = -EINVAL;
807                         goto out;
808                 }
809         }
810
811         if (input_path == NULL) {
812                 fprintf(stderr, "The -i option must always be passed\n\n");
813                 usage(argv[0]);
814                 ret = -EINVAL;
815                 goto out;
816         }
817
818         /*
819          * When the input format is 'x11grab' set some useful fallback options
820          * if not supplied by the user, in particular grab full screen
821          */
822         if (input_format_string && strcmp(input_format_string, "x11grab") == 0) {
823                 char *video_size;
824
825                 video_size = get_x_screen_size(input_path);
826
827                 if (!av_dict_get(options, "video_size", NULL, 0))
828                         av_dict_set(&options, "video_size", video_size, 0);
829
830                 if (!av_dict_get(options, "framerate", NULL, 0))
831                         av_dict_set(&options, "framerate", "60", 0);
832
833                 if (!av_dict_get(options, "draw_mouse", NULL, 0))
834                         av_dict_set(&options, "draw_mouse",  "1", 0);
835
836                 free(video_size);
837         }
838
839         ret = set_signal_handler(unset_run);
840         if (ret < 0) {
841                 perror("sigaction");
842                 goto out;
843         }
844
845         ret = am7xxx_init(&ctx);
846         if (ret < 0) {
847                 perror("am7xxx_init");
848                 goto out;
849         }
850
851         am7xxx_set_log_level(ctx, log_level);
852
853         ret = am7xxx_open_device(ctx, &dev, device_index);
854         if (ret < 0) {
855                 perror("am7xxx_open_device");
856                 goto cleanup;
857         }
858
859         ret = am7xxx_set_zoom_mode(dev, zoom);
860         if (ret < 0) {
861                 perror("am7xxx_set_zoom_mode");
862                 goto cleanup;
863         }
864
865         ret = am7xxx_set_power_mode(dev, power_mode);
866         if (ret < 0) {
867                 perror("am7xxx_set_power_mode");
868                 goto cleanup;
869         }
870
871         /* When setting AM7XXX_ZOOM_TEST don't display the actual image */
872         if (zoom == AM7XXX_ZOOM_TEST)
873                 goto cleanup;
874
875         ret = am7xxx_play(input_format_string,
876                           &options,
877                           input_path,
878                           rescale_method,
879                           upscale,
880                           quality,
881                           format,
882                           dev,
883                           dump_frame);
884         if (ret < 0) {
885                 fprintf(stderr, "am7xxx_play failed\n");
886                 goto cleanup;
887         }
888
889 cleanup:
890         am7xxx_shutdown(ctx);
891 out:
892         av_dict_free(&options);
893         free(input_path);
894         free(input_format_string);
895         return ret;
896 }