dcraw reset, ffmpeg+filejpeg+filesndfile fixes, vdevicex11 rework, bcbitmap fix,...
[goodguy/history.git] / cinelerra-5.1 / guicast / vframe.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2011 Adam Williams <broadcast at earthling dot net>
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 2 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, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include <errno.h>
23 #include <png.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdint.h>
27 #include <fcntl.h>
28 #include <sys/shm.h>
29 #include <sys/mman.h>
30
31 #include "bcbitmap.h"
32 #include "bchash.h"
33 #include "bcpbuffer.h"
34 #include "bcresources.h"
35 #include "bcsignals.h"
36 #include "bcsynchronous.h"
37 #include "bctexture.h"
38 #include "bcwindowbase.h"
39 #include "clip.h"
40 #include "bccmodels.h"
41 #include "vframe.h"
42
43 class PngReadFunction
44 {
45 public:
46         static void png_read_function(png_structp png_ptr,
47                    png_bytep data, png_size_t length)
48         {
49                 VFrame *frame = (VFrame*)png_get_io_ptr(png_ptr);
50                 if(frame->image_size - frame->image_offset < (long)length)
51                 {
52                         printf("PngReadFunction::png_read_function %d: overrun\n", __LINE__);
53                         length = frame->image_size - frame->image_offset;
54                 }
55
56                 memcpy(data, &frame->image[frame->image_offset], length);
57                 frame->image_offset += length;
58         };
59 };
60
61
62
63
64
65
66
67 VFrameScene::VFrameScene()
68 {
69 }
70
71 VFrameScene::~VFrameScene()
72 {
73 }
74
75
76
77
78
79
80
81 //static BCCounter counter;
82
83 VFramePng::VFramePng(unsigned char *png_data, double s)
84 {
85         long image_size =
86                 ((long)png_data[0] << 24) | ((long)png_data[1] << 16) |
87                 ((long)png_data[2] << 8)  |  (long)png_data[3];
88         if( !s ) s = BC_WindowBase::get_resources()->icon_scale;
89         read_png(png_data+4, image_size, s, s);
90 }
91
92 VFramePng::VFramePng(unsigned char *png_data, long image_size, double xs, double ys)
93 {
94         if( !xs ) xs = BC_WindowBase::get_resources()->icon_scale;
95         if( !ys ) ys = BC_WindowBase::get_resources()->icon_scale;
96         read_png(png_data, image_size, xs, ys);
97 }
98
99 VFramePng::~VFramePng()
100 {
101 }
102
103 VFrame *VFramePng::vframe_png(int fd, double xs, double ys)
104 {
105         struct stat st;
106         if( fstat(fd, &st) ) return 0;
107         long len = st.st_size;
108         if( !len ) return 0;
109         int w = 0, h = 0;
110         unsigned char *bfr = (unsigned char *)
111                 ::mmap (NULL, len, PROT_READ, MAP_SHARED, fd, 0);
112         if( bfr == MAP_FAILED ) return 0;
113         VFrame *vframe = new VFramePng(bfr, len, xs, ys);
114         if( (w=vframe->get_w()) <= 0 || (h=vframe->get_h()) <= 0 ||
115             vframe->get_data() == 0 ) { delete vframe;  vframe = 0; }
116         ::munmap(bfr, len);
117         return vframe;
118 }
119 VFrame *VFramePng::vframe_png(const char *png_path, double xs, double ys)
120 {
121         VFrame *vframe = 0;
122         int fd = ::open(png_path, O_RDONLY);
123         if( fd >= 0 ) {
124                 vframe = vframe_png(fd, xs, ys);
125                 ::close(fd);
126         }
127         return vframe;
128 }
129
130 VFrame::VFrame(VFrame &frame)
131 {
132         reset_parameters(1);
133         params = new BC_Hash;
134         allocate_data(0, -1, 0, 0, 0, frame.w, frame.h,
135                 frame.color_model, frame.bytes_per_line);
136         copy_from(&frame);
137 }
138
139 VFrame::VFrame(int w, int h, int color_model, long bytes_per_line)
140 {
141         reset_parameters(1);
142         params = new BC_Hash;
143         allocate_data(data, -1, 0, 0, 0, w, h,
144                 color_model, bytes_per_line);
145 }
146
147 VFrame::VFrame(unsigned char *data, int shmid, int w, int h,
148         int color_model, long bytes_per_line)
149 {
150         reset_parameters(1);
151         params = new BC_Hash;
152         allocate_data(data, shmid, 0, 0, 0, w, h,
153                 color_model, bytes_per_line);
154 }
155
156 VFrame::VFrame(unsigned char *data, int shmid,
157                 long y_offset, long u_offset, long v_offset,
158                 int w, int h, int color_model, long bytes_per_line)
159 {
160         reset_parameters(1);
161         params = new BC_Hash;
162         allocate_data(data, shmid, y_offset, u_offset, v_offset, w, h,
163                 color_model, bytes_per_line);
164 }
165
166 VFrame::VFrame(BC_Bitmap *bitmap, int w, int h,
167                  int color_model, long bytes_per_line)
168 {
169         reset_parameters(1);
170         params = new BC_Hash;
171         int shmid = 0;
172         unsigned char *data = 0;
173         if( bitmap->is_shared() )
174                 shmid = bitmap->get_shmid();
175         else
176                 data = bitmap->get_data();
177         allocate_data(data, shmid,
178                 bitmap->get_y_offset(),
179                 bitmap->get_u_offset(),
180                 bitmap->get_v_offset(),
181                 w, h, color_model, bytes_per_line);
182 }
183
184 VFrame::VFrame()
185 {
186         reset_parameters(1);
187         params = new BC_Hash;
188         this->color_model = BC_COMPRESSED;
189 }
190
191
192
193 VFrame::~VFrame()
194 {
195         clear_objects(1);
196 // Delete effect stack
197         prev_effects.remove_all_objects();
198         next_effects.remove_all_objects();
199         delete params;
200         delete scene;
201 }
202
203 int VFrame::equivalent(VFrame *src, int test_stacks)
204 {
205         return (src->get_color_model() == get_color_model() &&
206                 src->get_w() == get_w() &&
207                 src->get_h() == get_h() &&
208                 src->bytes_per_line == bytes_per_line &&
209                 (!test_stacks || equal_stacks(src)));
210 }
211
212 int VFrame::data_matches(VFrame *frame)
213 {
214         if(data && frame->get_data() &&
215                 frame->params_match(get_w(), get_h(), get_color_model()) &&
216                 get_data_size() == frame->get_data_size())
217         {
218                 int data_size = get_data_size();
219                 unsigned char *ptr1 = get_data();
220                 unsigned char *ptr2 = frame->get_data();
221                 for(int i = 0; i < data_size; i++)
222                 {
223                         if(*ptr1++ != *ptr2++) return 0;
224                 }
225                 return 1;
226         }
227         return 0;
228 }
229
230 // long VFrame::set_shm_offset(long offset)
231 // {
232 //      shm_offset = offset;
233 //      return 0;
234 // }
235 //
236 // long VFrame::get_shm_offset()
237 // {
238 //      return shm_offset;
239 // }
240 //
241 int VFrame::get_memory_type()
242 {
243         return memory_type;
244 }
245
246 int VFrame::params_match(int w, int h, int color_model)
247 {
248         return (this->w == w &&
249                 this->h == h &&
250                 this->color_model == color_model);
251 }
252
253
254 int VFrame::reset_parameters(int do_opengl)
255 {
256         status = 1;
257         scene = 0;
258         field2_offset = -1;
259         memory_type = VFrame::PRIVATE;
260 //      shm_offset = 0;
261         shmid = -1;
262         use_shm = 1;
263         bytes_per_line = 0;
264         data = 0;
265         rows = 0;
266         color_model = 0;
267         compressed_allocated = 0;
268         compressed_size = 0;   // Size of current image
269         w = 0;
270         h = 0;
271         y = u = v = a = 0;
272         y_offset = 0;
273         u_offset = 0;
274         v_offset = 0;
275         sequence_number = -1;
276         timestamp = -1.;
277         is_keyframe = 0;
278         draw_point = 0;
279         set_pixel_color(BLACK);
280         stipple = 0;
281
282         if(do_opengl)
283         {
284 // By default, anything is going to be done in RAM
285                 opengl_state = VFrame::RAM;
286                 pbuffer = 0;
287                 texture = 0;
288         }
289
290         prev_effects.set_array_delete();
291         next_effects.set_array_delete();
292         return 0;
293 }
294
295 int VFrame::clear_objects(int do_opengl)
296 {
297 // Remove texture
298         if(do_opengl)
299         {
300                 delete texture;
301                 texture = 0;
302
303                 delete pbuffer;
304                 pbuffer = 0;
305         }
306
307 // Delete data
308         switch(memory_type)
309         {
310                 case VFrame::PRIVATE:
311 // Memory check
312 // if(this->w * this->h > 1500 * 1100)
313 // printf("VFrame::clear_objects 2 this=%p data=%p\n", this, data);
314                         if(data)
315                         {
316 //printf("VFrame::clear_objects %d this=%p shmid=%p data=%p\n", __LINE__, this, shmid, data);
317                                 if(shmid >= 0)
318                                         shmdt(data);
319                                 else
320                                         free(data);
321 //PRINT_TRACE
322                         }
323
324                         data = 0;
325                         shmid = -1;
326                         break;
327
328                 case VFrame::SHMGET:
329                         if(data)
330                                 shmdt(data);
331                         data = 0;
332                         shmid = -1;
333                         break;
334         }
335
336 // Delete row pointers
337         switch(color_model)
338         {
339                 case BC_COMPRESSED:
340                 case BC_YUV410P:
341                 case BC_YUV411P:
342                 case BC_YUV420P:
343                 case BC_YUV420PI:
344                 case BC_YUV422P:
345                 case BC_YUV444P:
346                 case BC_RGB_FLOATP:
347                 case BC_RGBA_FLOATP:
348                         break;
349
350                 default:
351                         delete [] rows;
352                         rows = 0;
353                         break;
354         }
355
356
357         return 0;
358 }
359
360 int VFrame::get_field2_offset()
361 {
362         return field2_offset;
363 }
364
365 int VFrame::set_field2_offset(int value)
366 {
367         this->field2_offset = value;
368         return 0;
369 }
370
371 void VFrame::set_keyframe(int value)
372 {
373         this->is_keyframe = value;
374 }
375
376 int VFrame::get_keyframe()
377 {
378         return is_keyframe;
379 }
380
381
382 VFrameScene* VFrame::get_scene()
383 {
384         return scene;
385 }
386
387 int VFrame::calculate_bytes_per_pixel(int color_model)
388 {
389         return BC_CModels::calculate_pixelsize(color_model);
390 }
391
392 long VFrame::get_bytes_per_line()
393 {
394         return bytes_per_line;
395 }
396
397 long VFrame::get_data_size()
398 {
399         return calculate_data_size(w, h, bytes_per_line, color_model) - 4;
400 }
401
402 long VFrame::calculate_data_size(int w, int h, int bytes_per_line, int color_model)
403 {
404         return BC_CModels::calculate_datasize(w, h, bytes_per_line, color_model);
405 }
406
407 void VFrame::create_row_pointers()
408 {
409         int sz = w * h;
410         switch(color_model) {
411         case BC_YUV410P:
412                 if( this->v_offset ) break;
413                 this->y_offset = 0;
414                 this->u_offset = sz;
415                 this->v_offset = sz + w / 4 * h / 4;
416                 break;
417
418         case BC_YUV420P:
419         case BC_YUV420PI:
420         case BC_YUV411P:
421                 if( this->v_offset ) break;
422                 this->y_offset = 0;
423                 this->u_offset = sz;
424                 this->v_offset = sz + sz / 4;
425                 break;
426
427         case BC_YUV422P:
428                 if( this->v_offset ) break;
429                 this->y_offset = 0;
430                 this->u_offset = sz;
431                 this->v_offset = sz + sz / 2;
432                 break;
433         case BC_YUV444P:
434                 if( this->v_offset ) break;
435                 this->y_offset = 0;
436                 this->u_offset = sz;
437                 this->v_offset = sz + sz;
438                 break;
439         case BC_RGBA_FLOATP:
440                 if( this->v_offset || a ) break;
441                 a = this->data + 3 * sz * sizeof(float);
442         case BC_RGB_FLOATP:
443                 if( this->v_offset ) break;
444                 this->y_offset = 0;
445                 this->u_offset = sz * sizeof(float);
446                 this->v_offset = 2 * sz * sizeof(float);
447                 break;
448
449         default:
450                 rows = new unsigned char*[h];
451                 for(int i = 0; i < h; i++)
452                         rows[i] = &this->data[i * this->bytes_per_line];
453                 return;
454         }
455         y = this->data + this->y_offset;
456         u = this->data + this->u_offset;
457         v = this->data + this->v_offset;
458 }
459
460 int VFrame::allocate_data(unsigned char *data, int shmid,
461                 long y_offset, long u_offset, long v_offset, int w, int h,
462                 int color_model, long bytes_per_line)
463 {
464         this->w = w;
465         this->h = h;
466         this->color_model = color_model;
467         this->bytes_per_pixel = calculate_bytes_per_pixel(color_model);
468         this->y_offset = this->u_offset = this->v_offset = 0;
469 //      if(shmid == 0) {
470 //              printf("VFrame::allocate_data %d shmid == 0\n", __LINE__, shmid);
471 //      }
472
473         this->bytes_per_line = bytes_per_line >= 0 ?
474                 bytes_per_line : this->bytes_per_pixel * w;
475
476 // Allocate data + padding for MMX
477         if(data) {
478 //printf("VFrame::allocate_data %d %p\n", __LINE__, this->data);
479                 memory_type = VFrame::SHARED;
480                 this->data = data;
481                 this->shmid = -1;
482                 this->y_offset = y_offset;
483                 this->u_offset = u_offset;
484                 this->v_offset = v_offset;
485         }
486         else if(shmid >= 0) {
487                 memory_type = VFrame::SHMGET;
488                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
489 //printf("VFrame::allocate_data %d shmid=%d data=%p\n", __LINE__, shmid, this->data);
490                 this->shmid = shmid;
491                 this->y_offset = y_offset;
492                 this->u_offset = u_offset;
493                 this->v_offset = v_offset;
494         }
495         else {
496                 memory_type = VFrame::PRIVATE;
497                 int size = calculate_data_size(this->w, this->h,
498                         this->bytes_per_line, this->color_model);
499                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm) {
500                         this->shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
501                         if(this->shmid < 0) {
502                                 printf("VFrame::allocate_data %d could not allocate shared memory\n", __LINE__);
503                         }
504
505                         this->data = (unsigned char*)shmat(this->shmid, NULL, 0);
506 //printf("VFrame::allocate_data %d %d %d\n", __LINE__, size, this->shmid);
507
508 //printf("VFrame::allocate_data %d %p\n", __LINE__, this->data);
509 // This causes it to automatically delete when the program exits.
510                         shmctl(this->shmid, IPC_RMID, 0);
511                 }
512                 else {
513 // Have to use malloc for libpng
514 //printf("==vframe %d from %p\n", size, __builtin_return_address(0));
515                         this->data = (unsigned char *)malloc(size);
516                 }
517
518 // Memory check
519 // if(this->w * this->h > 1500 * 1100)
520 // printf("VFrame::allocate_data 2 this=%p w=%d h=%d this->data=%p\n",
521 // this, this->w, this->h, this->data);
522
523                 if(!this->data)
524                         printf("VFrame::allocate_data %dx%d: memory exhausted.\n", this->w, this->h);
525
526 //printf("VFrame::allocate_data %d %p data=%p %d %d\n", __LINE__, this, this->data, this->w, this->h);
527 //if(size > 1000000) printf("VFrame::allocate_data %d\n", size);
528         }
529
530 // Create row pointers
531         create_row_pointers();
532         return 0;
533 }
534
535 void VFrame::set_memory(unsigned char *data,
536         int shmid,
537         long y_offset,
538         long u_offset,
539         long v_offset)
540 {
541         clear_objects(0);
542
543         if(data)
544         {
545                 memory_type = VFrame::SHARED;
546                 this->data = data;
547                 this->shmid = -1;
548                 this->y_offset = y_offset;
549                 this->u_offset = u_offset;
550                 this->v_offset = v_offset;
551         }
552         else
553         if(shmid >= 0)
554         {
555                 memory_type = VFrame::SHMGET;
556                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
557                 this->shmid = shmid;
558         }
559
560         y = this->data + this->y_offset;
561         u = this->data + this->u_offset;
562         v = this->data + this->v_offset;
563
564         create_row_pointers();
565 }
566
567 void VFrame::set_memory(BC_Bitmap *bitmap)
568 {
569         int shmid = 0;
570         unsigned char *data = 0;
571         if( bitmap->is_shared() && !bitmap->is_zombie() )
572                 shmid = bitmap->get_shmid();
573         else
574                 data = bitmap->get_data();
575         set_memory(data, shmid,
576                 bitmap->get_y_offset(),
577                 bitmap->get_u_offset(),
578                 bitmap->get_v_offset());
579 }
580
581 void VFrame::set_compressed_memory(unsigned char *data,
582         int shmid,
583         int data_size,
584         int data_allocated)
585 {
586         clear_objects(0);
587
588         if(data)
589         {
590                 memory_type = VFrame::SHARED;
591                 this->data = data;
592                 this->shmid = -1;
593         }
594         else
595         if(shmid >= 0)
596         {
597                 memory_type = VFrame::SHMGET;
598                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
599                 this->shmid = shmid;
600         }
601
602         this->compressed_allocated = data_allocated;
603         this->compressed_size = data_size;
604 }
605
606
607 // Reallocate uncompressed buffer with or without alpha
608 int VFrame::reallocate(
609         unsigned char *data,
610         int shmid,
611         long y_offset,
612         long u_offset,
613         long v_offset,
614         int w,
615         int h,
616         int color_model,
617         long bytes_per_line)
618 {
619 //      if(shmid == 0) printf("VFrame::reallocate %d shmid=%d\n", __LINE__, shmid);
620         clear_objects(0);
621 //      reset_parameters(0);
622         allocate_data(data,
623                 shmid,
624                 y_offset,
625                 u_offset,
626                 v_offset,
627                 w,
628                 h,
629                 color_model,
630                 bytes_per_line);
631         return 0;
632 }
633
634 int VFrame::allocate_compressed_data(long bytes)
635 {
636         if(bytes < 1) return 1;
637
638 // Want to preserve original contents
639         if(data && compressed_allocated < bytes)
640         {
641                 int new_shmid = -1;
642                 unsigned char *new_data = 0;
643                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
644                 {
645                         new_shmid = shmget(IPC_PRIVATE,
646                                 bytes,
647                                 IPC_CREAT | 0777);
648                         new_data = (unsigned char*)shmat(new_shmid, NULL, 0);
649                         shmctl(new_shmid, IPC_RMID, 0);
650                 }
651                 else
652                 {
653 // Have to use malloc for libpng
654                         new_data = (unsigned char *)malloc(bytes);
655                 }
656
657                 bcopy(data, new_data, compressed_allocated);
658 UNBUFFER(data);
659
660                 if(memory_type == VFrame::PRIVATE)
661                 {
662                         if(shmid > 0) {
663                                 if(data)
664                                         shmdt(data);
665                         }
666                         else
667                                 free(data);
668                 }
669                 else
670                 if(memory_type == VFrame::SHMGET)
671                 {
672                         if(data)
673                                 shmdt(data);
674                 }
675
676                 data = new_data;
677                 shmid = new_shmid;
678                 compressed_allocated = bytes;
679         }
680         else
681         if(!data)
682         {
683                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
684                 {
685                         shmid = shmget(IPC_PRIVATE,
686                                 bytes,
687                                 IPC_CREAT | 0777);
688                         data = (unsigned char*)shmat(shmid, NULL, 0);
689                         shmctl(shmid, IPC_RMID, 0);
690                 }
691                 else
692                 {
693 // Have to use malloc for libpng
694                         data = (unsigned char *)malloc(bytes);
695                 }
696
697                 compressed_allocated = bytes;
698                 compressed_size = 0;
699         }
700
701         return 0;
702 }
703
704 int VFramePng::read_png(const unsigned char *data, long sz, double xscale, double yscale)
705 {
706 // Test for RAW format
707         if(data[0] == 'R' && data[1] == 'A' && data[2] == 'W' && data[3] == ' ') {
708                 int new_color_model = BC_RGBA8888;
709                 w = data[4] | (data[5] << 8) | (data[6]  << 16) | (data[7]  << 24);
710                 h = data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
711                 int components = data[12];
712                 new_color_model = components == 3 ? BC_RGB888 : BC_RGBA8888;
713 // This shares the data directly
714 //              reallocate(data + 20, 0, 0, 0, w, h, new_color_model, -1);
715
716 // Can't use shared data for theme since button constructions overlay the
717 // images directly.
718                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
719                 memcpy(get_data(), data + 16, w * h * components);
720
721         }
722         else if(data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
723                 int have_alpha = 0;
724                 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
725                 png_infop info_ptr = png_create_info_struct(png_ptr);
726                 int new_color_model;
727
728                 image_offset = 0;
729                 image = data;  image_size = sz;
730                 png_set_read_fn(png_ptr, this, PngReadFunction::png_read_function);
731                 png_read_info(png_ptr, info_ptr);
732
733                 w = png_get_image_width(png_ptr, info_ptr);
734                 h = png_get_image_height(png_ptr, info_ptr);
735
736                 int src_color_model = png_get_color_type(png_ptr, info_ptr);
737
738                 /* tell libpng to strip 16 bit/color files down to 8 bits/color */
739                 png_set_strip_16(png_ptr);
740
741                 /* extract multiple pixels with bit depths of 1, 2, and 4 from a single
742                  * byte into separate bytes (useful for paletted and grayscale images).
743                  */
744                 png_set_packing(png_ptr);
745
746                 /* expand paletted colors into true RGB triplets */
747                 if (src_color_model == PNG_COLOR_TYPE_PALETTE)
748                         png_set_expand(png_ptr);
749
750                 /* expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
751                 if (src_color_model == PNG_COLOR_TYPE_GRAY && png_get_bit_depth(png_ptr, info_ptr) < 8)
752                         png_set_expand(png_ptr);
753
754                 if (src_color_model == PNG_COLOR_TYPE_GRAY ||
755                     src_color_model == PNG_COLOR_TYPE_GRAY_ALPHA)
756                         png_set_gray_to_rgb(png_ptr);
757
758                 /* expand paletted or RGB images with transparency to full alpha channels
759                  * so the data will be available as RGBA quartets */
760                 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)){
761                         have_alpha = 1;
762                         png_set_expand(png_ptr);
763                 }
764
765                 switch(src_color_model)
766                 {
767                         case PNG_COLOR_TYPE_GRAY:
768                         case PNG_COLOR_TYPE_RGB:
769                                 new_color_model = BC_RGB888;
770                                 break;
771
772                         case PNG_COLOR_TYPE_GRAY_ALPHA:
773                         case PNG_COLOR_TYPE_RGB_ALPHA:
774                         default:
775                                 new_color_model = BC_RGBA8888;
776                                 break;
777
778                         case PNG_COLOR_TYPE_PALETTE:
779                                 if(have_alpha)
780                                         new_color_model = BC_RGBA8888;
781                                 else
782                                         new_color_model = BC_RGB888;
783                 }
784
785                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
786
787 //printf("VFrame::read_png %d %d %d %p\n", __LINE__, w, h, get_rows());
788                 png_read_image(png_ptr, get_rows());
789                 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
790         }
791         else {
792                 printf("VFrame::read_png %d: unknown file format"
793                         " 0x%02x 0x%02x 0x%02x 0x%02x\n",
794                         __LINE__, data[4], data[5], data[6], data[7]);
795                 return 1;
796         }
797         int ww = w * xscale, hh = h * yscale;
798         if( ww != w || hh != h ) {
799                 VFrame vframe(*this);
800                 reallocate(NULL, -1, 0, 0, 0, ww, hh, color_model, -1);
801                 transfer_from(&vframe);
802         }
803         return 0;
804 }
805
806 int VFrame::write_png(const char *path)
807 {
808         VFrame *vframe = this;
809         png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
810         png_infop info_ptr = png_create_info_struct(png_ptr);
811         FILE *out_fd = fopen(path, "w");
812         if(!out_fd) {
813                 printf("VFrame::write_png %d %s %s\n", __LINE__, path, strerror(errno));
814                 return 1;
815         }
816
817         int png_cmodel = PNG_COLOR_TYPE_RGB;
818         int bc_cmodel = get_color_model();
819         switch( bc_cmodel ) {
820         case BC_RGB888:                                          break;
821         case BC_RGBA8888: png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA; break;
822         case BC_A8:       png_cmodel = PNG_COLOR_TYPE_GRAY;      break;
823         default:
824                 bc_cmodel = BC_RGB888;
825                 if( BC_CModels::has_alpha(bc_cmodel) ) {
826                         bc_cmodel = BC_RGBA8888;
827                         png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA;
828                 }
829                 vframe = new VFrame(get_w(), get_h(), bc_cmodel, -1);
830                 vframe->transfer_from(this);
831                 break;
832         }
833         png_init_io(png_ptr, out_fd);
834         png_set_compression_level(png_ptr, 9);
835         png_set_IHDR(png_ptr, info_ptr, get_w(), get_h(), 8, png_cmodel,
836                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
837         png_write_info(png_ptr, info_ptr);
838         png_write_image(png_ptr, vframe->get_rows());
839         png_write_end(png_ptr, info_ptr);
840         png_destroy_write_struct(&png_ptr, &info_ptr);
841         fclose(out_fd);
842         if( vframe != this ) delete vframe;
843         return 0;
844 }
845
846
847 #define ZERO_YUV(components, type, max) \
848 { \
849         for(int i = 0; i < h; i++) \
850         { \
851                 type *row = (type*)get_rows()[i]; \
852                 for(int j = 0; j < w; j++) \
853                 { \
854                         row[j * components] = 0; \
855                         row[j * components + 1] = (max + 1) / 2; \
856                         row[j * components + 2] = (max + 1) / 2; \
857                         if(components == 4) row[j * components + 3] = 0; \
858                 } \
859         } \
860 }
861
862 int VFrame::clear_frame()
863 {
864         int sz = w * h;
865 //printf("VFrame::clear_frame %d\n", __LINE__);
866         switch(color_model) {
867         case BC_COMPRESSED:
868                 break;
869
870         case BC_YUV410P:
871                 bzero(get_y(), sz);
872                 bzero(get_u(), w / 4 * h / 4);
873                 bzero(get_v(), w / 4 * h / 4);
874                 break;
875
876         case BC_YUV411P:
877         case BC_YUV420P:
878         case BC_YUV420PI:
879                 bzero(get_y(), sz);
880                 bzero(get_u(), sz / 4);
881                 bzero(get_v(), sz / 4);
882                 break;
883
884         case BC_YUV422P:
885                 bzero(get_y(), sz);
886                 bzero(get_u(), sz / 2);
887                 bzero(get_v(), sz / 2);
888                 break;
889
890         case BC_RGBA_FLOATP: if( a ) {
891                 float *ap = (float *)a;
892                 for( int i=sz; --i>=0; ++ap ) *ap = 1.f; }
893         case BC_RGB_FLOATP: {
894                 float *rp = (float *)y;
895                 for( int i=sz; --i>=0; ++rp ) *rp = 0.f;
896                 float *gp = (float *)u;
897                 for( int i=sz; --i>=0; ++gp ) *gp = 0.f;
898                 float *bp = (float *)v;
899                 for( int i=sz; --i>=0; ++bp ) *bp = 0.f;
900                 break; }
901         case BC_YUV444P:
902                 bzero(get_y(), sz);
903                 bzero(get_u(), sz);
904                 bzero(get_v(), sz);
905                 break;
906
907         case BC_YUV888:
908                 ZERO_YUV(3, unsigned char, 0xff);
909                 break;
910
911         case BC_YUVA8888:
912                 ZERO_YUV(4, unsigned char, 0xff);
913                 break;
914
915         case BC_YUV161616:
916                 ZERO_YUV(3, uint16_t, 0xffff);
917                 break;
918
919         case BC_YUVA16161616:
920                 ZERO_YUV(4, uint16_t, 0xffff);
921                 break;
922
923         default:
924                 bzero(data, calculate_data_size(w, h, bytes_per_line, color_model));
925                 break;
926         }
927         return 0;
928 }
929
930 void VFrame::rotate90()
931 {
932 // Allocate new frame
933         int new_w = h, new_h = w, new_bytes_per_line = bytes_per_pixel * new_w;
934         unsigned char *new_data = new unsigned char[calculate_data_size(new_w, new_h, new_bytes_per_line, color_model)];
935         unsigned char **new_rows = new unsigned char*[new_h];
936         for(int i = 0; i < new_h; i++)
937                 new_rows[i] = &new_data[new_bytes_per_line * i];
938
939 // Copy data
940         for(int in_y = 0, out_x = new_w - 1; in_y < h; in_y++, out_x--)
941         {
942                 for(int in_x = 0, out_y = 0; in_x < w; in_x++, out_y++)
943                 {
944                         for(int k = 0; k < bytes_per_pixel; k++)
945                         {
946                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
947                                         rows[in_y][in_x * bytes_per_pixel + k];
948                         }
949                 }
950         }
951
952 // Swap frames
953         clear_objects(0);
954         data = new_data;
955         rows = new_rows;
956         bytes_per_line = new_bytes_per_line;
957         w = new_w;
958         h = new_h;
959 }
960
961 void VFrame::rotate270()
962 {
963 // Allocate new frame
964         int new_w = h, new_h = w, new_bytes_per_line = bytes_per_pixel * new_w;
965         unsigned char *new_data = new unsigned char[calculate_data_size(new_w, new_h, new_bytes_per_line, color_model)];
966         unsigned char **new_rows = new unsigned char*[new_h];
967         for(int i = 0; i < new_h; i++)
968                 new_rows[i] = &new_data[new_bytes_per_line * i];
969
970 // Copy data
971         for(int in_y = 0, out_x = 0; in_y < h; in_y++, out_x++)
972         {
973                 for(int in_x = 0, out_y = new_h - 1; in_x < w; in_x++, out_y--)
974                 {
975                         for(int k = 0; k < bytes_per_pixel; k++)
976                         {
977                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
978                                         rows[in_y][in_x * bytes_per_pixel + k];
979                         }
980                 }
981         }
982
983 // Swap frames
984         clear_objects(0);
985         data = new_data;
986         rows = new_rows;
987         bytes_per_line = new_bytes_per_line;
988         w = new_w;
989         h = new_h;
990 }
991
992 void VFrame::flip_vert()
993 {
994         unsigned char *temp = new unsigned char[bytes_per_line];
995         for(int i = 0, j = h - 1; i < j; i++, j--)
996         {
997                 memcpy(temp, rows[j], bytes_per_line);
998                 memcpy(rows[j], rows[i], bytes_per_line);
999                 memcpy(rows[i], temp, bytes_per_line);
1000         }
1001         delete [] temp;
1002 }
1003
1004 void VFrame::flip_horiz()
1005 {
1006         unsigned char temp[32];
1007         for(int i = 0; i < h; i++)
1008         {
1009                 unsigned char *row = rows[i];
1010                 for(int j = 0; j < bytes_per_line / 2; j += bytes_per_pixel)
1011                 {
1012                         memcpy(temp, row + j, bytes_per_pixel);
1013                         memcpy(row + j, row + bytes_per_line - j - bytes_per_pixel, bytes_per_pixel);
1014                         memcpy(row + bytes_per_line - j - bytes_per_pixel, temp, bytes_per_pixel);
1015                 }
1016         }
1017 }
1018
1019
1020
1021 int VFrame::copy_from(VFrame *frame)
1022 {
1023         int w = MIN(this->w, frame->get_w());
1024         int h = MIN(this->h, frame->get_h());
1025         timestamp = frame->timestamp;
1026
1027         switch(frame->color_model)
1028         {
1029                 case BC_COMPRESSED:
1030                         allocate_compressed_data(frame->compressed_size);
1031                         memcpy(data, frame->data, frame->compressed_size);
1032                         this->compressed_size = frame->compressed_size;
1033                         break;
1034
1035                 case BC_YUV410P:
1036                         memcpy(get_y(), frame->get_y(), w * h);
1037                         memcpy(get_u(), frame->get_u(), w / 4 * h / 4);
1038                         memcpy(get_v(), frame->get_v(), w / 4 * h / 4);
1039                         break;
1040
1041                 case BC_YUV420P:
1042                 case BC_YUV420PI:
1043                 case BC_YUV411P:
1044 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1045                         memcpy(get_y(), frame->get_y(), w * h);
1046                         memcpy(get_u(), frame->get_u(), w * h / 4);
1047                         memcpy(get_v(), frame->get_v(), w * h / 4);
1048                         break;
1049
1050                 case BC_YUV422P:
1051 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1052                         memcpy(get_y(), frame->get_y(), w * h);
1053                         memcpy(get_u(), frame->get_u(), w * h / 2);
1054                         memcpy(get_v(), frame->get_v(), w * h / 2);
1055                         break;
1056
1057                 case BC_YUV444P:
1058 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1059                         memcpy(get_y(), frame->get_y(), w * h);
1060                         memcpy(get_u(), frame->get_u(), w * h);
1061                         memcpy(get_v(), frame->get_v(), w * h);
1062                         break;
1063                 default:
1064 // printf("VFrame::copy_from %d\n", calculate_data_size(w,
1065 //                              h,
1066 //                              -1,
1067 //                              frame->color_model));
1068 // Copy without extra 4 bytes in case the source is a hardware device
1069                         memmove(data, frame->data, get_data_size());
1070                         break;
1071         }
1072
1073         params->copy_from(frame->params);
1074         return 0;
1075 }
1076
1077 int VFrame::transfer_from(VFrame *that, int bg_color, int in_x, int in_y, int in_w, int in_h)
1078 {
1079         if( this->get_color_model() == that->get_color_model() &&
1080             this->get_w() == that->get_w() && this->get_h() == that->get_h() &&
1081             this->get_bytes_per_line() == that->get_bytes_per_line() )
1082                 return this->copy_from(that);
1083
1084         timestamp = that->timestamp;
1085 #if 0
1086         BC_CModels::transfer(
1087                 this->get_rows(), that->get_rows(),          // Packed data out/in
1088                 this->get_y(), this->get_u(), this->get_v(), // Planar data out/in
1089                 that->get_y(), that->get_u(), that->get_v(),
1090                 0, 0, that->get_w(), that->get_h(),          // Dimensions in/out
1091                 0, 0, this->get_w(), this->get_h(),
1092                 that->get_color_model(), this->get_color_model(), // Color models in/out
1093                 bg_color,                                    // alpha blend bg_color
1094                 that->get_bytes_per_line(),
1095                 this->get_bytes_per_line());                 // rowspans (of luma for YUV)
1096 #else
1097         unsigned char *in_ptrs[4], *out_ptrs[4];
1098         unsigned char **inp, **outp;
1099         if( BC_CModels::is_planar(that->get_color_model()) ) {
1100                 in_ptrs[0] = that->get_y();
1101                 in_ptrs[1] = that->get_u();
1102                 in_ptrs[2] = that->get_v();
1103                 in_ptrs[3] = that->get_a();
1104                 inp = in_ptrs;
1105         }
1106         else
1107                 inp = that->get_rows();
1108         if( BC_CModels::is_planar(this->get_color_model()) ) {
1109                 out_ptrs[0] = this->get_y();
1110                 out_ptrs[1] = this->get_u();
1111                 out_ptrs[2] = this->get_v();
1112                 out_ptrs[3] = this->get_a();
1113                 outp = out_ptrs;
1114         }
1115         else
1116                 outp = this->get_rows();
1117         BC_CModels::transfer(outp, this->get_color_model(),
1118                         0, 0, this->get_w(), this->get_h(),
1119                         this->get_bytes_per_line(),
1120                 inp, that->get_color_model(),
1121                         in_x, in_y, in_w, in_h,
1122                         that->get_bytes_per_line(),
1123                 bg_color);
1124 #endif
1125         params->copy_from(that->params);
1126         return 0;
1127 }
1128
1129
1130 int VFrame::get_scale_tables(int *column_table, int *row_table,
1131                         int in_x1, int in_y1, int in_x2, int in_y2,
1132                         int out_x1, int out_y1, int out_x2, int out_y2)
1133 {
1134         int i;
1135         float w_in = in_x2 - in_x1;
1136         float h_in = in_y2 - in_y1;
1137         int w_out = out_x2 - out_x1;
1138         int h_out = out_y2 - out_y1;
1139
1140         float hscale = w_in / w_out;
1141         float vscale = h_in / h_out;
1142
1143         for(i = 0; i < w_out; i++)
1144         {
1145                 column_table[i] = (int)(hscale * i);
1146         }
1147
1148         for(i = 0; i < h_out; i++)
1149         {
1150                 row_table[i] = (int)(vscale * i) + in_y1;
1151         }
1152         return 0;
1153 }
1154
1155 void VFrame::push_prev_effect(const char *name)
1156 {
1157         char *ptr;
1158         prev_effects.append(ptr = new char[strlen(name) + 1]);
1159         strcpy(ptr, name);
1160         if(prev_effects.total > MAX_STACK_ELEMENTS) prev_effects.remove_object(0);
1161 }
1162
1163 void VFrame::pop_prev_effect()
1164 {
1165         if(prev_effects.total)
1166                 prev_effects.remove_object(prev_effects.last());
1167 }
1168
1169 void VFrame::push_next_effect(const char *name)
1170 {
1171         char *ptr;
1172         next_effects.append(ptr = new char[strlen(name) + 1]);
1173         strcpy(ptr, name);
1174         if(next_effects.total > MAX_STACK_ELEMENTS) next_effects.remove_object(0);
1175 }
1176
1177 void VFrame::pop_next_effect()
1178 {
1179         if(next_effects.total)
1180                 next_effects.remove_object(next_effects.last());
1181 }
1182
1183 const char* VFrame::get_next_effect(int number)
1184 {
1185         if(!next_effects.total) return "";
1186         else
1187         if(number > next_effects.total - 1) number = next_effects.total - 1;
1188
1189         return next_effects.values[next_effects.total - number - 1];
1190 }
1191
1192 const char* VFrame::get_prev_effect(int number)
1193 {
1194         if(!prev_effects.total) return "";
1195         else
1196         if(number > prev_effects.total - 1) number = prev_effects.total - 1;
1197
1198         return prev_effects.values[prev_effects.total - number - 1];
1199 }
1200
1201 BC_Hash* VFrame::get_params()
1202 {
1203         return params;
1204 }
1205
1206 void VFrame::clear_stacks()
1207 {
1208         next_effects.remove_all_objects();
1209         prev_effects.remove_all_objects();
1210         params->clear();
1211         status = 1;
1212 }
1213
1214 void VFrame::copy_params(VFrame *src)
1215 {
1216         status = src->status;
1217         params->copy_from(src->params);
1218 }
1219
1220 void VFrame::copy_stacks(VFrame *src)
1221 {
1222         clear_stacks();
1223
1224         for(int i = 0; i < src->next_effects.total; i++)
1225         {
1226                 char *ptr;
1227                 next_effects.append(ptr = new char[strlen(src->next_effects.values[i]) + 1]);
1228                 strcpy(ptr, src->next_effects.values[i]);
1229         }
1230         for(int i = 0; i < src->prev_effects.total; i++)
1231         {
1232                 char *ptr;
1233                 prev_effects.append(ptr = new char[strlen(src->prev_effects.values[i]) + 1]);
1234                 strcpy(ptr, src->prev_effects.values[i]);
1235         }
1236
1237         copy_params(src);
1238 }
1239
1240 int VFrame::equal_stacks(VFrame *src)
1241 {
1242         for(int i = 0; i < src->next_effects.total && i < next_effects.total; i++)
1243         {
1244                 if(strcmp(src->next_effects.values[i], next_effects.values[i])) return 0;
1245         }
1246
1247         for(int i = 0; i < src->prev_effects.total && i < prev_effects.total; i++)
1248         {
1249                 if(strcmp(src->prev_effects.values[i], prev_effects.values[i])) return 0;
1250         }
1251
1252         if(!params->equivalent(src->params)) return 0;
1253         return 1;
1254 }
1255
1256 void VFrame::dump_stacks()
1257 {
1258         printf("VFrame::dump_stacks\n");
1259         printf("        next_effects:\n");
1260         for(int i = next_effects.total - 1; i >= 0; i--)
1261                 printf("                %s\n", next_effects.values[i]);
1262         printf("        prev_effects:\n");
1263         for(int i = prev_effects.total - 1; i >= 0; i--)
1264                 printf("                %s\n", prev_effects.values[i]);
1265 }
1266
1267 void VFrame::dump_params()
1268 {
1269         params->dump();
1270 }
1271
1272 void VFrame::dump()
1273 {
1274         printf("VFrame::dump %d this=%p\n", __LINE__, this);
1275         printf("    w=%d h=%d colormodel=%d rows=%p use_shm=%d shmid=%d\n",
1276                 w, h, color_model, rows, use_shm, shmid);
1277 }
1278
1279
1280 int VFrame::get_memory_usage()
1281 {
1282         if(get_compressed_allocated()) return get_compressed_allocated();
1283         return get_h() * get_bytes_per_line();
1284 }
1285
1286 void VFrame::set_pixel_color(int rgb)
1287 {
1288         pixel_rgb = rgb;
1289         int ir = 0xff & (pixel_rgb >> 16);
1290         int ig = 0xff & (pixel_rgb >> 8);
1291         int ib = 0xff & (pixel_rgb >> 0);
1292         bc_rgb2yuv(ir,ig,ib, ir,ig,ib);
1293         pixel_yuv =  (ir<<16) | (ig<<8) | (ib<<0);
1294 }
1295
1296 void VFrame::set_stiple(int mask)
1297 {
1298         stipple = mask;
1299 }
1300
1301 int VFrame::draw_pixel(int x, int y)
1302 {
1303         if( x < 0 || y < 0 || x >= get_w() || y >= get_h() ) return 1;
1304         if( draw_point ) return (this->*draw_point)(x, y);
1305
1306 #define DRAW_PIXEL(type, r, g, b) { \
1307         type **rows = (type**)get_rows(); \
1308         rows[y][x * components + 0] = r; \
1309         rows[y][x * components + 1] = g; \
1310         rows[y][x * components + 2] = b; \
1311         if( components == 4 ) \
1312                 rows[y][x * components + 3] = mx; \
1313 }
1314         int components = BC_CModels::components(color_model);
1315         int bch = BC_CModels::calculate_pixelsize(color_model) / components;
1316         int sz = 8*bch, mx = BC_CModels::is_float(color_model) ? 1 : (1<<sz)-1;
1317         int is_yuv = BC_CModels::is_yuv(color_model);
1318         int pixel_color = is_yuv ? pixel_yuv : pixel_rgb;
1319         int ir = 0xff & (pixel_color >> 16);  float fr = 0;
1320         int ig = 0xff & (pixel_color >> 8);   float fg = 0;
1321         int ib = 0xff & (pixel_color >> 0);   float fb = 0;
1322         if( (x+y) & stipple ) {
1323                 ir = 255 - ir;  ig = 255 - ig;  ib = 255 - ib;
1324         }
1325         if( BC_CModels::is_float(color_model) ) {
1326                 fr = ir / 255.;  fg = ig / 255.;  fb = ib / 255.;
1327                 mx = 1;
1328         }
1329         else if( (sz-=8) > 0 ) {
1330                 ir <<= sz;  ig <<= sz;  ib <<= sz;
1331         }
1332
1333         switch(get_color_model()) {
1334         case BC_RGB888:
1335         case BC_YUV888:
1336         case BC_RGBA8888:
1337         case BC_YUVA8888:
1338                 DRAW_PIXEL(uint8_t, ir, ig, ib);
1339                 break;
1340         case BC_RGB161616:
1341         case BC_YUV161616:
1342         case BC_RGBA16161616:
1343         case BC_YUVA16161616:
1344                 DRAW_PIXEL(uint16_t, ir, ig, ib);
1345                 break;
1346         case BC_RGB_FLOAT:
1347         case BC_RGBA_FLOAT:
1348                 DRAW_PIXEL(float, fr, fg, fb);
1349                 break;
1350         }
1351         return 0;
1352 }
1353
1354
1355 // Bresenham's
1356 void VFrame::draw_line(int x1, int y1, int x2, int y2)
1357 {
1358         if( y1 > y2 ) {
1359                 int tx = x1;  x1 = x2;  x2 = tx;
1360                 int ty = y1;  y1 = y2;  y2 = ty;
1361         }
1362
1363         int x = x1, y = y1;
1364         int dx = x2-x1, dy = y2-y1;
1365         int dx2 = 2*dx, dy2 = 2*dy;
1366         if( dx < 0 ) dx = -dx;
1367         int r = dx > dy ? dx : dy, n = r;
1368         int dir = 0;
1369         if( dx2 < 0 ) dir += 1;
1370         if( dy >= dx ) {
1371                 if( dx2 >= 0 ) do {     /* +Y, +X */
1372                         draw_pixel(x, y++);
1373                         if( (r -= dx2) < 0 ) { r += dy2;  ++x; }
1374                 } while( --n >= 0 );
1375                 else do {               /* +Y, -X */
1376                         draw_pixel(x, y++);
1377                         if( (r += dx2) < 0 ) { r += dy2;  --x; }
1378                 } while( --n >= 0 );
1379         }
1380         else {
1381                 if( dx2 >= 0 ) do {     /* +X, +Y */
1382                         draw_pixel(x++, y);
1383                         if( (r -= dy2) < 0 ) { r += dx2;  ++y; }
1384                 } while( --n >= 0 );
1385                 else do {               /* -X, +Y */
1386                         draw_pixel(x--, y);
1387                         if( (r -= dy2) < 0 ) { r -= dx2;  ++y; }
1388                 } while( --n >= 0 );
1389         }
1390 }
1391
1392 // g++ -dD -E - < /dev/null | grep DBL_EPSILON
1393 #ifndef __DBL_EPSILON__
1394 #define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
1395 #endif
1396 // weakest fraction * graphics integer range
1397 #define RND_EPSILON (__DBL_EPSILON__*65536)
1398
1399 class smooth_line {
1400         int rnd(double v) { return round(v)+RND_EPSILON; }
1401         VFrame *vframe;
1402 public:
1403         int sx, sy, ex, ey;     /* current point, end point */
1404         int xs, ys;             /* x/y quadrant sign -1/1 */
1405         int64_t A, B, C;        /* quadratic coefficients */
1406         int64_t r, dx, dy;      /* residual, dr/dx and dr/dy */
1407         int xmxx, xmxy;         /* x,y at apex */
1408         int done;
1409
1410         void init0(int x1,int y1, int x2,int y2, int x3,int y3, int top);
1411         void init1(int x1,int y1, int x2,int y2, int x3,int y3);
1412         int64_t rx() { return r + xs*8*dx + 4*A; }
1413         void moveX(int64_t r) {
1414                 dx += xs*A;   dy -= xs*B;
1415                 this->r = r;  sx += xs;
1416         }
1417         int64_t ry() { return r + 8*dy + 4*C; }
1418         void moveY(int64_t r) {
1419                 dx -= B;      dy += C;
1420                 this->r = r;  ++sy;
1421         }
1422         void draw();
1423
1424         smooth_line(VFrame *vframe) { this->vframe = vframe; this->done = 0; }
1425 };
1426
1427
1428 void smooth_line::draw()
1429 {
1430         if( done ) return;
1431         if( abs(dy) >= abs(dx) ) {
1432                 if( xs*(sx-xmxx) >= 0 ) {
1433                         if( ys > 0 ) { done = 1;  return; }
1434                         if( dy < 0 || ry() < 0 ) { moveY(ry()); goto xit; }
1435                         xmxx = ex;  xmxy = ey;
1436                         ys = 1;  xs = -xs;
1437                 }
1438                 moveX(rx());
1439                 int64_t rr = ry();
1440                 if( abs(rr) < abs(r) )
1441                         moveY(rr);
1442         }
1443         else {
1444                 if( sy >= xmxy ) {
1445                         if( ys > 0 ) { done = 1;  return; }
1446                         xmxx = ex;  xmxy = ey;
1447                         ys = 1;  xs = -xs;
1448                 }
1449                 moveY(ry());
1450                 int64_t rr = rx();
1451                 if( abs(rr) < abs(r) )
1452                         moveX(rr);
1453         }
1454 xit:    vframe->draw_pixel(sx, sy);
1455 }
1456
1457 void VFrame::draw_smooth(int x1, int y1, int x2, int y2, int x3, int y3)
1458 {
1459         if( (x1 == x2 && y1 == y2) || (x2 == x3 && y2 == y3) )
1460                 draw_line(x1,y1, x3,y3);
1461         else if( x1 == x3 && y1 == y3 )
1462                 draw_line(x1,y1, x2,y2);
1463         else if( (x2-x1) * (y2-y3) == (x2-x3) * (y2-y1) ) {
1464                 // co-linear, draw line from min to max
1465                 if( x1 < x3 ) {
1466                         if( x2 < x1 ) { x1 = x2;  y1 = y2; }
1467                         if( x2 > x3 ) { x3 = x2;  y3 = y2; }
1468                 }
1469                 else {
1470                         if( x2 > x1 ) { x1 = x2;  y1 = y2; }
1471                         if( x2 < x3 ) { x3 = x2;  y3 = y2; }
1472                 }
1473                 draw_line(x1,y1, x3,y3);
1474         }
1475         else
1476                 smooth_draw(x1, y1, x2, y2, x3, y3);
1477 }
1478
1479 /*
1480   Non-Parametric Smooth Curve Generation. Don Kelly 1984
1481
1482      P+-----+Q'= virtual
1483      /     /       origin
1484     /     /
1485   Q+-----+R
1486
1487    Let the starting point be P. the ending point R. and the tangent vertex Q.
1488    A general point Z on the curve is then
1489         Z = (P + R - Q) + (Q - P) sin t + (Q - R) cos t
1490
1491    Expanding the Cartesian coordinates around (P + R - Q) gives
1492         [x y] = Z - (P + R - Q)
1493         [a c] = Q - P
1494         [b d] = Q - R
1495         x = a*sin(t) + b*cos(t)
1496         y = c*sin(t) + d*cos(t)
1497
1498    from which t can now be eliminated via
1499         c*x - a*y = (c*b - a*d)*cos(t)
1500         d*x - b*y = (a*d - c*b)*sin(t)
1501
1502    giving the Cartesian equation for the ellipse as
1503         f(x, y) = (c*x - a*y)**2 + (d*x - b*y)**2 - (a*d - c*b)**2 = 0
1504
1505    or:  f(x, y) = A*x**2 - 2*B*x*y + C*y**2 + B**2 - A*C = 0
1506    where: A = c**2 + d**2,  B = a*c + b*d,  C = a**2 + b**2
1507
1508    The maximum y extent of the ellipse may now be derived as follows:
1509         let df/dx = 0,  2*A*x = 2*B*y,  x = y*B/A
1510         f(x, y) == B**2 * y**2 / A - 2*B**2 * y**2 / A + C*y**2 + B**2 - A*C = 0
1511            (A*C - B**2)*y = (A*C - B**2)*A
1512            max x = sqrt(C), at y = B/sqrt(C)
1513            max y = sqrt(A), at x = B/sqrt(A)
1514
1515  */
1516
1517
1518 /* x1,y1 = P, x2,y2 = Q, x3,y3=R,
1519  *  draw from P to Q to R   if top=0
1520  *    or from P to (x,ymax) if top>0
1521  *    or from Q to (x,ymax) if top<0
1522  */
1523 void smooth_line::init0(int x1,int y1, int x2,int y2, int x3,int y3, int top)
1524 {
1525         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1526
1527         int a = x2-x1,  c = y2-y1;
1528         int b = x2-x3,  d = y2-y3;
1529         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1530
1531         sx = top >= 0 ? x1 : x3;
1532         sy = top >= 0 ? y1 : y3;
1533         xs = x2 > sx || (x2==sx && (x1+x3-sx)>=x2) ? 1 : -1;
1534         int64_t px = sx-x0, py = sy-y0;
1535         dx = A*px - B*py;  dy = C*py - B*px;
1536         r = 0;
1537
1538         if( top ) {
1539                 double ymy = sqrt(A), ymx = B/ymy;
1540                 ex = x0 + rnd(ymx);
1541                 ey = y0 + rnd(ymy);
1542         }
1543         else {
1544                 ex = x3;  ey = y3;
1545         }
1546
1547         ys = a*b > 0 && (!top || top*xs*(b*c - a*d) > 0) ? -1 : 1;
1548         if( ys < 0 ) {
1549                 double xmx = xs*sqrt(C), xmy = B/xmx;
1550                 xmxx = x0 + rnd(xmx);
1551                 xmxy = y0 + rnd(xmy);
1552         }
1553         else {
1554                 xmxx = ex; xmxy = ey;
1555         }
1556 }
1557
1558 /*  x1,y1 = P, x2,y2 = Q, x3,y3=R,
1559  *  draw from (x,ymax) to P
1560  */
1561 void smooth_line::init1(int x1,int y1, int x2,int y2, int x3,int y3)
1562 {
1563         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1564
1565         int a = x2-x1,  c = y2-y1;
1566         int b = x2-x3,  d = y2-y3;
1567         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1568
1569         double ymy = -sqrt(A), ymx = B/ymy;
1570         int64_t px = rnd(ymx), py = rnd(ymy);
1571         sx = x0 + px;  ex = x1;
1572         sy = y0 + py;  ey = y1;
1573         xs = x2 > x1 || (x2==x1 && x3>=x2) ? 1 : -1;
1574         dx = A*px - B*py;  dy = C*py - B*px;
1575         r = 4 * (A*px*px - 2*B*px*py + C*py*py + B*B - A*C);
1576
1577         ys = a*b > 0 && xs*(b*c - a*d) < 0 ? -1 : 1;
1578         if( ys < 0 ) {
1579                 double xmx = xs*sqrt(C), xmy = B/xmx;
1580                 xmxx = x0 + rnd(xmx);
1581                 xmxy = y0 + rnd(xmy);
1582         }
1583         else {
1584                 xs = -xs;
1585                 xmxx = ex; xmxy = ey;
1586         }
1587         if( xs > 0 )
1588                 vframe->draw_pixel(sx, sy);
1589         while( xs*(sx-xmxx) < 0 && (xs*dx < 0 || rx() < 0) ) {
1590                 moveX(rx());
1591                 vframe->draw_pixel(sx, sy);
1592         }
1593 }
1594
1595
1596 void VFrame::smooth_draw(int x1, int y1, int x2, int y2, int x3, int y3)
1597 {
1598 //printf("p smooth_draw( %d,%d, %d,%d, %d,%d )\n", x1,y1,x2,y2,x3,y3);
1599         if( y1 > y3 ) {         // make y3 >= y1
1600                 int xt = x1;  x1 = x3;  x3 = xt;
1601                 int yt = y1;  y1 = y3;  y3 = yt;
1602         }
1603         if( y1 > y2 && y3 > y2 ) {
1604                 smooth_line lt(this), rt(this); // Q on bottom
1605                 lt.init1(x1, y1, x2, y2, x3, y3);
1606                 rt.init1(x3, y3, x2, y2, x1, y1);
1607                 while( !lt.done || !rt.done ) {
1608                         lt.draw();
1609                         rt.draw();
1610                 }
1611         }
1612         else if( y1 < y2 && y3 < y2 ) {
1613                 smooth_line lt(this), rt(this); // Q on top
1614                 lt.init0(x1, y1, x2, y2, x3, y3, 1);
1615                 draw_pixel(lt.sx, lt.sy);
1616                 rt.init0(x1, y1, x2, y2, x3, y3, -1);
1617                 draw_pixel(rt.sx, rt.sy);
1618                 while( !lt.done || !rt.done ) {
1619                         lt.draw();
1620                         rt.draw();
1621                 }
1622         }
1623         else {
1624                 smooth_line pt(this);           // Q in between
1625                 pt.init0(x1, y1, x2, y2, x3, y3, 0);
1626                 draw_pixel(pt.sx, pt.sy);
1627                 while( !pt.done ) {
1628                         pt.draw();
1629                 }
1630         }
1631 }
1632
1633 void VFrame::draw_rect(int x1, int y1, int x2, int y2)
1634 {
1635         draw_line(x1, y1, x2, y1);
1636         draw_line(x2, y1 + 1, x2, y2);
1637         draw_line(x2 - 1, y2, x1, y2);
1638         draw_line(x1, y2 - 1, x1, y1 + 1);
1639 }
1640
1641 void VFrame::draw_arrow(int x1, int y1, int x2, int y2, int sz)
1642 {
1643         double angle = atan((float)(y2 - y1) / (float)(x2 - x1));
1644         double angle1 = angle + (float)145 / 360 * 2 * M_PI;
1645         double angle2 = angle - (float)145 / 360 * 2 * M_PI;
1646         int s = x2 < x1 ? -1 : 1;
1647         int x3 = x2 + s * (int)(sz * cos(angle1));
1648         int y3 = y2 + s * (int)(sz * sin(angle1));
1649         int x4 = x2 + s * (int)(sz * cos(angle2));
1650         int y4 = y2 + s * (int)(sz * sin(angle2));
1651
1652 // Main vector
1653         draw_line(x1, y1, x2, y2);
1654 //      draw_line(x1, y1 + 1, x2, y2 + 1);
1655
1656 // Arrow line
1657         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x3, y3);
1658 // Arrow line
1659         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x4, y4);
1660 }
1661
1662 void VFrame::draw_x(int x, int y, int sz)
1663 {
1664         draw_line(x-sz,y-sz, x+sz,y+sz);
1665         draw_line(x+sz,y-sz, x-sz,y+sz);
1666 }
1667 void VFrame::draw_t(int x, int y, int sz)
1668 {
1669         draw_line(x,y-sz, x,y+sz);
1670         draw_line(x+sz,y, x-sz,y);
1671 }
1672
1673