libavfilter/vsrc_life.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) Stefano Sabatini 2010
00003  *
00004  * This file is part of FFmpeg.
00005  *
00006  * FFmpeg is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * FFmpeg is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with FFmpeg; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00026 /* #define DEBUG */
00027 
00028 #include "libavutil/file.h"
00029 #include "libavutil/intreadwrite.h"
00030 #include "libavutil/lfg.h"
00031 #include "libavutil/opt.h"
00032 #include "libavutil/parseutils.h"
00033 #include "libavutil/random_seed.h"
00034 #include "avfilter.h"
00035 
00036 typedef struct {
00037     const AVClass *class;
00038     int w, h;
00039     char *filename;
00040     char *rule_str;
00041     uint8_t *file_buf;
00042     size_t file_bufsize;
00043 
00053     uint8_t *buf[2];
00054 
00055     uint8_t  buf_idx;
00056     uint16_t stay_rule;         
00057     uint16_t born_rule;         
00058     uint64_t pts;
00059     AVRational time_base;
00060     char *size;                 
00061     char *rate;                 
00062     double   random_fill_ratio;
00063     uint32_t random_seed;
00064     int stitch;
00065     int mold;
00066     char  *life_color_str;
00067     char *death_color_str;
00068     char  *mold_color_str;
00069     uint8_t  life_color[4];
00070     uint8_t death_color[4];
00071     uint8_t  mold_color[4];
00072     AVLFG lfg;
00073     void (*draw)(AVFilterContext*, AVFilterBufferRef*);
00074 } LifeContext;
00075 
00076 #define ALIVE_CELL 0xFF
00077 #define OFFSET(x) offsetof(LifeContext, x)
00078 
00079 static const AVOption life_options[] = {
00080     { "filename", "set source file",  OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
00081     { "f",        "set source file",  OFFSET(filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
00082     { "size",     "set video size",   OFFSET(size),     AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
00083     { "s",        "set video size",   OFFSET(size),     AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0 },
00084     { "rate",     "set video rate",   OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
00085     { "r",        "set video rate",   OFFSET(rate),     AV_OPT_TYPE_STRING, {.str = "25"}, 0, 0 },
00086     { "rule",     "set rule",         OFFSET(rule_str), AV_OPT_TYPE_STRING, {.str = "B3/S23"}, CHAR_MIN, CHAR_MAX },
00087     { "random_fill_ratio", "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1/M_PHI}, 0, 1 },
00088     { "ratio",             "set fill ratio for filling initial grid randomly", OFFSET(random_fill_ratio), AV_OPT_TYPE_DOUBLE, {.dbl=1/M_PHI}, 0, 1 },
00089     { "random_seed", "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl=-1}, -1, UINT32_MAX },
00090     { "seed",        "set the seed for filling the initial grid randomly", OFFSET(random_seed), AV_OPT_TYPE_INT, {.dbl=-1}, -1, UINT32_MAX },
00091     { "stitch",      "stitch boundaries", OFFSET(stitch), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
00092     { "mold",        "set mold speed for dead cells", OFFSET(mold), AV_OPT_TYPE_INT, {.dbl=0}, 0, 0xFF },
00093     { "life_color",  "set life color",  OFFSET( life_color_str), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX },
00094     { "death_color", "set death color", OFFSET(death_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
00095     { "mold_color",  "set mold color",  OFFSET( mold_color_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
00096     { NULL },
00097 };
00098 
00099 static const char *life_get_name(void *ctx)
00100 {
00101     return "life";
00102 }
00103 
00104 static const AVClass life_class = {
00105     "LifeContext",
00106     life_get_name,
00107     life_options
00108 };
00109 
00110 static int parse_rule(uint16_t *born_rule, uint16_t *stay_rule,
00111                       const char *rule_str, void *log_ctx)
00112 {
00113     char *tail;
00114     const char *p = rule_str;
00115     *born_rule = 0;
00116     *stay_rule = 0;
00117 
00118     if (strchr("bBsS", *p)) {
00119         /* parse rule as a Born / Stay Alive code, see
00120          * http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life */
00121         do {
00122             uint16_t *rule = (*p == 'b' || *p == 'B') ? born_rule : stay_rule;
00123             p++;
00124             while (*p >= '0' && *p <= '8') {
00125                 *rule += 1<<(*p - '0');
00126                 p++;
00127             }
00128             if (*p != '/')
00129                 break;
00130             p++;
00131         } while (strchr("bBsS", *p));
00132 
00133         if (*p)
00134             goto error;
00135     } else {
00136         /* parse rule as a number, expressed in the form STAY|(BORN<<9),
00137          * where STAY and BORN encode the corresponding 9-bits rule */
00138         long int rule = strtol(rule_str, &tail, 10);
00139         if (*tail)
00140             goto error;
00141         *born_rule  = ((1<<9)-1) & rule;
00142         *stay_rule = rule >> 9;
00143     }
00144 
00145     return 0;
00146 
00147 error:
00148     av_log(log_ctx, AV_LOG_ERROR, "Invalid rule code '%s' provided\n", rule_str);
00149     return AVERROR(EINVAL);
00150 }
00151 
00152 #ifdef DEBUG
00153 static void show_life_grid(AVFilterContext *ctx)
00154 {
00155     LifeContext *life = ctx->priv;
00156     int i, j;
00157 
00158     char *line = av_malloc(life->w + 1);
00159     if (!line)
00160         return;
00161     for (i = 0; i < life->h; i++) {
00162         for (j = 0; j < life->w; j++)
00163             line[j] = life->buf[life->buf_idx][i*life->w + j] == ALIVE_CELL ? '@' : ' ';
00164         line[j] = 0;
00165         av_log(ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);
00166     }
00167     av_free(line);
00168 }
00169 #endif
00170 
00171 static int init_pattern_from_file(AVFilterContext *ctx)
00172 {
00173     LifeContext *life = ctx->priv;
00174     char *p;
00175     int ret, i, i0, j, h = 0, w, max_w = 0;
00176 
00177     if ((ret = av_file_map(life->filename, &life->file_buf, &life->file_bufsize,
00178                            0, ctx)) < 0)
00179         return ret;
00180 
00181     /* prescan file to get the number of lines and the maximum width */
00182     w = 0;
00183     for (i = 0; i < life->file_bufsize; i++) {
00184         if (life->file_buf[i] == '\n') {
00185             h++; max_w = FFMAX(w, max_w); w = 0;
00186         } else {
00187             w++;
00188         }
00189     }
00190     av_log(ctx, AV_LOG_DEBUG, "h:%d max_w:%d\n", h, max_w);
00191 
00192     if (life->size) {
00193         if (max_w > life->w || h > life->h) {
00194             av_log(ctx, AV_LOG_ERROR,
00195                    "The specified size is %dx%d which cannot contain the provided file size of %dx%d\n",
00196                    life->w, life->h, max_w, h);
00197             return AVERROR(EINVAL);
00198         }
00199     } else {
00200         /* size was not specified, set it to size of the grid */
00201         life->w = max_w;
00202         life->h = h;
00203     }
00204 
00205     if (!(life->buf[0] = av_mallocz(sizeof(char) * life->h * life->w)) ||
00206         !(life->buf[1] = av_mallocz(sizeof(char) * life->h * life->w))) {
00207         av_free(life->buf[0]);
00208         av_free(life->buf[1]);
00209         return AVERROR(ENOMEM);
00210     }
00211 
00212     /* fill buf[0] */
00213     p = life->file_buf;
00214     for (i0 = 0, i = (life->h - h)/2; i0 < h; i0++, i++) {
00215         for (j = (life->w - max_w)/2;; j++) {
00216             av_log(ctx, AV_LOG_DEBUG, "%d:%d %c\n", i, j, *p == '\n' ? 'N' : *p);
00217             if (*p == '\n') {
00218                 p++; break;
00219             } else
00220                 life->buf[0][i*life->w + j] = isgraph(*(p++)) ? ALIVE_CELL : 0;
00221         }
00222     }
00223     life->buf_idx = 0;
00224 
00225     return 0;
00226 }
00227 
00228 static int init(AVFilterContext *ctx, const char *args, void *opaque)
00229 {
00230     LifeContext *life = ctx->priv;
00231     AVRational frame_rate;
00232     int ret;
00233 
00234     life->class = &life_class;
00235     av_opt_set_defaults(life);
00236 
00237     if ((ret = av_set_options_string(life, args, "=", ":")) < 0) {
00238         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
00239         return ret;
00240     }
00241 
00242     if ((ret = av_parse_video_rate(&frame_rate, life->rate)) < 0) {
00243         av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", life->rate);
00244         return AVERROR(EINVAL);
00245     }
00246 
00247     if (!life->size && !life->filename)
00248         av_opt_set(life, "size", "320x240", 0);
00249 
00250     if (life->size &&
00251         (ret = av_parse_video_size(&life->w, &life->h, life->size)) < 0) {
00252         av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", life->size);
00253         return ret;
00254     }
00255 
00256     if ((ret = parse_rule(&life->born_rule, &life->stay_rule, life->rule_str, ctx)) < 0)
00257         return ret;
00258 
00259 #define PARSE_COLOR(name) do { \
00260     if ((ret = av_parse_color(life->name ## _color, life->name ## _color_str, -1, ctx))) { \
00261         av_log(ctx, AV_LOG_ERROR, "Invalid " #name " color '%s'\n", \
00262                life->name ## _color_str); \
00263         return ret; \
00264     } \
00265 } while (0)
00266 
00267     PARSE_COLOR(life);
00268     PARSE_COLOR(death);
00269     PARSE_COLOR(mold);
00270 
00271     if (!life->mold && memcmp(life->mold_color, "\x00\x00\x00", 3))
00272         av_log(ctx, AV_LOG_WARNING,
00273                "Mold color is set while mold isn't, ignoring the color.\n");
00274 
00275     life->time_base.num = frame_rate.den;
00276     life->time_base.den = frame_rate.num;
00277 
00278     if (!life->filename) {
00279         /* fill the grid randomly */
00280         int i;
00281 
00282         if (!(life->buf[0] = av_mallocz(sizeof(char) * life->h * life->w)) ||
00283             !(life->buf[1] = av_mallocz(sizeof(char) * life->h * life->w))) {
00284             av_free(life->buf[0]);
00285             av_free(life->buf[1]);
00286             return AVERROR(ENOMEM);
00287         }
00288         if (life->random_seed == -1)
00289             life->random_seed = av_get_random_seed();
00290 
00291         av_lfg_init(&life->lfg, life->random_seed);
00292 
00293         for (i = 0; i < life->w * life->h; i++) {
00294             double r = (double)av_lfg_get(&life->lfg) / UINT32_MAX;
00295             if (r <= life->random_fill_ratio)
00296                 life->buf[0][i] = ALIVE_CELL;
00297         }
00298         life->buf_idx = 0;
00299     } else {
00300         if ((ret = init_pattern_from_file(ctx)) < 0)
00301             return ret;
00302     }
00303 
00304     av_log(ctx, AV_LOG_INFO,
00305            "s:%dx%d r:%d/%d rule:%s stay_rule:%d born_rule:%d stitch:%d seed:%u\n",
00306            life->w, life->h, frame_rate.num, frame_rate.den,
00307            life->rule_str, life->stay_rule, life->born_rule, life->stitch,
00308            life->random_seed);
00309     return 0;
00310 }
00311 
00312 static av_cold void uninit(AVFilterContext *ctx)
00313 {
00314     LifeContext *life = ctx->priv;
00315 
00316     av_file_unmap(life->file_buf, life->file_bufsize);
00317     av_freep(&life->rule_str);
00318     av_freep(&life->buf[0]);
00319     av_freep(&life->buf[1]);
00320 }
00321 
00322 static int config_props(AVFilterLink *outlink)
00323 {
00324     LifeContext *life = outlink->src->priv;
00325 
00326     outlink->w = life->w;
00327     outlink->h = life->h;
00328     outlink->time_base = life->time_base;
00329 
00330     return 0;
00331 }
00332 
00333 static void evolve(AVFilterContext *ctx)
00334 {
00335     LifeContext *life = ctx->priv;
00336     int i, j;
00337     uint8_t *oldbuf = life->buf[ life->buf_idx];
00338     uint8_t *newbuf = life->buf[!life->buf_idx];
00339 
00340     enum { NW, N, NE, W, E, SW, S, SE };
00341 
00342     /* evolve the grid */
00343     for (i = 0; i < life->h; i++) {
00344         for (j = 0; j < life->w; j++) {
00345             int pos[8][2], n, alive, cell;
00346             if (life->stitch) {
00347                 pos[NW][0] = (i-1) < 0 ? life->h-1 : i-1; pos[NW][1] = (j-1) < 0 ? life->w-1 : j-1;
00348                 pos[N ][0] = (i-1) < 0 ? life->h-1 : i-1; pos[N ][1] =                         j  ;
00349                 pos[NE][0] = (i-1) < 0 ? life->h-1 : i-1; pos[NE][1] = (j+1) == life->w ?  0 : j+1;
00350                 pos[W ][0] =                         i  ; pos[W ][1] = (j-1) < 0 ? life->w-1 : j-1;
00351                 pos[E ][0] =                         i  ; pos[E ][1] = (j+1) == life->w ? 0  : j+1;
00352                 pos[SW][0] = (i+1) == life->h ?  0 : i+1; pos[SW][1] = (j-1) < 0 ? life->w-1 : j-1;
00353                 pos[S ][0] = (i+1) == life->h ?  0 : i+1; pos[S ][1] =                         j  ;
00354                 pos[SE][0] = (i+1) == life->h ?  0 : i+1; pos[SE][1] = (j+1) == life->w ?  0 : j+1;
00355             } else {
00356                 pos[NW][0] = (i-1) < 0 ? -1        : i-1; pos[NW][1] = (j-1) < 0 ? -1        : j-1;
00357                 pos[N ][0] = (i-1) < 0 ? -1        : i-1; pos[N ][1] =                         j  ;
00358                 pos[NE][0] = (i-1) < 0 ? -1        : i-1; pos[NE][1] = (j+1) == life->w ? -1 : j+1;
00359                 pos[W ][0] =                         i  ; pos[W ][1] = (j-1) < 0 ? -1        : j-1;
00360                 pos[E ][0] =                         i  ; pos[E ][1] = (j+1) == life->w ? -1 : j+1;
00361                 pos[SW][0] = (i+1) == life->h ? -1 : i+1; pos[SW][1] = (j-1) < 0 ? -1        : j-1;
00362                 pos[S ][0] = (i+1) == life->h ? -1 : i+1; pos[S ][1] =                         j  ;
00363                 pos[SE][0] = (i+1) == life->h ? -1 : i+1; pos[SE][1] = (j+1) == life->w ? -1 : j+1;
00364             }
00365 
00366             /* compute the number of live neighbor cells */
00367             n = (pos[NW][0] == -1 || pos[NW][1] == -1 ? 0 : oldbuf[pos[NW][0]*life->w + pos[NW][1]] == ALIVE_CELL) +
00368                 (pos[N ][0] == -1 || pos[N ][1] == -1 ? 0 : oldbuf[pos[N ][0]*life->w + pos[N ][1]] == ALIVE_CELL) +
00369                 (pos[NE][0] == -1 || pos[NE][1] == -1 ? 0 : oldbuf[pos[NE][0]*life->w + pos[NE][1]] == ALIVE_CELL) +
00370                 (pos[W ][0] == -1 || pos[W ][1] == -1 ? 0 : oldbuf[pos[W ][0]*life->w + pos[W ][1]] == ALIVE_CELL) +
00371                 (pos[E ][0] == -1 || pos[E ][1] == -1 ? 0 : oldbuf[pos[E ][0]*life->w + pos[E ][1]] == ALIVE_CELL) +
00372                 (pos[SW][0] == -1 || pos[SW][1] == -1 ? 0 : oldbuf[pos[SW][0]*life->w + pos[SW][1]] == ALIVE_CELL) +
00373                 (pos[S ][0] == -1 || pos[S ][1] == -1 ? 0 : oldbuf[pos[S ][0]*life->w + pos[S ][1]] == ALIVE_CELL) +
00374                 (pos[SE][0] == -1 || pos[SE][1] == -1 ? 0 : oldbuf[pos[SE][0]*life->w + pos[SE][1]] == ALIVE_CELL);
00375             cell  = oldbuf[i*life->w + j];
00376             alive = 1<<n & (cell == ALIVE_CELL ? life->stay_rule : life->born_rule);
00377             if (alive)     *newbuf = ALIVE_CELL; // new cell is alive
00378             else if (cell) *newbuf = cell - 1;   // new cell is dead and in the process of mold
00379             else           *newbuf = 0;          // new cell is definitely dead
00380             av_dlog(ctx, "i:%d j:%d live_neighbors:%d cell:%d -> cell:%d\n", i, j, n, cell, *newbuf);
00381             newbuf++;
00382         }
00383     }
00384 
00385     life->buf_idx = !life->buf_idx;
00386 }
00387 
00388 static void fill_picture_monoblack(AVFilterContext *ctx, AVFilterBufferRef *picref)
00389 {
00390     LifeContext *life = ctx->priv;
00391     uint8_t *buf = life->buf[life->buf_idx];
00392     int i, j, k;
00393 
00394     /* fill the output picture with the old grid buffer */
00395     for (i = 0; i < life->h; i++) {
00396         uint8_t byte = 0;
00397         uint8_t *p = picref->data[0] + i * picref->linesize[0];
00398         for (k = 0, j = 0; j < life->w; j++) {
00399             byte |= (buf[i*life->w+j] == ALIVE_CELL)<<(7-k++);
00400             if (k==8 || j == life->w-1) {
00401                 k = 0;
00402                 *p++ = byte;
00403                 byte = 0;
00404             }
00405         }
00406     }
00407 }
00408 
00409 // divide by 255 and round to nearest
00410 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
00411 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
00412 
00413 static void fill_picture_rgb(AVFilterContext *ctx, AVFilterBufferRef *picref)
00414 {
00415     LifeContext *life = ctx->priv;
00416     uint8_t *buf = life->buf[life->buf_idx];
00417     int i, j;
00418 
00419     /* fill the output picture with the old grid buffer */
00420     for (i = 0; i < life->h; i++) {
00421         uint8_t *p = picref->data[0] + i * picref->linesize[0];
00422         for (j = 0; j < life->w; j++) {
00423             uint8_t v = buf[i*life->w + j];
00424             if (life->mold && v != ALIVE_CELL) {
00425                 const uint8_t *c1 = life-> mold_color;
00426                 const uint8_t *c2 = life->death_color;
00427                 int death_age = FFMIN((0xff - v) * life->mold, 0xff);
00428                 *p++ = FAST_DIV255((c2[0] << 8) + ((int)c1[0] - (int)c2[0]) * death_age);
00429                 *p++ = FAST_DIV255((c2[1] << 8) + ((int)c1[1] - (int)c2[1]) * death_age);
00430                 *p++ = FAST_DIV255((c2[2] << 8) + ((int)c1[2] - (int)c2[2]) * death_age);
00431             } else {
00432                 const uint8_t *c = v == ALIVE_CELL ? life->life_color : life->death_color;
00433                 AV_WB24(p, c[0]<<16 | c[1]<<8 | c[2]);
00434                 p += 3;
00435             }
00436         }
00437     }
00438 }
00439 
00440 static int request_frame(AVFilterLink *outlink)
00441 {
00442     LifeContext *life = outlink->src->priv;
00443     AVFilterBufferRef *picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE, life->w, life->h);
00444     picref->video->sample_aspect_ratio = (AVRational) {1, 1};
00445     picref->pts = life->pts++;
00446     picref->pos = -1;
00447 
00448     life->draw(outlink->src, picref);
00449     evolve(outlink->src);
00450 #ifdef DEBUG
00451     show_life_grid(outlink->src);
00452 #endif
00453 
00454     avfilter_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
00455     avfilter_draw_slice(outlink, 0, life->h, 1);
00456     avfilter_end_frame(outlink);
00457     avfilter_unref_buffer(picref);
00458 
00459     return 0;
00460 }
00461 
00462 static int query_formats(AVFilterContext *ctx)
00463 {
00464     LifeContext *life = ctx->priv;
00465     enum PixelFormat pix_fmts[] = { PIX_FMT_NONE, PIX_FMT_NONE };
00466     if (life->mold || memcmp(life-> life_color, "\xff\xff\xff", 3)
00467                    || memcmp(life->death_color, "\x00\x00\x00", 3)) {
00468         pix_fmts[0] = PIX_FMT_RGB24;
00469         life->draw = fill_picture_rgb;
00470     } else {
00471         pix_fmts[0] = PIX_FMT_MONOBLACK;
00472         life->draw = fill_picture_monoblack;
00473     }
00474     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
00475     return 0;
00476 }
00477 
00478 AVFilter avfilter_vsrc_life = {
00479     .name        = "life",
00480     .description = NULL_IF_CONFIG_SMALL("Create life."),
00481     .priv_size = sizeof(LifeContext),
00482     .init      = init,
00483     .uninit    = uninit,
00484     .query_formats = query_formats,
00485 
00486     .inputs    = (const AVFilterPad[]) {
00487         { .name = NULL}
00488     },
00489     .outputs   = (const AVFilterPad[]) {
00490         { .name            = "default",
00491           .type            = AVMEDIA_TYPE_VIDEO,
00492           .request_frame   = request_frame,
00493           .config_props    = config_props },
00494         { .name = NULL}
00495     },
00496 };