CHDK Forum

Using CHDK => CHDK Releases => Topic started by: lapser on 22 / November / 2012, 17:01:34

Title: Shot Histogram Request
Post by: lapser on 22 / November / 2012, 17:01:34
I've been experimenting with using the get_histo_range(from,to) function to set exposure in a time lapse script. The main problem I'm having is the resolution of the histogram. The function returns the percent of the total samples in the range instead of just the total samples. The offending instruction is the last line in shot_histogram.c

 return (rng*100)/tot;

It should just be

  return rng;

You could then remove the "tot" variable completely, which makes the routine more efficient

You can get the total (tot) easily in Lua with:

tot=get_histo_range(0,1023)

Of course, this will break all current scripts that use get_histo_range. Considering the improvement, I think that it would be worth it. Old scripts could be modified to take advantage of the increased resolution, or be changed to:

x=(get_histo_range(from,to)*100)/get_histo_range(0,1023)

If you want to avoid breaking old scripts, one way would be to test for "histo_to" less than zero as a flag to return rng instead of return rng*100/tot. Here's what could be done without breaking old scripts, but my vote is for just changing to : return rng
Code: (c) [Select]
int shot_histogram_get_range(int histo_from, int histo_to)
// Examines the histogram, and returns the percentage of pixels that
// have luminance between histo_from and histo_to
{
 int x, tot, rng ;
 tot=0;
 rng=0;
 
//New Code 1
 int frng;
 frng=histo_to; //<0 flags full rng return
 if(histo_to<0)
 {
   histo_to=-histo_to;
 }
//End New Code 1

 if(!shot_histogram_isenabled()) // TODO we could return an error somehow
  return 0;
 for (x = 0 ; x < SHOT_HISTOGRAM_SAMPLES; x ++ ) 
 {
tot += shot_histogram[x];
if (x>=histo_from  && x <= histo_to) 
   {
  rng += shot_histogram[x];
   }
 }

//New Code 2
 if(frng<0)
 {
   return rng;
 }
//End New Code 2

 return (rng*100)/tot;
}
Title: Re: Shot Histogram Request
Post by: waterwingz on 22 / November / 2012, 17:21:13
Or just add a new function - a small code size increase to ensure backward compatability ?
Title: Re: Shot Histogram Request
Post by: lapser on 22 / November / 2012, 17:42:10
Or just add a new function - a small code size increase to ensure backward compatability ?
That would probably be better. Maybe an optional parameter

function get_histo_range(from,to,flag)

flag: 0 or nil=old way, 1 new way
Title: Re: Shot Histogram Request
Post by: lapser on 23 / November / 2012, 01:13:00
I broke down and compiled a custom version with "return rng;". What an improvement!

My test program takes a series of shots from -2 ev to +2 ev by varying the shutter speed. After each picture, I wrote out the histogram with the new values, and then truncated to the old values in a line underneath. The step size for the histogram is 64, out of 1024 total.

The attached file shows the Tv96 starting value for each series of shots. I wrote out 3 lines for each shot. The first line shows get_exp_count(), relative ev from -192 to +192, and then the total points from get_histo_range(0,1023), which doesn't vary.

The 2nd line is the modified histogram with the actual count. The 3rd line is the truncated histogram that the function currently produces. You can see how much more accurate the new function is.

If we're going to modify the function, it would be useful to have 4 optional input parameters  that set the rectangular area to sample from (like spot metering). Whenever at least one of these parameters is present, the function would return the new, full resolution value.
Title: Re: Shot Histogram Request
Post by: philmoz on 23 / November / 2012, 03:05:41
Returning the value alone doesn't really tell you much unless you also know the total as well.

The current code attempts to give you the percentage of the histogram in the range; but loses too much precision.

Changing the return to (rng*10000)/tot would give you 2 extra digits of precision; while still keeping the value camera independent. This is probably accurate enough; but (rng*100000)/tot would give 3 extra digits precision if you want.

As you say, you could calculate the total separately and use it in your script; but then your just moving the overhead from the C code to Lua code. Calculating the total in the C code is not much overhead (but should be done in 'build_shot_histogram' not 'shot_histogram_get_range' as it is now).

Adding 4 parameters to 'get_histo_range' to set the histo sample rectangle won't work as the histogram has already been calculated by the time you call this. It would need a new function to be called before you take the shot (the histogram is calculated in raw_savefile).

Phil.

Edit: A backwards compatible solution would be to add a new function called 'set_histo_params(x1,y1,x2,y2,precision)'. This would set the histo rectangle and the return value precision for 'get_histo_range'. The defaults if the function is not called would be full image & 100 so existing scripts would not be affected.
Title: Re: Shot Histogram Request
Post by: lapser on 23 / November / 2012, 13:13:24
Edit: A backwards compatible solution would be to add a new function called 'set_histo_params(x1,y1,x2,y2,precision)'. This would set the histo rectangle and the return value precision for 'get_histo_range'. The defaults if the function is not called would be full image & 100 so existing scripts would not be affected.
That sounds perfect. Since you don't know the full range of x and y, they would need to be fractions. 1000 is 1.000, 500 is 0.500 of the full range, for example.

Will you make it so no precision parameter returns the actual values? The function could also return the total number.

Another thing that would be extremely useful would be a function that returns the average brightness of all the pixels used for the histogram, within the area, in Apex96 units. I think it would just be the average pixel value normalized to bit depth, converted to Apex96 units. It might be called:  get_histo_exp96() or get_shot_exp96(). It would be the amount of over or underexposure. That is, if the pixel average is 50% of maximum, then the exp96() value would be 0.

[edit] Would it be possible for set_histo_params to rebuild the histogram (and brightness calculation) each time it's called, so you could get histograms and brightness from different parts of the same image?
Title: Re: Shot Histogram Request
Post by: philmoz on 23 / November / 2012, 18:47:13
Edit: A backwards compatible solution would be to add a new function called 'set_histo_params(x1,y1,x2,y2,precision)'. This would set the histo rectangle and the return value precision for 'get_histo_range'. The defaults if the function is not called would be full image & 100 so existing scripts would not be affected.
That sounds perfect. Since you don't know the full range of x and y, they would need to be fractions. 1000 is 1.000, 500 is 0.500 of the full range, for example.

Will you make it so no precision parameter returns the actual values? The function could also return the total number.

I was offering a suggestion for doing this in a way that would not break existing scripts, plus offer better functionality.

CHDK is a collaborative effort - since you have some development experience you can implement something like this if you think it would be useful, and submit a patch for inclusion in the core code.

Quote
Another thing that would be extremely useful would be a function that returns the average brightness of all the pixels used for the histogram, within the area, in Apex96 units. I think it would just be the average pixel value normalized to bit depth, converted to Apex96 units. It might be called:  get_histo_exp96() or get_shot_exp96(). It would be the amount of over or underexposure. That is, if the pixel average is 50% of maximum, then the exp96() value would be 0.

The shot histogram is calculated from the RAW sensor data (scaled to 10 bits), and ignores the RGB BAYER pattern of the sensor.

The average value of this data on its own is not a measure of brightness or exposure. The sensor data is linear, you would first need to demosaic the BAYER sensor data then apply a tone curve, and then you would have to factor in the shutter speed, aperture and ISO used to take the image.

I can't see how this would tell you anything about under or over exposure of the image.

Quote
[edit] Would it be possible for set_histo_params to rebuild the histogram (and brightness calculation) each time it's called, so you could get histograms and brightness from different parts of the same image?

No, the shot histogram is calculated from the RAW sensor data at the time the image is captured. On most cameras this data is destroyed during the JPEG conversion process so the shot histogram can't be recalculated later.

Phil.

Title: Re: Shot Histogram Request
Post by: lapser on 23 / November / 2012, 22:09:09
CHDK is a collaborative effort - since you have some development experience you can implement something like this if you think it would be useful, and submit a patch for inclusion in the core code.
OK, I've been avoiding getting into the C programming side of CHDK, but I guess it's time to cross that bridge. I really appreciate your input and in depth knowledge of CHDK.


Title: Re: Shot Histogram Request
Post by: waterwingz on 23 / November / 2012, 22:21:07
OK, I've been avoiding getting into the C programming side of CHDK, but I guess it's time to cross that bridge.
Its a pretty small group of developers from CHDK beginning to current state when you think about how many Canon P&S cameras are out there in people's purses, pockets and desk drawers and even about how many people have found some pleasure / amusement from using CHDK.

I think philmoz was suggesting all help is appreciated .. although debate about coding style, quality, value of  features and functions, testing and documentation come with the territory.
Title: Re: Shot Histogram Request
Post by: lapser on 23 / November / 2012, 22:58:33
OK, I've been avoiding getting into the C programming side of CHDK, but I guess it's time to cross that bridge.
Its a pretty small group of developers from CHDK beginning to current state when you think about how many Canon P&S cameras are out there in people's purses, pockets and desk drawers and even about how many people have found some pleasure / amusement from using CHDK.

I think philmoz was suggesting all help is appreciated .. although debate about coding style, quality, value of  features and functions, testing and documentation come with the territory.
OK, I figured out how to compile with the windows shell. Can you explain the patch and diff files? If I just change the source files, how do I create the patch file to submit for inclusion in CHDK? If you have a link, that would be great, too.
Title: Re: Shot Histogram Request
Post by: philmoz on 23 / November / 2012, 23:05:44
OK, I've been avoiding getting into the C programming side of CHDK, but I guess it's time to cross that bridge.
Its a pretty small group of developers from CHDK beginning to current state when you think about how many Canon P&S cameras are out there in people's purses, pockets and desk drawers and even about how many people have found some pleasure / amusement from using CHDK.

I think philmoz was suggesting all help is appreciated .. although debate about coding style, quality, value of  features and functions, testing and documentation come with the territory.
OK, I figured out how to compile with the windows shell. Can you explain the patch and diff files? If I just change the source files, how do I create the patch file to submit for inclusion in CHDK? If you have a link, that would be great, too.

If you're using Windows then TortoiseSVN is the easiest thing to use.

Create a local repository from the CHDK SVN server.
Install TortoiseSVN then right click somewhere in Windows Explorer and select 'Repo borwser'.
Enter https://tools.assembla.com/svn/chdk as the URL.
When it finishes loading right click on the 'trunk' folder and select 'Checkout' - enter a local directory to store your copy.

After you've made your changes, then you can create the patch file using TortoiseSVN.

I also find WinMerge a very useful tool for comparing source trees.

Phil.
Title: Re: Shot Histogram Request
Post by: waterwingz on 24 / November / 2012, 00:38:45
If you're using Windows then TortoiseSVN is the easiest thing to use.

Create a local repository from the CHDK SVN server.
Install TortoiseSVN then right click somewhere in Windows Explorer and select 'Repo borwser'.
Enter https://tools.assembla.com/svn/chdk as the URL.
When it finishes loading right click on the 'trunk' folder and select 'Checkout' - enter a local directory to store your copy.
You can also get the 1.1.0 branch using a similiar process. 

It took me a while but I figured out how to make a batch file  to build the directories downloaded from the svn using the CHDK-Shell tools.    I never did figure out a way to use CHDK-Shell and Tortoise SVN together - CHDK-Shell likes to do things its own way.   CHDK-Shell is a great tool for building the latest version of CHDK - don't get me wrong - but for development that you want to submit patch files back to the svn for - Tortoise SVN and a batch build file will cover that better.


Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 01:36:55
Thanks for the info. I noticed that CHDK shell has a button for "source code tools" which opens a window with diff and patch options. Do you have any information on what that does?

The shot histogram is calculated from the RAW sensor data (scaled to 10 bits), and ignores the RGB BAYER pattern of the sensor.

The average value of this data on its own is not a measure of brightness or exposure. The sensor data is linear, you would first need to demosaic the BAYER sensor data then apply a tone curve, and then you would have to factor in the shutter speed, aperture and ISO used to take the image.
I'm trying to use the shot_histogram data to adjust the exposure when taking multiple shots with "shoot_full_only." I know the eV of the first picture, and want to know the change in ev compared to the first image. I'm hoping to be able to compute that from the histogram.

Now that I can get accurate values for all 1024 histogram points, I can experiment in Lua to see how that relates to eV. I'm thinking I can choose an area, say the upper left, that contains only sky. As the sun goes down, the sky gets darker and the average of the histogram data decreases. I'll try to relate that to eV. I'm not trying to set camera exposure from scratch, just sense slow lighting changes and slowly change exposure to compensate.

I noticed that the histogram ignores RGB and steps by 31. I assume it's sampling R, G, and B pixels alternately that way? Wouldn't averaging a large enough area be related to luminosity, especially if it was clear sky?
==
Again, thanks for all the help.
Title: Re: Shot Histogram Request
Post by: philmoz on 24 / November / 2012, 01:51:23
Thanks for the info. I noticed that CHDK shell has a button for "source code tools" which opens a window with diff and patch options. Do you have any information on what that does?

Probably creates and applies patches - haven't used it so I can't say for sure.
If you make some changes then run the diff tool see if it generates a .patch or a .diff file with the changes.

Quote
The shot histogram is calculated from the RAW sensor data (scaled to 10 bits), and ignores the RGB BAYER pattern of the sensor.

The average value of this data on its own is not a measure of brightness or exposure. The sensor data is linear, you would first need to demosaic the BAYER sensor data then apply a tone curve, and then you would have to factor in the shutter speed, aperture and ISO used to take the image.
I'm trying to use the shot_histogram data to adjust the exposure when taking multiple shots with "shoot_full_only." I know the eV of the first picture, and want to know the change in ev compared to the first image. I'm hoping to be able to compute that from the histogram.

Now that I can get accurate values for all 1024 histogram points, I can experiment in Lua to see how that relates to eV. I'm thinking I can choose an area, say the upper left, that contains only sky. As the sun goes down, the sky gets darker and the average of the histogram data decreases. I'll try to relate that to eV. I'm not trying to set camera exposure from scratch, just sense slow lighting changes and slowly change exposure to compensate.

I noticed that the histogram ignores RGB and steps by 31. I assume it's sampling R, G, and B pixels alternately that way? Wouldn't averaging a large enough area be related to luminosity, especially if it was clear sky?

Have a look at the 'get_bv96' Lua function - it may give you what you need.

Phil.
Title: Re: Shot Histogram Request
Post by: msl on 24 / November / 2012, 05:02:38
I never did figure out a way to use CHDK-Shell and Tortoise SVN together - CHDK-Shell likes to do things its own way.
It's not a big deal. You need only observe the subdir structures of the CHDK shell.

The shell create 2 subdirs for the CHDK source code: 'branches' & 'trunk'. In 'trunk' dir you find dirs like 'trunk2315'. This is the source code folder of trunk with revision 2315. The same in 'branches'. There begins the dir name with the branch name, e.g. 'philmoz-uitest2283'.

You can create new folders in 'trunk' & 'branches' for tortoise, e.g. 'trunk_work' in trunk dir or  'philmoz-uitest_work' in branches dir. In this folder you can check out a working copy of svn source code.

In the CHDK shell you choose the working copy with the button 'Change'.

Note: The CHDK shell modified some files of the source code, e.g. version.inc. You can reset this changes with an option of the CHDK shell context menu 'Reset Build Options ...'. This is important for the creation of a clean patch file.

I noticed that CHDK shell has a button for "source code tools" which opens a window with diff and patch options. Do you have any information on what that does?
In the shell you can see a big number of the revision. Click left beside this number and you can create a copy of the current source code. This is your working copy. In 'source code tools' you can make a patch file with the option 'diff'. You can choose a reference. With the option 'patch' you can insert patch files in the current source code.

I think, using tortoise is the better and more comfortable way.

msl


Title: Re: Shot Histogram Request
Post by: waterwingz on 24 / November / 2012, 08:56:17
I never did figure out a way to use CHDK-Shell and Tortoise SVN together - CHDK-Shell likes to do things its own way.
It's not a big deal. You need only observe the subdir structures of the CHDK shell.
If you use the "DOS box" icon in  CHDK-Shell,  the banner text tells you what to type in to build a particular camera & firmware version.  Using that,  you can change to wherever your SVN trunk is locate and compile.

I noticed that CHDK shell has a button for "source code tools" which opens a window with diff and patch options. Do you have any information on what that does?
In the shell you can see a big number of the revision. Click left beside this number and you can create a copy of the current source code. This is your working copy. In 'source code tools' you can make a patch file with the option 'diff'. You can choose a reference. With the option 'patch' you can insert patch files in the current source code.
The diff function works but using Tortoise SVN allows you to create patch files that are 100% usable by the devs. I only played with diff for a bit but was never able to really get the same compatibility.



Title: Re: Shot Histogram Request
Post by: msl on 24 / November / 2012, 09:21:07
If you use the "DOS box" icon in  CHDK-Shell,  the banner text tells you what to type in to build a particular camera & firmware version.  Using that,  you can change to wherever your SVN trunk is locate and compile
That's another way but not my way. I'm not the command line junkie.  ;)

The CHDK shell is really a great tool. But you're right the diff tool is not 100% useable.

msl
Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 12:41:21
static int luaCB_shot_histo_enable( lua_State* L )
{
  shot_histogram_set(luaL_checknumber( L, 1 ));
  return 0;
}

I want to change shot_histo_enable(1) to shot_histo_enable(1,x1,y1,x2,y2) where the new parameters are optional. How do I tell if the number of parameters is 1 or 5?

It looks like the total number of pixel samples can be returned by shot_histogram_set, and this value returned by Lua without breaking any old scripts. Is this correct?

lua_pushnumber( L, total )
Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 13:11:07
Have a look at the 'get_bv96' Lua function - it may give you what you need.
get_bv96() will give me a valid value for the first shot, but the rest of the shots are done with "shoot_full_only" without releasing "half_shoot". If I also compute the average of the histogram data for the first shot and save it, I have an eV reference point. If the average pixel value of subsequent shots goes above this reference, I know I'm over exposed, and can reduce exposure in the next shot.

My test script saves tv0 from get_tv96() after a half_shoot. It then takes a series of exposure bracketed shots from -2 ev to +2 ev in 1/3 ev increments, and prints the shot histogram for each shot (both truncated and full resolution), so you can see how the shot_histogram changes with each 1/3 ev step. I can use these test shots to calibrate how the histogram brightness average translates to eV changes. I'm not sure how well it will work, but it's a stab at adjusting exposure without the overhead of measuring it before each shot in a time lapse.

The log file from my test script is here:
http://chdk.setepontos.com/index.php?topic=8997.msg93658#msg93658 (http://chdk.setepontos.com/index.php?topic=8997.msg93658#msg93658)
Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 14:03:29
int newshot=0;

void build_shot_histogram()
{
  newshot=1;
  if(!shot_histogram_isenabled())
    return;
. . .
}

int shot_ready()
{
  ns=newshot;
  newshot=0;
  return ns;
}

This is my idea to tell when a new picture is ready when using "shoot_full_only". Currently, I'm using this method:

nxp=get_exp_count()
press("shoot_full_only")
while(nxp==get_exp_count)do sleep(10) end

With the shot_ready() function above, I could change the last line to:

repeat sleep(10) until shot_ready()

Do you know if build_shot_histogram() is called right after each picture, regardless of whether or not shot_histo is enabled? Thanks.
Title: Re: Shot Histogram Request
Post by: philmoz on 24 / November / 2012, 16:31:17
static int luaCB_shot_histo_enable( lua_State* L )
{
  shot_histogram_set(luaL_checknumber( L, 1 ));
  return 0;
}

I want to change shot_histo_enable(1) to shot_histo_enable(1,x1,y1,x2,y2) where the new parameters are optional. How do I tell if the number of parameters is 1 or 5?

It looks like the total number of pixel samples can be returned by shot_histogram_set, and this value returned by Lua without breaking any old scripts. Is this correct?

lua_pushnumber( L, total )

Use luaL_optnumber, third parameter is default value if the parameter is not included.
Code: [Select]
  coord x1 =luaL_optnumber(L,2,0);
  coord y1 =luaL_optnumber(L,3,0);
  coord x2 =luaL_optnumber(L,4,100);
  coord y2 =luaL_optnumber(L,5,100);

Phil.
Title: Re: Shot Histogram Request
Post by: philmoz on 24 / November / 2012, 16:32:32
Do you know if build_shot_histogram() is called right after each picture, regardless of whether or not shot_histo is enabled? Thanks.

build_shot_histogram is only called if a script is running and shot_histogram_isenabled returns true.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 17:22:00
build_shot_histogram is only called if a script is running and shot_histogram_isenabled returns true.
Thanks. I was able to add shot_ready() and test it, and it didn't work right anyway. It was a good exercise in learning to add Lua functions though.

Use luaL_optnumber, third parameter is default value if the parameter is not included.
Thanks again Phil. You're a great resource. I'll give it a try.

By the way, the zoom lever on the variable speed zoom sx260 works perfectly now.
Title: Re: Shot Histogram Request
Post by: lapser on 24 / November / 2012, 20:31:11
I was able to modify get_histo_range to add an optional 3rd parameter:
get_histo_range(from, to [, scale])

It should work with older scripts in Lua or uBasic. Here's the code from my test script:
Code: (lua) [Select]
    step=64
    for i=0,1023,step do
      hrange=get_histo_range(i,i+step)
      hfile:write(string.format("%5d",hrange))
    end
    hfile:write("\n")
    for i=0,1023,step do
      hrange=get_histo_range(i,i+step,1000)
      hfile:write(string.format("%5d",hrange))
    end
    hfile:write("\n")
    for i=0,1023,step do
      hrange=get_histo_range(i,i+step,0)
      hfile:write(string.format("%5d",hrange))
    end
It produces this output:
    0    2    1    1    1    2    5   13    9    6   12    6    3    8   14   11
    8   21   13   12   17   27   54  132   94   62  122   67   37   80  146  114
  107  253  166  154  211  331  657 1587 1130  753 1473  806  455  964 1756 1376

I was able to create "patch.txt" and "patch.diff" test files with CHDK shell, which are attached. Could you make changes using these files?

I'll add the range option to build_shot_histogram, and clean up the code next.
Title: Re: Shot Histogram Request
Post by: lapser on 25 / November / 2012, 20:58:34
I'm making some progress on the shot_histo modifications. I decided that adding a new function to set the histogram window was best. Here's the new function I added:

total_pixels=set_histo_area(xp1,yp1,xp2,yp2)

The xp and yp parameters are percentages, from 0 to 100, of the total histogram area. They default to 0,0,100,100, so you can call:  pix=set_histo_area() to reset to the defaults. shot_histo_set(1) also resets the full area default values.

From looking at the Bayer filter pictures, it looks likes if I use an odd number step size when sampling the raw pixels, I'll alternate between 2 colors and get a better estimate of luminace. I'm planning to add up all the pixel values and return the average as a 2nd parameter from get_histo_range, possibly converted to an APEX96 value if I can figure it out. A brightness of 50% of full white will return an APEX96 value of 0. It should be interesting.

range,average_brightness=get_histo_range(from, to, scale)

Any ideas or suggestions would be appreciated.
Title: Re: Shot Histogram Request
Post by: philmoz on 27 / November / 2012, 03:30:53
From looking at the Bayer filter pictures, it looks likes if I use an odd number step size when sampling the raw pixels, I'll alternate between 2 colors and get a better estimate of luminace.

You would probably be better to just sample the green channel.
My understanding is that the red and blue pixels are less sensitive (probably due to the color filter) and require a different tone curve. Sticking with just one channel should be more consistent across the image.

Quote
I'm planning to add up all the pixel values and return the average as a 2nd parameter from get_histo_range, possibly converted to an APEX96 value if I can figure it out. A brightness of 50% of full white will return an APEX96 value of 0.

What does the average of the raw sensor pixels tell you?
Why would an APEX number be any better than a value from 0 -1023?

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 27 / November / 2012, 06:46:06
Quote
I'm planning to add up all the pixel values and return the average as a 2nd parameter from get_histo_range, possibly converted to an APEX96 value if I can figure it out. A brightness of 50% of full white will return an APEX96 value of 0.
What does the average of the raw sensor pixels tell you?
Why would an APEX number be any better than a value from 0 -1023?
Phil.
I'm hoping to be able to use the average to set the shutter speed for the next shot in a time lapse. Since I need to enter an Apex96 value for shutter speed (and ISO), it would be best if the value I return is also Apex96. The absolute value of the average won't mean much, but how it changes between shots will tell me how to adjust the exposure for the next shot. It will take some experimenting to figure it out. I added a new function called:
get_histo_sum() to return the value. It's less confusing than returning a second value in get_histo_range(..)

I did get my new function working:

total_samples=set_histo_area(10,10,90,50)

I added some test code to get_raw_pixel(x,y) that stores a line off 0xff at the sampled pixel location. Then, I look at the pattern of dots to see if I have the right area. Also, by setting the step size to 1 (by mistake), I turned the entire area white.

One thing I noticed is that the old shot_histo used the entire sensor area minus a margin, so the dot pattern of samples went off screen to the left. I used the sensor active area values, and my sample area appears to be correctly centered.

I've attached a test picture which shows the area produced by the Lua statement above and my step size 1 bug. The lens distortion correction in the jpg makes it look like a sheet hanging on the line.
Title: Re: Shot Histogram Request
Post by: lapser on 30 / November / 2012, 04:06:52
Here's two test images that show the progress I'm making on shot_histo. They demonstrate the ability to set the area where the histogram is taken from. After I sampled each pixel and added it to the histogram, I called set_raw_pixel to set it to the WHITE_LEVEL. The resulting colored dots show the Bayer pattern in the area sampled. The normal step size is around 31 pixels, but I sample more pixels as the area gets smaller, keeping the total around 12,000 samples.

The first picture shows the sampled area in the center at about 30% of the full image. The 12,000 sampled pixels are more dense in the smaller area.

The second picture shows samples in the entire picture, so the histogram will reflect the entire image. However, I also add up the values of all the pixels to get a sum that roughly corresponds to exposure. I'm hoping to be able to adjust exposure using this value. The center dark area was also sampled for the histogram. But the sum of the pixels is computed from only the center area. That is, you can specify an area within the histogram where the sum will be calculated; a kind of spot metering.

[EDIT] Right Click, save or open full resolution image in new tab, click to expand so you can see the dot pattern.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2F34z6I.jpg&hash=695c6a5cbc92539b509d18a208b3cfff)

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FMlQFe.jpg&hash=9769347d1064239300f9c35b8c2fc9a7)
Title: Shot Histogram Sum experiment success!
Post by: lapser on 30 / November / 2012, 22:11:57
For this experiment, I had the camera calculate a shutter speed with half press. Then, I did a series of shots of a blank wall with shoot_full_only, varying the shutter speed from -192 to +192 relative to the calculated shutter speed. The change in tV exposure is -32 ev each time.

After each shot, I added up 12,000 evenly spaced pixel samples from the inner 50% of the raw image buffer, alternating pixel colors in the Bayer patern, (RGBG or similar). I took the sum of all pixels (12 bits each in this camera), and did a LOG base 2, multiplied by 96 (I call HSUM96). The printed values on the right are the HSUM96 minus the HSUM96 of the previous picture. The change in exposure is always -32 (1/3 ev). The HSUM96 is close to that, and the offset appears linear, so I should be able to find a constant to correct for it.

It looks like the idea of adding up the sum of pixels is a success, and should prove useful in setting the exposure of the next shot based on the sampled pixel sum from the last shot. By eliminating the half-shoot before each picture, this saves about 2 seconds between shots. Maximum speed apears to be about 1.5 shots per second this way.
 
Code: [Select]
  ev+- | deltaHSUM96
  -192     0
  -160   -33
  -128   -29
   -96   -29
   -64   -29
   -32   -27
     0   -27
    32   -26
    64   -23
    96   -23
   128   -22
   160   -18
   192   -19

  -192   304
  -160   -30
  -128   -31
   -96   -28
   -64   -29
   -32   -29
     0   -25
    32   -26
    64   -25
    96   -21
   128   -21
   160   -20
   192   -16

  -192   301
  -160   -30
  -128   -26
   -96   -31
   -64   -30
   -32   -26
     0   -27
    32   -26
    64   -23
    96   -24
   128   -22
   160   -18
   192   -18

  -192   300
  -160   -28
  -128   -31
   -96   -30
   -64   -27
   -32   -29
     0   -27
    32   -24
    64   -25
    96   -23
   128   -21
   160   -20
   192   -17

  -192   303
  -160   -30
  -128   -31
   -96   -27
   -64   -29
   -32   -28
     0   -24
    32   -27
    64   -25
    96   -21
   128   -22
   160   -20
   192   -17

Fri Nov 30 18:09:04 2012
  -192     0
  -160   -32
  -128   -31
   -96   -27
   -64   -30
   -32   -28
     0   -25
    32   -26
    64   -25
    96   -20
   128   -22
   160   -19
   192   -17

Fri Nov 30 18:09:29 2012
  -192     0
  -160   -28
  -128   -30
   -96   -31
   -64   -26
   -32   -28
     0   -27
    32   -25
    64   -25
    96   -23
   128   -19
   160   -20
   192   -19

  -192   301
  -160   -28
  -128   -31
   -96   -30
   -64   -27
   -32   -27
     0   -28
    32   -23
    64   -25
    96   -23
   128   -20
   160   -20
   192   -19
Title: Re: Shot Histogram Request
Post by: lapser on 01 / December / 2012, 00:27:00
I found the problem in the first experiment. I corrected for the non-zero black level in each pixel.
changed:  p=get_raw_pixel(x,y);
to:
p=((get_raw_pixel(x,y)-CAM_BLACK_LEVEL)*CAM_WHITE_LEVEL)/(CAM_WHITE_LEVEL-CAM_BLACK_LEVEL);

Here's the results. Remember the right column should all be -32, and it looks like it's pretty close now. It's certainly close enough to use for setting exposure without a half shoot. The small error now is probably from truncation. I can fix that by moving the black level correction out of the pixel level loop and correcting the total sum. Correcting the histogram gets trickier, but it should be possible. That will speed up the 12,000 points loop too.
Code: [Select]
  ev+- | deltaHSUM96
  -192     0
  -160   -29
  -128   -29
   -96   -30
   -64   -32
   -32   -29
     0   -32
    32   -32
    64   -29
    96   -32
   128   -32
   160   -30
   192   -32
   
  -192   366
  -160   -32
  -128   -29
   -96   -31
   -64   -32
   -32   -30
     0   -32
    32   -32
    64   -30
    96   -32
   128   -33
   160   -30
   192   -32
   
  -192   375
  -160   -32
  -128   -30
   -96   -32
   -64   -33
   -32   -29
     0   -32
    32   -33
    64   -30
    96   -32
   128   -32
   160   -29
   192   -33
   
  -192   378
  -160   -32
  -128   -33
   -96   -29
   -64   -33
   -32   -33
     0   -29
    32   -32
    64   -32
    96   -30
   128   -32
   160   -32
   192   -30
Title: Re: Shot Histogram Request
Post by: lapser on 02 / December / 2012, 10:22:10
In my last post, I figured out how to correct for the black level by adjusting each of the 12,000 pixel samples with this formula:
p=((get_raw_pixel(x,y)-CAM_BLACK_LEVEL)*CAM_WHITE_LEVEL)/(CAM_WHITE_LEVEL-CAM_BLACK_LEVEL);

To avoid doing 12,000 new multiplications and 12,000 new divisions, not to mention subtractions and additions and truncations, I tried to do the correction to the final sum:
hsum=(((hsum-CAM_BLACK_LEVEL*npts)*CAM_WHITE_LEVEL))/(CAM_WHITE_LEVEL-CAM_BLACK_LEVEL);
This led me down the overflow road to long int land, which got more complicated than I wanted. I decided to sleep on it.

This morning, I realized that since my result is log2_96(hsum), I don't need to do any multiplications, since log(x*y)=log(x)+log(y). I only need to subtract the black level from each pixel, and not worry about scaling it to full range. The scaling factor is constant, and just adds a fixed amount to the log result. I'm only using the difference between 2 pictures, not the absolute log value. I can skip the scaling part, and thus skip the overflow problems. The new equation has only 1 extra subtraction:
p=get_raw_pixel(x,y)-CAM_BLACK_LEVEL;

I can also move this out of the 12,000 pixels loop, without any overflow:
hsum=hsum-CAM_BLACK_LEVEL*npts;

I also discovered in my research that CAM_BLACK_LEVEL is an approximation. The active area of the sensor is towards the right side. The left side contains a masked area that doesn't receive any light. The average value of the masked pixels can be used to find the actual black level, which is affected mostly by temperature, and probably varies from camera to camera. Canon raw images include the masked pixels, but dng images don't, although dng does contain a black level value. This should probably be computed from the masked pixels average when creating a dng. Maybe I'll try some black level experiments in the future.

Here are the results from simply subtracting the black level from each pixel. The target for the values on the right is -32. The jump between series of shots should be 384. However, I do a new half shoot before each series, so part of that jump may be a small exposure change from the half shoot. The average of all the jumps within the series is -31.5. So this should make an extremely accurate exposure meter, much better than half_shoot.

Code: (txt) [Select]
  ev+- | deltaHSUM96
  -192     0
  -160   -29
  -128   -28
   -96   -32
   -64   -32
   -32   -29
     0   -32
    32   -33
    64   -30
    96   -31
   128   -32
   160   -29
   192   -33 (series average -30.8 )

  -192   368
  -160   -33
  -128   -29
   -96   -32
   -64   -33
   -32   -28
     0   -33
    32   -33
    64   -29
    96   -32
   128   -33
   160   -30
   192   -32 (series average -31.4)
   
  -192   376
  -160   -32
  -128   -29
   -96   -32
   -64   -33
   -32   -29
     0   -33
    32   -32
    64   -30
    96   -32
   128   -33
   160   -30
   192   -31 (series average -31.3)
   
  -192   376
  -160   -30
  -128   -32
   -96   -33
   -64   -30
   -32   -32
     0   -33
    32   -29
    64   -32
    96   -33
   128   -30
   160   -33
   192   -32 (series average -31.6)
   
  -192   379
  -160   -33
  -128   -33
   -96   -36
   -64   -32
   -32   -28
     0   -37
    32   -32
    64   -29
    96   -32
   128   -28
   160   -28
   192   -33 (series average -32.6)
             (average of all -31.5)
Title: Re: Shot Histogram Request
Post by: lapser on 02 / December / 2012, 11:22:24
I corrected the rounding error in my log2_96 function and did the test again. With the camera pointed at a blank wall, I took a series of shots, varying the shutter speed from -2 ev to +2 ev in 1/3 ev steps from the measured value of the initial shot, by keeping the shutter button half way down between shots using "shoot_full_only".

After each shot, I called my new function which adds up all the sampled pixel values in the resulting image, and returns 96*log2 of this sum. The absolute value is meaningless, but the difference between two shots tells you how much the exposure changed. In this test, it should be -32 each time, or 1/3 ev times 96. The results were perfect. Problem solved.

I'll post a test diff file and documentation of the new functions in a new topic, hopefully in a few days.
Code: (data) [Select]
  ev+- | deltaHSUM96
  -192     0
  -160   -31
  -128   -34
   -96   -33
   -64   -29
   -32   -34
     0   -33
    32   -30
    64   -34
    96   -32
   128   -30
   160   -33
   192   -33
   average=32.166

  -192   384
  -160   -32
  -128   -34
   -96   -29
   -64   -34
   -32   -33
     0   -30
    32   -32
    64   -34
    96   -30
   128   -32
   160   -33
   192   -31
   average=32.00
   
  -192   382
  -160   -30
  -128   -33
   -96   -33
   -64   -30
   -32   -34
     0   -32
    32   -30
    64   -33
    96   -34
   128   -30
   160   -32
   192   -34
   average=32.08
   
  -192   385
  -160   -30
  -128   -32
   -96   -34
   -64   -29
   -32   -34
     0   -33
    32   -30
    64   -33
    96   -33
   128   -30
   160   -33
   192   -33
   average=32.00
   
  -192   385
  -160   -33
  -128   -34
   -96   -30
   -64   -26
   -32   -35
     0   -31
    32   -33
    64   -32
    96   -30
   128   -34
   160   -32
   192   -31
   average=31.75
   
   overall average=31.99
Title: Re: Shot Histogram Request
Post by: philmoz on 05 / December / 2012, 03:01:15
Hmmm, I believe your logic is based on the assumption that a doubling or halving of the sum total of the raw sensor value from one image to the next, equates to a 1 f/stop change in image brightness.

I'm also assuming your using the existing logic in build_shot_histogram that only uses the top 10 bits of each raw value.

So your logic will only work if the dynamic range of the sensor is close to 10 f/stops.

If you were using your G1X then this will be reasonably close - the measured DR at base ISO is 10.8 stops for the G1X.

But the DR drops as the ISO rises so if you re-ran the test at a high ISO you might see very different results.

You are also likely to see quite different results on other cameras with different DR - the only measured value for the SX260 that I can find online is 7 stops (which I think is wrong). Another example, the G12 is reported as 11.2 stops at base ISO.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 05 / December / 2012, 03:37:11
I'm also assuming your using the existing logic in build_shot_histogram that only uses the top 10 bits of each raw value.

So your logic will only work if the dynamic range of the sensor is close to 10 f/stops.
I'm adding the sum of the pixel values before the bit shift, as I said in the other topic (I see what you mean, Waterwingz. You're right as usual.)

But the proof is in the data above. Over a range of 4 f-stops, I get an almost exact correlation. When I change the exposure (shutter speed) by 1/3 f-stop, the log2 of the pixel sum changes by the exact same amount. It should work over the entire dynamic range of the camera, no matter which camera it is.

I was kind of surprised to see how well it worked. But if you ever tried a program like LRTimelapse, it also measures brightness from the image and computes exposure compensation differences to feed back to Photoshop Lightroom. I'm doing the same thing with CHDK, but the exciting thing is I can feed back the exposure compensation to the camera, and have it correct the actual exposure, instead of the photo after the fact..
Title: Re: Shot Histogram Request
Post by: lapser on 05 / December / 2012, 14:15:23
To make things easier to follow, I'll post all my future progress here instead of in new topics (thanks Waterwingz). If I think a new topic is indicated, I'll check with Waterwingz first. To make things more coherent, I'll put unrelated ideas in different posts, all in this topic. That said, my next idea will be in the next post.
Title: Proposed Lua functions
Post by: lapser on 05 / December / 2012, 15:06:47
My code has gotten too complicated by mixing the old set_shot_histo and get_histo_range together with my new stuff. It also will be too hard to explain. So here's my new proposal.

1. Leave the old 2 routines the way they were. They will behave almost exactly like they have in the past (except fixing a few bugs).

But I don't think a histogram of the previous shot is useful. A histogram before taking a shot is very useful for framing the shot and setting exposure, but it doesn't tell you much after the shot, except giving an idea of over and underexposure in high contrast images. I think I can do that better in a new routine though.

2. I'll add two new routines:

To enable shot metering, you call:

npix=set_shot_meter(set_options,xp1,yp1,xp2,yp2,lowp,highp)

xp1,yp1,xp2,yp2 is the area of the image that will be used for metering. Values are in percent of the active area.

lowp,highp are the pixel levels in percentage for the "mini histogram" result (see below).

options: 0 disable, 1 enable, 2 set reference shot? future expansion

To disable shot metering, you call the set function without arguments or with option==0:

set_shot_meter(0)

To retrieve the data after a shot:

ev96rel, nlow, nhigh = get_shot_meter(get_options)

ev96rel is the change in ev from the reference shot, which can be added to the current exposure values so the next shot matches the brightness of the reference shot.

nlow is the number of pixel samples that are below the lowp value set above. This would be like:
  nlow=get_histo_range(0,lowp), only the value would be more accurate

nhigh is the number of pixel samples that are above the highp value set above. It would be like:
  nhigh=get_histo_range(highp,1023)

The number of pixels between nhigh and nlow would be: npix-nhigh-nlow. So you have a "mini histogram" with 3 ranges that is based on the actual number of pixels, and uses the full value of the pixel without bit shifting.

One of the "set_options" might be to use the actual, 12 or 14 bit pixel level as the cutoff, for greater accuracy. If you specify the high range as the white level, that could tell you how many totally blown pixels there are, or maybe how many hot pixels there are in a night image.

get_options could be used to return different data, like the actual log2(sum) instead of a relative value. That way you could save it, or compare it to an absolute value taken from a previous shot with the same area, without having a recent reference shot. You supply your own value from a reference shot taken in the past.

a possible set_option could be to use the entire image for the mini-histogram, and the area from set_shot_meter for the ev96rel value. That way, if something happened outside your metering area, like the sun setting or moon rising, you could detect it and adjust exposure if needed.

So I've got some more re-working of the code to do before I can put anything out. I welcome questions, comments or suggestions.
Title: Hot Pixel removal on the fly?
Post by: lapser on 05 / December / 2012, 15:19:37
In the past, Photoshop Lightroom would automatically remove hot pixels from an image when it loaded. You didn't even know they were there. I'm not sure it's still working, but it made me think.

One of the things I did in my histogram routines was store the maximum pixel value (WHITE_LEVEL) at the x,y position of each sample so I could see dots in the image. This told me if I was setting the area correctly, and helped me select pixels to sample representing all the colors, and as evenly distributed as possible.

Anyway, knowing I can change individual pixels, how about finding and correcting hot pixels? My understanding is that a hot pixel is a completely saturated single pixel. What makes it stand out is that the surrounding pixels are relatively dark. This could be detected by going through the raw image. Has anyone tried this? I know there are a lot of threads on hot pixels and raw images, but I'd love to have a go at it as a future project if the experts here think it might work.

It would be an interesting challenge to see how quickly it could be done. I accidentally used a step size of 1 in my histogram tests, and set the entire raw buffer to white. It added around 8 seconds, so I'm sure I could get through the entire image buffer much more quickly if I did it on purpose.
Title: First Test Script
Post by: lapser on 06 / December / 2012, 02:38:25
I finally got a test script to work. Don't save or try to run this. I'll be changing the names of the functions before the final version. Skip the stuff at the top and scroll down to the main loop at the bottom. It shows how I use the new functions to set the exposure during half shoot. Just messing around with it a little, it worked great. When you point the camera at something light and start the script, take a few shots, and move the camera to something dark... you get an underexposed shot of the dark area that my routine measures. The next shot has the dark area exposed correctly. The exposure is one shot behind, as expected, but it works great! More tests to follow.
Code: (php) [Select]
--[[
@title New Time Lapse
@param m = interval
@default 3
--]]

function restore()
  release("shoot_half")
  hfile:close()
  shot_histo_enable(0)
end

function press_half()
  press("shoot_half")
  repeat sleep(50) until get_shooting()
end

function release_half()
  release("shoot_half")
  while(get_shooting())do sleep(50) end
end

nkey=6
keys={"set","menu","left","right","up","down"}
function keypress(k)
  repeat
    for i=1,nkey do
      if(is_pressed(keys[i])) then
        if(k==nil or k==keys[i]) then return keys[i] end
      end
    end
    sleep(50)
  until false
end

function nopress()
  repeat
    none=true
    for i=1,nkey do
      if(is_pressed(keys[i])) then
        none=false
        sleep(50)
      end
    end
  until none
end

fname="A/CHDK/LOGS/H_"..os.date("%y%m%d%H%M")..".LOG"

props=require("propcase")
pTV=props.TV
pTV2=props.TV2
props=nil

shot_histo_enable(1,3,3,50,25) --upper left
hfile=io.open(fname,"wb")
hfile:write(string.format("%s\n",os.date()))

print("press set / menu exits")
done=keypress()=="menu"
press_half()
hfile:write(string.format("tv0=%d\n pic tv tvd\n",tv))
while(not done)do
  get_histo_ev96rel(2) --reset building histo flag
  press("shoot_full_only")
  repeat
    sleep(100)
  until get_histo_ev96rel(3)==0 -- building histo flag set to 0 when building is done
  release("shoot_full_only")
  sleep(500)
  tvd=get_histo_ev96rel() -- get exposure difference of this shot and reference shot
  tv=tv+tvd -- sets exposure of next shot based on the reference shot (first shot after histo_enable)
  if(tv<0)then tv=0 end
  set_prop(pTV,tv)
  set_prop(pTV2,tv)
  sleep(500)
  nxp=get_exp_count()
  hfile:write(string.format("%d %d %d\n",nxp,tv,tvd))
  done=is_pressed("menu")
end
restore()
Note that the call to: shot_histo_enable(1,3,3,50,25) sets the measurement area to the upper left corner. It also sets a flag to make the next shot the reference shot. The output of get_ev96rel() is relative to the reference shot. The first value for the first picture is always 0, since that IS the reference shot.
Title: Re: Proposed Lua functions
Post by: lapser on 06 / December / 2012, 10:58:37
But I don't think a histogram of the previous shot is useful.
WRONG! I realized that I can find a relative exposure change from the full histogram based on a criteria like:
   Calculate the exposure change needed so 3% of the pixels are above a specified value.

To find this, you would start from the top of the histogram. You would take the sum of the pixels from the top down to the point that the sum was 3% of the total sum. You would subtract this index from the top index to get the exposure increase needed.

Exposure changes move the histogram left or right by the amount of the change (linear).

To implement this exactly, I'll need the full histogram, not the bit shifted 10 bit version, which uses 1024 2-byte short int values (2K).

12-bit camera have 4 times the range of values, which increases the memory requirement to 8K.

14-bit cameras (the G1X) need 4 times that, or 32K.

This memory would only be activated by set_shot_histo(1), and released by the script terminating. I'll also have an option for just calculating brightness and not a histogram, which won't use any extra memory.

So do you think that increasing the temporary memory allocation by these amounts is OK?
Title: First Time Lapse Video with new shot_meter functions
Post by: lapser on 06 / December / 2012, 20:57:47
This was a good test in that it triggered a glitch that's easy to fix. But the scene was too bright to give a good test of the accuracy of the new shot_meter functions.

The first picture was so bright, the initial shutter speed was 1/2000, which is the input maximum for the sx260. Shot_meter kept asking for higher shutter speeds, and my lua script dutifully stored them in propcase TV. The camera maxed out near the beginning of the video at 1/3200 sec. But the program kept calling for higher and higher shutter speeds, finally reaching the nano-nano second range and maxing out a short integer at 32767. The next request was for 32770, which is a negative number corresponding to leaving the shutter open for around 10 years. Fortunately, the camera decided that 64 seconds was long enough.

The dot pattern at the upper left is the metering area, set by new parameters to set_shot_histo. The frame rate was 1 picture per second. With my new timing function, get_shot_ready(), I was able to use a 1 shot per second interval, with 0.4 seconds left over. So I should be able to shoot even faster than this in bright light. Of course, with a shutter speed of 64 seconds, the frame rate drops to less than 1 per minute.

I'll try again tomorrow with some out of range testing in the program, and the camera pointing away from the sun.

http://www.youtube.com/watch?v=gVft5lSjSMI#ws (http://www.youtube.com/watch?v=gVft5lSjSMI#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 08 / December / 2012, 02:00:21
I did some significant changes to the metering today, with good results. I was able to eliminate the reference shot requirement!

I set up the step size and metering area in set_shot_histo(), so I also know the total number of samples before build_shot_histogram goes through the image pixels. I initially set my reference to an average pixel level of 50 percent of its total range (white level-black level)/2. I add up the actual pixels and get the sum, then subtract the log of the actual sum from the log of the 50% level, and set a new shutter speed based on this difference. In other words, the reference picture is one with all pixels at 50 percent of maximum (50% grey).

It worked! But the histogram of the resulting image was "exposed to the right". That is, it was overexposed. So I subtracted 2 f/stops, which means my reference is an image with all the pixels at 12.5% of maximum. I think this is what the built in meter is set to, because the exposure matched the one calculated by the camera with the first half_shoot pretty closely.

For the following video, I just took all the pictures, unprocessed, and turned them into a 30fps time lapse at 1 shot per frame. The shots are taken at 1.5 shots per second. The metering area, set by parameters in my new script, is at the upper left.

Despite my efforts to keep the camera dry with an umbrella, it was still getting sprinkled, and I decided to give up. But I took a video of driving in the rain, still at 1.5 seconds per shot. This was a more difficult metering test, but it seemed to get the metering much better than the camera meter could have. I found a few times where the upper left was covered by a dark tree in one shot, and then showed brighter clouds in the next. The brightness jump was noticeable, but only lasted one shot. Mostly, the brightness of the images appear pretty uniform.

The log files show that the exposure of the 2 sections of cloud videos dropped 1.5 ev in the first part, and 2 ev in the second part. The exposure changes smoothly, with no sudden jumps that might flash in a time lapse. The only "flashes" I saw were rain drops hitting the lens!

http://www.youtube.com/watch?v=BauS8Jq0pHc#ws (http://www.youtube.com/watch?v=BauS8Jq0pHc#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 10 / December / 2012, 01:28:53
This time lapse was done at 2 seconds per shot, played back at 30 fps. It goes from day to night with the metering area set to a small box at the upper left. It's impressive how smooth the change from light to dark is, with no flashing. Remember, there's no half shoot, so nothing to adjust the exposure with but my get_shot_meter() routine.

As it gets darker, the meter keeps adjusting the exposure to keep the sky at the upper left at the same brightness, which overexposes the city lights at the end. The shutter time started at 1/367 second, and  was 29 seconds at the end.

The bump near the beginning was me putting a plastic bag over the camera to protect it from a few sprinkles of rain.

http://www.youtube.com/watch?v=pnIeuphozw4#ws (http://www.youtube.com/watch?v=pnIeuphozw4#ws)
I decided to use independent areas for the histogram and the meter. Coding that ended up a mess of variable switching and confusion. It was easier just to use arrays for the bounds of the meter and histogram areas.

Well one thing led to another, and I ended up with 4 independent meters you can set at different parts of the picture. Meter 0 goes with the histogram. It might be useful to have a spot meter, and an overall meter with histogram. The overall meter would have picked up the city lights changing. I could switch to the city lights meter when it suggested lower exposure than the sky meter and avoid the overexposure at the end.

I'm not sure what to do with 4 meters, but maybe someone will use all of them. The meters are working great, though. Next is to work on the histogram part to make it more useful for setting exposure. I'll start by making it 12-bit instead of 10 - still bit shifting the G1X down to 12 bits to save memory.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / December / 2012, 01:56:38
This is a full resolution picture demonstrating the ability to use 4 different meters each with its own area specification. This picture was produced by setting each pixel to 0xFF after reading it for a sample, so it shows both the sample area and sample density. If you click on the image and zoom in to full resolution, you can see the dot pattern. By using an odd number step size between samples, the color of the pixels alternates and gives a better sample.

I also shifted every other row to the right by 1/2 step size, to spread the samples out a little more.
 
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FXFcIv.jpg&hash=6fca7157a1d06794e81a9380b66fa9af)

The image was produced with this simple script:
Code: (lua) [Select]
shot_meter_enable(1,0,0,25,25)
shot_meter_enable(2,75,0,100,25)
shot_meter_enable(3,0,75,25,100)
shot_meter_enable(4,75,75,100,100)
shoot()
Title: 4 exposure metering areas
Post by: lapser on 10 / December / 2012, 23:38:40
I converted the histogram to full size. Before, it took 0.002 MB (2K). 12-bit sensors will now take 0.008 MB, and the 14-bit G1X will take 0.032 MB. CHDK on start up says it takes 0.24 MB, and the camera has 2.4MB available on both the G1X and SX260. The extra histogram memory is only allocated it you enable histograms. You can enable just the meters without allocating memory. I think the memory use will be worth it if I can calculate something useful for setting exposure. I'll try calculating an exposure change to make the next shot exposed to the right (ETTR). I'm not sure how worthwhile that would be, but I think it's possible.

I tried an experiment with 4 metering areas at a time. There's 1 at the upper left, another is the lower half, a third one is in the center, and the 4th is the entire picture. If you look at the dot pattern in the photo, you can see all 4 areas represented. At least it works.

It may be useful for special situations, like day to night. With one meter on the sky, and the other on the city, you could choose the meter with the least exposure (i.e. fastest shutter speed). The sky is brighter in the day, and the city lights are brighter at night. Maybe that would keep from over-exposing the lights when it gets dark.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FKXu0G.jpg&hash=78da51c1ea65339c7d8d96020727ef5a)
Title: Latest Test Time Lapse
Post by: lapser on 11 / December / 2012, 00:48:26
This actually got interesting enough that I wished I didn't have my test dots enabled. I was testing the new metering areas, but I missed getting a pretty good sunset.

I capped the exposure time at around 8 seconds at the end, so I didn't get a bad overexposure from trying to keep the sky at the same brightness as night fell. Note the video speeds up as the shutter time increases at the end. I've experimented with fading from one shot to the other at slower speeds, but it tends to look jerky. I think by shooting in continuous mode, the time between shots will be low enough that fading between them will look smoother.

http://www.youtube.com/watch?v=3B9XfdHIJ5o#ws (http://www.youtube.com/watch?v=3B9XfdHIJ5o#ws)
Title: 12 & 14 Bit Histograms
Post by: lapser on 12 / December / 2012, 12:35:15
I changed histogram.c to do the full histogram for higher than 10 bits. Then I decided it wasn't worth it, and took it out. In addition to the extra memory it takes (4 and 16 times the memory for 10-bit), there would need to be changes to get_histo_range(...) which I decided aren't worth the complications, not to mention trying to explain how to use it.

Anyway, I don't think the extra precision is needed. I was trying to figure out what to do with a shot histogram that might be more useful than get_histo_range(..). I read descriptions of how professional photographers use the histogram. What they describe is, they take a shot, look at the shot histogram, and adjust the exposure (or framing) so that the left and right side of the histogram are not clipped off.

So what I propose to do is calculate an exposure change, like I've done for the meters, based on the histogram. It would be easiest to understand by adding a function:

get_histo_meter(options...)

It would return the exposure change needed to move the histogram to the top, bottom, or in between, or whatever options I could figure out. You would use it just like the get_shot_meter(..). For example, option 1 might move the histogram to the right (ETTR):

Tv=Tv+get_histo_meter(1)

The options could specify a target for the end point, and percentage of pixels allowable over or under the target. I suppose the target should be linear, and in percent of full range. It could go like this:

Tv=Tv+get+histo_meter(1,50)

This might mean that you want the brightest pixels to be 50% of the full camera range, i.e. the white level/2. This is 1 f-stop below clipping. You could do a similar thing for the darkest pixels. I.E. change the exposure so the   darks are in range, i.e. exposure to the left.

The combination of the right and left exposed images might be all that's needed to produce an HDR image. If the two exposures were too far apart, you might need one in the middle.

Anyway, just updating my thoughts on where I'm going with the shot_histo research.
Title: Continuous (burst) mode discoveries
Post by: lapser on 12 / December / 2012, 13:30:11
I'm finding more and more advantages to using continuous mode for a time lapse. The fastest I can go in single shot mode is around 1 shot per second, by keeping half_shoot pressed, and using shoot_full_only. With continuous mode, you just keep shoot_full pressed the whole time. On my cameras, this yields around 2 shots per second. Other cameras have specs over 3 shots per second. Wow.

Another great thing about continuous mode that I just discovered is that the display shows the last picture! In single shot mode, the display goes blank while the camera is taking a picture. I think this is because the camera uses the display for pre-shot metering. At night, when you're taking long exposures, the screen is blank most of the time, with a short flash in between shots. You can't see what's happening. And by blank, I don't mean the back light is off. It's still draining power to show a dark screen.

But in continuous mode, the display shows a picture during long exposures. Try it with your camera in continuous shooting mode (with CHDK). Then take a series in single shot mode while holding half press between shots.

So continuous mode is ideal for time lapses, for speed and picture display. I can still adjust exposure between shots using the new get_shot_meter(..). The only problem is that you can't adjust the speed. The time lapse is ALWAYS 2 or 3 shots per second, even if you really want them 10 seconds apart. I can probably switch to single shot or get shoot_full_only to work with continuous mode, but I would lose the display part, and there's a jump from 1 shot per second up to 2 without the option of 1.5 seconds.

But from examining raw.c timing, I realized that you could add a precise delay in raw_save_file() that would work in continuous mode. In fact, there's already a delay before raw_save_file() is called to allow the exposure counter to update to the right file name. The comments note that this can slow down "burst" mode. But that's exactly what I want to do here.

But you don't want to let Lua just set a delay. If you set a delay of 10 minutes by mistake, the camera would hang for 10 minutes. Not good. Here's my idea:

set_shot_delay(enable) sets a 1 second delay.
set_shot_delay(disable) cancels delay in progress

if you don't call set_shot_delay(enable) again within 1 second, the delay times out and the shot continues. Or if you want the shot to continue immediately, use the disable option. It should be simple to code it in. I'll see how it works.
Title: Re: Shot Histogram Request
Post by: waterwingz on 12 / December / 2012, 15:11:25
But you don't want to let Lua just set a delay. If you set a delay of 10 minutes by mistake, the camera would hang for 10 minutes. Not good.
There are lots of ways to hang the camera while debugging a script.  This would just be one more that needed to be debugged and fixed.  I wouldn't waste any time trying to protect the programmer from this sort of mistake.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / December / 2012, 17:11:47
There are lots of ways to hang the camera while debugging a script.  This would just be one more that needed to be debugged and fixed.  I wouldn't waste any time trying to protect the programmer from this sort of mistake.
That's a good point. Thanks for the input. The idea is also to make it easy to program.
[edit] What I mean by easy to program is that limiting the delay to 1 second would require the Lua programmer to write a loop, calling the delay routine every second (or faster), and compute the last time delay at the end. Whew! Why not just delay for 20 seconds, if that's what you want. raw_save_file is just going to call sleep() anyway.

I'm going to try a sunset time lapse tonight with the new program. I set up 4 meters, 1 in each quadrant of the total frame. I go through each meter and choose the one that recommends the least exposure: that is, the meter that produces the darkest picture. It'll be fun to see what happens. Gotta go.
Title: 4 Meters Successful Test
Post by: lapser on 12 / December / 2012, 23:33:08
The clouds and drizzle didn't cooperate, but the new 4 exposure meter experiment worked like a charm. I set up the Lua script to enable all 4 exposure meters. Then, after each shot, it went through all the meters and picked the one with the highest value, which was the brightest area. It used the value of that meter to adjust exposure, that is it added that meters value to Tv to get the new exposure.

The first shot the script does is the only one metered by the camera, with half_shoot. Lua reads the Tv from this shot, and used it as the starting Tv. Then, the Lua program simply adds the value from the highest meter to the starting Tv and sets this new Tv for the second shot. In this case, the upper right part of the sky was the brightest, so the program used that value. The upper 2 (sky) meters were about 3 Ev brighter than the lower 2 meters of the picture. The initial camera exposure was in between these two.

Here's the log data for the first four pictures:
                                        Times (2 sec interval)
       Meter #   Meter Value (Tvd)     || Shot  Total || Tvd Tv Seconds
 1   158 | 2   172 | 3  -158 | 4  -157 ||   410   460 || 172 781 1/281
 1   -13 | 2     0 | 3  -329 | 4  -331 ||   320  1930 || 0 781 1/281
 1   -13 | 2     0 | 3  -330 | 4  -331 ||   320  2000 || 0 781 1/281
 1   -14 | 2     0 | 3  -331 | 4  -331 ||   320  2000 || 0 781 1/281

Here's what the first image, using the camera exposure, looked like. Note that for the first image, i drew the meter areas on the image in the raw buffer, so it shows up in the picture.
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FZkrjl.jpg&hash=b8d8d172d2e51d72b8b5f0b707c140a7)

Here's the second image. Note the exposure is correct for the upper right quadrant (meter 2). Meter 2 was used to correct the exposure, so the other quadrants are underexposed. This is exactly what I wanted for a sunset time lapse. All that's missing is the sun.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FXThKq.jpg&hash=0c74ad9f7593e69d4d5fdf0edf43fe21)
Title: set_shot_interval(time)
Post by: lapser on 13 / December / 2012, 11:19:35
I think I figured out the best way to implement a delay for continuous mode so it will be useful for time lapses, or other uses. I'll add a function called
set_shot_interval(time)

The interval would be the same as the interval in all time lapse scripts. A 2 second interval means delay the next shot until 2 seconds after the last shot. Writing a time lapse script would be simpler, since you wouldn't need to worry about a timer. It would go something like this:
Code: (lua) [Select]
interval=2000 -- for 2 seconds
set_shot_interval(interval)
press("shoot_full") -- in continuous mode
repeat
  nshot=get_shot_number()
  repeat sleep(10) until get_shot_number~=nshot
  -- set new exposure levels here using get_shot_meter()
until false
When the script is finished, CHDK would call set_shot_interval(0), like it does for shot_histogram. This would prevent a script from disabling the entire camera, and reset everything back to normal if you interrupt a script. The above script would work this way.

It would be nice to be able to put the camera in continuous mode with a script. get_drive_mode()==1 tells me I'm in continuous mode. But there doesn't appear to be a set_drive_mode(1). Does anyone know how to do that?

The interval delay should happen right before triggering a new shot (not in raw_save_file(). It would be good if the timing accuracy could be better than the 10 or 20 msec you get from get_tick_count(). I'll see if I can figure out where to put the new code, and how to do the timing from looking through the source files. If someone wants to help point me in the right direction, that would be nice. Anyone? . . . Anyone? . . . Philmoz?
Title: Re: Shot Histogram Request
Post by: philmoz on 13 / December / 2012, 14:12:55
The interval delay should happen right before triggering a new shot (not in raw_save_file(). It would be good if the timing accuracy could be better than the 10 or 20 msec you get from get_tick_count(). I'll see if I can figure out where to put the new code, and how to do the timing from looking through the source files. If someone wants to help point me in the right direction, that would be nice. Anyone? . . . Anyone? . . . Philmoz?

The only place I can think of that might work is in wait_until_remote_button_is_released.
However this isn't guaranteed to be called correctly (or at all) by all cameras - depends on the port. Most seem ok though.

10 msec is the best accuracy you can get - there aren't any higher resolution timers that I know and that's the time interval for task switching.

I need to think about this more; but a couple of quick suggestions.
- the relevant code should only be active when a script is running (and probably in continuous mode), alternatively you could add config items and menu UI items to allow it to be used outside a script. Not sure how useful it would be though.
- if it's only used by scripts then the value should be reset by the script engine when the script ends. This will prevent one script from affecting another if the first script forgets to clear the value.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 13 / December / 2012, 15:03:44
10 msec is the best accuracy you can get - there aren't any higher resolution timers that I know and that's the time interval for task switching.
Thanks Phil. I found something that looks interesting:
    extern volatile long shutter_open_tick_count;   // defined in platform/generic/capt_seq.c

I just tested it, and it does indeed contain a value that appears to be the time the shutter opened.

However, I can probably get away with simply delaying in raw_save_file based on the the time of the last call to raw_save_file, and not bother with anything else. That's probably the best solution, and plenty accurate. The per shot time should remain accurate, which is the main thing. Correcting for the shutter open time probably won't be necessary, although I'll have to think about that a little more.

As for the accuracy issue, take a look at line #321 in main.c. It calculates a value for:
camera_info.tick_count_offset
Can you explain what that is? It's used in dng.c at lines #567 and #576

And on a related issue, I thought I read that "long" was just a 32 bit "int" in CHDK. Is this correct? I hope not.

Thanks again.
Title: Re: Shot Histogram Request
Post by: philmoz on 13 / December / 2012, 16:30:08
10 msec is the best accuracy you can get - there aren't any higher resolution timers that I know and that's the time interval for task switching.
Thanks Phil. I found something that looks interesting:
    extern volatile long shutter_open_tick_count;   // defined in platform/generic/capt_seq.c

I just tested it, and it does indeed contain a value that appears to be the time the shutter opened.

However, I can probably get away with simply delaying in raw_save_file based on the the time of the last call to raw_save_file, and not bother with anything else. That's probably the best solution, and plenty accurate. The per shot time should remain accurate, which is the main thing. Correcting for the shutter open time probably won't be necessary, although I'll have to think about that a little more.

As for the accuracy issue, take a look at line #321 in main.c. It calculates a value for:
camera_info.tick_count_offset
Can you explain what that is? It's used in dng.c at lines #567 and #576

And on a related issue, I thought I read that "long" was just a 32 bit "int" in CHDK. Is this correct? I hope not.

Thanks again.

The camera_info.tick_count_offset value is used to set the msec part of the image capture time in the DNG header. It's only accurate to the same 10msec range as everything else.

The size of long and int are both 32 bits.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 13 / December / 2012, 17:23:29
The camera_info.tick_count_offset value is used to set the msec part of the image capture time in the DNG header. It's only accurate to the same 10msec range as everything else.

The size of long and int are both 32 bits.
Thanks! I like to explore all the options, and pick the simplest one. I appreciate your patience in answering so many questions.

OK, one last question. What function should I use for the "sleep" delay in raw.c?

I think that msleep(long t) is also used by the keyboard task, and thus by Lua. Is it safe to use in a different thread at the same time?

I noticed that capt_seq.c uses _SleepTask(10). Should I use this one?

So long IS 32 bits! That's important to know, thanks.

[EDIT]Here are the changes to raw.c  . . does this look right?
[EDIT2]OK, it's working in continuous mode shooting at 2.5 seconds per shot (normally it's 0.5 seconds per shot). There's a picture showing on the screen at all times, which can be turned off with set_backlight.
Code: (c) [Select]
...in raw_save_file()
if (state_kbd_script_run)
{
  if(shot_histogram_isenabled())build_shot_histogram();
  while((shot_interval>0)&&(get_tick_count()<shot_next))msleep(10); //set_shot_interval(0) aborts
  shot_next=get_tick_count()+shot_interval;
}
shot_number++; //polled by Lua get_shot_count()
...
int raw_get_shot_number() // called from Lua - increments after shot histo is ready
{
  return shot_number; //incremented in raw_save_file() ... different thread
}

void raw_set_shot_interval(int interval) //called from Lua ... sets minimum interval
{
  shot_interval=interval-5; //subtract 5 for rounding to 10msec sleep time
}
...
static int shot_number=0; //incremented after build_shot_histogram()
static int shot_interval=0; //msec .. minimum time between shots .. works in continuous mode
static int shot_next=0; //minimum tick time for next shot . . delay until this time
Title: First Time Lapse Video with new continuous mode delay function
Post by: lapser on 13 / December / 2012, 23:14:15
The delay function above worked well. It held the time between shots in continuous mode to 2500 msec, until the shutter time exceeded that. Even then, there is a minimum delay between shots compared to single shot mode and repeated shoot_full_only presses. It looks like msleep works fine in more than one thread, so it must be thread safe.

The screen display of the pictures during shooting worked too. It was nice to see exactly what the pictures looked like as they were being taken. My back light toggle also worked, since the keyboard thread is active while the delay takes place in the camera thread. This appears to be a superior method for doing time lapses.

http://www.youtube.com/watch?v=X5Zkw_G7KHs#ws (http://www.youtube.com/watch?v=X5Zkw_G7KHs#ws)

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2Ff9qba.jpg&hash=fa932b769723945a89281ce6f220eae7)
First shot with metering areas drawn on image.
Log file attached
Title: Re: Shot Histogram Request
Post by: lapser on 14 / December / 2012, 13:37:59
I noticed a few things from looking at the pictures and the log file above. First, the exposure didn't change on the second shot. The reason is that the 2nd shot happened immediately, with no delay. The Lua script  didn't calculate and store the adjusted tv value until the 2nd shot was already in progress. This is probably also happening on the shots where the shutter time exceeded the interval time, and the delay goes to 0. The exposure changes were so small, it's not possible to tell, but I'm pretty sure it was happening all the time. That means I would be 2 shots behind in setting exposure instead of one.

One reason is that the shot_number was being incremented AFTER the delay, instead of between the call to build_histogram and the start of the delay loop. shot_number++ signals the Lua script that the shot_meters are valid, so it can set the new TV values. But at this high shooting speed, it's a race between the camera and the script, and the script was losing. With the shot_number++ set up this way, the problem was probably happening after every shot.

I'll start by adding a minimum 20 msec delay AFTER shot_number++,  and before returning and letting the camera shoot the next picture. If that's not enough time, I can add a longer delay that can be aborted by the Lua script after it sets the new TV values.
=========
I also figured out what's happening when going from light to dark areas rapidly, like taking a picture of a bright monitor at night, and then at a dark area of the room. Going from bright picture to dark picture is no problem. The shot_meter correctly estimates the exposure change needed. The first shot is dark, and the next one is exposed properly. With a really dark area, there might be a 3rd shot needed to zero in on the correct exposure, but usually not.

Going from dark to bright is a different story. The first shot of the computer monitor taken with the dark exposure is totally white, all pixels blown, as expected. To the shot meter, totally white is only 1 f/stop above the 50% exposure level. I return 2 f/stops below that, so the maximum correction the meter will make downward from a totally blown white shot is 3 f/stops. It works, but it takes 3 or 4 pictures, 3 f/stops less each picture, to get the right exposure. It's interesting to watch the details appear out of white picture a little more each shot, but it's not the desired result.

I need to add an extra correction based on how far above 50% the linear pixel average is. A completely blown picture might need 7 or 8 f/stops less exposure, instead of the 3 maximum. I can probably design an experimental lua script that collect this data systematically, and computes an adjustment factor for the various over exposure levels. I guess I'll have to take a few thousand more pictures of my blank wall! Fun.
Title: Re: Shot Histogram Request
Post by: jmac698 on 15 / December / 2012, 23:06:48
Hi,
I'm interested in this for doing auto HDR, but at extreme levels.  Taking shots at night for example, I have the problem that an auto exposure sits at the maximum which returns complete black.  So if you have black or white, just think that a normal picture has say 8 stops exposure and you need to vastly change the settings.  My night exposure needed 6 or 8 fstops more, depending on camera.  The most efficient way is to do a binary search pattern.  Also I think a blank wall is an unrealistically low dynamic range to test with.  I've also graphed a sunrise with a light meter, and it obviously goes over a huge range very quickly.

So ultimately, I'd like the camera to do what I do manually, take test shots until I find a good range to start shooting, and to know when to stop for extreme HDR.

Also to guess where you're at, you can guess at a normal histogram and compare, to see how much you should change.. would have to work out those ideas, it could be simple or complex, and in fact is probably what autoexposure does anyhow....
Title: Re: Shot Histogram Request
Post by: waterwingz on 15 / December / 2012, 23:39:35
I guess I'll have to take a few thousand more pictures of my blank wall!
Also I think a blank wall is an unrealistically low dynamic range to test with.
You probably need to spend several hundred hours of your time working on CHDK development to understand what lapser meant.  Reyalp's keyboard,  the oak tree outside my window and a lone koala bear might be the most photographed things in history.

Title: Re: Shot Histogram Request
Post by: lapser on 16 / December / 2012, 00:31:51
Also I think a blank wall is an unrealistically low dynamic range to test with.  I've also graphed a sunrise with a light meter, and it obviously goes over a huge range very quickly.
Actually, you're correct that a blank wall wouldn't work for the problem I stated, which is, too many pixels blown out to get an accurate exposure correction for the next shot. The solution isn't all that complicated, though, as you suggested. When you have a lot of blown pixels, give up on getting the right exposure in the next shot.  Just decrease by 6 or 8 EV instead of 3. Once you find a spot where the pixels are in the linear range, not too many totally dark or blown pixels, you can hit the right exposure on the next shot. I got to it eventually (in 3 to 5 shots) with 3 EV steps.

I've got the shot meter working perfectly (thanks to the blank wall). The histogram analysis shouldn't be that hard, either. Instead of using the average of all the pixels like in the shot meter, I'll add up the number pixels from the top of the histogram down, until I get to 1% of the total pixels (or some other percentage). The exposure correction is the desired level minus the 1% level (in log units). There's no binary search involved. If the pixels are in range, you hit the exposure you want on the next shot. It works for the shot meter, and hopefully it will work for the histogram.

The blank wall was ideal for calibrating the shot meter part. The histogram part will require a wide dynamic range so there will be dark and bright pixels represented. I was kind of kidding about the blank wall thing, but I'm almost serious now when I say that I may need a few thousand pictures of a black and white wall now.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / December / 2012, 01:00:12
I've been working on the timing part of time lapse, and made some good progress. I added some code that delays the camera between the time the histogram (and meters) are ready, and the saving of the jpg, and I think it's debugged and working now. It allows very high speed shooting in continuous mode, with a little delay included to give Lua a chance to read the meters and change the exposure (I was 1 shot behind in the last test). There's a function to set the interval between shots, which eliminates the need to program a shot timer in Lua.

I also modified the set_tv,sv,av functions so they occur immediately when get_shooting() is true, instead of delaying until the next half_shoot. This eliminates the need to use propcases. I never figured out how to set av with propcases, and my somewhat complicated sv propcase solution worked, but I'm not sure how reliable it would be. This change will make life for the half_shoot Lua programmer much easier.

I'm working now on an Apex96 conversion function for Lua that outputs integer values from the C functions in shooting.c. It will make it very convenient for Lua programs to display shutter speeds instead of Tv96 values, and enter shutter speeds as parameters, and convert them to Tv96.

I've noticed that most of the function names start with set_ or get_. Based on this, the name for the Apex96 conversion function would be:

get_convert96(value, type)

I would prefer to drop the get_ and use convert96(...). The word "convert" implies that the function has an output value, so "get_" is redundant. Any opinions on this name, or ideas for other names?
Title: Histogram processing ideas
Post by: lapser on 16 / December / 2012, 11:46:58
OK, first of all, I changed my mind (again) on the size of the histogram. It's now 2K, would go up to 8K for 12 bit cameras, and 32K for the 14-bit G1X. I just can't bring myself to bit shift away all the extra precision of 12 and 14 bit cameras for a measly 8K or 32K memory savings. Activating a histogram is optional, but if you want it, you want it all the way.

The next thing is getting the most out of the extra histogram memory. When I added the ability to do 4 meters  (or more), I din't think it would be that useful. But as I test it, I see it will add a significant capability to the camera metering. I also realized that I can add up a full histogram for each of the meters for very little time, and no extra memory overhead. Only the last meter would be saved between shots, but I could compute and save ETTR exposure change values (and maybe ETTL) for all the meters.

So the next step is to go back to the full histogram size, based on the bits per pixel of the camera. I did that once and threw it away, so it shouldn't be hard too put it back (in an even better way). Then, I'll add the code to compute a histogram for each meter (trivial). Finally, I'll work on a new function that uses the meter histograms to calculate recommended exposure changes to give to the Lua script.

Each meter histogram would have its own area. So let's say you're doing a sunset. If you use a histogram of the whole shot, it will include the sun, and you'll never get ETTR on the sun. So you could set your metering areas to exclude the sun, which would be the area to the right of the initial position of the sun, down to the horizon. (people in Australia, who live their lives upside down, might not be able to use this technique:). This might also avoid having the image brighten temporarily as the sun goes down, which doesn't look natural.

So I'll add the capability, with the hope that professional photographers with a lot more knowledge than I have, will find new ways to use it.
Title: Re: Shot Histogram Request
Post by: reyalp on 16 / December / 2012, 17:37:55
OK, first of all, I changed my mind (again) on the size of the histogram. It's now 2K, would go up to 8K for 12 bit cameras, and 32K for the 14-bit G1X. I just can't bring myself to bit shift away all the extra precision of 12 and 14 bit cameras for a measly 8K or 32K memory savings. Activating a histogram is optional, but if you want it, you want it all the way.
What application actually needs this precision ? 32K is actually quite a lot in CHDK land...

If you are calculating exposures, it seems to me the discarded precision is going to be a tiny fraction of a  stop, utterly meaningless from a photographic perspective.
Title: Re: Shot Histogram Request
Post by: philmoz on 16 / December / 2012, 18:15:59
OK, first of all, I changed my mind (again) on the size of the histogram. It's now 2K, would go up to 8K for 12 bit cameras, and 32K for the 14-bit G1X. I just can't bring myself to bit shift away all the extra precision of 12 and 14 bit cameras for a measly 8K or 32K memory savings. Activating a histogram is optional, but if you want it, you want it all the way.
What application actually needs this precision ? 32K is actually quite a lot in CHDK land...

If you are calculating exposures, it seems to me the discarded precision is going to be a tiny fraction of a  stop, utterly meaningless from a photographic perspective.


The G1X has 2.5MB free memory without using exmem so should be no problem using 32K extra.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / December / 2012, 21:01:38
What application actually needs this precision ? 32K is actually quite a lot in CHDK land...
If you are calculating exposures, it seems to me the discarded precision is going to be a tiny fraction of a  stop, utterly meaningless from a photographic perspective.
That's what I was thinking when I decided to stay with 10 bits and 2K. But it gets more significant at low light levels. One of the reasons I wanted to try metering the shot in the raw buffer was that the standard meter started jumping by 1/2 Fstop when it got real dark. My time lapses were flashing noticeably.

Starting from 0, each extra bit of precision is an Fstop. And remember the memory is dynamically allocated, so I will only use the extra 2, 8, or 32K memory while a script is running that enabled the shot histogram. It will also be interesting to be able to show the full resolution histogram to see what's going on in the lower bits. I'm wondering if the G1X really has 14 significant bits of precision.

Are there any 16 bit sensors on the horizon?

The G1X has 2.5MB free memory without using exmem so should be no problem using 32K extra.
Thanks Phil. I appreciate you putting in your two bits worth. :) And I promise to bit shift the 16 bit cameras. Or maybe . . . ??

Title: Using capt_seq_hook_set_nr() for interval delay
Post by: lapser on 17 / December / 2012, 17:31:29
I got my continuous mode interval timer working pretty well by adding a delay in raw_savefile() right after build_shot_histogram(). But this happens AFTER the shot, and you really want to time the interval from the start of the shot. I've been looking for a way to do this for awhile, but I think I finally found it.

There's already a hook that happens immediately before the shot. It looks like the purpose of this hook is to turn off dark frames, which is one of the most useful features of CHDK for night shots. But I also discovered that I can put my interval timer delay at the end of this function. It works!

With the delay right before the shutter opens, it should be almost perfectly accurate, since it doesn't depend on the shutter speed, or file save time. Delaying after the shot is not accurate when the shutter time or file save time changes between shots.

I recently discovered that in continuous drive mode, the last picture taken is displayed on the screen, instead of the screen going blank for the entire exposure (with review mode off). But while delaying in raw_savefile(), the picture isn't ready to show, so the picture before it shows on the screen during the delay. Moving the delay to right before the next shot solves this problem. The screen shows the shot just taken while waiting to take the next shot.

The delay only happens when a script is active, and the script called "set_shot_interval(delay)." But the delay happens in any mode, not just continuous.  After setting a shot interval, each new shot will delay until the time between the new shot and the last shot exceeds that interval, even if you use a new half_press, or the shoot() function. A simple time lapse script would be:

set_shot_interval(10000) -- 10 seconds
repeat shoot() until false

When the script is terminated by pressing the shutter button, script.c calls set_shot_interval(0), and the delay is cancelled. The last picture will then be taken immediately.

Code: [Select]
void __attribute__((naked,noinline)) capt_seq_hook_set_nr()
{
 asm volatile("STMFD   SP!, {R0-R12,LR}\n");
    switch (core_get_noise_reduction_value()){
    case NOISE_REDUCTION_AUTO_CANON:
        // leave it alone
...
 raw_shot_delay(); //wait delay interval, if any, before continuing shot ******************
 
 shutter_open_time=_time((void*)0);
 shutter_open_tick_count = get_tick_count();

 asm volatile("LDMFD   SP!, {R0-R12,PC}\n");
}
I also added a double shot option to use with shot metering in continuous mode. It's activated with set_shot_interval(-2). After this, every other shot will have no delay.

Since shot metering takes place after the shot, the new exposure can't be applied until the next shot. If the shots are far apart, say 1 or 2 minutes, then the metering may not be accurate since the scene might change. So for long shot intervals, this option takes a "metering" shot, followed by a correctly exposed shot derived from the metering shot.
Title: DIFF files coming later
Post by: lapser on 17 / December / 2012, 21:56:55
[EDIT] diff file attachment removed. Making too many changes now. See the documentation in the next post for more info on what's coming soon.
Title: Preliminary Documentation
Post by: lapser on 18 / December / 2012, 23:06:49
I've attached a rough draft of the documentation I've written so far. I'm working on the shot_histogram part now, so those functions won't work like the documentation yet. I've included some Lua examples, which I haven't tested yet, but explain how to use the functions.

Rather than releasing new diff files, it might be easier to send them to philmoz to put in his branch?
Title: Re: Shot Histogram Request
Post by: waterwingz on 19 / December / 2012, 01:28:57
http://xkcd.com/1148/ (http://xkcd.com/1148/)
Making too many changes now. See the documentation in the next post for more info on what's coming soon.
Lapser !

I'll be back in two weeks.

Let me know how this all worked out ? Do the drugs wear off after a while ?

WW
Title: Re: Shot Histogram Request
Post by: lapser on 19 / December / 2012, 09:04:55
I'll be back in two weeks.
Let me know how this all worked out ? Do the drugs wear off after a while ?
Good one! Have a nice trip, assuming you're tripping!

Hopefully, before you get back, I'll have this all done and organized. I accidentally deleted the documentation file last night instead of the diff fie (after the morning drugs had worn off  ::)).  It's in the last post again if you want to take a look at it.

"The distance between insanity and genius is measured only by success."
James Bond: Tomorrow Never Dies
Title: Timing Problems Solved
Post by: lapser on 19 / December / 2012, 14:18:01
The fastest way to take multiple shots is in continuous mode (at 2 or 3 shots per second). But there is no way to control the shot rate, or meter exposure. You can change the exposure between shots (i.e. bracketing in continuous mode), but you don't know how much to change it.

The new get_histo_meter() function returns an exposure value based on the previous shot that works well for measuring exposure. I'm also working on turning the histogram of the last shot into a meaningful exposure correction value.

Now, I've also solved the timing problem in continuous mode. It depends on the new function:
set_shot_interval(interval, delay)

"interval" is the time, in msec from the last shot, to wait BEFORE taking a shot. The delay occurs right before the shutter opens, and sets the interval between shots very precisely (within 10 or 20 msec).

"delay" is the time to wait AFTER the shot. The delay occurs right after the shot meters and shot histogram are ready, and "shot_number" has incremented. The lua script is waiting for "shot_number" to increment, and then it reads the shot meters and sets the exposure for the next shot. But I found that shots are going by so fast in continuous mode that there wasn't enough time for the script to finish. The "delay" after the shot gives the script time.

The last piece of the puzzle is for the script to be able to abort the delay when it is finished with the histogram and meters. This is done with:
set_shot_interval(-1)

Here's how to do a time lapse as fast as possible, with exposure correction between shots:
Code: (lua) [Select]
set_shot_meter(1) -- enable meter #1 with full sensor measurement area
set_shot_interval(0,500) -- no pre-shot delay, 1/2 second (max) post shot delay
-- if you want your shots at 1 per second: set_shot_interval(1000,500)
ishot=0 -- get_shot_number() always starts at 0 now
press("shoot_full")
repeat
  nshot=ishot
  repeat
    sleep(10)
    ishot=get_shot_number()
  until ishot~=nshot --signals new shot is ready
  -- post shot delay starts here
  if(nshot==0)then tv=get_tv96_direct() end-- metered by camera on first shot
  tv=tv+get_shot_meter(1) -- adjust exposure time
  -- more processing here if needed, i.e. write log file
  set_tv96_direct(tv) -- happens immediately now instead of next half shoot
  set_shot_interval(-1) -- abort post shot delay. Camera takes next shot as fast as possible now
until false
An unexpected bonus from using this method is that the pictures are displayed on the screen (even with review off). In other shooting modes, the live view is displayed, and the screen goes blank during the exposure. At night, with long exposures, all you see is the screen flash between shots. But with this method, the screen shows the last shot for the entire duration of the long exposure. This is a big improvement.
Title: Re: Shot Histogram Request
Post by: lapser on 20 / December / 2012, 21:12:55
I tried a time lapse at 1 shot per second with the new functions. Lua stopped working towards the end, while I was stopped in the shopping center parking lot. The message was:
1219010
Press Shutter To Continue

But the interesting thing was that the pictures kept right on coming. The log and shot metering stopped, and the frame rate must have dropped, since the post shot delay was timing out at 1 second.  But you can't even tell where Lua stopped working when looking at the pictures and video. Note that the video continues past the stop at the shopping center where Lua stopped. I'm pretty sure the cause was closing and reopening the log file in case of a power loss. This sometimes took longer than 1 second, so the camera went on to the next shot before the lua script was ready. Whatever happened, it wasn't good. A longer, or no time out may be better. All delays are aborted when a script ends, so if the camera hung from a script error, it would be cleared when the script was ended with a shutter press.

CHDK Time Lapse Test (http://www.youtube.com/watch?v=ayBqE0v9BQI#ws)

The attached log file shows how accurate the pre-shot interval delay was. It was always exactly 1000 msec, except where I closed and reopened the log file. The second timing number measures the get_shot_ready() to get_shot_ready() time, i.e. when the shot meters are ready.

I got rid of the shot counter and added these new functions, which worked and are much easier to use and understand than the shot counter:

get_shot_ready() -- true when shot_meters and histogram are ready
reset_shot_ready()  abort post shot delay after processing shot data and reset shot_ready flag for next shot
Title: New Time Lapse - Timing Progress
Post by: lapser on 28 / December / 2012, 14:39:46
I've made a lot of progress with the timing of shots in the last few days. I set up a handshake from the camera shooting routines in continuous mode, to the Lua script so they wait for each other. This was my first test of the new routines, on the SX260 and also the G1X. Here's the G1X video (watch in HD):

http://www.youtube.com/watch?v=1-Dez4slXU4#ws (http://www.youtube.com/watch?v=1-Dez4slXU4#ws)
It's instructive to look at the first two frames, and the last frame of the video. Here they are, in full resolution:

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2Fq18CL.jpg&hash=ed0782901077d50b26ff74d37c90cba1)
This shot was metered by the camera with the standard center metering area. I set 4 shot metering areas, one in each quadrant, which are drawn over the first picture. If you click on the picture and zoom in, you can see that the areas are slightly separated from each other.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FWIW96.jpg&hash=edd94fcb0f797eebc5569a1c8fe6f16d)
This shot was taken about 1/2 second after the first shot, and is metered by the new shot_meter functions using the first shot. Each metering area returns an exposure correction to the script. The script picks the darkest correction, and sets the exposure for the next (this) shot. This results in optimum exposure of the sky, and underexposure of the darker part below, which is what I wanted.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FS7mOq.jpg&hash=b2e47003a768ff593c7326b9a22009e5)
This is the last shot of the video, when the SDHC card filled up (with RAW images). The camera kept on shooting correctly exposed images that were never saved, but were logged and timed. I knew something wasn't correct, but didn't realize it was a full card. I'll have to check for this in the future. The log says that the script was ready for this shot 730 msec early (out of a 1000 msec total interval). That's pretty good. However, the next shot was 1200 msec LATE! That's horrible. The script spent about 2 full seconds hung up by the file save problem, it would appear, which delayed the next shot because of the hand shake.

The result of this test is that I realized that the Lua script can't keep up with the speed of continuous mode shooting. I'll move the exposure adjustments into the C shoot loop, and the script will just monitor what's going on, enter new exposure compensation values occasionally, and start/stop the whole thing. I know this will work because I've done it by setting my interval to 0, which disables the hand shake. The script misses shots, but still sets exposure whenever it can, so it looks ok for a time lapse. By moving the set exposure part into the C shoot loop, each shot will be correctly exposed.

I'm not sure I've gotten across how useful this all is. Time lapses come out crystal clear, and slow enough to appreciate, when each shot can be a single frame. This requires high speed shooting. And with a picture every 1/2 second, you're pretty close to having a video, but with 4000x3000 resolution, 14 bit dynamic range, and accurate exposure using shot metering. The pictures in this time lapse have enough resolution to zoom in on the post office and watch the trucks come and go. The first picture shows 4 trucks at the post office loading dock. The last picture shows 5 trucks. You could look through the pictures and find exactly when the 5th truck arrived, or make a video zoomed in at the post office lot. Right click on the picture, and save or open it in a new tab to see the full resolution image. The place I'm talking about is in a notch in the trees towards the lower, right center of the image.

Also, I was showing some friends how fast the camera took pictures in continuous mode, and how it still adjusted the exposure between shots. They hammed it up in front of the camera for awhile, but when they stopped, there was one image where their phony smiles became real smiles for just a moment. Those moments don't happen very often, and you don't capture them with correct exposure unless you're really lucky. High speed multi-shot metering could be an extremely useful feature for point and shoot cameras. Stay tuned.
Title: Re: Shot Histogram Request
Post by: waterwingz on 31 / December / 2012, 14:46:19
Rather than releasing new diff files, it might be easier to send them to philmoz to put in his branch?
@lapser :   I've scanned as many of your threads as I could find looking for patch files.  I have a few moments and I thought I'd like to try out some of the tricks you've learned.  But the only one I could find is the recent one in the "Improvements to press, click, release for shooting keys" tread and that's not what I'm looking for.

Did you ever pull together anything on your histogram metering & continuous shooting sync / timing stuff ?

Title: Re: Shot Histogram Request
Post by: lapser on 31 / December / 2012, 22:19:24
Did you ever pull together anything on your histogram metering & continuous shooting sync / timing stuff ?
I did get a little side tracked on the key function changes. I finally found that all day bug, and have it working.

I'll make it the top priority to get a new diff file out, and an understandable demo Lua script. I'll post it here as soon as possible. Thanks for your interest, and your help.
Title: Re: Shot Histogram Request
Post by: Lightning_Lee on 02 / January / 2013, 01:51:26
lapser, I absolutely love your work mate, I would like to go thank everyone in this forum/community but not to be annoying...I won't.
I have followed your work now for a while at the same time as trying to get my head around using and working with CHDK. The things you are working on will come in very handy for me one day, that is when I get a few P&S's(already ordered) and see what I can't blow up...I mean figure out! :) Going to be a steep learning curve for me but one day I hope I can help out some and give back something!

Cheers again!
Title: Re: Shot Histogram Request
Post by: lapser on 02 / January / 2013, 04:32:49
lapser, I absolutely love your work mate, I would like to go thank everyone in this forum/community but not to be annoying...I won't.
I have followed your work now for a while at the same time as trying to get my head around using and working with CHDK. The things you are working on will come in very handy for me one day, that is when I get a few P&S's(already ordered) and see what I can't blow up...I mean figure out! :) Going to be a steep learning curve for me but one day I hope I can help out some and give back something!
Thanks for the comments. I'm looking forward to your input. Let me know if there's anything I can do to help, and don't be afraid to ask stupid questions. Hopefully, I'll have something ready for you to try out when you get your CHDK camera going. Good luck.
Title: New Sunset Time Lapse Tests
Post by: lapser on 04 / January / 2013, 00:21:36
I finally got a real sunset to test the new shot metering routines. It was too cold to stay very long after dark, but I got a nice smooth fade with both cameras, with no flashes.

The G1X was pointed west, with the sun in the initial frame. I don't have the script set to change anything but Tv, so I set ISO to 800 for the dark part. But the sun was way too bright. I set the aperture as small as possible, which helped a lot. The shot interval was 1.5 seconds per shot.  Here's the video from the unedited pictures at 24fps:
http://www.youtube.com/watch?v=Qi8lkk6SlWQ#ws (http://www.youtube.com/watch?v=Qi8lkk6SlWQ#ws)

I also set up the SX260 at 2 shots per second pointed East, starting about 5 minutes before official sundown. It was clear enough to see the snow covered 3 Sisters volcanoes on the horizon. The sx260 hit the maximum 6 second shutter speed I set for it, and got dark. But the stars and cars were visible. At 2 seconds apart, and 1 frame per shot, the car motion seemed smooth at 48X normal speed. Here's the video:
http://www.youtube.com/watch?v=Ymq2E5hMH_E#ws (http://www.youtube.com/watch?v=Ymq2E5hMH_E#ws)

I've attached the 2 log files, which show the timing variables, and the shutter speed for each shot. It's interesting that all the times for the SX260 are slightly faster than for the G1X. The G1X uses the Digic 4, while the SX260 has the Digic 5. This might be the reason for the difference.
Title: One shot per second test
Post by: lapser on 10 / January / 2013, 01:39:34
I had to hurry off the hill before the rain/snow shower arrived, but this time lapse was interesting while it lasted. And it lasted for over 2,000 shot! One shot per second is really fast!
http://www.youtube.com/watch?v=WFdCfd5VkjE#ws (http://www.youtube.com/watch?v=WFdCfd5VkjE#ws)
Title: Two New Time Lapse Videos
Post by: lapser on 17 / January / 2013, 23:48:43
I used both cameras last night at 1 shot per second for over 2,000 shots each. Both cameras stopped with a lua error number (large number). I've seen this happen before. I think it's related to writing a lot of data to the log file at the same time that the camera is writing pictures in continuous mode as fast as it can. I've modified the script to print only to the screen and not to a log file. I'll try to test it again soon.

I used 4 shot meters, one in each quadrant, on both cameras. The script is set up to pick the brightest meter, which gives the darkest picture. Because of the moving fog below the top of the mountain, where I was, the brightest meter was on the moving fog, and there was some flickering of exposure when looking at the sky above the fog. It would have been best to move the meter to the sky. The meter should be on something that isn't changing brightness, like empty sky, or even a card in front of the camera.

I also modified my exposure algorithm so it adjusts shutter speed until it reaches 1 second, then adjust ISO until it gets to 800, then goes back to shutter speed. The transition isn't noticeable.

http://www.youtube.com/watch?v=OzZ3giiQcNg#ws (http://www.youtube.com/watch?v=OzZ3giiQcNg#ws)

http://www.youtube.com/watch?v=sUAnTJ_LFGI#ws (http://www.youtube.com/watch?v=sUAnTJ_LFGI#ws)

In addition to the log file write conflict, I discovered a bug in the depth of field function in Lua that philmoz has already corrected. While investigating the bug, I improved the focus part of the script so it focuses faster, and restores auto-focus when the script exits, instead of leaving the camera in manual focus.
Title: Finished Time Lapse Video
Post by: lapser on 23 / January / 2013, 01:26:43
http://chdk.setepontos.com/index.php?topic=9270.0 (http://chdk.setepontos.com/index.php?topic=9270.0)
The original request I started with was to improve get_histo_range so it had more precision. Take a look at the above link, where the new functions are actually used to successful set exposure for ETTR (exposure to the right), and maximum dynamic range.

I've been a little side tracked, but I did find the time to make this finished time lapse video from my pictures last Wednesday above the fog at sunset:

http://www.youtube.com/watch?v=4pAmnpii3HU#ws (http://www.youtube.com/watch?v=4pAmnpii3HU#ws)

I ran the pictures through lightroom for leveling and color tweaking, and added some background music. The effect is kind of surreal.

I did a similar time lapse during the summer from Mary's Peak, with clouds below that looked like the ocean. The shot rate was much lower back then, and I processed the video by cross-fading between frames. It works, but takes all day to do a single video. It's much easier now with 1 shot per frame, and no cross-fading. Here's the Mary's Peak video:

http://www.youtube.com/watch?v=Ed_HXjPew2A#ws (http://www.youtube.com/watch?v=Ed_HXjPew2A#ws)
Title: Re: Shot Histogram Request
Post by: pigeonhill on 23 / January / 2013, 09:03:32
Lapser

Great timelapse work. I see you use LR. I also use LR for my timelapse work, but with LRTimelase. I find LRT to be the ideal adjunct to LR. Have you looked at LRT? 

Also how do you use your ETTR calls?

Cheers

Garry
Title: Re: Shot Histogram Request
Post by: lapser on 23 / January / 2013, 14:54:49
Great timelapse work. I see you use LR. I also use LR for my timelapse work, but with LRTimelase. I find LRT to be the ideal adjunct to LR. Have you looked at LRT? 

Also how do you use your ETTR calls?
Thanks! The higher speed shot interval really helps.

I haven't written any ETTR calls yet. The idea is to return an Apex96 expsoure value that you can add to Tv96 to reach ETTR on the next shot. I'm thinking it could be something like this:

tv96=get_ettr(5)+tv96-32

This would mean 5/1000 of the pixels can be above white leve -1/3 fstop. You could have a similar function for ETTL. Does that sound like it would be useful?

====
I've used LRTimelapse, but I don't think it's worth the $100. I also don't like the way he writes warnings that you haven't paid him in all the pictures.

My get_shot_meter() function allows smooth exposure changes without the need for post processing in LRTimelape. It's much better to get the exposure right the first time (sounds like a Billy Joel song).

It would be nice to be able to adjust the white balance in CHDK. They always say not to use auto white balance with a time lapse, but it might work, depending on how course the adjustment is. I'll experiment around a little.

The only useful thing LRTimelapse does for me at the moment is smoothly change Lightroom settings between two key pictures. The implementation is pretty clunky, though. I noticed the smoothing curves are wrong too. They overshoot the key points.

Eventually, I'll write a LRTimelapse replacement that just modifies the XMP data of pictures between Lightroom key points. It's just text manipulation, so I may even do it in Lua for Windows, which I already have.
Title: Re: Shot Histogram Request
Post by: pigeonhill on 23 / January / 2013, 15:58:08
Lapser

The timelapse community talk of the holy grail technique, that lets you address jumps in the exposure, because of ISO jumping etc. I believe the other 'holy grail' is how to achieve in-camera ETTR. I believe CHDK, and your histo functions, could lead the way here, at least until the next generation of camera come out with this feature built in.

I say this, as your histogram calls get us further along the line, as you are moving us away from being restricted to using the low data content of the 8-bit LCD-like histograms that the camera gives us. Thus the current ETTR strategy has to go something like this: take your first guesstimate shot, chimp at the histogram and or the 'blinkies', adjust as far as you think you can go, based on a JPEG histogram created from a very downsampled in-camera image; hope you haven't overshot and rely on a bit of RAW headroom in post.

Your calls give the in-camera ETTRer some tools, however, I think the real challenge, as you imply, is to come up with a suitable algorithm to maximize the probability of getting the exposure as far to the right as possible, without blowing out too much of the image. Hence, the first algorithmic problem, how do you differential between specular and blown out data that you can live with, and bits of the image that you don't want to be blown out?

In other words, ETTR to me implies someone wishes to take a single image and ensure the maximum RAW data content. But what about the bracketers!

When I do auto-bracketing (for HDR), I believe, at one level, I am addressing ETTR and ETTL, at the same time. The difference between single-image-capture ETTR and auto-bracketing-based ETTR is that one creeps up on ETTR (and ETTL) over several brackets with one, whilst the 'holy grail' ETTR script would attempt to 'jump' to the ETTR 'bracket' in the minimum number of goes, ideally 2 or 1.

When I use my auto-bracketing script, there are several strategies I could adopt:
1. Meter with an evaluative (image wide) base exposure (0Ev) and let the script take as many brackets +ve or -ve as it needs to meet my criteria;
2. Spot meter for the darkest shadow were I wish to see 'image data' and, once again, let the script run;
3. Spot meter for the highlights were I wish to see 'image data' and, once again, let the script run.

I must say, I tend to use strategy 2, and then my script creates one exposure brighter, as I call this function first and it must take at least one image to assess the histogram. I then move to the function that addresses highlights and it takes as many of these ETTR-like images as it needs, ie it takes images until I have an ETTR image that meets my criterion, ie is the lapser-count in my sub-zone (usually a 1/3 of a stop from the top) less than my count criterion.

I believe the auto-bracketing strategy gives us ETTR and it is scene-independent. The 'over head' being I will take more images than I need, if I had a holy grail, single-image ETTR shooting mode. But, as I say, with auto bracketing and cheap SD cards, is this a problem. Well it could be if I wanted to shoot fast and freeze a scene, ie one image. But, for me, bracketing serves me well, and motion blur can be artistic!

BTW my thoughts o this subject will likely take a few posts, so I wont complete my thinking here. Also I always reserve the right to change my mind if a better idea comes up!

However, one thought I have had is this. Is there a way to get CHDK to take an image without recording it to the SD card, look at the histogram and based on this take a decision to record the image or adjust the image exposure and take another non-recorded image to evaluate that histogram? Just a thought?

Bottom line: I believe any reasonable auto-bracketing script, IMHO like mine, is a form of ETTR; it just comes with an overhead of needing more memory and shooting time. But it has the 'advantage' in that you don't need to worry about the scene-specific algorithmics. In other words, I worry about these in post-processing. BTW my post-processing for brackets these days is to create a 32-bit file in LR, using Merge to 32bit HDR, and process the image in a 32-bit LR space.

Cheers

Garry
Title: Re: Shot Histogram Request
Post by: lapser on 23 / January / 2013, 16:44:48
Actually, I've already gotten to the time lapse holy grail with my get_shot_meter() function. That's how I made all these time lapses with the sun going down. Instead of the histogram, it uses the shot meter, which returns an exposure compensation change so the average of the pixels values in the next shot will be 2 f/stops below the 50% value of 2048. By returning the change in Apex96 units instead of linear, it's useful for setting exposure on the next shot.

With 4 shot meters available, I can set each one at a different spot in the picture, and use an algorithm to choose the meter. For testing, I've been setting a meter for each quadrant and picking the brightest meter. But the lua script can do whatever it wants. It probably will give better results for time lapse to use the average meter value, rather than go for ettr, especially with the sun in the shot at the beginning. But the script will have all the meters and ettr, ettl values available to it. It should give a lot of flexibility for setting exposure.

get_ettr(x) would do the same thing as get_shot_meter(), but instead of using the average of the pixel values, it would find the exposure change to get to the point where x/1000 of the pixels would be above white level. Then, you would subtract Apex96 units from there. By starting at that point, and subtracting 32 for each subsequent picture, you would bracket the ETTR value. It's just a faster way of doing what you're doing by starting closer to the target ETTR value. The magic of working with Apex96 log values is that it's just simple addition to change exposure however you want.

One feature I've included is the ability to take more than one shot per interval. You specifiy that with:

set_shot_interval(10000,3), for example. Every 10 seconds, this would take 3 quick shots (in continuous mode). The idea is to get the correct exposure after a long delay.

I've asked several times if one of the hackers could figure out a way to throw away the shot without creating and saving the jpg. It takes about 250 msec to get to the raw buffer, so throwing it away give you a really quick meter, probably quicker and more accurate than the pre-shot meter in the camera. I can see future cameras doing all their final metering this way, maybe including an HDR bracketing option using the ettr,ettl values.
Title: Re: Shot Histogram Request
Post by: waterwingz on 26 / January / 2013, 12:30:23
Did you ever pull together anything on your histogram metering & continuous shooting sync / timing stuff ?
I did get a little side tracked on the key function changes. I finally found that all day bug, and have it working.  I'll make it the top priority to get a new diff file out, and an understandable demo Lua script. I'll post it here as soon as possible. Thanks for your interest, and your help. 
@lapser :  Its been a couple of week, time for a "bump" on this one?  Unless I missed it in one of your (many) other threads ;)
Title: Re: Shot Histogram Request
Post by: lapser on 26 / January / 2013, 13:51:43
@lapser :  Its been a couple of week, time for a "bump" on this one?  Unless I missed it in one of your (many) other threads ;)
Point taken! It would be easier for me to compile a version for your camera and tidy up the documentation for the functions that are working so far so you can start playing with them. Would that be acceptable?

I've been really stuck on the timing thing at high shot rates in continuous mode. I figured out that writing a log file at shot rates faster than about 1.5 per second creates long delays. I can see the print(..) statements falling behind and then catching up (with print_screen), but there are no delays without print_screen.

I thought I was going to have to add auto exposure adjust functions to get the timing right, which turns out to be pretty complicated. But now I know that Lua can keep up as long as there aren't any writes to the SD card.

For logging, I think I can write a buffered Lua bwrite(string) function that saves everything in a string array and writes it out at the end.

Anyway, let me know your camera (or cameras) model and firmware revision, and I'll post something for you today.

====== EDIT =========
I've updated and attached the documentation for the time lapse modifications as they exist at the current moment. I'm ready to post a build for you as soon as I know your camera model/firmware.

The build also includes the Apex96 exposure functions discussed here:

http://chdk.setepontos.com/index.php?topic=9335.msg96139#msg96139 (http://chdk.setepontos.com/index.php?topic=9335.msg96139#msg96139)

I think I'll need to add a scale factor for ISO conversions for accuracy. I need to test that.

1000 is the default scale for shutter speed, which means msec accuracy. reyalp likes usec (microseconds) with no scale option. The shooting_set_shutter_speed_ubasic function uses 100,000 as the scale.

1000 is also the default scale for av96 conversions.
Title: Re: Shot Histogram Request
Post by: waterwingz on 26 / January / 2013, 15:19:36
Anyway, let me know your camera (or cameras) model and firmware revision, and I'll post something for you today.
Thanks,  but I tend to rebuild daily (to test my changes and those posted by others) so having a custom build is not a lot of use.   A patch file would help - even if it won't apply immediately I can probaly tweak the parts I need for  the current build and then just carry those changes forward myself.

Quote
I've updated and attached the documentation for the time lapse modifications as they exist at the current moment.
Thanks again but without a patch file to work with having documentation for functions but no source code doesn't do me a lot of good.

Rather than ask you to go to a lot of additional work,  I'll go back to my other projects.  When you get ready to release something I'll see it in the forum and give it a try.



Title: Re: Shot Histogram Request
Post by: lapser on 26 / January / 2013, 15:53:45
Thanks,  but I tend to rebuild daily (to test my changes and those posted by others) so having a custom build is not a lot of use.   A patch file would help - even if it won't apply immediately I can probaly tweak the parts I need for  the current build and then just carry those changes forward myself.
OK, when I have a more stable patch file ready, I'll post it and notify you. Thanks for offering to test it.
Title: Time Lapse Mods Diff File
Post by: lapser on 26 / January / 2013, 18:05:27
OK, here's the current diff file. I'm experimenting with the shoot() bug, so you can probably just delete the action stack portion if you want to.

It's still preliminary, but it seems to work on my cameras.

I also updated the directions a little, and attached the latest documentation file.

Thanks to everyone who made CHDK possible, and especially to reyalp, philimoz and waterwingz for all the help that got me this far.
Title: Re: Shot Histogram Request
Post by: waterwingz on 26 / January / 2013, 18:08:49
OK, here's the current diff file.
Thanks - wasn't really expecting you to take time out to do this.   I'll play with it this week after I get over the shock of doing the first pass through my 2012 taxes.

Title: Re: Shot Histogram Request
Post by: lapser on 27 / January / 2013, 14:51:56
http://www.youtube.com/watch?v=MQah7sksQaw#ws (http://www.youtube.com/watch?v=MQah7sksQaw#ws)
I did another time lapse with the sx260 and g1x last night in the rain. I tried Saran (plastic) Rap and tape to protect the cameras from the rain. That worked pretty well, but some water still got on the lens. I put on one of those butterfly lens hoods on the G1X and that kept most of the water out. You can see me putting it on in the video.

The G1X did about 3,500 shots until the battery died. There was a sudden increase in brightness near the end, which I also noticed in my last test video (not uploaded). That could be in the script, or a bug in set_sv96(..). I'll figure that one out later.

The sx260 halted with an unspecified Lua error at about 1500 shots, giving only the "SCRIPT TERMINATED" message. This has happened before on both cameras while writing a log file, but this time I wasn't writing a log, so it must be related to something else.

Both cameras were in continuous mode, slowed down by the delay right before shutter open, set with set_shot_interval. The sx260 was set to 2000 msec, and the g1x 1500 msec. I have a possible answer, and solution:

My current get_shot_ready() function returns false until the shot meters and histogram are ready, and then returns true only once per shot. In continuous mode, you wait for get_shot_ready(), read the shot meters, set the exposure, and go back to waiting for get_shot_ready(). The problem is that get_shot_ready() has a timeout, which defaults to 100 msec. Normally, that's plenty of time, but occasionally, it starts timing out. I think the problem may be related to the script reading the shot meters while they're being computed for the next shot.

I realized that there's no need for a timeout in get_shot_ready(). It always returns immediately, so the script can implement a timeout if it wants to.

In continuous mode, the camera keeps shooting all the time. set_shot_interval(..) slows it down, but the shots can come fast and furious. The camera keeps up as well as possible by buffering shots. I think this is what the 2 raw buffers are for.

I think you can still set Sv96 and Tv96 during the delay in capt_seq_hook_set_nr(), but I'll have to test that more. It's taking awhile to figure out all these complications, but once I do, I should be able to keep up and meter exposure in continuous mode reliably at 2 shots per second or more.
====

I've also done some experiments with the histogram using a step size of 1, which samples the entire raw buffer. It takes about 16 seconds to do this, using get_raw_pixel(x,y). I just discovered that it only takes 1.5 seconds to go through (trash) the entire raw buffer using the raw buffer base address. A little in-line assembly code might even speed it up a little more.

I'm actually more interested in hot pixel removal in the raw buffer for long exposure night shots. It looks like 1.5 seconds is the minimum time it could take, which would be a big improvement over taking a dark frame every shot that doubles the time for each shot. Looks like another project for the future.

My latest shoot() bug idea got shot down in tests by skrytlen. I'll try to hold off until I can reproduce the bug on a camera that I can test myself.

Here's the test video I did last night from Skinner Butte in Eugene, Oregon, named after the city founder, Eugne Skinner. The highest spot in the background, towards the left, is Spencer's Butte, which is about 2,000 feet (600m) high. A lot of my other time lapse videos are taken from there.
[url=http://I did another time lapse with the sx260 and g1x last night in the rain. I tried Saran (plastic) Rap and tape to protect the cameras from the rain. That worked pretty well, but some water still got on the lens. I put on one of those butterfly lens hoods on the G1X and that kept most of the water out. You can see me putting it on in the video.

The G1X did about 3,500 shots until the battery died. There was a sudden increase in brightness near the end, which I also noticed in my last test video (not uploaded). That could be in the script, or a bug in set_sv96(..). I'll figure that one out later.

The sx260 halted with an unspecified Lua error at about 1500 shots, giving only the "SCRIPT TERMINATED" message. This has happened before on both cameras while writing a log file, but this time I wasn't writing a log, so it must be related to something else.

Both cameras were in continuous mode, slowed down by the delay right before shutter open, set with set_shot_interval. The sx260 was set to 2000 msec, and the g1x 1500 msec. I have a possible answer, and solution:

My current get_shot_ready() function returns false until the shot meters and histogram are ready, and then returns true only once per shot. In continuous mode, you wait for get_shot_ready(), read the shot meters, set the exposure, and go back to waiting for get_shot_ready(). The problem is that get_shot_ready() has a timeout, which defaults to 100 msec. Normally, that's plenty of time, but occasionally, it starts timing out. I think the problem may be related to the script reading the shot meters while they're being computed for the next shot.

I realized that there's no need for a timeout in get_shot_ready(). It always returns immediately, so the script can implement a timeout if it wants to.

In continuous mode, the camera keeps shooting all the time. set_shot_interval(..) slows it down, but the shots can come fast and furious. The camera keeps up as well as possible by buffering shots. I think this is what the 2 raw buffers are for.

I think you can still set Sv96 and Tv96 during the delay in capt_seq_hook_set_nr(), but I'll have to test that more. On thing that's taking so long is figuring out all these complications, but once I do, I should be able to keep up and meter exposure in continuous mode reliably at 2 shots per second or more.
====

I've also done some experiments with the histogram using a step size of 1, which samples the entire raw buffer. It takes about 16 seconds to do this, using get_raw_pixel(x,y). I just discovered that it only takes 1.5 seconds to trash the entire raw buffer using the raw buffer base address. A little in-line assembly code might even speed it up a little more.

I'm actually more interested in hot pixel removal in the raw buffer for long exposure night shots. It looks like 1.5 seconds is the minimum time it could take, which would be a big improvement over taking a dark frame every shot that doubles the time for each shot. Looks like another project for the future.

My latest shoot() bug idea got shot down in tests by skrytlen. I'll try to hold off until I can reproduce the bug on a camera that I can test myself.

Here's the test video I did last night from Skinner Butte in Eugene, Oregon, named after the city founder, Eugne Skinner. The highest spot in the background, towards the left, is Spencer's Butte, which is about 2,000 feet (600m) high. A lot of my other time lapse videos are taken from there.
Title: Re: Shot Histogram Request
Post by: pigeonhill on 27 / January / 2013, 17:36:59
lapser

I assume you did no post processing deflickering? In other words your script ensures a sufficiently smooth transition during the day to night shooting? Do you do any ISO changes, or do you restrict yourself to only Tv changes?

Also, would you be prepared to share your script? I find looking at other scripts is a great way of learning more about CHDL/LUA scripting. I am still a novice 'scripter', but wishing to learn more.

Finally, are all the functions you use in the version you previously sent me for my S95 and G11? In other words the exposure adjustment calls?

Cheers

Garry
Title: Re: Shot Histogram Request
Post by: lapser on 27 / January / 2013, 18:51:14
I assume you did no post processing deflickering? In other words your script ensures a sufficiently smooth transition during the day to night shooting? Do you do any ISO changes, or do you restrict yourself to only Tv changes?
I made the video with the free program, Videomach, without processing the pictures. In fact, I left all the photos on the SD card, and output only the video file to the computer. Each picture is a frame. Using the shot meters to adjust exposure in 1/96 ev increments, combined with the high shot rate makes a very smooth time lapse, plus a very easy post production process. I think I tried auto white balance this time. That's where LRTimelapse would come in handy, because CHDK can't adjust white balance  (yet).

The exposure changes are done in the script. This test script sets sv96 to 100 ISO, and adjusts tv96 until it gets to 1/2 second. Then it adjusts SV96 until it gets to 800 ISO. Then it goes back to tv96 up to 10 seconds. After that, things get dark fast.

My previous scripts used the brightness, bv96, to adjust the exposure as it got dark, to avoid overexposing, i.e. 192 ev96 down between +500 and -500 bv96. I haven't implemented that in this script yet, but it works pretty well.
Quote
Also, would you be prepared to share your script? I find looking at other scripts is a great way of learning more about CHDL/LUA scripting. I am still a novice 'scripter', but wishing to learn more.
My creative process is pretty messy, but I'll see if I can clean up the script a little and post it for you soon.
Quote
Finally, are all the functions you use in the version you previously sent me for my S95 and G11? In other words the exposure adjustment calls?
I've been changing things pretty fast, so it might be better to start with new builds. I'll post those with the script for you when I get something ready.

I just finished changing the get_shot_ready() function so it doesn't time out, and doesn't delay at all in single shot mode (not needed). I also changed the test for single shot mode from
single=get_drive_mode()~=1
to
single=get_drive_mode()==0

The G1X has a continuous drive mode with auto-focus that returns a drive mode of 2. Using a script, though, it doesn't always auto-focus. The first time I run this script, it does auto-focus:
Code: (lua) [Select]
--[[
@title Clapse
--]]
--MUST BE IN CONTINUOUS MODE
press("shoot_half")
repeat sleep(10) until get_shooting()
print("Holding shoot_full")
print("Press <menu> to exit")
press("shoot_full_only") -- continuous mode
repeat
  sleep(100)
until is_pressed("menu")
The second time I run it in continuous mode, it does NOT auto focus, although it does shoot continuously. Also, it seems to only focus with shoot_full_only, and not with just shoot_full.

I think there's code that releases all the keys when a script ends, so I haven't bothered to do it in restore(). I'm not sure this is working right on the G1X. Maybe Phil could take a look.
Title: Re: Shot Histogram Request
Post by: pigeonhill on 27 / January / 2013, 19:31:22
Thanks
Title: Re: Shot Histogram Request
Post by: philmoz on 28 / January / 2013, 02:09:56
The G1X has a continuous drive mode with auto-focus that returns a drive mode of 2. Using a script, though, it doesn't always auto-focus. The first time I run this script, it does auto-focus:
Code: (lua) [Select]
--[[
@title Clapse
--]]
--MUST BE IN CONTINUOUS MODE
press("shoot_half")
repeat sleep(10) until get_shooting()
print("Holding shoot_full")
print("Press <menu> to exit")
press("shoot_full_only") -- continuous mode
repeat
  sleep(100)
until is_pressed("menu")
The second time I run it in continuous mode, it does NOT auto focus, although it does shoot continuously.

Works fine on my G1X.
Possibly some other camera or CHDK setting might be interfering.
Try deleting or renaming your CCHDK2.CFG or CCHDK3.CFG file (depends on version you are running) and using the unmodified trunk or release version.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 28 / January / 2013, 15:40:21
Works fine on my G1X.
Possibly some other camera or CHDK setting might be interfering.
Try deleting or renaming your CCHDK2.CFG or CCHDK3.CFG file (depends on version you are running) and using the unmodified trunk or release version.
Thanks Phil. I reformatted my SD card and started from scratch with the full version. The script worked before and after I applied my time lapse patches, so you were right (as usual).

I have the new get_shot_ready([enable]) working. The optional parameter [enable] refers to the post shot wait for the script to call get_shot_ready() again. get_shot_ready(0) never waits, get_shot_ready(1) always waits, and get_shot_ready() only waits in continuous mode. I changed the test for continuous mode to:
get_drive_mode()!=0 (mode 2 is continuous with auto focus on my cameras).

get_shot_ready(-1) ends the script wait, but doesn't reset the ready flag. This call can be used to let the shot processing continue after the time critical script code is finished, i.e. setting the new exposure.
====
One other new thing I just added is a minimum interval option based on shutter time.

set_shot_interval(interval [,imin ,nshots])

imin + shutter time is used if it is longer than interval. imin defaults to 0, which gives a 0 delay as it gets dark and the shutter time increases beyond the interval time. Setting imin >450 or 500 should keep the interval ahead of the shutter time a little, so there's always some delay and the interval increases smoothly as it gets darker, rather than being dependent on the variable shot processing time. This may be hard to understand, but it should result in a video whose speed accelerates smoothly as it gets dark. With imin>750 and an interval of 1000, there should be enough delay to keep the buffers from clogging up at too fast a shot rate in continuous mode. More testing is needed. If it doesn't work, I'll eat my shor... on second thought, not.
Title: Re: Shot Histogram Request
Post by: lapser on 29 / January / 2013, 21:18:31
I tested the new time lapse changes yesterday at sunset with the G1X. My SX260 is all wrapped up and ready to mail back to Canon for warranty repair.

I also bought a floor model SX50 at Costco with a good discount. It looks like a nice camera. CHDK is being ported, with good progress. I haven't done anything with the camera except take a few pictures. I did notice that it holds manual focus when the display is  turned off and back on, unlike the G1X. The viewfinder is electronic, while the G1X has an optical viewfinder.

Anyway, back to the G1X time lapse test. It took 2,800 pictures at 1 shot per second with logging without any problem. I used a 750 msec minimum interval plus shutter time. I need a better name for it besides minimum interval. But I think it helped keep the camera from backing up saving files to disk. The script wait time was always under 50 msec max. I did notice the screen printing lag behind a little sometimes. The camera would flash its busy signal during this time. But it always caught back up by the next shot.

I think I'm understanding what happens in continuous mode. There are two raw buffers used in continuous mode. The camera shoots as soon as a raw buffer is empty. It seems to take around 250 or 300 msec from shutter open to when the raw buffer is ready. Then the camera takes another shot immediately and puts it in the alternate raw buffer. It then waits until the raw data in the main buffer has been converted to jpg and saved to the SD card. As soon as the main buffer is clear, it takes the next shot into the main buffer.  The 2 buffers allow a higher shot rate. In single shot mode, you can get about 1 shot per second. The 2nd buffer increases that to 2 shots per second, since shooting and filling the buffer are decoupled from the jpg conversion and file saving.

This presents a problem for my shot meter, though. The next picture is already taken, or waiting to be taken in my interval delay loop right before shutter open. It's not certain that the exposure changes calculated by the shot meter can be applied to the next shot. It appears to be a shot behind. The first two shots in the video, which I hold for 4 seconds each, show this. The first shot is metered by the camera, with the 4 metering areas drawn. The next shot is metered with the shot_meter from the first shot, but the exposure change didn't make it in time to be applied. So the second shot has the same exposure as the 1st shot. The 3rd shot shows an exposure change, probably computed from the first shot, but could be from the second shot. I'll have to fix this.

The problem is that the shot meter returns a relative value, not an absolute brightness. When you add the shot meter value to the current Tv96, the next shot should be properly exposed. It's important that the Tv96 used to take the metered shot is known, since that's the reference Tv96 for the meter. But it looks like the TV96 used for the current shot is taken from 2 shots back, not the last shot. With the light changing the script will over-correct based on 2 shots ago. The next shot, based on the brighter meter value 2 shots ago, will be underexposed. The meter sees that and over exposes the following shot. In other words, it might oscillate up and down one or 2 ev. I have seen this happening, but I thought it was from clouds going by or compression artifact.

So I'll have to save tv96, sv96 and av96 for each shot right before the shutter opens, and use these values to get an absolute Bv96 from the meter after the shot. This should also make the shot meter return value identical to the get_bv96() return value in the camera. get_shot_bv96() may be a more appropriate name if this works out, rather than get_meter_bv96().

I also noticed that there is a sudden brightness jump towards the end of the video again. This time I had a log file, and the brightness jump occurred when tv96 reached 0, or 1 second shutter time. It jumped immediately to 2 seconds. In the video, this means it gets suddenly brighter, and faster, since the shutter time is longer than the shot interval. But at least the speed of the video accelerates smoothly after that, as the shutter time increases to 6 seconds. The new code, where I base the minimum interval on the shutter time seems to work well, and gives a smoother speed increase than just letting the camera shoot as fast as it can. Plus, there were no script delays writing to disk, which I now think are caused by full file buffers. This seems to slow the camera to a crawl, so it's best to avoid it by slowing the shot rate.

I'm not sure what caused the sudden exposure jump from 1 to 2 seconds. I'm setting sv96 and tv96 using the built in routines in shooting.c modified to set immediately in half_shoot. I'm doing another test now using propcases in Lua to set sv96 and tv96 to see if the problem is with the modified routines in shooting.c.

Here's the video and attached log file of last night's test:

http://www.youtube.com/watch?v=v-iRfz2dy78#ws (http://www.youtube.com/watch?v=v-iRfz2dy78#ws)
Title: Time Lapse Test using propcases to set exposure
Post by: lapser on 30 / January / 2013, 00:25:59
This test uses propcases for exposure instead of the modified set_sv96(..) and set_tv96_direct that works immediately in half_shoot. I didn't see the sudden exposure change at 1 second, so there must be something wrong with one of these functions. My guess is set_sv96(..) is the culprit. There's a lot of code in there to set the base sv that just doesn't make much sense. set_tv96_direct just sets the propcases the same way I do in Lua, so it's probably not the problem.

I'll try modifying set_sv96(..) so it just sets 2 propcases and ignores the base. It gives the right exposure, which is what counts. The ISO speed is also correct, to the nearest Canon value, in the Exif data. Reyalp doesn't seem to want to fix anything in the exposure functions, so I may have to write a new function: set_sv96_correctly()  :)

This test produced 3500 pictures in 2 hours, mostly at 1 shot per second. The script starts at 100 ISO until the shutter time goes to 1/2 second, increases to 800 ISO, and then increases the shutter to 10 seconds. The playback speed goes up at the end of the video as the shutter time exceeds the interval time. But I increased the minimum interval time based on shutter time to make sure there was a little delay between shots so the buffers don't back up. It worked. The delay between shots (idle delay) started at 600 msec with 1/100 shutter. This means that it could have gone at 2 shots per second and still have 100 msec delay left over.

However, as the shutter time increased, the idle time between shots dropped to 100 msec. This still kept the buffers running smoothly. The script wait time was 30-40 msec most of the time, with one 60 msec, but no higher. This is with writing 2 lines of log data per shot, so it looks good.

I tried to compare the script shot counter with get_exp_count(), and the script counter was 1 behind. I'll have to work on matching up the shot the meters measured, and the exposure used for that shot. Also, it would be nice to know the exposure number, i.e. the filename, that goes the exposure data.

This video always chose meter #1, the upper left quandrant, as the brightest meter. The meter values didn't really show oscillations, but they drop very slowly at 1 shot per second.

http://www.youtube.com/watch?v=iOvEj74TTh8#ws (http://www.youtube.com/watch?v=iOvEj74TTh8#ws)
Title: Some new discoveries
Post by: lapser on 01 / February / 2013, 14:17:49
I added a minimum delay of 100 msec in capt_seq_hook_nr() right before the shutter opens. I did another sunset time lapse last night, and the delay seemed to work to keep the file save buffers from filling up, as I hoped. The shot rate stayed constant, and the script processing times stayed in the 40 msec range.

But the script still halted with a script error, and when I re-started it, it halted again almost immediately. I then changed the delay to use the shutter time to set the minimum interval, and it didn't halt again. So it's related to certain timing conditions, and not the file write buffer full problem like I thought before.

Because the shutter opens and takes a shot on it's own in continuous mode, the script may be setting the exposure values (sv96 & tv96) at the wrong time, i.e. when the shutter is open. You might even have sv96 set, and tv96 missed, for example. Also, the exposure values used for the shot may be different from what they are by the time script reads the meters.

The exposure timing problem can be solved by setting exposure in capt_seq_hook_nr() right before the shutter opens. I tested this on the G1X, and setting tv96 at this time works. So I'll write a new function: set_exp96(sv,tv,av,nd) that sets the exposure right before the next shutter open. Then I can match up these values later when I'm computing the shot meter. Setting aperture and ND filter may require a delay afterwards, so I'll have to incorporate that too. Does anyone know a way to tell if the aperture and ND filter are ready? I'll have to experiment some more to figure this out.

I also need to return bv96 from the shot meter, not a deltaEv value. The script can then compute the correct exposure independent of the current exposure values. Also, I want to know bv96 so I can adjust exposure to get darker as the brightness goes down, i.e. underexpose at night.

Here's last night's time lapse at 30 fps made from 1 shot per second.

http://www.youtube.com/watch?v=Pz_SNSxfb_s#ws (http://www.youtube.com/watch?v=Pz_SNSxfb_s#ws)
Title: Re: Shot Histogram Request
Post by: philmoz on 01 / February / 2013, 16:47:55
The sx260 halted with an unspecified Lua error at about 1500 shots, giving only the "SCRIPT TERMINATED" message. This has happened before on both cameras while writing a log file, but this time I wasn't writing a log, so it must be related to something else.

There isn't anything in CHDK that would print "SCRIPT TERMINATED" - did you mean the "*** TERMINATED ***" message when there is an error in the script?

If so it should have displayed an error message as well - what did that say?

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 01 / February / 2013, 17:41:27
There isn't anything in CHDK that would print "SCRIPT TERMINATED" - did you mean the "*** TERMINATED ***" message when there is an error in the script?

If so it should have displayed an error message as well - what did that say?
Yes, it said "*** TERMINATED ***", with a large number like, 65094782 or something like that. Unfortunately, I lost the log file when I restarted the script. I'll have to use the print_screen(-1) option next time to append the log. I'll see if I can reproduce it and let you know the exact number if I can.
Title: Re: Shot Histogram Request
Post by: lapser on 03 / February / 2013, 01:29:43
I made a new time lapse tonight with over 4,600 shots, without the script halting with an error like the last time. I added a busy flag to build_shot_histogram that I think may have worked. get_shot_meter now waits until the busy flag is clear, so it doesn't read values that are being calculated at the same time in a different thread. Hopefully, this will fix the problem.

Another interesting thing I tested tonight was the ND filter. I started with the ND filter IN, so the sun wouldn't be over-exposed. It worked pretty well. When it got darker, I stopped the script, set the ND filter to OUT, and restarted the script. I deleted the first shot in the new sequence. The shot meter exposed the 2nd shot perfectly, matching the shot with the ND filter IN at the end of the first sequence.  The exposure change was about 2.75 EV when the ND filter went out. You can see the glitch at 1:11 in the video. There's a noticeable color change, so I guess the ND filter isn't quite ND. Here's the video:
http://www.youtube.com/watch?v=cpKlTpvoSWk#ws (http://www.youtube.com/watch?v=cpKlTpvoSWk#ws)
Title: New Discoveries
Post by: lapser on 04 / February / 2013, 23:59:00
I've been experimenting with Continuous Mode with some interesting results. First, I want to match up the exposure of the shot with the result from the shot_meter. The script sets the exposure, but triggering of the shots is done automatically by the camera. So the exposure the script sets may not end up as the exposure of the next shot_meter.

So I set up a buffer to save the exposure values Just before shutter open, I read the propcases for sv, tv, av, and nd_filter and save them in a buffer array that corresponds to the shutter shot count. I also have a raw shot count, which I use to read the exposure values out of the buffer. That way, these values correspond to the actual exposure of the shot as saved just before shutter open.

To avoid having the script set new exposure values at the wrong time, I added a new lua function:

set_exp96(tv[,sv,av,nd_filter])

The function saves the exposure values, which are stored into the propcases just before shutter open. These values usually become valid for the shot, but it looks like it may need a 10 msec delay after storing them to be totally reliable.

I decided to triple buffer the values. The third buffer is used for the script to print out the values without slowing the shot rate. The sequence is as follows:

1. Exposure values written to buffer using shutter_count index%3  (triple buffer)

2. Values are read from buffer in raw_save_file() using raw_count. These values are passed to the shot meter, which I'll use to computer Bv.

3. When the shot meters are ready, after build_shot_histogram(), the raw_shot_counter is incremented. This signals get_shot_ready() to return true. The script is waiting for this, and reads the shot meters. It computes new exposure values and saves them with: set_exp96(tv,sv). During this time, raw_save_file() waits for the next call to get_shot_ready() from the script.

4. After the script calls set_exp96, it then calls get_shot_ready(-1), which triggers raw_savefile to stop waiting for the script and move on to the next shot. However, the exposure values remain in the buffer, and can still be read by the script using the wait_count. get_shot_ready() sets wait_count=raw_count whenever it's called when the shot isn't ready. So the wait_count stays valid until the script finishes writing the data.

It sounds a little complicated, but the triple buffer keeps the shots coming as fast as possible without having to wait for the script to write log data. The camera can be exposing a new shot into one raw picture buffer while build_histogram is computing the shot meters for the last shot from the other raw buffer, and the script is printing out the log data out of the data buffer from the shot before that.

I tried a new time lapse today with a shot interval of 800 msec, or 1.25 shots per second. Everything went smoothly for 3,235 shots, without a glitch.
Skinner Butte 130204 CHDK G1X (http://www.youtube.com/watch?v=lVGfP0HWCdI#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 06 / February / 2013, 02:03:52
I finally figured out how to return bv96 from the shot meters. Before calculating the meters in build_shot_histogram(), I save bvbase=tv96+av96-sv96. The meter value + bvbase is the bv96 for that meter.

One of the reasons to use a shot meter rather than the built in camera meter is that get_bv96(), which returns the camera meter value, loses accuracy around -700 or so, which is a dark, starry night. The time lapse flashes at these low light levels, every time bv96 changes. By -750, it's changing by 70 ev96 at a time.

I tested my new shot meter bv96 with the lens cap on in a dark closet. The value was around -1500, varying by 50 maximum, probably from pixel noise. I set the exposure at 10 seconds and ISO 800. I'm hoping this means the meter will be accurate in the -750 range.

The other thing you can do with bv is gradually underexpose as it gets darker. I found that underexposing 1.5 ev at -500 starting from 0 at +500 looked good. I'll program that into my script for the next time lapse.

I have it set now for get_shot_meter(0) to return the bvbase value. So you can find the bv for any meter by adding it's value to bvbase. For example:

bvbase=get_shot_meter(0)
bv1=get_shot_meter(1)+bvbase

That's useful, but a little confusing. It may be better to add a get_shot_bv96() function.
Title: More Continuous Mode findings
Post by: lapser on 08 / February / 2013, 14:15:53
I've been doing a lot of testing in continuous drive mode. I got all those buffers working, but I discovered I may not need them.

I have 2 hooks where I delay the shooting process. First is in capt_seq_hook_nr(), which I call pre_shot. It happens right before the shutter opens. Next is in raw_save_file(), after the exposure is finished and the raw picture buffer is valid. I call this post_shot.

pre_shot: This is where I delay to get the desired shot interval. As long as the new exposure values are set before the end of the delay, it applies to the shot. If not, it takes effect on the next shot, which means you're 2 shots behind.

post_shot: Here I call build_shot_histogram() which calculates the shot meters. After they are ready, the Lua routine, get_shot_ready() returns true (once). The script then calculates and stores the new exposure values and signals the post_shot routine, which is now waiting for the script, to go ahead.

To faciliate this, I added a new Lua function: set_exp96(tv,sv,av,nd). This sets all the possible exposure values at one time, and then signals the post_shot_routine. The next call to get_shot_ready() also signals the post shot routine to proceed, in case the script isn't setting exposure.

A major discovery is that the pre shot and post shot routines never execute at the same time (at least on the G1X). As long as the post shot routine is waiting for the script signal, the pre shot routine isn't called. This means that the next shot always gets the exposure from the last shot, without missing shots. The key is to delay post shot until the exposure is set. It actually works (on the G1X). I discovered this when I added a pre shot wait for script, and stored the delay time. It was always 0. That is, the script was always ready before the pre shot routine was called. I confirmed this by writing values to the screen at the beginning and end of the pre and post shot routines.

So this is good news. I don't have to buffer all the exposure values for the shot meters. I just need to store one value, I call bvbase=tv+av-sv. I then return this value with the next get_shot_meter(0), and add it to the value returned by a meter to get bv96 for that meter.

The buffers did work really well for printing the log file, though. The script sets the exposure first, as soon as possible, and the next pre shot starts immediately afterwards. But the script is still reading the values from the last shot out of the buffer. Without the buffer, they disappear as soon as the next pre shot starts. The script could print the exposure values it just calculated as well as the shot meter values from the last shot that it used for those calculations. That should be enough, as long as the pre shot and post shot routines are always executed in sequence. I'll have to test this on my other cameras, the sx260 and sx50 (when I get it working).

I think the new handshake timing, along with the busy flag in build_shot_histogram() has fixed the script error problem. The new timing prevents the script from calling get_shot_meter() during the histogram build, but it's also possible that the script won't follow the handshake, so the busy flag is the backup.

The handshake only occurs in continuous mode, since it's not needed in single shot. Activating the handshake also requires a call to set_shot_interval(interval, nshots). If nshots>0, then the handshake is activated. nshots is the number of shots per interval. 0 is the same as 1, except without the handshake. Everything is disabled when a script is not active.

I'll leave the buffers in for now, for testing, since they also contain a lot of shot timing data useful for debugging.

I also modified my script to adjust for Bv as it gets darker, to avoid overexposure. Here's the exposure portion of the script, for those who might be interested:

Code: (php) [Select]
set_shot_interval(m,n)
if(not single)then press("shoot_full_only") end
repeat
  if(single)then press("shoot_full_only") end
  repeat
    sleeper(10) -- sleeps at least once, so it will yield each loop
  until get_shot_ready() or is_pressed("menu") -- waits for build_histogram --
  if(is_pressed("menu"))then break end
  if(single)then release("shoot_full_only") end
  --find meter with lowest exposure (brightest)
  tvd=-100000
  for i=1,nmeters do
    tx=get_shot_meter(i)
    if(tvd<tx)then
      tvd=tx
      im=i
    end
  end
  --adjust bv as it gets darker
  bv=tvd+get_shot_meter(0) --bv96
  if(bv>=bv1)then bvd=0
  elseif(bv<=bv2)then bvd=bvdmax
  else bvd=((bv-bv1)*bvdmax)/(bv2-bv1) end

  tv=tv+tvd+bvd+svmin-sv
  sv=svmin
  if(tv<tvs)then
    sv=sv+tvs-tv
    tv=tvs
    if(sv>svmax)then
      tv=tv-(sv-svmax)
      sv=svmax
    end
  end

  if(tv<tvmin)then tv=tvmin
  elseif(tv>tvmax)then tv=tvmax end

  set_exp96(tv,sv) -- aborts script wait too

And finally, here's the time lapse from last night:
http://www.youtube.com/watch?v=eOtKYe11pIk#ws (http://www.youtube.com/watch?v=eOtKYe11pIk#ws)
Title: More testing
Post by: lapser on 10 / February / 2013, 18:54:44
I found a spot near a pioneer cemetery with a view to the west, and set up the G1X at 1 shot per second. It took 16 seconds to take the 3rd picture, but after that it took the next 4,000 or so pictures without any delays. I have to work on the initialization of the handshake part. But at least it always got the exposure change applied on the next shot, and never missed the 1000 msec interval until the shutter open time was over 0.6 seconds. The shutter open to raw ready time stayed relatively constant at 300 msec for the whole time.

I started right before sunset, and stayed until it got as dark as it was going to get. As usual, the clouds rolled in and then reflected the city lights. The Bv bottomed out at around -900 because of the lit clouds. Bv reached -949 on the G1X with the camera meter when it was totally dark. It stepped from -908 to -949 with nothing in between, resulting in a flash in the time lapse. The shot meter should have better resolution at these levels. It didn't get that dark, but there was no flash with the shot meters at low light levels.  I'll be sure to point the camera away from city lights next time, and see if I can get down to -949 or below.

I got the new SX260 1.01a that  I just got from Canon repair working with CHDK. I installed it first on a 4GB class 6 card and tested the time lapse. The slower card makes a big difference in the shot rate. The class 6 card could only keep up with 1 shot per second for around 20 shots, and then started to fall behind and become irregular. It will be a good way to test my handshake routines to see if I can get them to handle this. But the slowdown happens even without CHDK installed, just by holding the shutter down in continuous mode. Fortunately, after I switched to a Class 10 card, everything kept up at 1 shot per second, and faster.

I did explore the pioneer cemetery after getting the camera going. It was really sad to see how many very young children were buried there. Child and infant mortality was very high in the 1800's before antibiotics and vaccinations.

For this test, I set the Bv to underexpose by 1 2/3 EV at -500. Next time, I'll try 2 EV. The shutter time reached about 12 seconds at the end. I lowered the frame rate at the end to compensate somewhat, at the expense of a jerky video. The plan is to fade between shots to get a smoother video at lower frame rates, in the future.

http://www.youtube.com/watch?v=1gxImATXFJo#ws (http://www.youtube.com/watch?v=1gxImATXFJo#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 13 / February / 2013, 01:01:35
After much testing, I've confirmed that raw_save_file() and capt_seq_hook_nr() are never active at the same time. This simplifies things, eliminating the need for data buffers. I was able to re-write and simplify the continuous mode time lapse code and get it working well.

The pre-shot function sets the interval exactly. Then the post shot function calls build_shot_histogram() to calculate the shot meters, and signals the script that they're ready by returning get_shot_ready() true. Then the post shot function waits until the next call to get_shot_ready(). That is, it waits until the script has processed the shot. Then it returns, and the camera then converts the shot to jpg and saves it. This happens AFTER the script has written it's log data, and doesn't hang the script writing. The time waiting for the script is about 50 or 60 msec if the post shot function waits for it. Without the wait, the script time can be 1000 msec since it's competing with the camera jpg save. So waiting for the script in the post shot function solves a lot of problems.
======
I did a time lapse test with the G1X and the SX260 in a darker location. The Bv values went down below -1000 smoothly, so it looks like this will work well with low light, below the range of the camera pre-shot meter. I did have one picture that was exposed almost 1 ev brighter than it should have been, but the next picture was exposed correctly. This happened while adjusting sv96, so it may be related to that, or it could be the shot meter timing.  That is, it might be that I'm reading the shot meter in one thread before the other thread is finished.

http://www.youtube.com/watch?v=aVzhkdzdpZg#ws (http://www.youtube.com/watch?v=aVzhkdzdpZg#ws)

====
I also did a time lapse with the sx260 in the car at 1.33 shots per second (750 msec interval). The script stopped once with that "Interrupted" message and a large number. It took over 7,000 pictures successfully, so it's probably related to the shot meter calculation being interrupted.  The script stopped again when the battery ran down, so there are 2 breaks in the video.

http://www.youtube.com/watch?v=b_nVZbV-MR4#ws (http://www.youtube.com/watch?v=b_nVZbV-MR4#ws)
Title: *** TERMINATED ***
Post by: lapser on 13 / February / 2013, 13:50:53
I finally got the script termination message error while printing a log file. This time it said:

set
*** TERMINATED ***

So I guess the error string is "set". Do you know what that means?

I triggered the error by setting the shot interval to 1 msec (no pre shot delay). With the post shot wait for script delay enabled, I got a measured interval of around 550 msec. Without waiting for the script, the interval was about 430 msec, and this triggered the terminated error. If I can trigger it repeatedly this way, I can test different things to prevent it, and figure out the cause.

Without the wait for script, the script is calling get_shot_meter() and set_exp96(), and writing log data, without regard to the camera state, so the error is probably triggered by a thread conflict.
Title: Re: Shot Histogram Request
Post by: reyalp on 14 / February / 2013, 21:16:31
It's very unlikely this is a deliberate error message, actual lua errors aren't single words or guru mediation numbers. It sound a bit like the issue discussed in http://chdk.setepontos.com/index.php?topic=8273.15 (http://chdk.setepontos.com/index.php?topic=8273.15) and http://chdk.setepontos.com/index.php/topic,4131.msg39296.html#msg39296 (http://chdk.setepontos.com/index.php/topic,4131.msg39296.html#msg39296) where some random data would be treated as the error. Current versions should tell if the error was null or empty, but not if they are garbage.
Title: Re: Shot Histogram Request
Post by: lapser on 15 / February / 2013, 13:33:55
It's very unlikely this is a deliberate error message
I'm pretty sure it's related to the script accessing variables as they're being changed by build_shot_histogram() in a different thread. I added a busy flag to build_shot_histogram(), so the script thread waits until it's finished. I don't have a busy flag for the script call to get_shot_meter(), so that could be the problem. I'll have to be absolutely certain both busy flags are never true at the same time, or that would hang both threads.

I'm thinking it would be best to make both flags "volatile" so I know the values are always current. Does that sound like a good idea?
===========

I made an interesting discovery from my test last night. As the light fades, changing the shutter speed to compensate seems to overshoot the desired amount. Then it corrects on the next shot, and oscillates 1 or 2 EV96 units. It only becomes visible with rapidly changing light after sundown as the sky darkens, and the compression artifacts bring it out.

Changing the ISO doesn't seem to have this problem, though. It shows no oscillations in the log, and looks smoother in the video. I explain it more in the description on YouTube.

There's also a hot or dead red pixel that shows up near the end of the video. It looked like a comet at first. I thought maybe I captured the meteorite that hit Russia a few hours later  :P
[EDIT]That's not a hot pixel. It's a small lens reflection from the street light at the bottom.

http://www.youtube.com/watch?v=Lx53E5AeXWU#ws (http://www.youtube.com/watch?v=Lx53E5AeXWU#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 16 / February / 2013, 21:14:21
I'm pretty sure it's related to the script accessing variables as they're being changed by build_shot_histogram() in a different thread.
Having not looked at the code, I don't know. However, the only way I could see this causing the behavior you describe is if your code got the values and did something with them that corrupted the Lua state or other memory. Lua isn't going to care that C code in one task is reading variables that are "out of date" with respect to some other task.

Note that lua API calls should only ever be made from the kbd_task, with the possible exception of loading a script like ptp does (I'm not sure if that's 100% safe either, but it seems to work...)
Quote
I'm thinking it would be best to make both flags "volatile" so I know the values are always current. Does that sound like a good idea?
I prefer something like
Code: [Select]
static int some_busy_flag;
int get_some_busy_flag() {return some_busy_flag;}
Because
1) this also forces the variable to be loaded fresh from ram, just like volatile
2) if in the future the ready state gets more complicated (perhaps by using proper task synchronization structures) then the calling code doesn't need to change.
3) People tend to attribute magic to volatile which it does not possess.
Title: Re: Shot Histogram Request
Post by: lapser on 17 / February / 2013, 00:08:53
Code: [Select]
static int some_busy_flag;
int get_some_busy_flag() {return some_busy_flag;}

//this is what I have right now
static int hbusy; //change to volatile?
void build_shot_histogram()
{
  hbusy=1;
  //calculations that take about 30msec
  hbusy=0;
}

int get_shot_meter()
{
  while(hbusy)msleep(10);
  //calculations, with call to log10(x)
}
So the problem isn't reading the busy flag, it's making sure it is stored immediately in build_shot_histogram().
=====

I modified get_shot_meter() to try to reduce the oscillations visible in the video as the light fades. It seems to have worked pretty well.

Code: [Select]
result= //calculations
if(result>0)result--;
if(result<0)result++;
return result;

[EDIT]This doesn't work right with an ev correction, so it has to be done in the script, not in CHDK. My script makes the exposure darker as it gets darker (ev correction), so the shot meter isn't returning 0 for no change.

[EDIT 2]Changed my mind again and put it back in the C code. I test if set_shot_interval(..) is active, and if it is, compare the current result with the last result, and reduce the amount of change by 1 as above.
Title: Re: Shot Histogram Request
Post by: lapser on 18 / February / 2013, 13:01:30
I've done several tests with over 8,000 pictures and haven't had the script stop. I did change the flag variables to volatile for now, so I know they are stored immediately and they'll test correctly in the other thread. I think this is one of the accepted uses of volatile:
http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766 (http://www.drdobbs.com/cpp/volatile-the-multithreaded-programmers-b/184403766)

I moved everything to shot_histogram.c so it will be easier to make into a module in the future. All that's left in raw.c is the slightly modified call to build_shot_histogram(). There's also a call to the pre-shot delay routine in capt.seq.c. The rest of the new calls are all in luascript.c, and there are initialization and termination calls in script.c.

There's lots of cleanup to do, but I think the time lapse and shot meter parts are working now. I still need to figure out why the shot meters don't work on the SX50.

I also need to finish up the shot histogram part, and see if I can return a shot meter value based on the histogram, so you can get the correct exposure on the next shot. I should be able to add up a histogram for all 4 shot meters, and save a few exposure values (ETTR, ETTL ?) for each meter. Meter #1 will hold a valid histogram between shots for use with get_histo_range(..)

Here's the latest 2 test videos. The first is from Skinner's Butte again, but with a 650 msec shot interval, or 1.5 shots per second. You can go faster, but the shots tend to back up saving to the card occasionally. Of course, as it gets dark, the shutter open time increases and lowers the shot interval. I capped the shutter time at 8 seconds here, and set the exposure compensation to -192 ev at -500 Bv.

The second video is a 12 hour, overnight sequence using my external lithium battery with the G1X. It still didn't run out of power. The battery only weighs one pound, so I should be able to carry it backpacking. The shot interval was set to 750 msec, but the shutter time of 10 seconds makes the video go much faster overnight. The fog really rolls in at sunrise, so the last half of the video shows the fog getting lighter. It's a good test of the exposure change smoothness, but it's not very interesting to watch. There were some birds that flew by in the fog a few times, and appeared on single frames.

http://www.youtube.com/watch?v=l0KdUiCoQ8M#ws (http://www.youtube.com/watch?v=l0KdUiCoQ8M#ws)

http://www.youtube.com/watch?v=SLGAmLpTXxo#ws (http://www.youtube.com/watch?v=SLGAmLpTXxo#ws)
Title: Script interrupted
Post by: lapser on 22 / February / 2013, 13:32:01
I'm still having occasional script interrupted errors even with all the thread safe coding I've been doing. I added some flags so I could tell where the script was interrupting. Of course, it's not in the place I thought it was.

Since installing the flags, the script interrupted on 2 occasions AFTER capt_seq_hook_set_nr() is called, and BEFORE raw_save_file() is called. This time period is around 250 msec plus the shutter open time. During this time period, core_spytask() and the script are both active in different threads.

The flags also show that the script error happens when the script is waiting for the shot to be ready. The last flagged routine was get_shot_ready(). However, during the loop, I also am calling other functions, including:

is_pressed("display")
is_pressed("menu")
is_pressed("set")
sleep(10)
get_shot_ready()

I've added a flag in each of these routines to try to determine where the script error happens, but I haven't been able to trigger the error with the new flags yet. I think core_spytask() is calling is_pressed() too, so it might be possible that is_pressed() is being called from different threads at the same time.

Anyway, I'm getting a little closer to an answer, I hope. If anyone has an idea how a multi-threading problem could cause a script interrupted error at this point in the shooting cycle, please let me know. The error message is "set" the last 3 times it happened. Here's the end of the last log file:

1524 3519 3470 30 50 411 88 -3 1/5.78
1525 3520 3450 40 30 411 89 -2 1/5.69
1526 3521 3460 40 30 411 89 -2 1/5.61
set
*** TERMINATED ***

This is what I'm printing in the log: (G1X)
shot#,  exposure#,  pre-shot delay time (4 sec interval), shot meter time, script time, sv96, bv correction, ev96 change, shutter time

=========
The exposure time, tv96, isn't as accurate as sv96. So when you set tv96 based on get_shot_meter(), it sometimes over-corrects and causes small oscillations in brightness in the time lapse video. These are only visible as it gets dark. Anyway, I modified get_shot_meter() to under_correct by 1 ev96, which appears to have eliminated or greatly reduced the oscillations.

My test time lapses lately have been deadly dull, since it's just watching fog get darker or lighter. But at least they change exposure smoothly. Here's the one from this morning (no script interrupt, unfortunately):

http://www.youtube.com/watch?v=fM0TV7bm4tA#ws (http://www.youtube.com/watch?v=fM0TV7bm4tA#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 23 / February / 2013, 18:13:28
Anyway, I'm getting a little closer to an answer, I hope. If anyone has an idea how a multi-threading problem could cause a script interrupted error at this point in the shooting cycle, please let me know.
I don't really see how you concluded this is a "multi-threading" problem. The script stuff all runs in one task. Other threads doing stuff won't cause it to randomly die, unless they are corrupting memory or something like that.
Quote
The error message is "set" the last 3 times it happened. Here's the end of the last log file:
As I said before, this isn't an error message in any normal sense. It's garbage, presumably left around due to the is_pressed("set") in your code.

Quote
I think core_spytask() is calling is_pressed() too, so it might be possible that is_pressed() is being called from different threads at the same time.
This would not be a problem.
Title: Re: Shot Histogram Request
Post by: lapser on 23 / February / 2013, 18:24:13
As I said before, this isn't an error message in any normal sense. It's garbage, presumably left around due to the is_pressed("set") in your code.
That's a help, thanks.
is_pressed("set") is the last function I called before sleep(10) and then get_shot_ready(). I switched it so is_pressed("display") is last. We'll see if that ends up as the next error message, if it ever happens again.
Title: Tonight's Time Lapse Test
Post by: lapser on 24 / February / 2013, 01:27:26
http://chdk.setepontos.com/index.php?topic=9496.0 (http://chdk.setepontos.com/index.php?topic=9496.0)

I'm trying wait_click instead of is_pressed in my script wait loop in case the script error is coming from is_pressed. I've had to modify wait_click a little for short timeouts, as described in the above link.

I tried a 4 second interval tonight, which generated the "set" error before. No error this time. I ended up with an interesting video and a few shots of the International Space Station flying by (at 57 seconds):

http://www.youtube.com/watch?v=Jel8iw99ikM#ws (http://www.youtube.com/watch?v=Jel8iw99ikM#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 26 / February / 2013, 09:16:30
Phil helped me fix an error in the log10 function address in the SX50 port, so I was able to get my first time lapses with the new camera. The 50X optical zoom is fantastic! Here's a short time lapse of the full moon last night:

Moon Time Lapse 130225 Canon SX50 CHDK (http://www.youtube.com/watch?v=HXffHEPv7UM#ws)

And here's my first sunset time lapse with the SX50:

Skinner Butte 130225 Canon SX50 CHDK (http://www.youtube.com/watch?v=qhOGiC9JpBQ#ws)

And here's the same sunset with the G1X:

Skinner Butte 130225 Canon G1X CHDK (http://www.youtube.com/watch?v=nL26mUAGil0#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 04 / March / 2013, 16:05:59
I switched to the new wait_click(10) in my loop waiting for get_shot_ready() instead of using 3 is_press() calls with "set", "menu", and "display". I was getting script interrupted errors once in awhile, but did not have one with the new wait_click until last night. Instead of a "set" error, I got a "NULL" error with the sx260.

I'll try calling wait_click(10) only between shots, and not repeatedly in a tight loop. I think the error is coming from the call to get_clicked_key() in wait_click(), possibly from a conflict with calls from a different task accessing the same function and keyboard variables. Calling it only once per shot is a small script change, and we can see if it still gives interrupted errors.

I hiked Spencer Butte yesterday to get an extra sunset test using all 3 cameras. The SX260 was on my worst mini-tripod, so it blew over in the wind. I switched to my even worse imitation gorillapod, with a lower center of gravity, and it stayed upright long enough to throw the error. The video turned out pretty interesting.

Here's the last 6 time lapse tests with all 3 cameras. Descriptions are in the YouTube info sections.

http://www.youtube.com/watch?v=lWSAgGiC0Fc#ws (http://www.youtube.com/watch?v=lWSAgGiC0Fc#ws)

http://www.youtube.com/watch?v=FR6rWXkivqM#ws (http://www.youtube.com/watch?v=FR6rWXkivqM#ws)

http://www.youtube.com/watch?v=DqoWVgAZRZ8#ws (http://www.youtube.com/watch?v=DqoWVgAZRZ8#ws)

http://www.youtube.com/watch?v=ALWIlL9l0YI#ws (http://www.youtube.com/watch?v=ALWIlL9l0YI#ws)

http://www.youtube.com/watch?v=OuZdgg1owGc#ws (http://www.youtube.com/watch?v=OuZdgg1owGc#ws)

http://www.youtube.com/watch?v=8W9z6BnbOx4#ws (http://www.youtube.com/watch?v=8W9z6BnbOx4#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 04 / March / 2013, 17:18:11
I switched to the new wait_click(10) in my loop waiting for get_shot_ready() instead of using 3 is_press() calls with "set", "menu", and "display". I was getting script interrupted errors once in awhile, but did not have one with the new wait_click until last night. Instead of a "set" error, I got a "NULL" error with the sx260.
Was the error "ERROR:NULL error message" ?

This certainly seems like our old friend http://chdk.setepontos.com/index.php?topic=8273.0 (http://chdk.setepontos.com/index.php?topic=8273.0)

There are relatively few ways a Lua script can end. If you look at the patch I posted in http://chdk.setepontos.com/index.php?topic=8273.msg87882#msg87882 (http://chdk.setepontos.com/index.php?topic=8273.msg87882#msg87882) it covers the area in question (note this patch will probably not work as-is with the current trunk)

As I posted in http://chdk.setepontos.com/index.php?topic=8273.msg87915#msg87915 (http://chdk.setepontos.com/index.php?topic=8273.msg87915#msg87915) the results of this were very strange and I couldn't really make sense of it. I don't completely remember what all I'd figured out from this, I'll have go dig around and see if what I can get out of the notes and dumps.

Possibly making a complete memory dump at the time the abnormal termination happens would shed some light on it, though it could be challenging to interpret.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / March / 2013, 14:45:22
Was the error "ERROR:NULL error message" ?
Yes, that's the one. I've been able to reproduce the bug once a night on the sx260, and I'm tracking it down slowly but surely. The bug happens when lua calls wait_click(10) or sleep(10). I set a variable to a different number in the C code for each function that my script calls, and sleep(10) is the culprit with this in the script:

repeat sleep(10) until get_shot_ready()

I did a lot of investigating of the keyboard functions. They aren't totally thread safe, but I couldn't show that was causing a problem.

I also dug into lua as far as I could get, and came up with a possibility. The sleep(10) function calls   lua_yield( L, 0 ).   lua_count_hook () also calls lua_yield(), which creates the possibility of a double yield with no resume. There's a test for that, but it might be fooled under rare timing conditions (I think?).

Anyway, scripts have a voluntary yield when they call sleep(10), and a preemptive yield from lua_count_hook(). My script doesn't need the preemptive yield, since it spends most of its time in a sleep(10) loop. So I'm trying disabling the preemptive yield with:

set_yield(-1,-1)

The script works fine this way. In fact, this reduces the time waiting for the script to set the exposure between shots to 10 msec each time, instead of 10 or 20 msec. I'll keep it in the script even if it doesn't fix the lua error bug. But I've got my fingers crossed that this is the problem, and I won't see that error again!

Last Wednesday, I caught a pretty nice sunset time lapse from the top of Spencer's Butte with the SX260, but the lua error stopped it while the clouds were still lit up. Here's the latest tests:

http://www.youtube.com/watch?v=6DWLPU0y4Ig#ws (http://www.youtube.com/watch?v=6DWLPU0y4Ig#ws)

The G1X doesn't seem to trigger the bug (yet), and I only saw it once with the SX50. Here's the latest test with these two cameras:

http://www.youtube.com/watch?v=HA7fh8viei0#ws (http://www.youtube.com/watch?v=HA7fh8viei0#ws)

http://www.youtube.com/watch?v=hkBVi7MKB78#ws (http://www.youtube.com/watch?v=hkBVi7MKB78#ws)
Title: set_yield(-1,-1) didn't work
Post by: lapser on 08 / March / 2013, 22:42:57
Tonight's test with set_yield(-1,-1), didn't work. That is, the SX260 had one script interrupted error, and the G1X had 2.

So the next step is to take the sleep(10) out of the script wait loop, and use the  lua_count_hook () function to do the yield every 10 ms. That is:

repeat until get_shot_ready()

I shot over 5,000 pictures of the tv screen this afternoon with the sx260, and no error. The errors all have happened as it gradually gets darker, and the shutter open time gets to a certain point, longer than 10 msec. So maybe I'll try changing the script so it changes tv96 by 1 each time, and see if I can trigger the error more often.
 
Title: Script interrupted solution?
Post by: lapser on 09 / March / 2013, 08:34:27
I thought about it some more, and eliminating the sleep(10) from the wait loop is a bad idea. It would hog the cpu, and still probably not solve the problem.

But the solution is relatively simple: add this function:

wait_shot_ready()

The bug occurs when lua is in a yield / resume loop. Something about the timing causes an error with resume. wait_shot_ready() uses only one yield at the beginning, and a single resume at the end.  The timing of the resume is well after the shutter open/close cycle is complete, so that shouldn't cause a problem. I think it's going to work, but we'll see tonight.

Here are the time lapse videos from last night (with script interrupt/restart glitches)

http://www.youtube.com/watch?v=G_Jspt9xvH4#ws (http://www.youtube.com/watch?v=G_Jspt9xvH4#ws)

http://www.youtube.com/watch?v=oFl-5baRxcw#ws (http://www.youtube.com/watch?v=oFl-5baRxcw#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 09 / March / 2013, 14:07:09
wait_shot_ready() is done and working.

I also changed set_backlight(..) so it saves its state in "bldark". Then in the action stack AS_... function for sleep(), wait_click(), and wait_shot_ready(), I added:

  if (bldark) TurnOffBackLight();

I also added code to turn it back on when the script ends or errors out. All this makes set_backlight(0) almost work, except for the flashing between shots. It still should save battery power.

So I'm all set for another test tonight, with high hopes there won't be any script interrupted errors.

Title: Re: Shot Histogram Request
Post by: reyalp on 09 / March / 2013, 15:39:50
The bug occurs when lua is in a yield / resume loop. Something about the timing causes an error with resume.
You know this how?

The fact that you get "ERROR:NULL error message" means Lua is terminating "normally", in the sense that lua_resume is returning based on an error status from resume_error in lib/lua/ldo.c.

If you look at the patch I linked earlier, the case being hit was the one that generated 'A/LUARES1.DMP'

The bizarre thing is that luaD_rawrunprotected doesn't look like it is creating an error status.
Title: Re: Shot Histogram Request
Post by: lapser on 09 / March / 2013, 16:51:42
The bug occurs when lua is in a yield / resume loop. Something about the timing causes an error with resume.
You know this how?
I set a variable, "lapser1", to a different value in every luascript.c function that my script calls. The error only occurs in the sleep() function that is called repeatedly waiting for get_shot_ready() to signal that the shot histogram is done.

I can't seem to trigger the bug except when doing a time lapse, as the shutter time is slowly increased. The fastest shutter speed it has happened at is 10 msec.

repeat sleep(10) until get_shot_ready()   yields and resumes around 60 times per shot with a 1 second interval.
wait_shot_ready() yields only once per shot. Since the bug happens after a resume, I'm hoping that eliminating all but one resume will prevent it.
Quote
The bizarre thing is that luaD_rawrunprotected doesn't look like it is creating an error status.
Could this happen with a hardware interrupt inside an internal lua function that isn't thread safe?

Do you know how the shutter open/close is timed? Maybe there's an extra interrupt timer that generates an extra interrupt when its time to close the shutter? Since there's a firmware function to open and close the mechanical shutter, the timing might be controlled by the camera processor instead of a hardware timer. I'm just shooting in the dark here, but you know me and my theories.

If I trigger the bug again, can you describe how to do a memory dump?

Thanks for the help.
Title: Re: Shot Histogram Request
Post by: reyalp on 09 / March / 2013, 17:29:43
Could this happen with a hardware interrupt inside an internal lua function that isn't thread safe?
A hardware interrupt should be completely transparent to Lua, just like any other vanilla C code. I don't see how thread safety wouldn't come into it, the Lua code is single threaded since it executes entirely in kbd_task.

One possible area that might be suspect is the implementation of setjmp/longjmp (which are custom, in lib/lua/setjmp.S), but I couldn't see any way this would be affected.

The combination of the debug hook yield and sleep yield also seems like it might be worth further investigation. One way to do this might be to make the debug hook yield more frequently and see if the problem happens more often.

If this problem is in fact the problem encountered earlier, it is not strictly tied to shooting. The fact that you get the NULL error message error suggests that it is the same, or at least closely related.
Quote
Do you know how the shutter open/close is timed?
No. Interrupts are probably involved, see http://chdk.setepontos.com/index.php?topic=8312.msg87949#msg87949 (http://chdk.setepontos.com/index.php?topic=8312.msg87949#msg87949)

Quote
Maybe there's an extra interrupt timer that generates an extra interrupt when its time to close the shutter?
I don't still don't see how interrupts would be involved. But then, I don't have a good theory of how this happens... or a bad one, for that matter :-[

Quote
If I trigger the bug again, can you describe how to do a memory dump?
If you want to dump the entire camera RAM, see main.c dump_memory() (used by the debug menu memory dump option)

I would suggest putting it as close as possible to where the Lua error state is triggered, probably something like
Code: [Select]
   status = luaD_rawrunprotected(L, resume, L->top - nargs);
   if (status != 0) {  /* error? */
+    if(status != LUA_YIELD) {
+       dump_memory();
+    }
     L->status = cast_byte(status);  /* mark thread as `dead' */

in ldo.c lua_resume

Note that doing something useful with this will be decidedly non-trivial. It will also dump memory on any Lua error...
Title: Re: Shot Histogram Request
Post by: lapser on 09 / March / 2013, 19:16:24
The combination of the debug hook yield and sleep yield also seems like it might be worth further investigation. One way to do this might be to make the debug hook yield more frequently and see if the problem happens more often.
Except the bug still happened with:
set_yield(-1,-1)

My current script keeps the yield hook disabled, and there's only 1 yield per shot at the beginning of my new wait_shot_ready().

If the bug happens again, assuming I can restrain the urge to throw my camera against the wall, I'll look more at the gui_handler stuff. Is that called from the keyboard task? I'm wondering if script_gui_handler could be generating a spurious shoot_full click that's interrupting the script when it's not in the right state or something. If get_clicked_key() or similar is called outside the keyboard task, that could cause trouble.
Quote
If this problem is in fact the problem encountered earlier, it is not strictly tied to shooting. The fact that you get the NULL error message error suggests that it is the same, or at least closely related.
Actually, the null error message was when I was using wait_click(10) for my delay. With sleep(10), the error message is the last string passed to is_key().

With is_key("set") before the sleep(10), the error was "set".
With is_key("up") the error is "up".

I also got an error of "0" on one camera with wait_click(10), instead of "NULL".

I think it's using what was on the stack before the yield as the error. It sounds like a stack error of some kind.
Title: Re: Shot Histogram Request
Post by: reyalp on 09 / March / 2013, 19:49:42
If the bug happens again, assuming I can restrain the urge to throw my camera against the wall, I'll look more at the gui_handler stuff. Is that called from the keyboard task?
Yes, it should be.
Quote
I'm wondering if script_gui_handler could be generating a spurious shoot_full click that's interrupting the script when it's not in the right state or something. If get_clicked_key() or similar is called outside the keyboard task, that could cause trouble.
If the script were somehow being interrupted by a spurious shoot click, then you wouldn't get the bogus or null error messages. It would just act like you had pressed the shutter. When the shutter is pressed, it triggers kbd_task to kill the Lua environment *outside* of the Lua code (meaning lua has already returned from lua_resume, and probably waited for the next iteration of kbd_task)

Quote
I think it's using what was on the stack before the yield as the error. It sounds like a stack error of some kind.
The error comes form the lua state stack, not the C stack. Lua is dying in some way that returns an error (edit: I mean, a code path that would normally be an error), but fails to put an error on the (edit: Lua) stack.
Title: Success!
Post by: lapser on 10 / March / 2013, 00:14:38
I got all 3 cameras to take around 5,000 pictures each through an entire sunset, without a script interrupt. Hurrah!

This is with wait_shot_ready() and set_yield(-1,-1). The script actually works better with the yield hook disabled. I haven't found the cause of the bug, but at least I have a way to work around it now, and make sure I get a complete time lapse.

The next step is to see if the bug happens with the yield hook enabled. For a good test, I'll try set_yield(1,10), for a yield every 200 lua operations. My guess is that the yield hook won't trigger the bug, and that it comes from the transition from Lua to a C subroutine getting the stack wrong or something. My wait_shot_ready() has no parameters. Maybe I'll try it with a dummy parameter and see if that causes trouble.

I would like to have an escape option for wait_shot_ready() when you press a key, so a parameter might be useful. One thing I'm wondering is how I can return a value from wait_shot_ready?

Could I end wait_shot_ready() with:
return lua_yield( L, 1 );  ??

Then, I would use lua_pushnumber() from the action stack routine when it finishes?

Speaking of action stacks, maybe that could be causing this lua problem. There's a lot of pushing and popping going on with a function like sleep(10).  I haven't gone through all the action stack logic, but it might be worth it to follow the code for a sleep(10) call from start to finish.
Title: Re: Shot Histogram Request
Post by: reyalp on 10 / March / 2013, 00:45:08
The next step is to see if the bug happens with the yield hook enabled. For a good test, I'll try set_yield(1,10), for a yield every 200 lua operations.
You could also lower the multiplier in the code, YIELD_CHECK_COUNT in luascript.c

Quote
Could I end wait_shot_ready() with:
return lua_yield( L, 1 );  ??
I have no idea where wait_shot_ready is or what it does.
Quote
Then, I would use lua_pushnumber() from the action stack routine when it finishes?
I think you are supposed to be able to do this, but if you haven't already you should take a look at the lua documentation for yield and resume.  http://www.lua.org/manual/5.1/manual.html#lua_yield (http://www.lua.org/manual/5.1/manual.html#lua_yield)

edit:
You might want to look at read_usb_msg() which does something similar.

You don't want to use lua_yield( L, 1 );, that would be returning something to lua_resume.

Quote
Speaking of action stacks, maybe that could be causing this lua problem. There's a lot of pushing and popping going on with a function like sleep(10).  I haven't gone through all the action stack logic, but it might be worth it to follow the code for a sleep(10) call from start to finish.
I don't understand how this could be connected.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / March / 2013, 01:56:16
You might want to look at read_usb_msg() which does something similar.
That's exactly what I was looking for. Thanks!

wait_shot_ready() is like wait_click(), only it waits for get_shot_ready(), which returns 1 right after build_shot_histogram finishes. wait_shot_ready() is equivalent to:

repeat sleep(10) until get_shot_ready()

The sleep(10) loop triggered the bug, but wait_shot_ready didn't.

I'd like to add an escape key to wait_shot_ready(), so if you press "menu", for example, it would exit immediately. It would return true if the shot was ready, and false if the escape key was pressed.

while(wait_shot_ready("menu"))do
  --process shot
end
Title: Re: Shot Histogram Request
Post by: philmoz on 10 / March / 2013, 05:00:24
I got all 3 cameras to take around 5,000 pictures each through an entire sunset, without a script interrupt. Hurrah!

This is with wait_shot_ready() and set_yield(-1,-1). The script actually works better with the yield hook disabled. I haven't found the cause of the bug, but at least I have a way to work around it now, and make sure I get a complete time lapse.

The next step is to see if the bug happens with the yield hook enabled. For a good test, I'll try set_yield(1,10), for a yield every 200 lua operations. My guess is that the yield hook won't trigger the bug, and that it comes from the transition from Lua to a C subroutine getting the stack wrong or something. My wait_shot_ready() has no parameters. Maybe I'll try it with a dummy parameter and see if that causes trouble.

I've create a test branch, philmoz-modulesV2, which has Lua version 5.1.5 (among other things).

It might be worth trying in case the problem is in Lua rather than CHDK.

Phil.
Title: coroutine.yield
Post by: lapser on 10 / March / 2013, 14:03:37
This is something exciting that I just discovered after looking at the Lua docs for yield (thanks reyalp). I always assumed that sleep(10) was the only way to yield, but a better way is:

coroutine.yield()

This eliminates the call to a C function from Lua, which yields from C, and may be the cause of the bug. It seems much safer to yield from Lua.

Code: (lua) [Select]
--[[
@title Yield Test
@param y yield hook?
@default y 0
--]]
--set_console_layout(0,0,45,14) -- full screen
if(y==0)then set_yield(-1,-1) end
tick0=get_tick_count()
n=1
repeat
  coroutine.yield()
  tick=get_tick_count()
  print(n,tick-tick0)
  tick0=tick
  n=n+1
until is_pressed("menu")
set_yield()

It looks like coroutine.yield() is the same as sleep(10), but without the overhead and bug risk of a C yield.

I accidentally discovered that setting the console to full screen increases the time between yields from 10 to 40 or 50 msec on my sx260. I'm assuming that's a problem with the console routines.

Anyway, I'll try my time lapse script using coroutine.yield() instead of sleep(10) or wait_shot_ready(). If it works, and I think it will, it will prove that the bug is coming from the lua_yield() call from C.

[EDIT] Here's the new wait loop in my time lapse routine. This way is more flexible than wait_shot_ready() since you can do other tests while waiting:

Code: (lua) [Select]
  repeat
    wait_click(1) -- just checks for key, no delay or yield
    if(is_key("set"))then
      bl=bitxor(bl,1) -- 0 or 1
      set_backlight(bl)
    elseif(is_key("display")) then
      nd=bitxor(nd,3) -- 1 or 2 for nd filter
    end
    done=is_key("menu")
    coroutine.yield() -- same as sleep(10) but without C yield bug (hopefully)
  until get_shot_ready() or done
  if(done) then break end -- script over
Title: Re: Shot Histogram Request
Post by: reyalp on 10 / March / 2013, 16:16:07
This is something exciting that I just discovered after looking at the Lua docs for yield (thanks reyalp). I always assumed that sleep(10) was the only way to yield, but a better way is:

coroutine.yield()

This eliminates the call to a C function from Lua, which yields from C, and may be the cause of the bug. It seems much safer to yield from Lua.
What do you think coroutine.yield does under the hood?
static int luaB_yield (lua_State *L) {
  return lua_yield(L, lua_gettop(L));
}
Title: Re: Shot Histogram Request
Post by: lapser on 10 / March / 2013, 18:36:44
What do you think coroutine.yield does under the hood?
static int luaB_yield (lua_State *L) {
  return lua_yield(L, lua_gettop(L));
}
Well, I guess everything is C under the hood. I meant it yields from code written by Lua programmers instead of us.  At least it doesn't start a new action stack with a delay. It just yields. I think it will work, but we'll C.

Here's the videos from last night, which were uninterrupted, except for the guy who walked in front of the SX260 and created a flash.

http://www.youtube.com/watch?v=I-8i1e8Da_E#ws (http://www.youtube.com/watch?v=I-8i1e8Da_E#ws)

http://www.youtube.com/watch?v=ZQMdG8TV7Xg#ws (http://www.youtube.com/watch?v=ZQMdG8TV7Xg#ws)

http://www.youtube.com/watch?v=34nT5m7urOc#ws (http://www.youtube.com/watch?v=34nT5m7urOc#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 10 / March / 2013, 18:57:03
Well, I guess everything is C under the hood. I meant it yields from code written by Lua programmers instead of us.
It's a C function just like ours, which calls exactly the same lua API function that sleep() etc call. (luaB_yield is registered in lua as coroutine.yield)
Quote
  At least it doesn't start a new action stack with a delay. It just yields. I think it will work, but we'll C.
Huh?
If it doesn't put something on the action stack, then you will just yield for one iteration of kdb_task, which is what sleep(0) does now in the trunk, because AS_SCRIPT_RUN will still be on top of the stack. Unless you've butchered the script action stack handling in some other way...
Title: coroutine.yield bites the dust
Post by: lapser on 11 / March / 2013, 02:24:24
The SX50 triggered the bug again, this time with coroutine.yield(). I also have wait_click(1) and is_key() calls in the wait loop with coroutine.yield(). It's possible that caused the problem, but it seems to be a bug in lua yield(). I'll see if I can try Phils lua updated branch when I get the time. Here's the log file after the error:

menu
*** TERMINATED ***
Lapser:      7 3209594  3473    -1

I added the last line. "7" shows that is_key() was the last C function called before the error. The next number is the return value from resume(), which appears to be a pointer, probably to "menu". The error occurred after 3473 pictures, and happened during the pre_shot timing delay in capt_seq_hook_nr().


If it doesn't put something on the action stack, then you will just yield for one iteration of kdb_task, which is what sleep(0) does now in the trunk, because AS_SCRIPT_RUN will still be on top of the stack. Unless you've butchered the script action stack handling in some other way...
Shouldn't sleep(<=10) also just yield() without action stacking?

Anyway, I'll go back to wait_shot_ready(), and check for key clicks while waiting. Ii'll see if I can return TRUE if a key is pressed, and FALSE if the shot is ready with no key pressed.

while(wait_shot_ready())do
  if(is_key("menu"))then done=true break end
end

By the way, I consider myself a Kosher butcher, but the action stack code in my builds is still pure, virgin, philmoz beef filet.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / March / 2013, 12:42:54
The new wait_shot_ready() worked perfectly last night, including returning TRUE if a key was clicked. I used all 3 cameras without a script error, so I'm declaring the Lua yield() bug successfully fixed, well, worked around.

I also added some code to keep the backlight off that worked well. It's all in luascript.c, but requires adding a test in all the AS_WAIT functions. A better way would be to put one test in action_stack.c which would also work for ubasic. I'll get out my action_stack filet knife and see if I can butcher it correctly!

Last Sunday night, I went out to the airport and stuck the sx260 lens through the tiny hole in the chain link fence at the start of the runway. I used a Gorillapod hooked into the fence to hold the camera. I set the SX260 at 2 shots per second, which is faster than my other cameras can go. The SX260 uses a 32K Transcend Class 10 SDHC card, which appears to be faster than the 64K Transcend Class 10 in the SX50, maybe because of a larger FAT32 block size. The Transcend cards appear to be faster than the SanDisk 64K Class 10 in the G1X, but I would have to test them in the same camera to see. So here's the airport sunset video:

http://www.youtube.com/watch?v=x8rvMn6fXfQ#ws (http://www.youtube.com/watch?v=x8rvMn6fXfQ#ws)

And here are the 3 sunset videos from last night:

http://www.youtube.com/watch?v=lVRcbv1yiq8#ws (http://www.youtube.com/watch?v=lVRcbv1yiq8#ws)

http://www.youtube.com/watch?v=HbNCs-MrHJc#ws (http://www.youtube.com/watch?v=HbNCs-MrHJc#ws)

http://www.youtube.com/watch?v=y9Klroj6V6A#ws (http://www.youtube.com/watch?v=y9Klroj6V6A#ws)
Title: Over 10 Thousand Pictures!
Post by: lapser on 13 / March / 2013, 16:30:41
I left the SX50 running overnight hooked to A/C power without a script error, using wait_shot_ready(). It worked! It may be the most boring time lapse ever, but it demonstrates that the program is ready to take out in the field somewhere and do some real time lapsing.

I also updated my keep the backlight off logic, and got it working really well. I decided to butcher kbd.c this time, instead of action_stack, so the turn off backlight call will come sooner after the camera turns it on.

This way, I discovered that the backlight stays off completely when used with "shoot_full_only" in single shot mode. There's a brief flash with my time lapse script in continuous mode. I'll do some new power tests, but I think this will save a significant amount of power over trying to keep the backlight off with Lua or Basic alone. Here's the backlight code:

Code: [Select]
//kbd.c
long kbd_process()
{
    static int key_pressed;

    if(camera_info.state.backlight_off)
    {
        if (camera_info.state.state_kbd_script_run)TurnOffBackLight();
        else
        {
          camera_info.state.backlight_off=0;
          TurnOnBackLight();
        }
    }

//luascript.c
static int luaCB_set_backlight( lua_State* L )
{
  camera_info.state.backlight_off = (luaL_checknumber(L,1)==0);
  if (!camera_info.state.backlight_off) TurnOnBackLight(); //turns off in kbd.c
  return 0;
}


//in lua_script_run()
  if (Lres == LUA_YIELD)return SCRIPT_RUN_RUNNING; //yielded
  camera_info.state.backlight_off=0; //error or finished script
  TurnOnBackLight(); //makes error visible

Here's the Lua script that's tests the backlight off code:

Code: (lua) [Select]
--[[
@title Shoot Test
--]]
bl=1 -- backlight on
print("<set> to toggle backlight")
print("<menu> to exit")
print("using shoot()")
repeat
  shoot()
  wait_click(1)
  if(is_key("set"))then
    bl=bitxor(bl,1) -- 0 or 1
    set_backlight(bl)
  end
until is_key("menu")

bl=1
set_backlight(1)

print("using shoot_full_only")
press("shoot_half")
repeat sleep(10) until get_shooting()
repeat
  sleep(2000)
  click("shoot_full_only")
  wait_click(1)
  if(is_key("set"))then
    bl=bitxor(bl,1) -- 0 or 1
    set_backlight(bl)
  end
until is_key("menu")


And finally, here's the most boring time lapse ever:
http://www.youtube.com/watch?v=f3y4dd4OXCo#ws (http://www.youtube.com/watch?v=f3y4dd4OXCo#ws)
Title: Re: Shot Histogram Request
Post by: waterwingz on 13 / March / 2013, 17:24:16
I'll do some new power tests, but I think this will save a significant amount of power over trying to keep the backlight off with Lua or Basic alone.
Based on my testing here,

http://chdk.setepontos.com/index.php?topic=9049 (http://chdk.setepontos.com/index.php?topic=9049)

you gain about 20% on you battery life by turning the backlight off.   I would expect results from your mods to be about the same.

Title: Re: Shot Histogram Request
Post by: lapser on 13 / March / 2013, 19:51:25
you gain about 20% on you battery life by turning the backlight off.   I would expect results from your mods to be about the same.
You're probably right, but this way doesn't even flash the backlight in half_shoot. I'm shooting at 1 shot per second with no focusing or pre-shot metering, so maybe the backlight flashing will be a larger part of the power drain.

Anyway, this will let scripts keep the backlight off with just set_backlight now. I added the code to ubasic, and tested it with a basic script. I'll do some more checking and testing tomorrow, and submit a patch file for you to test, and possibly add to the trunk.

I'm off to climb a butte and see if I can get a shot of the comet and crescent moon in between clouds tonight.
Title: Re: Shot Histogram Request
Post by: lapser on 14 / March / 2013, 21:22:30
Nice day but boring sunset on Spencer's Butte last night, so I turned the camera to time lapse the people, and got something more interesting. For one thing, dogs are very busy creatures!

No script interrupted errors, but I did have a slow ending of the script and strange behavior of the camera afterwards. That happened once before. I'm pretty sure it's related to stopping the script in the middle of build_shot_histogram(), and clearing some of the pointers or something while they're being used. That would trash random memory. It's pretty simple to prevent, so I'll add that code next.

I finished the keep backlight off code, including getting it to work with ubasic. reyalp didn't think it's worth putting in the trunk, so I'll drop it for now. I need it in my timelapse code because I have to use wait_shot_ready() instead of a Lua sleep loop to wait for the shot. This is the only way to avoid the script interrupt bug at the moment. So I can't keep the backlight off with just Lua.

By turning off the backlight in CHDK, the timing keeps it completely off between shots, which avoids the flashing seen with a Lua loop. I think this might be important for a camera in a car, as mentioned in this recent post:

I want to extend drivelapse.bas to turn off the LCD display to save battery and avoid distraction while the script is running (and then turn it back on when the script ends). Is this possible?
So the code is ready to fix this problem if it's needed.

Here's the time lapse from last night:

http://www.youtube.com/watch?v=am_JqGg7CeU#ws (http://www.youtube.com/watch?v=am_JqGg7CeU#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 14 / March / 2013, 23:30:59

So the code is ready to fix this problem if it's needed.
If you post a patch, then it it would be available to anyone who want it, regardless of whether I think it should be in the trunk or not.
Title: Re: Shot Histogram Request
Post by: lapser on 15 / March / 2013, 00:16:13
If you post a patch, then it it would be available to anyone who want it, regardless of whether I think it should be in the trunk or not.
That's a good idea. But now that I've figured out that the script interrupt bug is related to Lua yield(), and a way around it, my time lapse / shot meter code is working reliably. I think I'll work on cleaning up the code and improving my Lua time lapse script, and post the whole thing as one big patch and a finished script.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / March / 2013, 18:43:26
I cleaned up the time lapse script yesterday, adding a few more options to the parameter list. One was the option to enter the minimum and maximum ISO. I was using sv96, but those are hard numbers to figure out, so I changed it to enter ISO, and convert with my new conversion routines.

In order to be able to enter "Market" ISO, I had to convert it to "Real" sv96.

By setting the camera to ISO 100 (market), and running a script that does:
get_sv96()
I discovered that 100 Market is 411 sv96. If you then do:
sv96_to_iso(411)
you get 65 ISO, which is the "Real" ISO.

If you convert 100 (real) ISO to sv96,
iso_to_sv96(100)
you get 470. This is 59 more than 411, which is the sv96 offset to use. So here's how I get "real" sv96 from the "market" ISO input

@param z ISO Max
@default z 800
@param s ISO Min
@default s 100

svdiff=59 -- real to market difference
svmin=iso_to_sv96(s)-svdiff
svmax=iso_to_sv96(z)-svdiff

To print out the Market ISO for each shot, I use:
sv96_to_iso(sv+svdiff)

I've got some rounding error problems in my iso conversion I need to work on. Entering ISO 800 ends up ISO 802 after being converted to sv96 and back. So I think I need a scale factor for ISO, i.e. ISO 8000 for ISO 800, or maybe ISO 800000.

The sky was relatively clear for a few hours at sunset last night, so I hauled 2 big tripods, a Gorillapod, 3 cameras, external batteries, extra warm clothes, water, headlamp, and a cheeseburger up to the top of Spencer's Butte. Unfortunately, the ribbon of clouds on the western horizon blocked the view of the comet. Fortunately, the clouds were really beautiful.

http://www.youtube.com/watch?v=uRio1KM-LuM# (http://www.youtube.com/watch?v=uRio1KM-LuM#)
Title: Re: Shot Histogram Request
Post by: blackhole on 17 / March / 2013, 05:19:42
Too bad you did not capture comet, yesterday I could capture a comet for the first time but I really struggled. With the naked eye is completely invisible without binoculars would not could to find. I made two pictures, one with the A590, and another through a telescope with the EOS 1100D.
Title: Re: Shot Histogram Request
Post by: lapser on 17 / March / 2013, 12:30:37
I could capture a comet for the first time but I really struggled.
That makes me feel better. I never would have found the comet even if the horizon was clear, so at least I had a pretty cloud to catch in the time lapse.

I did try a time lapse of the moon with the SX50 at 50X zoom. The pistol grip ball head that came with the tripod isn't steady enough, especially since there was some wind blowing. I ordered the Manfrotto 486RC2 from Amazon. Here's the video:

http://www.youtube.com/watch?v=xFPNoiwaWsQ#ws (http://www.youtube.com/watch?v=xFPNoiwaWsQ#ws)
Title: Idea: wait_for("LuaFunc") function
Post by: lapser on 17 / March / 2013, 12:49:59
Working around the Lua yield() bug with wait functions works great so far. But I had an idea of a way to generalize it so you don't need a different wait function for each test condition. What if you used lua_pcall() to call a Lua function from the action stack wait? The Lua function would return TRUE if the test condition was met, or FALSE to continue waiting. It would be equivalent to:

repeat sleep(10) until func()

you would call this with:

wait_for("func")

it could be modified to work like this:

wait_for("get_shooting",false)

As far as I know, pcall() doesn't do lua_yield() so it should work around the bug. A secondary benefit would be to make the lua script a little more concise when writing wait loops.

wait_for("reyalp_likes_it", false)
what_for("reyalp_says", no) --?
Title: Re: Shot Histogram Request
Post by: reyalp on 17 / March / 2013, 16:15:58
you would call this with:

wait_for("func")

it could be modified to work like this:

wait_for("get_shooting",false)

As far as I know, pcall() doesn't do lua_yield() so it should work around the bug.
I don't like this at all. It's ugly and pcall imposes severe limits on what chdk functions the called code can use.

Fixing the bug would be a much better solution. If the bug is in fact caused by repeated yields, that should be a significant step toward nailing down the root cause.
Quote
A secondary benefit would be to make the lua script a little more concise when writing wait loops.
This is not a benefit, it's the opposite. Making scripts use less characters is not a goal of the script inteferace. Wait loops are a clear description of what is going on, and are far more flexible than your approach.
Title: Re: Shot Histogram Request
Post by: lapser on 17 / March / 2013, 19:09:23
I don't like this at all. It's ugly...
Ha, I knew you'd say that. My job is to throw up new ideas. Your job is to tell me to throw away what I throw up.

And Jo mamma's ugly too!  :D
Quote
Fixing the bug would be a much better solution. If the bug is in fact caused by repeated yields, that should be a significant step toward nailing down the root cause.
Agreed.

Will you take a look at this Lua bug report and see if you think it could be related?

http://www.lua.org/bugs.html#5.2.0-4 (http://www.lua.org/bugs.html#5.2.0-4)
Title: Re: Shot Histogram Request
Post by: srsa_4c on 17 / March / 2013, 19:43:31
Working around the Lua yield() bug
... it seems to be a bug in lua yield(). I'll see if I can try Phils lua updated branch when I get the time.
I hope you don't mind my question, but have you tried that branch already?

The bug you're mentioning has this note:
Quote
Wrong handling of nCcalls in coroutines.
reported by Alexander Gavrilov on 18 Apr 2012. existed since 5.2.0. fixed in 5.2.1.
Title: Re: Shot Histogram Request
Post by: lapser on 18 / March / 2013, 00:11:06
I hope you don't mind my question, but have you tried that branch already?
Phil's branch is still Lua 5.1.something. Apparently, updating to 5.2 would require a lot more changes.

I think Phil's going to merge his branch into the trunk soon, so I was kind of waiting for that to happen to apply my time lapse patches. Fixing the bug has moved down the priority list a little since I discovered the work around.

I appreciate the suggestion.
Title: Re: Shot Histogram Request
Post by: reyalp on 18 / March / 2013, 00:50:45
http://www.lua.org/bugs.html#5.2.0-4 (http://www.lua.org/bugs.html#5.2.0-4)
I don't think that bug applies to the 5.1.x code (hence the "existed since 5.2.0" comment), but I could be wrong.
Title: Re: Shot Histogram Request
Post by: lapser on 18 / March / 2013, 01:51:11
I don't think that bug applies to the 5.1.x code (hence the "existed since 5.2.0" comment), but I could be wrong.
Thanks, I didn't notice that. I think you're right.

There's a bug in 5.1.3 that could be the culprit:
http://www.lua.org/bugs.html#5.1.3-2 (http://www.lua.org/bugs.html#5.1.3-2)

Since Phil updated from 5.1.3 to 5.1.5, this bug should be fixed in his branch, so it's worth testing. How soon do you think it will be until Phil merges the 5.1.5 branch into the trunk?

4. Updated Lua to version 5.1.5 (Feb 2012 release) from 5.1.3 (Jan 2008 release).
I also looked at 5.2; but the changes are much more substantial so will take a lot more effort to update.
Title: Re: Shot Histogram Request
Post by: philmoz on 18 / March / 2013, 03:06:42
How soon do you think it will be until Phil merges the 5.1.5 branch into the trunk?

Not for a while I'm afraid. Work getting in the way at the moment.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 18 / March / 2013, 11:15:17
Not for a while I'm afraid. Work getting in the way at the moment.
OK, I'll test that branch as soon as I finish what I'm working on (setting the metering area using draw_rect)

Speaking of that, I'm planning to save the shot meter area data in:

A/CHDK/DATA/Shot_Meters.dat

Is that the right place?

Title: Re: Shot Histogram Request
Post by: srsa_4c on 18 / March / 2013, 20:52:50
I'm planning to save the shot meter area data in:

A/CHDK/DATA/Shot_Meters.dat

Is that the right place?
I think you can create a new directory in A/CHDK. Don't forget that your cameras can't handle long filenames, and that there's a limit (32 characters?) on path + filename length.
Title: Lua function for drawing shot meter areas
Post by: lapser on 18 / March / 2013, 21:35:13
I think you can create a new directory in A/CHDK. Don't forget that your cameras can't handle long filenames, and that there's a limit (32 characters?) on path + filename length.
Thanks. I just finished the lua function that will set the shot meter areas. You can look through the script to see what the keys do, but this is basically how it works.

up,down,left,right:  move or grow the metering rectangle
set: toggles between move and grow
zoom: change step size to 1 or 10
display: moves to next meter (4 max)
half_shoot: starts over
menu: exits and prints metering areas (percent)

Code: (lua) [Select]
--[[
@title Draw Test
--]]

function get_meters()
  local move=262 --green
  local grow=259 --red
  local nmeters
  local imeter -- current
  local meters=nil
  local i
  local mode
  local step
  repeat
    if(meters==nil)then
      meters={30,30,70,70, 30,30,70,70, 30,30,70,70, 30,30,70,70}
      nmeters=1
      imeter=1
      mode=move
      step=10
    end
    local xd=0
    local yd=0
    local step_string=string.format("%2d",step)
    draw_clear()
    repeat
      draw_string(0,0,step_string,mode,257)
      i=1
      local cmeter
      for cmeter=1,nmeters do
        local ax1=(meters[i]*359+50)/100
        local ay1=(meters[i+1]*239+50)/100
        local ax2=(meters[i+2]*359+50)/100
        local ay2=(meters[i+3]*239+50)/100
        local color=271 -- yellow
        local bcolor=256 -- clear
        if(imeter==cmeter)then
          color=mode
          bcolor=257 -- black
        end
        draw_rect(ax1-1,ay1-1,ax2+1,ay2+1,257,3)
        draw_rect(ax1,ay1,ax2,ay2,color)
        draw_string((ax1-5+(ax2-ax1)/2),(ay1-6+(ay2-ay1)/2),cmeter,color,bcolor)
        i=i+4
      end
      wait_click(200)
    until not is_key("no_key")
    if(is_key("menu"))then break end
    if(is_key("set"))then
      if(mode==move)then mode=grow else mode=move end
    elseif(is_key("left"))then
      xd=-step
    elseif(is_key("right"))then
      xd=step
    elseif(is_key("up"))then
      yd=-step
    elseif(is_key("down"))then
      yd=step
    elseif(is_key("zoom_in"))then
      step=10
    elseif (is_key("zoom_out"))then
      step=1
    elseif (is_key("shoot_half"))then
      meters=nil -- start over
    elseif (is_key("display"))then
      imeter=imeter+1
      if(nmeters<4)then nmeters=nmeters+1 end
      if(imeter>4)then imeter=1 end
      step=10
      mode=move
    end
    if((xd~=0)or(yd~=0))then
      i=(imeter-1)*4+1
      local x1=meters[i]
      local y1=meters[i+1]
      local x2=meters[i+2]
      local y2=meters[i+3]

      x2=x2+xd
      y2=y2+yd
      if(mode==move)then
        x1=x1+xd
        if(x2>100)then
          x1=x1+100-x2
          x2=100
        elseif(x1<0)then
          x2=x2-x1
          x1=0
        end

        y1=y1+yd
        if(y2>100)then
          y1=y1+100-y2
          y2=100
        elseif(y1<0)then
          y2=y2-y1
          y1=0
        end
      else -- mode==grow
        if(x2>100)then x2=100 end
        if(y2>100)then y2=100 end
      end
      if(x2<=x1)then x2=x1+1 end
      if(y2<=y1)then y2=y1+1 end
      meters[i]=x1
      meters[i+1]=y1
      meters[i+2]=x2
      meters[i+3]=y2
    end
  until false
  for imeter=1,nmeters do
    i=(imeter-1)*4+1
    print(meters[i],meters[i+1],meters[i+2],meters[i+3])
  end
end

get_meters()

Title: Re: Shot Histogram Request
Post by: lapser on 19 / March / 2013, 14:08:58
I finished adding the shot meter area drawing function posted above to my main time lapse program. It works well, and lets you set the meter areas based on what the camera is seeing.

For sunsets, I'd like to try putting a relatively small metering area over the sun before it sets. That should keep the sun from blowing out everything around it without having to underexpose the whole time lapse. It should work kind of like a histogram.

When I added the capability to do multiple meters, I didn't know how I would use them. But now that I can adjust the location and size of each meter, there are a lot of possibilities. A small meter on the brightest part of the picture would be like histogram based exposure compensation. Averaging the meters and putting one inside the other would give a kind of center weighted metering.

To do HDR, for example, you could place one meter on the brightest area, and one meter on the darkest. Then you would take 2 pictures, one based on each meter.

You could even use the meters for motion detection. You could focus the camera on a bird feeder at night with a 1 second exposure time, and put a small meter where the bird lands. When the meter detected a sudden change in brightness, it could trigger the camera to take a picture with flash.

I'm looking forward to exploring the possibilities opened up by being able to set the size and location of 4 different exposure meters. Try the test script in the post above to get an idea of how the meter sizes and postions are set.
====
On another subject, I decided to enter the interval time in seconds*10, i.e. tenths of a second, instead of milliseconds. The tick count is only accurate to 1/100 second, so the last digit is always 0. But I've found that I never need 1/100 second precision either. 1/10 second is perfect.  So one second is entered as "10".
Title: Re: Shot Histogram Request
Post by: hwntw on 20 / March / 2013, 08:06:04
Quote
To do HDR, for example, you could place one meter on the brightest area, and one meter on the darkest. Then you would take 2 pictures, one based on each meter.
My iPod Touch 4g has a few apps that do what you describe, dob the touch screen and the exposure points can be moved around and the shot exp comp is previewed.
Would you mind summarising your work so far on shot histogram and say how it will fit into the general usage of CHDK, for simpletons like me?

Colin
Title: Re: Shot Histogram Request
Post by: lapser on 20 / March / 2013, 11:54:06
My iPod Touch 4g has a few apps that do what you describe, dob the touch screen and the exposure points can be moved around and the shot exp comp is previewed.
That's interesting. I think of CHDK as an interface for Lua "apps". It's a good idea to be able to move the metering areas around and see the result. My metering is done after the shot, and applied to the next shot. But you can see the pictures as they're taken when in continuous mode. So I could move the meters during the time lapse and see the result. It might be useful.
Quote
Would you mind summarising your work so far on shot histogram and say how it will fit into the general usage of CHDK, for simpletons like me?
So far, I've just increased the resolution of the histogram. There's only one way to get the results of the histogram, at the moment:

get_histo_range(from,to)

The width of the histogram (range of from,to) is 1024,  The values returned are in percent, from 0 to 100, so it's not accurate enough to set exposure.

I've added the ability to specify a scale:

get_histo_range(from,to,scale)

A scale of 0 gives the actual number of points sampled in that range. I also return the total number of points with get_histo_range(-1)

I'm still experimenting with adding new features to the shot histogram routines. I got side tracked on the shot meter and time lapse timing functions. My plan is to return an exposure compensation value to achieve ETTR or ETTL on the next shot.

So the plan for the histogram routines in the future is to be able to use it for setting exposure similar to the way the shot meters work now.  Stay tuned.

You may want to look at this thread for more info about the new histogram routines I'm working on:
http://chdk.setepontos.com/index.php?topic=9270.0 (http://chdk.setepontos.com/index.php?topic=9270.0)
Title: Shot Meter Area test
Post by: lapser on 22 / March / 2013, 10:39:20
I did my first test with my new script where I can move and resize the meter areas while looking at the live view. I was able to put a metering area in the bright spot between cloud layers where the sun was setting, resulting in a 2 fstop reduction in exposure compared to the camera meter. I guess it worked.

I need to work on my focus method a little, so it will work with any camera. I've been using:

  post_levent_for_npt("PressSw1AndMF") --toggles manual focus mode

It works on my cameras, but I got a report that it crashed on a camera without manual focus. I need a more generalized method.

I think what I can do is: set_focus(d), press half_shoot, and see if it focused. I think that works on cameras without manual focus. If it didn't focus, then I can try switching to manual focus with the above statement. Hopefully, cameras without manual focus won't get to that statement.

I can't find any way for a script to tell if a camera has manual focus capability. Does anyone know how to do that in a script?

Here's the video with the meter area and size set from the live view:

http://www.youtube.com/watch?v=iFmMxsjB1kM#ws (http://www.youtube.com/watch?v=iFmMxsjB1kM#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 24 / March / 2013, 16:18:03
If the bug is in fact caused by repeated yields, that should be a significant step toward nailing down the root cause.
FWIW...

To test the hypothesis that there could be some conflict between debug hook yield and explicit yield with sleep() etc, I modified luascript.c to be call the debug hook every vm instruction. (edit  #define YIELD_CHECK_COUNT 1)

with this change set_yield(1...) hangs the camera script. set_yield(2,...) works, and should cause lua to yield every other vm instruction. I've tried running script with while(true) sleep(1) end on my a540 for > 12 hours, and have not seen the error. I also ran it on my d10 for several hours and did not see the error.

As an aside, there is a lua assert if the script is interrupted in the shutter button, presumably due to trying to yield in the restore() function. Problems with restore yielding have been noted before.
Title: Re: Shot Histogram Request
Post by: hwntw on 24 / March / 2013, 19:51:43
I finished adding the shot meter area drawing function posted above to my main time lapse program. It works well, and lets you set the meter areas based on what the camera is seeing.

For sunsets, I'd like to try putting a relatively small metering area over the sun before it sets...
When I added the capability to do multiple meters, I didn't know how I would use them. But now that I can adjust the location and size of each meter, there are a lot of possibilities. A small meter on the brightest part of the picture would be like histogram based exposure compensation. Averaging the meters and putting one inside the other would give a kind of center weighted metering.

To do HDR, for example, you could place one meter on the brightest area, and one meter on the darkest. Then you would take 2 pictures, one based on each meter.
I'm looking forward to exploring the possibilities opened up by being able to set the size and location of 4 different exposure meters. Try the test script in the post above to get an idea of how the meter sizes and postions are set.
...
Making this work on a touch screen camera would replicate app behaviour on iDevices/Android 4.2 devices, where HDR exposures are not made by using preset Ev ranges, but are metered from relevant areas of the shot, multi spot readings if you like, which are identified as High or Low (exposure). I think @philmoz has got CHDK working on a touch screen model, Ixus 310 HS I think. Your shot metering thingy seems to have a large potential for constructive uses
Colin
Title: Re: Shot Histogram Request
Post by: lapser on 24 / March / 2013, 20:12:37
Making this work on a touch screen camera would replicate app behaviour on iDevices/Android 4.2 devices, where HDR exposures are not made by using preset Ev ranges, but are metered from relevant areas of the shot, multi spot readings if you like, which are identified as High or Low (exposure).
I didn't realize there was "an app for that." Thanks for the info. I love when other people use my ideas before I think of them.  :)

Cell phone cameras area getting way ahead of "real" cameras in functionality because of app capability. It's only a matter of time before a camera company realizes this, and puts app capability on a high end camera. Maybe even the Android operating system would work? But at least for now, we have CHDK.
Title: Re: Shot Histogram Request
Post by: lapser on 24 / March / 2013, 20:15:30
To test the hypothesis that there could be some conflict between debug hook yield and explicit yield with sleep() etc,
I'm pretty sure this isn't the problem because the bug happened with set_yield(-1,-1). It happened with sleep(10) or coroutine.yield(). It's prevented by using the action stack to wait for the shot to be ready, rather than repeated sleep(10) or coroutine.yield()
Quote
As an aside, there is a lua assert if the script is interrupted in the shutter button, presumably due to trying to yield in the restore() function.
I assume that's one of the "ugly" problems with pcall() you were talking about. Does this only happen with a yield in the yield hook? It seems like doing a sleep() in restore works.

Maybe the C equivalent of set_yield(-1,-1) should be done before calling restore()?

====
I just got back from a camping trip where I left the G1X shooting 1 shot per 1.5 seconds starting at 7 P.M. It was connected to an 8.4 volt lithium external battery that weighs about 1 pound. I was hoping to get a sunset and sunrise in the same time lapse.

The G1X lasted until 11:15 A.M. the next morning, over 16 hours, and was still running. I had to shut it off because it was past time to leave. I ended up with 19,000 pictures, which I'll turn into a test video and post sometime soon.

The moon was out most of the night, so it was hard to see any stars. The moon was badly overexposed, since the shot was metered by the upper half of the picture, and not just the moon. This is where it might be really useful to be able to set the exposure using the histogram instead of the light meter.


Title: Re: Shot Histogram Request
Post by: lapser on 25 / March / 2013, 11:22:22
Here's the 16 hour time lapse I mentioned in the last post. I actually like the effect of the over-exposed moon and sun, with the clouds going by. I guess it's all art.

To protect the camera, I used plastic wrap, with a rubber band and scotch tape holding it around the base of the lens of the G1X. I screwed in the tripod quick release plate through the plastic wrap with no problem. I also used a lens hood. You can see the screen through the plastic, and all the buttons work fine. The lens and barrel are left uncovered. If it were raining, it might be a good idea to wrap a thin piece of plastic wrap around the extended lens barrel with the camera on.

I think the plastic wrap held in the heat of the camera so it didn't fog up. The lens didn't fog or frost over, although the lens hood was covered with frost.

http://www.youtube.com/watch?v=5O3Jn2OX9P8#ws (http://www.youtube.com/watch?v=5O3Jn2OX9P8#ws)
Title: Re: Shot Histogram Request
Post by: ahull on 25 / March / 2013, 20:08:20
lapser  :D - I could watch that all day (don't think I'd get paid though).
Title: Re: Shot Histogram Request
Post by: lapser on 25 / March / 2013, 20:47:30
lapser  :D - I could watch that all day (don't think I'd get paid though).
Thanks! It is pretty fascinating to see things with the help of technology in a way that was previously impossible. I was hoping for clear skies, but now I'm glad I got the clouds. It made the video more interesting.

I made a shorter time lapse with the SX50 right before the last video started. I wasn't expecting my external battery pack to last so long, so I wanted to start the G1X right before sunset. Anyway, here's the SX50 video:

http://www.youtube.com/watch?v=9_m2INhl2pE#ws (http://www.youtube.com/watch?v=9_m2INhl2pE#ws)

I also fired up the SX50 at first light from my tent using a Gorillapod in the vestibule. I must have been a little sleepy, because I had the camera in Manual Exposure mode. I discovered this at 2:25 into the video (after a cup of hot tea) and switched it to Aperture Priority while the script was running. The shot rate sped up and the pictures got much clearer. I think maybe setting the aperture with the script while in manual exposure mode was causing the aperture motor to move back and forth between each shot, or during the exposure. The clicking sound also changed in AP mode.

http://www.youtube.com/watch?v=ImpRHRcU5gY#ws (http://www.youtube.com/watch?v=ImpRHRcU5gY#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 28 / March / 2013, 20:57:03
I decided to take another look at smoothing out the small exposure changes to avoid the "fluttering" effect in the dark parts of the picture that show up sometimes. My first attempt was in the shot meter routine (CHDK mod), but I realized it wasn't right. The exposure is set by the Lua script, so the proper place for smoothing is in the script, not the shot meter. So I took all the smoothing stuff out of the shot meter, and wrote some new smoothing into the script.

I added an input parameter to the script I call "smoothing". Basically, the script doesn't change the exposure as long as it's within plus or minus the smoothing factor. I.E. if smoothing = 16, then the exposure doesn't change until the photo is overexposed by 16, or underexposed by 16.

This seems to work, but it leaves the shot always over or under exposed by 16. So I added a test that if it's over or underexposed more than 2, I adjust it by 1. The idea is to bring the exposure slowly to the middle, proper exposure when it suddenly jumps. I'm not sure I'm explaining it properly, but here's the Lua code involved:
Code: (lua) [Select]
  --tvd is the change in exposure computed by the shot meter
  --you add tvd to the current exposure and use it for the next shot
  tx=0
  if(tvd>0)then
    if(tvd>2)then tx=1 end
    tvd=tvd-smooth
    if(tvd<0)then tvd=tx end
  elseif(tvd<0)then
    if(tvd<-2)then tx=-1 end
    tvd=tvd+smooth
    if(tvd>0)then tvd=tx end
  end
I'll try to test this tonight, weather permitting.

Here's a pretty interesting time lapse I did last night on Spencer's Butte:

http://www.youtube.com/watch?v=X2o6Cderq10#ws (http://www.youtube.com/watch?v=X2o6Cderq10#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 01:29:17
Great sunset tonight. From the log files, it looks like the smoothing worked well. The only small mistake was using < instead of <= and > instead of >=
Code: (lua) [Select]
  tx=0
  if(tvd>0)then
    if(tvd>2)then tx=1 end
    tvd=tvd-smooth
    if(tvd<=0)then tvd=tx end -- changed to <=
  elseif(tvd<0)then
    if(tvd<-2)then tx=-1 end
    tvd=tvd+smooth
    if(tvd>=0)then tvd=tx end -- changed to >=
  end
Here's one of the pictures from the G1X:
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi.imgur.com%2FcQnxJIy.jpg&hash=e4e4e9390c0c91ab34d7811f0b4f41d0)
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 10:44:14
Would your script work on my ancient SD300 (Ixus 40) and the latest SVN build ? If so, any chance of posting the full script, the results are pretty impressive. 
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 10:59:16
Would your script work on my ancient SD300 (Ixus 40) and the latest SVN build ? If so, any chance of posting the full script, the results are pretty impressive.
It requires a custom build I've been developing that adds a lot of functions to CHDK. I'd be interested in seeing if it does work on old cameras, so if you're game, let me know your firmware version and I'll post a build for you to try.
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 12:22:38
I have a couple of old cameras we can try, you could start with the Ixus 40, its on f/w 1.00k and I have just stuck
ixus40_sd300-100k-1.2.0-2653-full on an SD card, shoved it in a slightly butchered IXUS II WP-DC10 dive housing I got for next to nothing from ebay. (It fits in quite well with a little filing and a bit of blue tac, don't worry, I filed the case, not the camera  :P).

I'm running one of the existing sunset time lapse scripts and have stuck it at the end of the garden to give us a baseline to compare with. Don't expect results quite as good as the G1X  :D  Especially since it is the middle of the day here at the moment.


Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 13:05:27
ixus40_sd300-100k-1.2.0-2653-full
OK, see if the attached CHDK build runs your current scripts.

My time lapse script switches to manual focus using:
post_levent_for_npt("PressSw1AndMF")

I think that may crash cameras without manual focus.

Does anyone know how to tell from a script if the camera has manual focus or not?

Without manual focus, I think you can just use set_focus, press shoot_half, and aflock, but newer cameras only set focus in manual focus mode. Anyway, maybe we can figure it out on your older cameras.

Let me know if the build works, and I'll post the script for you to test.
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 16:50:44
OK Good news, bad news time...

Good news is that that build loads OK on my camera (confused me slightly because it doesn't show the CHDK splash screen at startup, the first time,  so I thought it wasn't loading).

Good news,
I see the fancy new menu layout.
I can shoot DNG

Bad news, RawTherapee cant make sense of the .DNG file (I'll investigate this later, maybe try  DNG 1.1).
EDIT: Nope, and .CRW looks like nonsense as well. Neither RawTherapee nor UFRAW can make any sense of them, they look like a noise with a narrow horizontal band of dark colour about 1/4 of the way down from the top.
 
Good news, it runs the sunset timelapse script I used for the first test run.

More bad news, the internal SD card reader in my laptop suffered a fatal mechanical breakdown (i.e. the cheap'n nasty plasticky POS fell apart, and spat out a couple of very expensive looking  (and very small) plastic pieces,  I guess nothing lasts forever these days).

Good news, I dug out an old external card reader and that works.

Bad news, next the battery went flat, the second battery I tried was also flat. Good news, the third one is fully charged (and the others are now charging).

More good news, its my work laptop, so it looks like they will have to pick up the tab to fix it  :P

Bad news, after all that faffing about, its dark now, so no sunset time lapse from me tonight.

What do you want to test next?
Title: Re: Shot Histogram Request
Post by: srsa_4c on 29 / March / 2013, 16:58:53
Bad news, RawTherapee cant make sense of the .DNG file (I'll investigate this later, maybe try  DNG 1.1).
EDIT: Nope, and .CRW looks like nonsense as well. Neither RawTherapee nor UFRAW can make any sense of them, they look like a noise with a narrow horizontal band of dark colour about 1/4 of the way down from the top.
This is fixed in the ixus30 port. Does it help if you set image size to L (I mean if it's currently set to a smaller size)?
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 17:03:28
Image size is set to Superfine and L (2272x1704)
Title: Re: Shot Histogram Request
Post by: srsa_4c on 29 / March / 2013, 17:08:25
Image size is set to Superfine and L (2272x1704)
It's worse then. I'll look into backporting the ixus30 version in the near future...
The raw hook is at the wrong place.
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 17:26:04
Good news is that that build loads OK on my camera (confused me slightly because it doesn't show the CHDK splash screen at startup, the first time,  so I thought it wasn't loading).
I think the splash screen is a configuration issue. I'm not sure if it works for older cameras, but I would try resetting by deleting the file:
CHDK/CCHDK3.CFG

I'm still back on 2619, so anything that's been fixed on the camera since then isn't there.

Also, are you sure you got ALL the files in the zip onto your card, including the modules? You have to overwrite all the modules, since a lot of my new code is in the lua module.

Forgetting about the raw files for now, the next thing to try would be to run the time lapse script. It's still pretty rough, and not documented, but see if you can figure it out. You can try using all the defaults, and just press <menu> to get it started.

If it works, you can try changing the various parameters, and setting the metering areas before you press <menu> and see what happens. I predict that the camera may crash if you set the focus to 1 (hyperfocal distance) or -1 (infinity). Good luck.
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 17:30:30
Image size is set to Superfine and L (2272x1704)
It's worse then. I'll look into backporting the ixus30 version in the near future...
The raw hook is at the wrong place.

Hmmm odd, I reset all the settings on the camera and tried again, this time I think it works, let me check everything carefully. It *may* have been due to a low battery.
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 17:41:43
Good news is that that build loads OK on my camera (confused me slightly because it doesn't show the CHDK splash screen at startup, the first time,  so I thought it wasn't loading).
I think the splash screen is a configuration issue. I'm not sure if it works for older cameras, but I would try resetting by deleting the file:
CHDK/CCHDK3.CFG

I'm still back on 2619, so anything that's been fixed on the camera since then isn't there.

Also, are you sure you got ALL the files in the zip onto your card, including the modules? You have to overwrite all the modules, since a lot of my new code is in the lua module.

Forgetting about the raw files for now, the next thing to try would be to run the time lapse script. It's still pretty rough, and not documented, but see if you can figure it out. You can try using all the defaults, and just press <menu> to get it started.

If it works, you can try changing the various parameters, and setting the metering areas before you press <menu> and see what happens. I predict that the camera may crash if you set the focus to 1 (hyperfocal distance) or -1 (infinity). Good luck.

The script runs, I can move the metering square about, and takes a picture (just the one), I'll have a play with this tomorrow. Looks like it may well work.

Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 17:48:43
The script runs, I can move the metering square about, and takes a picture (just the one), I'll have a play with this tomorrow. Looks like it may well work.
That doesn't sound good. It should start taking 1 picture every 2 seconds.

What happens after it takes 1 picture? The next thing I do is sum up pixel samples in the raw buffer to compute the shot meter, so if the raw buffer address is wrong, it would crash or something. We may need to move on to a camera that can save raw correctly. Does yours work with the standard CHDK build for saving raw?
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 17:56:25
It's worse then. I'll look into backporting the ixus30 version in the near future...
The raw hook is at the wrong place.
That might hang my script without crashing, if raw_savefile() is never called. I also need capt_seq_hook_set_nr() to be working.
Title: Latest Time Lapses with smoothing
Post by: lapser on 29 / March / 2013, 18:02:31
http://www.youtube.com/watch?v=dl59JrWj9HU#ws (http://www.youtube.com/watch?v=dl59JrWj9HU#ws)

http://www.youtube.com/watch?v=wHnqeQ3ZtlI#ws (http://www.youtube.com/watch?v=wHnqeQ3ZtlI#ws)

http://www.youtube.com/watch?v=QYQLnUm6ujw#ws (http://www.youtube.com/watch?v=QYQLnUm6ujw#ws)
Title: Re: Shot Histogram Request
Post by: ahull on 29 / March / 2013, 18:25:21
The script runs, I can move the metering square about, and takes a picture (just the one), I'll have a play with this tomorrow. Looks like it may well work.
That doesn't sound good. It should start taking 1 picture every 2 seconds.

What happens after it takes 1 picture? The next thing I do is sum up pixel samples in the raw buffer to compute the shot meter, so if the raw buffer address is wrong, it would crash or something. We may need to move on to a camera that can save raw correctly. Does yours work with the standard CHDK build for saving raw?


I think the problem with RAW was actually due to low battery causing SD card corruption during the long save process.  I am now running on a fresh battery and have saved a couple of raw files which RawTherapee *does* like. I wont get a chance to do any further testing till tomorrow. This camera takes longer than 2 seconds (more like 5 or 6 seconds) to save a raw picture, not sure if that will be a problem or not. 

If that is a show stopper, I may abandon the idea and use some other camera. It would be nice to know if lapser's enhancements  work on older cameras though, so I am prepared to keep trying till we run out of options.
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 18:39:53
I think the problem with RAW was actually due to low battery causing SD card corruption during the long save process.  I am now running on a fresh battery and have saved a couple of raw files which RawTherapee *does* like. I wont get a chance to do any further testing till tomorrow. This camera takes longer than 2 seconds (more like 5 or 6 seconds) to save a raw picture, not sure if that will be a problem or not. 

If that is a show stopper, I may abandon the idea and use some other camera. It would be nice to know if lapser's enhancements  work on older cameras though, so I am prepared to keep trying till we run out of options.
OK, so if raw save is working, then the raw hook is ok. When you test tomorrow, try it first with raw save off. Also, see if you can demonstrate that you can turn dark frames off and on in the raw menu, and that it works. It should take twice as long to take a picture with dark frames on (use a long exposure with the camera only).

6 seconds is how long it takes for CHDK raw on my sx260. SX50 and G1X have built in raw, which is a lot faster. I haven't tested my time lapse routines with raw enabled. Obviously, you won't get 2 shots per second, but you should be able to get a shot every 6.5 seconds or so.

To get over 1 shot per second, you need to be in continuous mode before starting the script.
Title: Re: Shot Histogram Request
Post by: srsa_4c on 29 / March / 2013, 19:53:45
Also, see if you can demonstrate that you can turn dark frames off and on in the raw menu, and that it works.
That does not currently work, but soon will.
Another issue with this camera is that CHDK overrides are only applied before the actual shot, but not when half-shooting. I guess it's not your concern, since you're working with the raw data.
Title: Re: Shot Histogram Request
Post by: lapser on 29 / March / 2013, 20:34:48
Also, see if you can demonstrate that you can turn dark frames off and on in the raw menu, and that it works.
That does not currently work, but soon will.
Another issue with this camera is that CHDK overrides are only applied before the actual shot, but not when half-shooting. I guess it's not your concern, since you're working with the raw data.
The important thing is that capt_seq_hook_set_nr() is called right before the shot. I added a pre-shot delay here so I can set a precise shot interval that also works in continuous mode. This routine also saves the precise shutter open time so it can be saved in the CHDK raw file, if needed.

I do everything in half shoot, and set the exposure directly using propcases. I assume this should work with this camera?
Title: Re: Shot Histogram Request
Post by: ahull on 30 / March / 2013, 10:50:38
This is what I have so far. Lapser's CHDK version works and runs the same timelapse script I was using originally.

I have given up on raw for the time being I think it kinda works but I didn't try it again*, if you want more info about raw I'll grab the camera. It is in the garden watching the world/clouds/sunshine/snow go by at the moment. 

Lapser's script takes one shot then stops. It doesn't seem to crash the camera, nor does it do anything noticeably  odd it simply stops. All of the other parts of the script seem to work, in as much as I can resize and move the metering box set the script going, play with the various parameters etc. but as I said when I set it running it takes a picture then stops.

Oh and I am charging up half a dozen nb-4l batteries, so I have a sporting chance of being able to shoot tonights sunset.

Edit: Nope, RAW (.DNG) more kinda *doesn't* work. I took 6 images, 2 look fine, 4 look terrible, with varying degrees of distortion (banding and snow starting at the top of the image, covering between 20% and 100% of the picture), so let me try the standard build of CHDK and see if that is OK.
Title: Re: Shot Histogram Request
Post by: srsa_4c on 30 / March / 2013, 11:18:41
Improved capt_seq.c for ixus40 100k attached. It has all needed hooks, DNG seems alright with it.
Title: Re: Shot Histogram Request
Post by: lapser on 30 / March / 2013, 12:56:28
Improved capt_seq.c for ixus40 100k attached. It has all needed hooks, DNG seems alright with it.
THANKS!

Here's the Lapser enhanced build with the new capt_seq.c
Title: Re: Shot Histogram Request
Post by: ahull on 30 / March / 2013, 13:16:33
 :D Raw now works, I get perfect .DNG files.

Let me try lapser's script again.
Title: Re: Shot Histogram Request
Post by: ahull on 30 / March / 2013, 13:26:33
OK The script works as before, it takes a picture, saves it, then sits waiting, as if expecting me to do something more... Let me play around a bit, see if I can figure out what is going on. 

Does the script rely on continuous drive mode? 'cos this camera doesn't have that.

Actually what the camera says briefly after taking the picture is

***Terminated***
 6 2 0 -2
Title: Re: Shot Histogram Request
Post by: srsa_4c on 30 / March / 2013, 13:56:00
Actually what the camera says briefly after taking the picture is

***Terminated***
 6 2 0 -2
The log says
:353: bad argument #6 to 'format' (number expected, got nil)
XLapser.lua from the previous page.

Quote
Does the script rely on continuous drive mode? 'cos this camera doesn't have that.
It does. Press "down" in shooting mode...
Title: Re: Shot Histogram Request
Post by: lapser on 30 / March / 2013, 14:11:52
Actually what the camera says briefly after taking the picture is

***Terminated***
 6 2 0 -2
The log says
:353: bad argument #6 to 'format' (number expected, got nil)
XLapser.lua from the previous page.

Quote
Does the script rely on continuous drive mode? 'cos this camera doesn't have that.
It does. Press "down" in shooting mode...
There's an error in the tv96 to shutter speed conversion.

This relies on the log10 function. There was an error in the address of the log10 function that we discovered with the SX50. Can you check to make sure that address is correct?

[EDIT] Here's where we fixed it for the SX50
http://chdk.setepontos.com/index.php?topic=8932.msg97220#msg97220 (http://chdk.setepontos.com/index.php?topic=8932.msg97220#msg97220)

[EDIT 2]
Try running this script. It should print "96" if log10 is working:

print(shutter_to_tv96(500))
Title: Re: Shot Histogram Request
Post by: srsa_4c on 30 / March / 2013, 14:28:53
There's an error in the tv96 to shutter speed conversion.

This relies on the log10 function. There was an error in the address of the log10 function that we discovered with the SX50. Can you check to make sure that address is correct?
There's a list of function pointers in this firmware, in their names' alphabetical order, it should be correct.

Which CHDK functions are involved?

print(shutter_to_tv96(500))
96
What else could it be?
Title: Re: Shot Histogram Request
Post by: lapser on 30 / March / 2013, 14:42:15
Wait, let me get the right script. I'll attach it in a minute.

OK, found it. I did a change that I didn't test.

Line 326 of the script says:
  tvd0=tdv -- for log

It should say tvd0=tvd

I'll test it and post the correct script in a few minutes.

[EDIT lost count] OK, a few minutes are up. Here it is. Sorry for the confusion.
Title: Re: Shot Histogram Request
Post by: srsa_4c on 30 / March / 2013, 14:57:25
Line 326 of the script says:
  tvd0=tdv -- for log

It should say tvd0=tvd
Better :)
It now appears to work (shoots continuously, exposition is adjusted).
Title: Re: Shot Histogram Request
Post by: lapser on 30 / March / 2013, 15:09:34
Better :)
It now appears to work (shoots continuously, exposition is adjusted).
Great!

I wonder what the focus parameter would do if you set it to 1? That's supposed to set it to the hyperfocal distance, but it tries to go into manual focus first. I need to figure out how to focus correctly on cameras without manual focus.

The minimum and maximum ISO will probably be a little off. The first line of the script should be different for each camera. I think I can figure out that info in my conversion routines in the future.

svdiff=59 -- real to market difference

Thanks for the help in getting it to work on a new camera!
Title: Re: Shot Histogram Request
Post by: ahull on 30 / March / 2013, 16:28:37
Thanks for your help. Sadly too late for this evening. I should get another chance to try it tomorrow.

Meanwhile, here is yesterdays effort with a different script. (Quite a few exposure issues as you can see).

Test timelapse from SD-300 (Ixus 40) using CHDK (http://www.youtube.com/watch?v=C6FAOQNOb24#)
Title: Re: Shot Histogram Request
Post by: lapser on 30 / March / 2013, 19:06:14
Meanwhile, here is yesterdays effort with a different script. (Quite a few exposure issues as you can see).
You have a beautiful spot for time lapsing. Is there much light pollution at night? Where are you located?

The online specs for the camera says it can take over 2 shots per second in continuous mode. If you enter an interval of "5", that would be 0.5 seconds per shot, or 2 shots per second. The first number printed on the screen is the time left over. If it's positive, it means you're shooting at 2 shots per second. When it goes negative, it's not keeping up with the shot rate.

Be sure that you set the review time to 0 seconds, or that will slow you up. I try to set everything I can in the camera's menus to off. I use "cloudy" for white balance with sunsets, even on sunny days. Auto white balance doesn't look good with time lapse.

I just did the "smoothing" factor, and used it once, but it looks like it worked. I used a smoothing factor of "8" for sunset.

Most of my time lapses are of the computer screen. You can go back and forth from the screen to a dark spot and watch the exposure follow, if it's working right.

Setting the log file to "1" is what I recommend. It saves a log with an 8 digit name of "month-day-hour-minute.LOG" The modified print_screen(n) function names the log file "nnnnnnnn.LOG" if n>9999.

I'm looking forward seeing your future creations. Good luck.
Title: Re: Shot Histogram Request
Post by: ahull on 31 / March / 2013, 06:46:59
Hi lapser, that timelapse was shot facing north, the hills in the distance form part of the "Highland boundary fault" (http://en.wikipedia.org/wiki/Highland_Boundary_Fault) dividing the Scottish Highlands from the Lowlands. Light pollution is more of a problem to the south where the light from Edinburgh and Glasgow creeps over the hills.

Looking north we do sometimes see the northern lights, but I haven't as yet managed to film them.

I have a battery pack setup which I intend to attach to a camera in a weatherproof box and set up on a fencepost not far from here. Probably I will use that little Ixus 40, as it gives good results, and gives good battery life. I can shoot about 1000 frames on the internal NB-4L battery.  I do have a couple of other options when it comes to CHDK cameras, but based on previous results, I will probably stick with this set up. Another advantage of the Ixus models is that they are well built, with good optics and sensors, and can shoot images suitable for HD timelapses.

Furthermore, they can be picked up for very little on e-bay, so in the unlikely event that someone pinches it, while it is unattended in some remote spot, I am not too much out of pocket.

Not sure if I will get a chance tonight, but I do intend to test your script as soon as I get an opportunity. I'll post the results here of course.
Title: Re: Shot Histogram Request
Post by: ahull on 31 / March / 2013, 12:01:31
 ??? Hmmm now we get one shot, then the camera crashes. I will check everything later.  srsa_4c I presume it worked for you on an Ixus 40, if so, must be something odd on my setup.
Title: Re: Shot Histogram Request
Post by: srsa_4c on 31 / March / 2013, 12:06:12
??? Hmmm now we get one shot, then the camera crashes. I will check everything later.  srsa_4c I presume it worked for you on an Ixus 40, if so, must be something odd on my setup.
There's a known way to crash the cam, by setting a too low ISO override (the source mentions crash below ISO 58).
My script params were as attached, cam in P mode, continuous drive.
Title: Re: Shot Histogram Request
Post by: lapser on 31 / March / 2013, 12:28:38
Try setting all the overrides to off. My script is setting all the exposure parameters, so it might be conflicting with the CHDK overrides.

The script recognizes the camera exposure compensation setting, so if you want the entire sequence darker or lighter, you can use that.

Try setting infinity focus on the camera before starting the script. Don't set the focus parameter in the script. I think it might crash the camera.

I also turn as much as I can off in the camera menus, like IS and such. The mode should not be "auto". Try it with Av (aperture priority) if the camera has that feature. I think P mode should also work, since everything is in half shoot. But it will use the aperture setting of the first shot. You probably want the widest aperture possible. Maybe you could put your hand over the camera for the first shot to get the widest aperture (infinity focus mode), and that would work.
Title: Smoothing Test
Post by: lapser on 31 / March / 2013, 13:21:34
I went to a dark place last night (literally, not figuratively) and pointed the G1X at the sky while it went from light to dark.

The smoothing algorithm worked well to keep the exposure changes to 0 or -1 for each shot. There's no back and forth oscillations like I had before. The -1 changes do tend to bunch up together in groups of 3 because I don't do any changes if the exposure is within plus or minus 2, to prevent oscillations.  I think I can modify this so it's OK to do a -1 or +1 change if the last change was in the same direction. This should prevent the oscillations, and the bunching up in groups of 3 (I think). The bunching up is more visible at the beginning of the video when the exposure is changing more slowly.

[EDIT] After a little more thought, I realized that the oscillations and bunching up of -1 changes are due to the inaccuracy of the shutter speed changes. A -1 change in Tv96 is not precise, which shows up in the shot meter, and "pumping" of the dark areas in the video.  But a change of -1 in Sv96 is much more precise, and doesn't produce the "pumping" or "bunching". The script switched to Sv96 changes and held shutter speed at 1/2 second during the middle part of the video. That's why it "pumps" more at the beginning.

I've attached the log file. I added a description in the file of what the numbers mean. Here's the (kind of boring) video:

http://www.youtube.com/watch?v=lbBMdFa9Cmk#ws (http://www.youtube.com/watch?v=lbBMdFa9Cmk#ws)
Title: Re: Shot Histogram Request
Post by: ahull on 31 / March / 2013, 15:30:20
Setting up the camera *exactly* as per srsa_4c's settings (I assumed P mode was Portrait, as this cam has an Auto and Manual mode, but nothing specifically called P If this is not the correct mode srsa_4,  let me know)... and it works  :D. It seems a little flakey if I use any other settings.

By the time I had checked everything, it was just past sunset time, so I am going to let it shoot a little twilight, for as long the battery lasts. I just sat it on the fence post, no waterproof housing, slightly risky as there is a chance of frost. I notice the script doesn't switch off the display, not sure if this is possible, but it would help preserve the battery life a bit if it is. 

If I get any usable results I'll post them soon.


Edit:  :D Looks like it works (and having said there is little light pollution, I lied  :P, in the village there is some, hence the rosy pink glow in the foreground near the end of the sequence).


Test timelapse 2 from SD-300 (Ixus 40) using CHDK Test build (ixus40_sd300-100k-1.2.0-r2619_130330) and lapser's script. (http://www.youtube.com/watch?v=rXm1_Mbrc_M#)

PS. Ignore a couple of dodgy frames at the start of the video, not sure how they sneaked in there, not the fault of the script, entirely the fault of the camera man.
Title: Re: Shot Histogram Request
Post by: lapser on 31 / March / 2013, 16:26:12
(I assumed P mode was Portrait, as this cam has an Auto and Manual mode, but nothing specifically called P If this is not the correct mode srsa_4,  let me know)... and it works  :D. It seems a little flakey if I use any other settings.
P is "Program" auto exposure that sets aperture and shutter speed. You could try it in Manual, setting the aperture as wide as possible (lowest F stop). Portrait mode probably isn't right for a sunset.
Quote
I just sat it on the fence post, no waterproof housing, slightly risky as there is a chance of frost. I notice the script doesn't switch off the display, not sure if this is possible, but it would help preserve the battery life a bit if it is. 
You switch the display on and off by pressing <set> while the shots are being taken. Be careful not to jiggle the camera, though. <up> and <down> move the log line. <right> and <left> turns the metering area display on or off. <display> controls the ND filter (if any). That may crash the camera, so don't try it unless you're ready for that possibility.

I waterproofed my G1X on the snowshoe trip by putting it display side down in the middle of a sheet of plastic wrap. I wrapped it around the camera, and put a rubber band around the barrel of the lens to hold it.  Then I cut the plastic with scisssors so it's not in the shot. With a point and shoot, you'd have to do it with the camera turned on and the lens out. It worked pretty well. I think it holds the camera heat in enough to keep the lens from fogging, or the camera from freezing. Plus you can see the screen and all the buttons work.
Title: Re: Shot Histogram Request
Post by: srsa_4c on 31 / March / 2013, 20:07:02
Sorry about the confusion, Canon is only using "P" mode on cameras with manual modes. On Ixus cameras, it's displayed as "M" mode (but it doesn't provide full manual control, the name is misleading).
Title: Re: Shot Histogram Request
Post by: lapser on 01 / April / 2013, 12:07:22
Canon is only using "P" mode on cameras with manual modes. On Ixus cameras, it's displayed as "M" mode (but it doesn't provide full manual control, the name is misleading).
I seemed to have a conflict in Manual Exposure mode on the SX50 when overriding exposure in half shoot. I haven't tracked it down, but it may have been related to setting the Av propcase. I heard clicking, and it slowed down the shot rate until I switched the mode dial to Aperture Priority mode. It was also in continuous shooting mode, so that might be it too. There's a continuous mode with auto focus that may have been triggered for some reason.

I'd be interested to see how fast you can shoot in continuous mode. If you set the interval to 5 (1/2 second), that would be a good test. An interval of 1 would shoot as fast as possible (but slightly irregular).
==========

I did another test from Skinner Butte last night. I set a small shot meter area on one street and another on the sky. When the sky got dark, the the other shot meter kept the exposure correct for the city lights, and had the added benefit of keeping the shutter time under 1/2 second so it didn't slow down the shot rate (and speed up the resulting video).

I used a Norah Jones song for the music, but EMI blocks the video in some countries. I apologize if you're in one of them:

http://www.youtube.com/watch?v=pozFliELR4w#ws (http://www.youtube.com/watch?v=pozFliELR4w#ws)
Title: Re: Shot Histogram Request
Post by: ahull on 02 / April / 2013, 14:35:01
Hi lapser, Love all of the detail with the traffic lights and traffic in that last time lapse.

As far as my testing goes...  they say that if you make things idiot proof, it just inspires a better kind of idiot to break it. Looks like I figured out how to break your script in a new and interesting manner.

Since I couldn't make it load in Auto or Manual mode for some reason (one shot, then camera crash, as I described previously...) I decided to see what mode other than Portrait it would work in. So I put the camera in night snapshot mode, set it up and left it to do its thing.

When I returned it had taken a bunch of pictures, *but* every other picture was exposed differently. The odd numbered images got progressively darker as the sun set, the even numbered images got lighter.  Not sure how I and/or the camera  managed this feat (would perhaps make for some interesting HDR  shots, but didn't make a very good timelapse).  Its not a complaint about the script, I'm just trying to figure what fat fingered mistake I made.... That was last nights effort.

Tonight is overcast, and the local farmer is shifting his ewes down to the yard, so dog walk was curtailed, and no test tonight. I am going to try again tomorrow if I get a chance
Title: Re: Shot Histogram Request
Post by: lapser on 02 / April / 2013, 15:31:26
Since I couldn't make it load in Auto or Manual mode for some reason (one shot, then camera crash, as I described previously...) I decided to see what mode other than Portrait it would work in. So I put the camera in night snapshot mode, set it up and left it to do its thing.

When I returned it had taken a bunch of pictures, *but* every other picture was exposed differently.
It's still a very experimental script, and CHDK modifications, so it's not something you did. For testing, you don't need to wait for sunset. Just point the camera at the screen and hold it there, and start the script.

Will you try setting "Show Meters" to 1, and "Log File" to 1. Then, the first picture will show the metering area in the picture. It should be about the same as the metering area you see and can move around when the script starts. The picture at the end of the last time lapse script is a good example of what it looks like.

If the log file works, you should see a file in the CHDK/LOGS folder like:

04021308.LOG

If you can post this log file, and the first picture (small size is ok) with the metering lines on it, that might help.

You can also try setting MAX ISO to 100 (same as MIN ISO) and see if that changes anything, in case there's an error in setting ISO on that camera.
Title: Re: Shot Histogram Request
Post by: ahull on 02 / April / 2013, 18:51:45
Good suggestions. I'll give them a try when I can. 
I may continue my testing at sunset routine though as sounds likely to produce more interesting results  :P
Besides these days just around sunset is about the only time I am likely to have a few spare moments.

Title: Re: Shot Histogram Request
Post by: lapser on 02 / April / 2013, 21:12:54
Good suggestions. I'll give them a try when I can. 
OK, be sure to try continuous mode and infinity focus. I think you press the <left> for focus and <down> for continuous drive mode (burst mode).

If nothing else, I'd like to see if the pictures are displayed on the screen in continuous mode like on my camera.
=================

I wasn't totally happy with the smoothing routine because it bunches up ev96 changes in groups of 3, and that's more visible than I'd like. I updated it to only do a ev96 change every 4 unchanged shots. I'll see if that works tonight. It looks like it might be a good sunset.

Last night was really nice, but I got 11,000 pictures and I'm processing them all through Lightroom, which takes all day. It should make the sunset colors a little brighter, though. I'll try to post something when it's ready.

Here's my current smoothing code:

Code: (lua) [Select]
  --smoothing
    if(tvd>1)then
      tvd=tvd-smooth
      if(tvd<=0)then
        if(nztvd>3)then tvd=1 else tvd=0 end
      end
    elseif(tvd<-1)then
      tvd=tvd+smooth
      if(tvd>=0)then
        if(nztvd>3)then tvd=-1 else tvd=0 end
      end
    else
      tvd=0
      nztvd=-1
    end
    if(tvd==0)then nztvd=nztvd+1 else nztvd=0 end
Title: Re: Shot Histogram Request
Post by: lapser on 03 / April / 2013, 17:25:38
I think the smoothing code above worked better from looking at the log file, but I'll have to see what the video looks like tomorrow (still processing in Lightroom).

I finished the videos from April 1, which was a really pretty, light up the sky kind of sunset:

http://www.youtube.com/watch?v=deOMHla_MGk#ws (http://www.youtube.com/watch?v=deOMHla_MGk#ws)

http://www.youtube.com/watch?v=MrpzuGwGsrs#ws (http://www.youtube.com/watch?v=MrpzuGwGsrs#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 04 / April / 2013, 15:20:42
The smoothing code did work better for most of the video, except at the beginning. I had one meter set on the sun as it was just about to set, so the shutter time was 1/2500 at the start. At this high speed, changes of one tv96 unit apparently aren't as accurate as they are at slower speeds. I think this is what caused the "fluttering" at the beginning of the video in the darker, upper left corner away from the sun. After the sun went down, I didn't see any more "flutter" even as it got dark and the stars came out.

I've been planning to add automatic ND filter control to the script. Maybe I could apply the ND filter if the shutter speed was over 1/1000 or so. The filter is around 2.5 Fstop, but would have to be calibrated more accurately to keep from flashing when it went in or out.

SX50:
http://www.youtube.com/watch?v=WiVrgVYbuh8#ws (http://www.youtube.com/watch?v=WiVrgVYbuh8#ws)

G1X:
http://www.youtube.com/watch?v=eY7bjRyNUhY#ws (http://www.youtube.com/watch?v=eY7bjRyNUhY#ws)
Title: Rounding Error
Post by: lapser on 05 / April / 2013, 10:18:43
This smoothing/fluttering problem smelled like rounding errors, so I looked into it.

I was converting the shot meter result from (double) to (int) using truncation since the absolute value isn't critical, only the relative value from the last shot. However, truncation doesn't work correctly for signed values. That is, everything between -1.0 and +1.0 is truncated to integer 0.

The usual way of rounding is to add 0.5 and truncate. However, for negative numbers, you need to subtract 0.5.  The correct rounding function is:

Code: [Select]
int iround(double x)
{
  return (int)(x+((x>0)?0.5:-0.5))
}

Here's a more complete discussion of rounding:
http://www.cs.tut.fi/~jkorpela/round.html (http://www.cs.tut.fi/~jkorpela/round.html)

I'm not sure this fix will solve my "fluttering" problem, but it should help.

[EDIT] Is there a built in rounding function I can use that will round negative numbers correctly, i.e. rint() or lrint()? How would I call them? Thanks.

[EDIT2] I also corrected the rounding in my new Apex96 conversion functions. The shutter time conversions are accurate now for negative tv96 values (Shutter time >1 sec). For example, instead of showing 4.97 seconds when I wanted 5 seconds, it now shows 5.00 seconds.
Title: Re: Shot Histogram Request
Post by: ahull on 05 / April / 2013, 18:21:48
I'm quite pleased with the results I got tonight, I put the 2361 frames shot on a single battery together at 6 fps, but I might redo at 12 fps, as at  6 1/2 mins it is a little long. However the result is very respectable, for very little effort on my part (and a great deal on the part of lapser, for which many thanks). I just set up lapser's script, grabbed a fairly large section in the middle of the frame to meter from. Dumped the camera on a fence post and took the dog for a walk. I left the camera to run till the battery went flat. 

Bear in mind this is shot unattended,  on an old Ixus 40 using the cameras battery, rather than an external power source, at 4Mp, and converted to 1920x1080 (HD). Not bad for a camera you can pick up for a song these days.

Ben Lomond sunset early April (http://www.youtube.com/watch?v=o0wMMAdEayw#ws)

The mountain is Ben Lomond in the Trossachs area of Scotland,

The frames are made in to a movie with mencoder using a Linxux PC and this simple bash script.
Code: [Select]
#!/bin/bash
# The Ixus 40 is set up to create a new folder for every 10 images
# I copy these folders to ~/Pictures/Timelpase
# Then the script grabs all of them and moves them to a folder called ./Pics
# it then builds te movie with mencoder.
#

for file in $(find . |grep JPG)
do
    mv  $file ./Pics/.
done

PIC_DIR="./Pics"

# For lower res, use something like..
#WIDTH="640"
#HEIGHT="480"

# 1920x1080 gives full HD
WIDTH="1920"
HEIGHT="1080"

FPS=12
BITRATE="1500"
DEST_VIDEO="timelapse6.mpg"

mencoder mf://$PIC_DIR/\*.JPG -mf w=$WIDTH:h=$HEIGHT:fps=$FPS:type=jpg -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o $DEST_VIDEO

Title: Re: Shot Histogram Request
Post by: lapser on 05 / April / 2013, 19:29:53
I'm quite pleased with the results I got tonight, I put the 2361 frames shot on a single battery together at 6 fps, but I might redo at 12 fps
Very nice! That's a really beautiful place.

I usually shoot at 1 or 2 frames per second, and play back at 25 or 30 FPS. 2 or 3 minutes is a good target time for a sunset video.

From your previous posts, I was worried that the exposure adjustments weren't working right. Did you find a mode that worked? How did you set the focus? The tree at the left was in sharp focus, so I wonder what the focal length was.

If you set the log file parameter to 1, it will save a log that shows the focal distance, and a lot more.

Glad to see your having some success with the script, and the camera.

Title: Re: Shot Histogram Request
Post by: ahull on 06 / April / 2013, 06:44:26
I'm quite pleased with the results I got tonight, I put the 2361 frames shot on a single battery together at 6 fps, but I might redo at 12 fps
Very nice! That's a really beautiful place.
Thanks, it can be a very beautiful spot, particularly in the spring when the sunsets are long (we are relatively far north).
Quote

I usually shoot at 1 or 2 frames per second, and play back at 25 or 30 FPS. 2 or 3 minutes is a good target time for a sunset video.

I just picked 6fps to see if it gave usable results on youtube, a bit of fine tuning is required I suspect, certainly 12fps is better, I am slightly limited in duration as this camera can only use up to 2Gb SD cards, so far the card has filled before the battery has gone flat, which is a little surprising as I didn't think I would get anywhere near this limit.  2000+ shots on one charge of an NB-4L is pretty good going I would say.

Quote

From your previous posts, I was worried that the exposure adjustments weren't working right. Did you find a mode that worked? How did you set the focus? The tree at the left was in sharp focus, so I wonder what the focal length was.

If you set the log file parameter to 1, it will save a log that shows the focal distance, and a lot more.

I got it working in manual mode with a little bit of trial and error, several combinations of settings froze the camera. If I get a chance I'll post the full details. I then set the camera for Scenery (Left arrow > Mountains), flash off (it tends to default to Auto every time you power on the camera), Continuous mode (down arrow) and focused the camera and started CHDK and the script. The script is set for focus at infinity, and I will check the SD card to see if I remembered to leave the logging on, if not I will try again tonight with logging enabled.

EDIT: Logging is enabled, log file attached from last night.

Quote

Glad to see your having some success with the script, and the camera.

Its fun to get such creative use out of what might be dismissed as an incapable old camera. Thanks mainly to being inspired by your results.
Title: Re: Shot Histogram Request
Post by: lapser on 07 / April / 2013, 01:39:54
EDIT: Logging is enabled, log file attached from last night.
Thanks for posting the log file. It's interesting to see the comparison with an older camera.

My SX50 takes about .25 seconds to process a shot, and your camera takes about .50 seconds. The minimum time between shots also depends on the speed of saving the files, so I can't sustain 4 shots per second (more like 2).

The exposure went to 800 ISO maximum, but that's probably a little too noisy on your camera. I'd set it to 400 ISO, although the time between shots will increase to as much as 10 seconds as it gets darker.

There's a little "fluttering" of exposure when it got dark. I didn't notice anything in the video, though.
=====
I've made some progress with the script and CHDK patches in the last few days. First, I was able to apply the patches to the latest CHDK build. Phil updated Lua from 5.1.3 to 5.1.5, so I have high hopes that the problem I had with Lua yield/resume halting the script will be fixed now. I'll change the script to add the sleep(10) loop back in, or maybe coroutine.yield(), and leave a camera or two running overnight to see if the script works right now.

I'm also pretty satisfied with the script smoothing code. I fixed the rounding error in the shot meter for negative values, and added code in the script that minimizes each change (usually just 1 or -1), and spreads out the changes instead of bunching them up 3 or 4 at a time. The test videos are coming out pretty smooth.

I did have a "glitch" last night where one picture was darker by 43 and the next picture went back to normal. This happened once in 10,000 pictures. I also noticed a "glitch" during my 17,000 picture overnight camping trip, where one picture flashed much brighter. I had logging disabled, so I wasn't sure what happened. But the new "glitch" was logged, and showed that the picture that triggered the glitch looked the same as the the previous pictures. That is, it must have been an error in the value the meter returned. I'm not sure why this happened, but I added a "glitch" detector to the script. If there's a single change over 16, I ignore it, and disable the glitch detector for the next 5 shots. So it will take 2 shots to respond to sudden changes in brightness, instead of 1. But for sunsets, there shouldn't be any sudden changes, except for glitches.

Now that I've figured out a pretty simple and effective smoothing algorithm in the script, I'll see if I can move it to the shot meter code in C, adding a smoothing parameter to the shot meter enable function. I might be able to use the (double) values from the shot meter instead of the rounded integer values the script gets.
Title: Re: Shot Histogram Request
Post by: ahull on 07 / April / 2013, 12:14:45
If you have merged back in to the "bleeding edge" build, does that mean I can try you script out on a couple of other models now?

Title: Re: Shot Histogram Request
Post by: lapser on 07 / April / 2013, 13:19:04
Sure. Give me the models and firmware versions and I'll post builds for you.

I've attached the latest script and ixus40 build
If you have merged back in to the "bleeding edge" build, does that mean I can try you script out on a couple of other models now?
Title: Re: Shot Histogram Request
Post by: ahull on 07 / April / 2013, 13:30:47
If it isn't directly available from the download server - "The Latest Builds - Unstable New Development Version 1.2" - link, how about rolling a version for the Ixus 115 HS and the Powershot A2200, I'll give those two a try for starters, would be interesting to compare all of the results (assuming the weather improves, gone very overcast here after a week or more of great sunsets).

I'll also stick that new version on the Ixus 40, and see if I can break anything  :P

Edit: The new version of CHDK works fine, however I forgot to update to your new lua script, before I left the camera out filming the local farmer ploughing in the twightlight and the dark.

I might get some interesting effects from the lights on the tractor, but even if I don't, it should be a fairly good test.  Tomorrow I will try something similar with your updated lua script.

 
Title: Re: Shot Histogram Request
Post by: lapser on 07 / April / 2013, 14:33:22
how about rolling a version for the Ixus 115 HS and the Powershot A2200
I need the firmware versions.

My time lapse mods are too experimental for the "experimental" trunk, so you'll have to get the build from me for each camera.
Title: Re: Shot Histogram Request
Post by: ahull on 07 / April / 2013, 17:37:34
how about rolling a version for the Ixus 115 HS and the Powershot A2200
I need the firmware versions.

My time lapse mods are too experimental for the "experimental" trunk, so you'll have to get the build from me for each camera.

OK lapser I'll get the versions for you soon.
Title: Re: Shot Histogram Request
Post by: lapser on 07 / April / 2013, 18:33:08
OK lapser I'll get the versions for you soon.
Start by installing the "full" version 1.2 from the main download page for each camera. My builds install over the full version, since they don't include all the files. They only work with the card locked (auto boot).
Title: Lua Resume Bug Strikes Again
Post by: lapser on 08 / April / 2013, 00:07:05
I thought Phil's update to Lua had fixed the resume bug. However, I triggered the bug again tonight. It seems to happen as it gets dark and the shutter time increases. Here's what it printed:

ERROR: NULL error message
*** TERMINATED ***
Lapser:     -9 3209878     0     0

The "Lapser" line is debug variables I defined. Only the first one is significant here.

lapser1 = -9

This is a lucky break, because the only time lapser1 is -9 is in luascript.c here:

Code: [Select]
// Wait for a button to be pressed and released (or the timeout to expire)
static int action_stack_AS_LUA_WAIT_CLICK()
{
lapser1=-9;
    // Check key pressed or timeout
    if ((get_tick_count() >= action_top(2)) || camera_info.state.kbd_last_clicked)
    {
        // If timed out set key state to "no_key", otherwise key pressed so set last checked time
        if (!camera_info.state.kbd_last_clicked)
            camera_info.state.kbd_last_clicked=0xFFFF;
        else
            camera_info.state.kbd_last_checked_time = camera_info.state.kbd_last_clicked_time;
lapser1=9;
        action_pop_func(1);
        return 1;
    }
    return 0;
}
So it looks like action_stack_AS_LUA_WAIT_CLICK() didn't return, or lapser1 would be 9, not -9. Interesting!

If this is true, it may be that the function, get_tick_count() never returned (EDIT or messed up the stack somehow?). I suspect that it's not thread safe. Here's the code for get_tick_count() in platform/generic/wrappers.c

Code: [Select]
long get_tick_count()
{
long t;
#if !CAM_DRYOS
    _GetSystemTime(&t);
    return t;
#else
    return (int)_GetSystemTime(&t);
#endif
}

I added a delay in capt_seq_hook_set_nr() that includes this code:

Code: [Select]
      tick=get_tick_count();
      while(tick<shot_next)
      {
        msleep(10);
        tick=get_tick_count();
      }
My theory is that there's a hard interrupt during the call to get_tick_count() above, and then get_tick_count() is called in wait_click(10) and messes up the stack.

But it looks like I could change my wait loop to avoid get_tick_count() like this:

Code: [Select]
      tick=get_tick_count();
      if(tick<shot_next)
      {
        msleep(shot_next-tick);
        tick=shot_next;
      }
I was using msleep(10) so I cold abort the wait by setting shot_next to 0 when I exit the program, but I can minimize the calls to get_tick_count() if that's will fix the bug.

So this may not be a "lua yield" bug after all. It may be that get_tick_count() is called from different threads but isn't thread safe.

So if this is the cause of the bug, I may be able to trigger it more reliably by calling get_tick_count() in a tight loop many times, in both threads. I'll try it and see what happens.
====
[EDIT 2]
The SX260 triggered the same bug about an hour later:

ERROR: NULL error message
*** TERMINATED ***
Lapser:     -9 3146878     0     0

The second number is a little different and looks like an address. Here's where "lapser2" comes from:

Code: [Select]
int lua_script_run(void)
{
//snip
  Lres = lua_resume( Lt, top );
  lapser2=Lres;
Here's are the values for lapser2:

SX50:   3209878  0x30FA96
SX260: 3146878  0x30047E
Title: Re: Shot Histogram Request
Post by: reyalp on 08 / April / 2013, 00:59:18
I don't understand how get_tick_count() not being thread safe could cause the symptom.

The "null error message" means that problem happened while lua was executing, inside lua_resume. Of course,  the lua state could have got messed up before the call to lua_resume.

If get_tick_count() didn't return, then the entire kbd_task would be hung, and lua would never resume, or (if it was the call inside luaCB_wait_click) lua_resume would never return.

unless I'm mistaken, lapser1 would stay -9 if the return 0 (timeout) case were hit.

Looking at the implementation of  _GetSystemTime (on D10) I don't see how it would not be thread safe. It's a very simple function, it basically just disables interrupts, reads a variable, restores interrupts and returns.

There is an oddity in luaCB_wait_click though, it returns 1 even though it pushes nothing on the Lua stack. That is wrong, although I suspect it is harmless.

edit: I've fixed a few instances of that mistake in the trunk and release branches.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / April / 2013, 01:45:14
unless I'm mistaken, lapser1 would stay -9 if the return 0 (timeout) case were hit.
  lapser1=9;
is right before
  action_pop_func(1);

It should have stayed in the action stack loop and not called resume. So something else must have moved the stack pointer, I think?
Quote
Looking at the implementation of  _GetSystemTime (on D10) I don't see how it would not be thread safe. It's a very simple function, it basically just disables interrupts, reads a variable, restores interrupts and returns.
That's good to know that _GetSystemTime is threadsafe (disables interrupts). However, I don't think the wrapper is threadsafe, since it could be interrupted and called again from another thread.

  long t;
  return (int)_GetSystemTime(&t);
is actually 2 returns. If an interrupt occurs between the returns, that could be a problem. If the stack pointer were in the wrong place because of it, it's possible that it would effectively do the action stack pop thinking it was popping variable "t".
Quote
There is an oddity in luaCB_wait_click though, it returns 1 even though it pushes nothing on the Lua stack. That is wrong, although I suspect it is harmless.
I think Phil changed the meaning of the 1 return when he re-worked action stack.
[EDIT] Oh, you're talking about luaCB_wait_click(). Yes I noticed that too, but I figured Phil knew what he was doing  :D

In any event, this suggests a way try to trigger the bug with repeated calls to get_tick_count() from 2 different "tasks". The hardest part about this bug is that it only happens every 10,000 pictures!

One thing that bothers me is that the bug also happened with coroutine.yield(), as I recall. I don't think that calls get_tick_count(), but get_tick_count() might be called somewhere else in the action stack code. But I think having the action stack abort abnormally and call resume() might explain the strange error code.

Thank you for your help.
Title: Re: Shot Histogram Request
Post by: reyalp on 08 / April / 2013, 01:52:54
Per http://www.lua.org/manual/5.1/manual.html#lua_resume (http://www.lua.org/manual/5.1/manual.html#lua_resume)
lua resume is supposed to return a limited number of constants
Code: [Select]
/* thread status; 0 is OK */
#define LUA_YIELD 1
#define LUA_ERRRUN 2
#define LUA_ERRSYNTAX 3
#define LUA_ERRMEM 4
#define LUA_ERRERR 5
You might check whether the values you got are within the CHDK binary or heap space.

If you want to try to drill down to where the bad status is coming from, ldo.c lua_resume would be the place. I mentioned back here http://chdk.setepontos.com/index.php?topic=8997.msg97669#msg97669 (http://chdk.setepontos.com/index.php?topic=8997.msg97669#msg97669) that I traced it into a particular case in this function (assuming Alarik's problem was the same as yours).
Title: Re: Shot Histogram Request
Post by: philmoz on 08 / April / 2013, 01:53:08
While I doubt it's an issue of 'thread safeness' there does seem to be something strange here.

Just to clarify, the line:
    Lapser:     -9 3209878     0     0
is being displayed in the console after the script terminates, correct?

The script should have been suspended until action_stack_AS_LUA_WAIT_CLICK finished (after the action_pop_func call).

So I want to double check that the '-9' being displayed is not a result of the simply not updating the display/log after the script has ended.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / April / 2013, 01:58:50
The script should have been suspended until action_stack_AS_LUA_WAIT_CLICK finished (after the action_pop_func call).

So I want to double check that the '-9' being displayed is not a result of the simply not updating the display/log after the script has ended.
Yes, that's what caught my attention. Here's where I print lapser1:

Code: [Select]
int lua_script_error(lua_State *Lt,int runtime)
{
//snip

    script_console_add_line(LANG_CONSOLE_TEXT_TERMINATED);

    char osd_buf[50];
sprintf(osd_buf, "Lapser: %6d%6d%6d%6d",lapser1,lapser2,lapser3,lapser4);
script_console_add_line((long)osd_buf);


script_print_screen_statement(0); //close print file
    shot_histogram_set(0); //disables meters and interval too

    return SCRIPT_RUN_ERROR;
}

Title: Re: Shot Histogram Request
Post by: reyalp on 08 / April / 2013, 01:59:51
That's good to know that _GetSystemTime is threadsafe (disables interrupts).
It's not thread safe because it disables interrupts. It's thread safe because it only reads globals and uses the stack. Even if some other thread was changing the globals underneath it, that wouldn't cause the code to malfunction.

Quote
However, I don't think the wrapper is threadsafe, since it could be interrupted and called again from another thread.

  long t;
  return (int)_GetSystemTime(&t);
is actually 2 returns. If an interrupt occurs between the returns, that could be a problem. If the stack pointer were in the wrong place because of it, it's possible that it would effectively do the action stack pop thinking it was popping variable "t".
This is nonsense. Each task has it's own stack, and the OS handles switching them. t is a stack variable, so every thread gets it's own, although if you look at the dryos version of _GetSystemTime, it doesn't even use t ;) (edit: well, the D10 version doesn't, some others might...)

Quote
I think Phil changed the meaning of the 1 return when he re-worked action stack.
No, phil did not change the semantics of lua C functions. In a lua C function, (one that is called from lua, meaning all the luaCB functions in the CHDK API), the return value is the number of values that function returns in Lua. The actual values are pushed on the Lua stack.
Title: Re: Shot Histogram Request
Post by: reyalp on 08 / April / 2013, 02:16:46
To me, the fact that Lres (=lapser2) contains a nonsense value (which looks like an address) should be a big hint. The lua state is getting corrupted somewhere, which matches the strange debug dumps I got from Alarik. get_tick_count is a red herring, IMO.
Title: Re: Shot Histogram Request
Post by: philmoz on 08 / April / 2013, 02:30:24
The only way I can see that lapser1 could be displayed as -9 is if the error occurred calling luaCB_wait_click.

The luaCB_wait_click function calls action_stack_AS_LUA_WAIT_CLICK which will set lapser1 to -9.
Since action_stack_AS_LUA_WAIT_CLICK would have returned 0, then luaCB_wait_click must have called return lua_yield(L,0).
The Lua error must have then been triggered from this return - otherwise action_stack_AS_LUA_WAIT_CLICK would have taken over the action stack and the script would have been suspended.

Phil.

Title: Re: Shot Histogram Request
Post by: lapser on 08 / April / 2013, 02:49:36
The only way I can see that lapser1 could be displayed as -9 is if the error occurred calling luaCB_wait_click.

The luaCB_wait_click function calls action_stack_AS_LUA_WAIT_CLICK which will set lapser1 to -9.
Since action_stack_AS_LUA_WAIT_CLICK would have returned 0, then luaCB_wait_click must have called return lua_yield(L,0).
The Lua error must have then been triggered from this return - otherwise action_stack_AS_LUA_WAIT_CLICK would have taken over the action stack and the script would have been suspended.

Phil.
Yes, that makes sense. I'm calling wait_click(10), so it's probably just yielding right away? Anyway, the bug also occurs with sleep(10) and coroutine.yield(), so I guess we haven't learned much new.

Sorry for the false alarm, but I thought maybe we had something. I'll have to keep using wait_shot_ready() and avoid yield() as much as possible until we figure it out, I suppose.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / April / 2013, 02:52:33
One more thing I've been wondering about. Do you think it's possible that resume() could occur in the same action stack cycle after the yield()? Would that cause a problem if it did?
Title: Re: Shot Histogram Request
Post by: reyalp on 08 / April / 2013, 03:12:23
Do you think it's possible that resume() could occur in the same action stack cycle after the yield()?
Off the top of my head, I can't think of a way that would occur in the current chdk code. Each kbd_task iteration should only call lua_script_run once.
Quote
Would that cause a problem if it did?
It shouldn't matter at all. Lua yield and resume are really just regular C function, they don't know anything about OS level tasks.

Thank you for persisting with your investigation of this BTW. It's very frustrating to have such a serious bug and not be able to reproduce it.
Title: Lua bug solved (again!)
Post by: lapser on 09 / April / 2013, 13:03:14
OK, I really think I got it this time . :D

First of all, I think the Lua error was triggered by CHDK calling resume() without a yield(). I think this happened because the action stack cleared abnormally before action_stack_AS_LUA_WAIT_CLICK() was finished. Here's the relevant code:

Code: [Select]
static int action_stack_AS_LUA_WAIT_CLICK()
{
lapser1=-9;
    // Check key pressed or timeout
    if ((get_tick_count() >= action_top(2)) || camera_info.state.kbd_last_clicked)
    {
        // If timed out set key state to "no_key", otherwise key pressed so set last checked time
        if (!camera_info.state.kbd_last_clicked)
            camera_info.state.kbd_last_clicked=0xFFFF;
        else
            camera_info.state.kbd_last_checked_time = camera_info.state.kbd_last_clicked_time;
lapser1=9;
        action_pop_func(1);
        return 1;
    }

    return 0;
}

static int luaCB_wait_click( lua_State* L )
{
lapser1=8;
    int delay = luaL_optnumber( L, 1, 0 );
    //if (delay == 0) delay = -1;
    if(delay<2)delay--; //delay 1 for no delay or 0 for no timeout 
    delay = sleep_delay(delay);
    // Reset 'clicked' key if it has not changed since last time
    if (camera_info.state.kbd_last_clicked_time <= camera_info.state.kbd_last_checked_time)
    {
        camera_info.state.kbd_last_clicked = 0;
    }
    // Set up for wait or click testing
    action_push(delay);
    action_push_func(action_stack_AS_LUA_WAIT_CLICK);

    // Check for short delay or key already pressed by calling action stack routine once now
    if (action_stack_AS_LUA_WAIT_CLICK() == 0)
    {
        return lua_yield( L, 0 );
    }
    //return 1;
    return 0;
}

static int luaCB_is_key( lua_State* L )
{
lapser1=7;
  lua_pushboolean( L, script_key_is_clicked(lua_get_key_arg( L, 1 )));
  return 1;
}

  repeat wait_click(10)
    if(is_key("set"))then
[snip series of is_key calls]
  until get_shot_ready()

[Lua error was exactly the same as yesterday on the same camera, sx50)
ERROR: NULL error message
*** TERMINATED ***
Lapser:     -9 3209878     0     0

So the only way lapser1=-9 can happen is if  action_stack_AS_LUA_WAIT_CLICK() returns "1". In that case, luaCB_wait_click( lua_State* L ) calls  lua_yield(). Lua should not resume until  lapser1=9, but it did. This means the action stack ended abnormally.

If wait_click(10) had returned, the script calls is_key("set"), and lapser1 is set to 7. This is what happened before the lua update, and the error message was "set". The Lua update added a check having to do with stack overflow (I think), so maybe it no longer would resume() without a yield like it did before, and terminated the script in wait_click(10). Hence, lapser1=-9.

So the thing to figure out is how action stack could think it's finished. It happens very rarely, but the script is gradually changing the shutter time, which may be triggering an interrupt at gradually changing times from the last tick. So if another task is calling the same action stack routine as the keyboard task, you'd have a thread safety issue that might be the cause.

So do you think this could be happening? Is action stack called from a different task?
Title: Re: Shot Histogram Request
Post by: ahull on 09 / April / 2013, 14:36:36
Sure. Give me the models and firmware versions and I'll post builds for you.

I've attached the latest script and ixus40 build
If you have merged back in to the "bleeding edge" build, does that mean I can try you script out on a couple of other models now?

That version of the script crashes on the ixus 40 at startup with :1: unexpected symbol near '0'
*** TERMINATED ***
Lapser:   0 0 0 0

I suspect I have failed to copy over some files.. I'll check.

Title: Re: Shot Histogram Request
Post by: lapser on 09 / April / 2013, 15:08:26
I suspect I have failed to copy over some files.. I'll check.
Maybe. Be sure to copy all the files in the zip. Lua is in a module, which changes with each update.
Title: Re: Shot Histogram Request
Post by: reyalp on 09 / April / 2013, 16:47:17
First of all, I think the Lua error was triggered by CHDK calling resume() without a yield().
This should not be possible. It would mean either that multiple tasks were running the action stack, or that something within a lua C function called lua_script_run.

However, you could test what happens if you call resume without a yield by adding code to force that.
Quote
I think this happened because the action stack cleared abnormally before action_stack_AS_LUA_WAIT_CLICK() was finished.
I don't understand how this could happen. kbd_task isn't going to run another iteration until the call returns, which means that lua has yielded. The entire kbd_task including all the lua code and action stack functions run sequentially. Once lua has been entered, action stack processing does not happen again until lua has yielded or exited. The only way to get back into lua is if action_stack_AS_SCRIPT_RUN is on top of the stack.

Perhaps I don't understand what you are trying to say.
Quote
So do you think this could be happening?
No.
Quote
Is action stack called from a different task?
Not unless something is very badly wrong, and if it did, it would lead to near instant corruption of the lua state, which would very quickly cause crashes and other bad behavior. The exact nature of the bad behavior would be highly dependent on timing and memory organization, so it would be exceedingly unlikely to show the exact same symptom across different builds, cameras and scripts.

Looking at your debug code:
If action_stack_AS_LUA_WAIT_CLICK() returns 0, then you can yield with labser1 == -9

lua_yield will eventually make lua_resume return, so it's quite possible that the error occurs after that yield.

You could add new lapser1 value right before the return 0 to check for this.
Title: Re: Shot Histogram Request
Post by: lapser on 09 / April / 2013, 17:28:11
However, you could test what happens if you call resume without a yield by adding code to force that.
I was trying to do that through action stack, but just crashed the camera.
Quote
Looking at your debug code:
If action_stack_AS_LUA_WAIT_CLICK() returns 0, then you can yield with labser1 == -9
lua_yield will eventually make lua_resume return, so it's quite possible that the error occurs after that yield.
Yes, I know it's calling lua_yield() with lapser1==-9. But that also means that AS_LUA_WAIT_CLICK() is still on the action stack. It should continue executing that function until AS_LUA_WAIT_CLICK() times out (next cycle), and calls POP_FUNC. But it also sets lapser1=9 when it does that.

So the question is, how does it get to lua_resume() without lapser1 being set to 9? Forget all my other theories. This is the problem I can't figure out.

I also don't understand why there are multiple action stacks, and process_all(). It looks like action_stack_AS_SCRIPT_RUN() is in a different action stack? This is what calls lua_script_run() which calls lua_resume() and throws the error. But if lapser1==-9, then AS_LUA_WAIT_CLICK() should still be on the "active stack." So maybe the active stack got changed when it shouldn't have?

This is all an AS_HEADACHE(), but I hope we're figuring it out.
Title: Re: Shot Histogram Request
Post by: philmoz on 09 / April / 2013, 17:38:43
So the question is, how does it get to lua_resume() without lapser1 being set to 9? Forget all my other theories. This is the problem I can't figure out.

It doesn't 'get' to lua_resume - the call to 'luaCB_wait_click' was made from within a previous call to 'lua_resume' from the last time Lua regained control.

When luaCB_wait_click calls lua_yield, it causes control to return back out of the previous lua_resume call - at this point it is getting the bad status value in lua_script_run.

So sometime after Lua resumed executing the script code, up to the point where luaCB_wait_click calls lua_yield, something corrupted the lua state.

It's not necessarily even related to luaCB_wait_click - it could have been any of script statements run within the lua timeslice that caused the problem, or a bug in Lua itself.

Given the random nature of the errors I wonder if it's a problem with the Lua garbage collector.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 09 / April / 2013, 18:44:47
It doesn't 'get' to lua_resume - the call to 'luaCB_wait_click' was made from within a previous call to 'lua_resume' from the last time Lua regained control.

Given the random nature of the errors I wonder if it's a problem with the Lua garbage collector.
OH, I see it now (finally). When wait_click() calls lua_yield(),  lua then RETURNS from resume() (with lapser1==-9), and then CHDK enters action stack. When it finishes action stack, it then calls resume() (with lapser1==9).

So lapser1==-9 just means wait_click yielded, instead of returning.

Since I don't get the bug when waiting with wait_shot_ready(), I'm assuming my code isn't trashing the Lua state. I like your garbage collection suggestion. I know it's incremental in Lua, so it could be happening any time.

Since lapser1==-9 only happened after the update, and the update added a Lua stack overflow check, I wonder if it's stack related. Maybe garbage collection uses a lot of extra stack?

Is there a separate Lua stack? Is there any way to increase its size?

[EDIT] I think I just answered my own question. There is a Lua stack. I've increased it, and I'll try another time lapse test tonight to see if that fixes the Lua yield bug. See this post for more details:

http://chdk.setepontos.com/index.php?topic=9607.msg99095#msg99095 (http://chdk.setepontos.com/index.php?topic=9607.msg99095#msg99095)
Title: Re: Shot Histogram Request
Post by: lapser on 09 / April / 2013, 20:23:20
This is the time lapse from last night with the G1X (which didn't trigger the yield bug). I think my exposure smoothing routine worked really well. I need to generalize it so it will work with intervals larger than 1 shot per second, though. Rather than try to add the smoothing to CHDK so I can smooth before rounding, I think I'll add a scale option to get_shot_meter() so it can return tv96*1000, for more accuracy in computing the smoothing.

Details about the video are in the description on YouTube
http://www.youtube.com/watch?v=qhkVtBtY3t0#ws (http://www.youtube.com/watch?v=qhkVtBtY3t0#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 09 / April / 2013, 22:34:22
http://chdk.setepontos.com/index.php?topic=9607.msg99095#msg99095 (http://chdk.setepontos.com/index.php?topic=9607.msg99095#msg99095)
Since we've already done so much discussion of the bug here, it might be clearer to keep all the code related stuff in one thread.

LUA_MINSTACK is not the lua stack size. If I understand correctly, it's the minimum number of Lua stack slots that need to be available when Lua calls a C function.

LUAI_MAXCSTACK in luaconf.h is the maximum size of the Lua stack. luaconf.h is where most of the user adjustable knobs live.

If the lua stack were exhausted, it should generate an error.

edit:
My opinion is still that the corrupted lua state (as shown by the bogus return value from lua_resume and bogus error message) is the important clue. Narrowing down where it gets corrupted and what parts would be the logical next steps to me.

edit 2:
If you want to test garbage collection related theories, see collectgarbage
http://www.lua.org/manual/5.1/manual.html#5.1 (http://www.lua.org/manual/5.1/manual.html#5.1)
you could call collectgarbage('collect') in your main loop to make or adjust the step values to make it run more frequently.

edit 3:
Going through the code a bit more, the bogus return value from lua_resume isn't necessarily a corrupt lua_State. If there was an error, it will be the return value of luaD_rawrunprotected. This should in theory also be a Lua error code, with the value coming from luaD_throw lj.status

I went back through my dumps from Alarik, and was reminded just how weird it was: luaD_throw was never called before the error, and lj.status was not non-zero at the end of luaD_rawrunprotected. The dump showed the lua_State status was 1 (=yield) and the rest of the state that I decoded seemed to be sane.
Title: Re: Shot Histogram Request
Post by: reyalp on 10 / April / 2013, 02:27:42
I've attached an updated version of my debug dump patch. To use it, build with

OPT_DBG_DUMP=1
in your buildconf.inc or localbuildconf.inc

You can also add OPT_DBG_LUA_ASSERT=1

This patch will create various named dump files in the if lua hits an error. This includes "normal" errors like a syntax error etc. The files will be overwritten every time the triggering condition is met.

The dump includes a stack trace and some other possibly relevant information.

The dumps can be decoded in chdkptp using
!m=require'extras/dbgdump'
!return m.load('<filename>.DMP')

Module code will just be labeled as "heap" in the stack trace, since the decoder doesn't know where modules are loaded.

Modules addresses can be figured out manually if you turn on module logging in the "miscellaneous -> modules" menu.

The stack trace is also fixed size, so it may run off the end of the tasks actual stack, probably showing bits of other tasks stacks.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / April / 2013, 02:44:42
@reyalp
Thanks for the help, and the patch. I'll give it a try tomorrow night.

Both cameras terminated with the same error tonight. I was still home when the sx50 stopped, so I restarted it and it worked until I got back about 2 hours later. I had the G1X pointed at the sunset from my Forest Ridge drive viewpoint, and there was a really bright ISS flyby which I think was just out of view. I'm hoping the SX50 caught it from my house.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / April / 2013, 14:09:31
I've attached an updated version of my debug dump patch.
OK, I got it working, including the module logging. I added a test error to my script by calling an unknown function (with an obscene name in German) :) when you press <display>. I ended up with 4 .DMP files, and MODULES.LOG

I'll try to trigger the lua yield() error tonight, and then send you the files.

I also modified luascript.c to use one Lua thread, as Phil described. It works, except for ptpcamgui fails to init after the change. I guess it needs the 2 threads?

I changed "L" and "Lt" to static variables and removed them from luascript.h without any problems. I didn't find any references to luascript.h other than in luascript.c.
Title: Re: Shot Histogram Request
Post by: reyalp on 10 / April / 2013, 16:50:09
I also modified luascript.c to use one Lua thread, as Phil described. It works, except for ptpcamgui fails to init after the change. I guess it needs the 2 threads?
I doubt it. It shouldn't be much different from regular script, but ptp specific code might reference Lt somewhere.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / April / 2013, 19:37:54
It shouldn't be much different from regular script, but ptp specific code might reference Lt somewhere.
First I just replaced the new thread call with Lt=L; That worked, but ptpCamGui wouldn't init. Then I replaced all "L" with "LT" and removed the declaration for L and made Lt static, and removed L and Lt from luascript.h. So there must can't be any references to L because it's no longer there. But I got the same result.

Maybe someone else can check out Lua over PTP with just one Lua thread?
===========

I did catch the ISS flyby last night, but just barely. It shows up briefly at 2:10 in the video at the extreme left. It got brighter and brighter after it went out of frame, and looked like a police helicopter with a searchlight or something.
http://www.youtube.com/watch?v=fHMj0xVPK0M#ws (http://www.youtube.com/watch?v=fHMj0xVPK0M#ws)
Title: Logs for reyalp
Post by: lapser on 11 / April / 2013, 12:17:21
I left the sx260 and sx50 running at home while I took the G1X up Spencer's Butte for sunset. The G1X has never triggered the script interrupted error since the Lua update. When I got home, the SX50 display showed the interrupted error, and the SX260 was off with the lens extended.

Both cameras got the error about 10 minutes after I left. Usually, it takes longer. This time, I set a small metering area where clouds were moving by, so the shutter time was varying a lot. My smoothing routine limited the Tv96 changes to plus or minus 1. I suspect that the timing of an extra interrupt that occurs to close the shutter may be involved. That is, an interrupt in a function that isn't thread safe (or something). Perhaps this could be the Lua incremental garbage collector. Maybe it has something to do with the 2 Lua threads also.

Anyway, one of reyalp's new logs appeared for both cameras. I'm also including the romlog from the SX260, but the crash may not be significant. The time in the romlog is 2013:04:10 09:40:45. I have the camera clock in AM/PM mode, so if the time was 9 p.m. that would make sense. I had an external battery connected that switches itself off automatically, so I suspect the "crash" was just a sudden loss of power. I also included the script log, which shows the error code at the end. Everything looks normal in the script log until the error. The second "Lapser" number is the return value from resume(). I think it's just a pointer to the NULL error message string.

I don't know enough at this point to tell much from the new Lua logs, but every time one of my new "theories" is shot down, I learn a little more. Thanks!
Title: Re: Shot Histogram Request
Post by: reyalp on 11 / April / 2013, 17:19:03
Thanks for the logs. I don't have to go through them in detail right now, but the fact both cameras only have LUARES1.DMP suggests it is very similar to the earlier ones from Alarik. I'll try to take a more detailed look later.

If you have the main.bin.dump (or main.bin) from the CHDK build that was running when this was taken, that will help. The module elfs would also help.

I suspect we will need to find a way to trace further back to get a real handle on this. I have some ideas but it will take time to get it into code.
I'm also including the romlog from the SX260, but the crash may not be significant. The time in the romlog is 2013:04:10 09:40:45. I have the camera clock in AM/PM mode, so if the time was 9 p.m. that would make sense.
I would be surprised if the romlog respected the camera UI 12/24 hour setting, but in any case that romlog looks like an assert that is triggered you try to have too many files open simultaneously. This could happen if you try to log too soon after a shot.
Title: Re: Shot Histogram Request
Post by: lapser on 11 / April / 2013, 19:35:29
If you have the main.bin.dump (or main.bin) from the CHDK build that was running when this was taken, that will help. The module elfs would also help.
Where do I find those files?
Quote
that romlog looks like an assert that is triggered you try to have too many files open
That's probably from earlier then. I crashed the camera that morning when I intentionally test triggered your patch to write its logs, without the proper compile options.

I'm sure glad that the G1X didn't get the error. The sunset was really nice last night:

http://www.youtube.com/watch?v=yJWqL3krjiw#ws (http://www.youtube.com/watch?v=yJWqL3krjiw#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 11 / April / 2013, 22:03:39
Where do I find those files?
main.bin and main.bin.dump are in the core directory after you build.

the module .elf files are in the modules directory.

If you are using chdkshell to build, you may need to turn off the clean after build option.
Title: Re: Shot Histogram Request
Post by: reyalp on 11 / April / 2013, 23:31:51
Here's the weirdness. In lib/lua/ldo.c
Code: [Select]
  status = luaD_rawrunprotected(L, resume, L->top - nargs);
  if (status != 0) {  /* error? */
    dbg_dump_write("A/LUARES1.DMP",0,sizeof(lua_State),(void *)L);
    L->status = cast_byte(status);  /* mark thread as `dead' */
    luaD_seterrorobj(L, status, L->top);
    L->ci->top = L->top;
  }
This is the only place LUARES1.DMP can be created. It will be hit if luaD_rawrunprotected returns non-zero.

Here's luaD_rawrunprotected
Code: [Select]
  int r = setjmp(lj.b);
  if(r == 0) {
    (*f)(L, ud);
  } else {
    dbg_dump_write("LUALJ1.DMP",0,r,NULL);
  }
  if(lj.status) {
    dbg_dump_write("A/LUALJ2.DMP",0,sizeof(lj),(char *)&lj);
  }

  L->errorJmp = lj.previous;  /* restore old error handler */
  return lj.status;
If lj.status is non-zero, A/LUALJ2.DMP should be written.

What am I missing  :blink:

If you try a regular runtime error (return 1+nil), you get

LUALJ1.DMP - because setjmp returned via longjump
LUALJ2.DMP - because lj.status was non non-zero
LUARES1.DMP - because we hit the error case in resume (same as the real bug)
LUATHROW.DMP - because luaD_throw threw (longjmp) the error

My gut want's blame setjmp/longjmp, especially since it is a custom implementation lifted from web, but I can't really see how.
Title: Re: Shot Histogram Request
Post by: philmoz on 12 / April / 2013, 00:02:13
My gut want's blame setjmp/longjmp, especially since it is a custom implementation lifted from web, but I can't really see how.

Weird indeed.
The setjmp.h / setjmp.s code is difficult to follow with all the #ifdef clutter.
Is it worth stripping these files back to just what is needed for CHDK?

Phil.
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 00:09:19
The setjmp.h / setjmp.s code is difficult to follow with all the #ifdef clutter.
Is it worth stripping these files back to just what is needed for CHDK?
It wouldn't hurt, but you can get a de-cluttered version from the disassembler
Code: [Select]
00010c20 <setjmp>:
   10c20: 4778      bx pc
   10c22: 46c0      nop ; (mov r8, r8)

00010c24 <.arm_start_of.setjmp>:
   10c24: e8a07ff0 stmia r0!, {r4, r5, r6, r7, r8, r9, sl, fp, ip, sp, lr}
   10c28: e3a00000 mov r0, #0
   10c2c: e31e0001 tst lr, #1
   10c30: 01a0f00e moveq pc, lr
   10c34: e12fff1e .word 0xe12fff1e

00010c38 <longjmp>:
   10c38: 4778      bx pc
   10c3a: 46c0      nop ; (mov r8, r8)

00010c3c <.arm_start_of.longjmp>:
   10c3c: e8b07ff0 ldm r0!, {r4, r5, r6, r7, r8, r9, sl, fp, ip, sp, lr}
   10c40: e1b00001 movs r0, r1
   10c44: 03a00001 moveq r0, #1
   10c48: e31e0001 tst lr, #1
   10c4c: 01a0f00e moveq pc, lr
   10c50: e12fff1e .word 0xe12fff1e
Note the last .word is a bx lr
Title: Re: Shot Histogram Request
Post by: philmoz on 12 / April / 2013, 00:53:04
The setjmp.h / setjmp.s code is difficult to follow with all the #ifdef clutter.
Is it worth stripping these files back to just what is needed for CHDK?
It wouldn't hurt, but you can get a de-cluttered version from the disassembler
Code: [Select]
00010c20 <setjmp>:
   10c20: 4778      bx pc
   10c22: 46c0      nop ; (mov r8, r8)

00010c24 <.arm_start_of.setjmp>:
   10c24: e8a07ff0 stmia r0!, {r4, r5, r6, r7, r8, r9, sl, fp, ip, sp, lr}
   10c28: e3a00000 mov r0, #0
   10c2c: e31e0001 tst lr, #1
   10c30: 01a0f00e moveq pc, lr
   10c34: e12fff1e .word 0xe12fff1e

00010c38 <longjmp>:
   10c38: 4778      bx pc
   10c3a: 46c0      nop ; (mov r8, r8)

00010c3c <.arm_start_of.longjmp>:
   10c3c: e8b07ff0 ldm r0!, {r4, r5, r6, r7, r8, r9, sl, fp, ip, sp, lr}
   10c40: e1b00001 movs r0, r1
   10c44: 03a00001 moveq r0, #1
   10c48: e31e0001 tst lr, #1
   10c4c: 01a0f00e moveq pc, lr
   10c50: e12fff1e .word 0xe12fff1e
Note the last .word is a bx lr

How is the first 'bx pc' instruction in each function switching to ARM mode?
The PC value should still be odd at this point so why would this cause a mode switch?

Also I thought using the PC register in any BX instructions was deprecated.

Phil.
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 01:15:45
How is the first 'bx pc' instruction in each function switching to ARM mode?
The PC value should still be odd at this point so why would this cause a mode switch?
From: "ARM Architecture Reference Manual" A6.1 About the Thumb instruction set
Quote
When R15 is read, bit[0] is zero and bits[31:1] contain the PC.

Quote
Also I thought using the PC register in any BX instructions was deprecated.
gcc interworking does it the same way:
Code: [Select]
00175db8 <__mkdir_from_thumb>:
  175db8: 4778      bx pc
  175dba: 46c0      nop ; (mov r8, r8)
  175dbc: eaff847a b 156fac <mkdir>
The kicker is that for any defect in setjmp to be causing this, it would have to succeed 99.999% or more of the time, every call to lua resume goes through the setjmp code, and every lua error goes through longjmp. More likely would be the jumpbuf on the stack getting corrupted, but the check on lj.status is done after it has returned.

I think my next approach is to keep some kind of circular log to see where it actually comes from when that code is hit.
Title: No error with one Lua thread!
Post by: lapser on 12 / April / 2013, 02:06:26
I decided to see what would happen if I changed lua_script_start() so it only used one Lua thread, by changing 1 line:
Code: [Select]
    //Lt = lua_newthread( L );
    Lt=L;
I left the SX50 with the new build running at the house, and took the G1X and SX260 to a spot with a better view of more sky so I could catch a ISS flyby. I managed to see the ISS in both cameras. The SX260 was using the old build (with 2 Lua threads), and it triggered the bug before the ISS appeared. So I restarted the script, and the bug happened again after a few seconds.  I started it again, and it ran for about an hour with no bug, and caught the ISS.

So I got home expecting the SX50 to have stopped again, but it was still running. So mabe there's a bug in Lua related to multiple Lua threads, possibly a garbage collection problem as Phil suggested.

I'll put the new, 1 thread build on all the cameras, and see if the bug recurs over the next few nights.

Whe I started the script, the meters weren't quite right, so I stopped it with the menu key (normal exit) after about 10 seconds, and restarted. I discovered that there was a new .dmp file created, time stamped when I stopped the script. I'll attach it for you to look at, along with the modules.log.
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 02:20:54
Here's quick and dirty patch to log some calls to a buffer, maybe we can see how it gets to that "impossible" return value.

I very much doubt the L vs Lt thing is the cause, but then again, I don't have any good explanation so why not  :-[
Title: Re: Shot Histogram Request
Post by: lapser on 12 / April / 2013, 02:41:15
Here's quick and dirty patch to log some calls to a buffer, maybe we can see how it gets to that "impossible" return value.
so why not  :-[
I'll install the new patch and give it a try tomorrow when I test all 3 cameras with the single thread. Or I can go back to 2 threads and try to trigger the bug again so you'll have the new log?

I wonder what the second thread is doing? And why does ptpCamGui fail to init when there's only one thread. Do you think you could test this on your cameras with the Lt=L change and see if you can get ptpCam to init? I would really like to solve that problem because 2 of my SD cards don't have write protect tabs now and ptpCamGui is the only way to load new builds (other than Scotch tape).  Thanks.
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 02:50:53
Or I can go back to 2 threads and try to trigger the bug again so you'll have the new log?
It's up to you, but for me the closer it is to stock CHDK the less chance there is of confounding factors.
Quote
I wonder what the second thread is doing?
As I said in the other thread (:P), nothing. Everything is running the Lt thread, nothing is executed in the "main" thread at all. Lua "threads" aren't really like OS threads, a better name would be "coroutine state" or something like that. They don't execute unless they are explicitly executed.
Quote
And why does ptpCamGui fail to init when there's only one thread.
I have no idea, and I don't have time to dig into that code right now.
Title: Re: Shot Histogram Request
Post by: philmoz on 12 / April / 2013, 08:12:39
And why does ptpCamGui fail to init when there's only one thread. Do you think you could test this on your cameras with the Lt=L change and see if you can get ptpCam to init? I would really like to solve that problem because 2 of my SD cards don't have write protect tabs now and ptpCamGui is the only way to load new builds (other than Scotch tape).  Thanks.

I don't use ptpCamGui; but chdkptp works fine with this change.
You can also use chdkptp in console mode (with batch files) to simplify downloading updates to the camera.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / April / 2013, 12:14:33
I very much doubt the L vs Lt thing is the cause, but then again, I don't have any good explanation so why not  :-[
Ha. I have a thousand explanations. Unfortunately all of them are wrong (so far).

My theory (one of them) is that the bug is triggered by an interrupt that occurs  while the Lua code is executing a function that isn't thread safe, possibly garbage collection. The bug seems to be triggered by variations in shutter time, which I assume is generating an extra interrupt without incrementing the tick count.

If that's true, it might be possible to add a delay function call right before lua resume() that adds a varying delay from 0 to 10 msec. That way the next tick count incrementing interrupt would occur at a different time after the start of each call to lua resume().

The idea is to try to trigger the bug with a CHDK patch, and simple Lua script:

repeat sleep(10) until false

Then you guys could figure it out in no time, I bet.
I don't use ptpCamGui; but chdkptp works fine with this change.
Thanks for that info. This may be my incentive to learn chdkptp batch mode, which I'm sure works much better once you learn it.

I still wonder why ptpCamGui won't init, though. This may be related to why CHDK starts a second Lt thread. ptpCamGui runs a Lua program on the camera, so maybe this program starts a new Lua thread? Is the Lt thread necessary to do that? As Phil said initially, "there must be some reason."

Also, did anyone look at the LUAASRT.DMP file I posted here?
http://chdk.setepontos.com/index.php?topic=8997.msg99161#msg99161 (http://chdk.setepontos.com/index.php?topic=8997.msg99161#msg99161)

I'm wondering why it was generated when there was no Lua error?

I'll see if I can trigger the bug again with the 2 thread CHDK and post the new log files from reyalp's new patch.
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 12:43:47
My theory (one of them) is that the bug is triggered by an interrupt that occurs  while the Lua code is executing a function that isn't thread safe, possibly garbage collection.
I don't understand this. Lua code is just regular C code. It's the OS's responsibility to ensure interrupts don't affect the state of a running task, there's no special "thread safety" required for this. If there was some defect in this area, the odds of it it causing exactly the same symptom in one specific place over many different builds appear small.


Quote
I still wonder why ptpCamGui won't init, though.
So why not debug it? ptpCamGui uses regular PTP calls and lua. Some specific thing must be failing...

Quote
Also, did anyone look at the LUAASRT.DMP file I posted here?
It means that that an assert was hit in Lua code. The specific assertion is
Code: [Select]
ASSERT ldo.c:401 ci == L->base_ci && firstArg > L->base
I haven't looked into what this means yet.
Title: Re: Shot Histogram Request
Post by: rudi on 12 / April / 2013, 15:35:33
And why does ptpCamGui fail to init when there's only one thread. Do you think you could test this on your cameras with the Lt=L change and see if you can get ptpCam to init? I would really like to solve that problem because 2 of my SD cards don't have write protect tabs now and ptpCamGui is the only way to load new builds (other than Scotch tape).  Thanks.

I don't use ptpCamGui; but chdkptp works fine with this change.
You can also use chdkptp in console mode (with batch files) to simplify downloading updates to the camera.

Phil.

I tested ptpcam/ptpcamGUI and chdkptp cli with change "Lt = L". All applications will not return luar results.
Notes for tests:
- changes are in lua modul not in bin file
- luar is different
    ptpcam: luar get_buildinfo()
    chdkptp: luar return get_buildinfo()

rudi
Title: Re: Shot Histogram Request
Post by: reyalp on 12 / April / 2013, 16:12:12
I tested ptpcam/ptpcamGUI and chdkptp cli with change "Lt = L". All applications will not return luar results.
Notes for tests:
- changes are in lua modul not in bin file
- luar is different
    ptpcam: luar get_buildinfo()
    chdkptp: luar return get_buildinfo()
This suggests the PTP message interface is broken. I don't see why offhand, but it does use Lt explicitly in a few places. chkdptp relies on this heavily, so if chdkptp works correctly for Phil, maybe he has implemented the change differently.
Title: Re: Shot Histogram Request
Post by: philmoz on 12 / April / 2013, 18:27:00
I tested ptpcam/ptpcamGUI and chdkptp cli with change "Lt = L". All applications will not return luar results.
Notes for tests:
- changes are in lua modul not in bin file
- luar is different
    ptpcam: luar get_buildinfo()
    chdkptp: luar return get_buildinfo()
This suggests the PTP message interface is broken. I don't see why offhand, but it does use Lt explicitly in a few places. chkdptp relies on this heavily, so if chdkptp works correctly for Phil, maybe he has implemented the change differently.

Comment out the line after 'Lt = L;' that contains:
     lua_setfield( L, LUA_REGISTRYINDEX, "Lt" );
This will fix the return results from luar.

(If you don't call lua_newthread to create Lt then there is nothing on the lua stack for lua_setfield to use).

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / April / 2013, 19:08:56
Comment out the line after 'Lt = L;' that contains:
     lua_setfield( L, LUA_REGISTRYINDEX, "Lt" );
This will fix the return results from luar.

(If you don't call lua_newthread to create Lt then there is nothing on the lua stack for lua_setfield to use).
Thanks Phil. I was typing a question about that line when your post appeared. I'll give it a try.

[edit] It worked, thanks again. I deleted the declaration for "L", and changed the references to "L" into "Lt". Since there are a lot of "L" references as function paramaters, I just compiled it and fixed the "L" reference errors. I made Lt static, and removed L and Lt from luascript.h. This cleans up the code and clears up the "L" confusion.

I did a build for the sx260 with the original  2-thread CHDK and reyalp's new logging patch for lua. I'll see if I can trigger the bug with the sx260 tonight. It bugged out twice last night with the sx260. I've attached the files reyalp requested for this build (let me know if they're not the files you want).

I'll also repeat the test with the SX50 and the 1 thread modification to see if it triggers the bug, since it worked last night for a long time without the bug happening. It's possible that the 2 thread version might be causing the bug somehow.
Title: Re: Shot Histogram Request
Post by: philmoz on 13 / April / 2013, 00:07:18
Had a look at the dbg dump files from this post:
http://chdk.setepontos.com/index.php?topic=8997.msg99135#msg99135 (http://chdk.setepontos.com/index.php?topic=8997.msg99135#msg99135)

If I'm reading the files correctly then for the SX260 we have
Lres value from lua_resume = 3144556 (0x2FFB6C) - from 04101716.log
Lua module load address = 0x2f80c8 - from modules.log

So the Lres value is in the middle of the Lua code @ 0x7AA4 bytes from the start of the module.

For the SX50:
Lres = 3214364 (0x310C1C)
Lua load address = 0x309178

Again Lres is in the Lua code @ 0x7AA4 bytes from the start of the module.

Can't be a coincidence; but no idea why this is happening.

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 13 / April / 2013, 00:56:21
So the Lres value is in the middle of the Lua code @ 0x7AA4 bytes from the start of the module.
Can you see what's at that address?

Both the sx260(2 lua threads) and sx50(1 lua thread) ran for about 5 hours without triggering an error or writing any of reyalp's error logs. So now I have another 35,000 pictures of the fog behind my house! Maybe they'll be valuable some day.
Title: Re: Shot Histogram Request
Post by: philmoz on 13 / April / 2013, 01:04:29
So the Lres value is in the middle of the Lua code @ 0x7AA4 bytes from the start of the module.
Can you see what's at that address?


Copy the attached Makefile over your modules/Makefile and rebuild.
You should get a lua.elf.dumpobj file in the modules directory which will include a disassembly of the lua module.

To be accurate the source code needs to match what you used when you created the dump files. Since I was looking at the original dumps you posted you would probably need to remove any other changes (e.g. the Lt changes).

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 13 / April / 2013, 11:29:42
To be accurate the source code needs to match what you used when you created the dump files.
Hmm, I'm not confident I can do that. I've also added reyalp's new patch since then. However, I do have some new data.

I did another test this morning with the sx260 (2 lua threads) and sx50 (1 lua thread). The sx260 worked normally, but the sx50 crashed (power off, lens extended).

One thing interrupts do is use extra stack space. I added a function call in capt_seq_hook_set_nr() that use stack, as well as a function call in raw_savefile(). If an interrupt happened at a spot when CHDK code was deeper into the stack for that task than the camera ever gets without CHDK, that might cause a stack overflow and trash whatever memory is next to the stack for that task. I don't know the internals, so maybe you can think of a better idea.

I created a zip with the romlog from the sx50 and the TLUARES1.DMP file. The time stamp on this file is the same as the last jpg picture before the crash. I had the backlight off with my backlight patch, which put a lot of turnbacklightoff calls into the romlog, so that's not the problem.

I also compiled with your modules makefile and added lua.elf.dumpobj to the zip. That made it too big to attach, so it's posted here:

http://www.adrive.com/public/b7bfgJ/ReyalpLogs_130413.zip (http://www.adrive.com/public/b7bfgJ/ReyalpLogs_130413.zip)

Title: Re: Shot Histogram Request
Post by: reyalp on 13 / April / 2013, 16:47:45
I did another test this morning with the sx260 (2 lua threads) and sx50 (1 lua thread). The sx260 worked normally, but the sx50 crashed (power off, lens extended).
One thing that might be useful is to keep a detailed list of how long each build ran and whether it hit the bug.

Quote
One thing interrupts do is use extra stack space. I added a function call in capt_seq_hook_set_nr() that use stack, as well as a function call in raw_savefile(). If an interrupt happened at a spot when CHDK code was deeper into the stack for that task than the camera ever gets without CHDK, that might cause a stack overflow and trash whatever memory is next to the stack for that task. I don't know the internals, so maybe you can think of a better idea.
This is possible, but the we modify the kbd_task to have a much larger stack. In general I would say if you are running simple lua code it's very unlikely you would use the whole 8K of stack. An interrupt would basically just push the registers on the stack, which is roughly ~ 128 bytes. If this were the cause, it seems quite unlikely it would cause exactly the same symptom across many different builds, scripts and cameras. There should be enough variation that stack corruption would cause all kinds of different crashes, hangs etc. One extra stack variable or function call in the entire stack should change the behavior significantly.

This problem does reek of memory corruption *somewhere* but if so, it has to be very tightly constrained to some specific code / offset. The address identified philmoz earlier may be a clue.
Quote
I also compiled with your modules makefile and added lua.elf.dumpobj to the zip. That made it too big to attach, so it's posted here:
Can you clarify whether this objdump is from the same elf that was actually running on the camera? If it wasn't built from exactly the same source code, then the value is limited.

Note that in the future you can just post the .elf (which is much smaller) and I can disassemble it myself.
Title: Re: Shot Histogram Request
Post by: reyalp on 13 / April / 2013, 16:55:30
The romlog is the fsionotify thing, which means we tried to have too many file handles open at once.

Also, I should have requested core/main.elf instead of main.bin. If I disassemble main.bin, I don't get symbols which will makes things a lot harder to follow. My bad :(

edit:
where did the "TLUARES1.DMP" name come from? My code should only create LUARES*, without a T on the front. If this got manually renamed in copying, that's fine. If it wasn't, we have another mystery....

edit:
Looking at the romlog, it appears that the second dump with the execution trace was the one that triggered the assert (0x0030D57D <- lua + 43f5 - inside dbg_dump_write). Bummer.

One odd thing in the ROMLOG, there are several bunch of instances of 0x00310C6E which is lua+ 7AE6. This is very close to the lres result value Phil noted earlier. I've attached my annotated romlog.
Title: Re: Shot Histogram Request
Post by: reyalp on 13 / April / 2013, 17:55:03
I have to do some other stuff today, but it would be helpful if I could build the code that you are actually going to run, so we don't have so much back and forth trying to get the right dumps and elfs.

If you can provide your current code, I can work off of that. Or if you can run stock CHDK for testing, I can provide builds of that.
Title: Re: Shot Histogram Request
Post by: philmoz on 13 / April / 2013, 20:02:50
To be accurate the source code needs to match what you used when you created the dump files.
Hmm, I'm not confident I can do that. I've also added reyalp's new patch since then. However, I do have some new data.

I did another test this morning with the sx260 (2 lua threads) and sx50 (1 lua thread). The sx260 worked normally, but the sx50 crashed (power off, lens extended).

One thing interrupts do is use extra stack space. I added a function call in capt_seq_hook_set_nr() that use stack, as well as a function call in raw_savefile(). If an interrupt happened at a spot when CHDK code was deeper into the stack for that task than the camera ever gets without CHDK, that might cause a stack overflow and trash whatever memory is next to the stack for that task. I don't know the internals, so maybe you can think of a better idea.

I created a zip with the romlog from the sx50 and the TLUARES1.DMP file. The time stamp on this file is the same as the last jpg picture before the crash. I had the backlight off with my backlight patch, which put a lot of turnbacklightoff calls into the romlog, so that's not the problem.

I also compiled with your modules makefile and added lua.elf.dumpobj to the zip. That made it too big to attach, so it's posted here:

http://www.adrive.com/public/b7bfgJ/ReyalpLogs_130413.zip (http://www.adrive.com/public/b7bfgJ/ReyalpLogs_130413.zip)



Do you have your script log file from this crash so we can see the Lres value?

Phil.
Title: Re: Shot Histogram Request
Post by: lapser on 13 / April / 2013, 20:24:50
Also, I should have requested core/main.elf instead of main.bin.

where did the "TLUARES1.DMP" name come from?
Thanks for all your help. Yes, the files come from the same SX50 build that was running when the crash happened. Here's the main.elf file from that build:
http://www.adrive.com/public/tvG7fW/main.elf (http://www.adrive.com/public/tvG7fW/main.elf)

I added the T in "TLUARES1.DMP" with the file browser so it wouldn't be overwritten.  Then I restarted the camera and script to continue the test. So at least one mystery is solved (sorry, I forgot about doing that.)

When the script is running, the camera is saving pictures very rapidly and the script is writing the log file at the same time. I print out the time that the print(...) statement takes, and it's usually 20 msec. Sometimes, though, it's much longer, 1000 msec or more even. So it's possible writing the dump files could overload the file system since it's already at maximum capacity.

I wonder if this has anything to do with the error.I don't recall ever triggering the error with logging off, but it would be hard to tell what stopped the script without the log. I wonder how Lua handles a print(...) statement when it takes 1000 msec or more to return, and if that would cause a problem.

I've attached the script log that was being written when the camera crashed. Interestingly, the last picture file number in the log was the last picture written to disk before the crash. Usually, the log misses a few at the end with a camera crash because the log file is never closed. It looks like writing the .DMP file must have flushed the print log.

@Phil, the script log is attached, but it crashed before it printed the lres value.


Title: Re: Shot Histogram Request
Post by: lapser on 14 / April / 2013, 14:31:43
I added an option to the script to use wait_click(10) or wait_shot_ready(). wait_shot_ready() avoids the multiple, rapid lua yield/resume() which triggers the bug, so I'll use it unless I'm doing a bug test.

Don't get bogged down with this if you have other things to do. I think we may need to find a way to trigger the bug more often, and on your cameras, if we're going to figure this one out.
=====
I updated the script to improve the "glitch detector" that ignores a large meter change until it happens twice in a row. I've had glitches for some reason, in my long night time lapses that cause a flash for no apparent reason.  The meter reading is off on one shot even though the picture looks the same as the last one.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / April / 2013, 02:10:05
I finally got the SX50 to trigger the bug again. This time, I set the interval to 1.5 seconds instead of 1 second, so the file system wasn't as busy saving pictures, and it didn't crash the camera writing reyalp's logs.

So I captured reyalp's new lua log file for the first time. I've also included all the relevant files you requested before. Hopefully, this will provide some useful info this time.

http://www.adrive.com/public/BjmcjC/ReyalpLogs_130415.zip (http://www.adrive.com/public/BjmcjC/ReyalpLogs_130415.zip)
Title: Re: Shot Histogram Request
Post by: lapser on 16 / April / 2013, 02:38:12
I think I have the brightness smoothing working really well now. Here's the latest video, taken with the G1X. Also, I haven't had the G1X trigger the Lua Bug we've been talking about, only the SX50 and SX260.

http://www.youtube.com/watch?v=ovTpGkKBFhU#ws (http://www.youtube.com/watch?v=ovTpGkKBFhU#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 17 / April / 2013, 00:37:53
So I captured reyalp's new lua log file for the first time. I've also included all the relevant files you requested before. Hopefully, this will provide some useful info this time.
This captures the trace log. It's doesn't solve the mystery, but it certainly confirms the weirdness
Code: [Select]
>lua_resume
>luaD_rawrunprotected
>resume
resume yield
>lua_yield
<lua_yield
<resume
<luaD_rawrunprotected
lua_resume 310252
0x310252 is the Lres value (confirmed in the script log). "resume yield" means resume is resuming from a yield (rather than starting the script).

Taking the lua load address as 0x309178, this makes the lres 0x70da in the lua module, which is not the same as before, but not far off. According to lua.elf.objdump, this would correspond to
Code: [Select]
000070d8 <luaD_reallocstack>:
    70d8: b5f0      push {r4, r5, r6, r7, lr}
    70da: 6a03      ldr r3, [r0, #32]
This it doesn't seem like 70da would end up on the stack as a return address (and it should be thumb if it was) or as a pointer in the code. Note reallocstack refers the Lua stack, not the C stack.

Very strange.

I've have some ideas for further debugging, but am short on time at the moment.
Title: Re: Shot Histogram Request
Post by: lapser on 17 / April / 2013, 01:00:28
Taking the lua load address as 0x309178, this makes the lres 0x70da in the lua module, which is not the same as before, but not far off.
I'm using a new trunk 2698 in this build. I think Phil made some changes in the Lua module in this trunk.
https://trac.assembla.com/chdk/changeset/2698 (https://trac.assembla.com/chdk/changeset/2698)

Did this change really save 10K when running Lua? That's great. Now I don't feel as bad for wanting to use 8K for the 12-bit histogram instead of 2K.

Before the Lua update to 5.5, the Lres value was apparently a pointer to a string on the Lua stack, because the error message would be "display" or "set", which came from the script calling is_key("display") or is_key("set") before the lua yield that triggered the bug.

====
There's no rush on this. I've modified the script to be able to use wait_click(10) to try to trigger the bug, or my new wait_shot_ready() to avoid the bug. I'm running the G1X overnight with wait_click(10) tonight. I haven't seen the bug with the G1X since the Lua update.
Title: Re: Shot Histogram Request
Post by: ahull on 17 / April / 2013, 08:04:08
Most impressive results, as ever.
 
I may have some spare time later on today if you would like me to test on the Ixus 40
Title: Re: Shot Histogram Request
Post by: lapser on 17 / April / 2013, 11:42:12
I may have some spare time later on today if you would like me to test on the Ixus 40
Sound good. Attached is the latest CHDK build, and the latest script.

Reload the script like it's a new one, and then choose the option to reset to default parameters. That should set them for your camera, I think.

I still need to work on the focus part of the script to get it to work for older cameras. Just do the same thing you did before to focus, for now.
Title: Re: Shot Histogram Request
Post by: ahull on 17 / April / 2013, 15:28:57
Thanks lapser, that installed without a hitch. I have set up the camera pointing out of the window at the weather scudding past.  We can add these pictures to your fog ones if you like.  :P

I forgot to check if the battery was 100% charged, so I may only get a short sequence. I'll post the results later, probably tomorrow afternoon.
Title: Re: Shot Histogram Request
Post by: ahull on 17 / April / 2013, 18:12:03
Well we got a good result, camera kept going till the card was full. The exposure is glitch free.  :D

I put the frames together at 16fps

http://youtu.be/tCB8IlDBBv4 (http://youtu.be/tCB8IlDBBv4)

Now all we need is for the weather to improve.
Title: Re: Shot Histogram Request
Post by: reyalp on 18 / April / 2013, 00:02:04
Before the Lua update to 5.5, the Lres value was apparently a pointer to a string on the Lua stack, because the error message would be "display" or "set", which came from the script calling is_key("display") or is_key("set") before the lua yield that triggered the bug.
The lua error message is the value on the top of the stack. The lres value is not the value on the top of the stack. It *should* be the return status of resume which would be one of a handful of predefined constants mentioned earlier. In all the cases where we've had sufficient information to tell, it's an address inside the lua module. It doesn't have the low bit set, so it's not a return address.

It appears to me that what is happening is lua_resume is returning a garbage value when it should be returning LUA_YIELD (1). This means that whatever happened to be on top of the lua stack is treated as the error message, which would explain occasionally seeing things like "set".

This does suggest a really horrible workaround... if nothing else is wrong, we could just detect values outside of the acceptable range, and switch them to LUA_YIELD
Title: Re: Shot Histogram Request
Post by: lapser on 22 / April / 2013, 17:20:25
This does suggest a really horrible workaround... if nothing else is wrong, we could just detect values outside of the acceptable range, and switch them to LUA_YIELD
I'll give that a try. Do you think this would work?

Code: [Select]
  if (Lres == LUA_YIELD)return SCRIPT_RUN_RUNNING; //yielded
//print Lres and message here
  if ((Lres >5)||(Lres<0))return SCRIPT_RUN_RUNNING; //TESTING

Do you think this info in asmsafe.h is relevant?

macros to safely call C functions from most inline ASM
these should replace the use of __attribute__((naked)) functions for C code,
because C code is not actually legal in naked functions and can break in obscure ways.
see http://chdk.wikia.com/wiki/CHDK_Coding_Guidelines#Naked_functions (http://chdk.wikia.com/wiki/CHDK_Coding_Guidelines#Naked_functions)
usage

This is where I added my pre-shot delay. Is it possible that an interrupt at just the wrong time could mess up a register that Lua is using?
Code: [Select]
void __attribute__((naked,noinline)) capt_seq_hook_set_nr()
{
 asm volatile("STMFD   SP!, {R0-R12,LR}\n");
 
     shot_histogram_shot_delay(); //wait delay interval, if any, right before taking shot
    //note: must delay BEFORE setting NR values

    switch (conf.raw_nr){
    case NOISE_REDUCTION_AUTO_CANON:
        // leave it alone
#if defined(NR_AUTO) // If value defined store it (e.g. for G12 & SX30 need to reset back to 0 to enable auto)
        *nrflag = NR_AUTO;
#endif
        break;
    case NOISE_REDUCTION_OFF:
        *nrflag = NR_OFF;
        break;
    case NOISE_REDUCTION_ON:
        *nrflag = NR_ON;
        break;
    };

 camera_info.state.shutter_open_time = _time((void*)0);
 camera_info.state.shutter_open_tick_count = get_tick_count();

 asm volatile("LDMFD   SP!, {R0-R12,PC}\n");
}

Title: Crater Lake Time Lapsing
Post by: lapser on 22 / April / 2013, 17:40:01
I camped out in a wet, windy blizzard on Friday night hoping that the weather would clear the next day as the forecast promised.  It did, and I did several time lapses, including sunrise Saturday morning, and all night Saturday night.

I turned off logging and used wait_shot_ready() to avoid the Lua bug. Everything worked great. The G1X maxed out at 1/4000 shutter time on Saturday morning with the sun in the frame. Adding automatic ND filter control is on my list to do next.

Here are 3 of the time lapses I did. First is the sunrise on Saturday morning, and then the all night video starting Saturday evening. The third video was taken with the SX50 zoomed in on Mount Scott, until the ISS was about to show up, and I zoomed all the way out to capture it.

http://www.youtube.com/watch?v=nhhYVKMKnC8#ws (http://www.youtube.com/watch?v=nhhYVKMKnC8#ws)
http://www.youtube.com/watch?v=luIXZWJUFvw#ws (http://www.youtube.com/watch?v=luIXZWJUFvw#ws)
http://www.youtube.com/watch?v=N4X8mxuvQ4A#ws (http://www.youtube.com/watch?v=N4X8mxuvQ4A#ws)
Title: Re: Shot Histogram Request
Post by: reyalp on 22 / April / 2013, 17:48:21
This does suggest a really horrible workaround... if nothing else is wrong, we could just detect values outside of the acceptable range, and switch them to LUA_YIELD
I'll give that a try. Do you think this would work?

Code: [Select]
  if (Lres == LUA_YIELD)return SCRIPT_RUN_RUNNING; //yielded
//print Lres and message here
  if ((Lres >5)||(Lres<0))return SCRIPT_RUN_RUNNING; //TESTING
No. I would do this in lua_resume()
Code: [Select]
  status = luaD_rawrunprotected(L, resume, L->top - nargs);
+  if(status > 5)  // LUA_ERRERR
+   status = 0
You might also want to add a console log or something so you know it happened and whether the script continued to run after that. Note that this is *not* a fix, even if it appears to work, it is terribly wrong and could have other unforeseen consequences down the road. But whether it "works" or not might give us some clue about the nature of the problem.

Quote
Do you think this info in asmsafe.h is relevant?
Off the top of my head, I think it's unlikely:
1) capt_seq_hook_set_nr happens in the capt_seq task, not the kbd task. Even if it was hosing kbd_task, it's hard to see it always causing this exact symptom
2) capt_seq_hook_set_nr is generally set up safely (for most ports), adding additional function calls is probably OK.

If you are making any lua calls in shot_histogram_shot_delay(), that would be a Bad Thing. Don't do that.

edit:
I messed this up originally. Status should be set to 0, because it's only used as the return status if it's non-zero. LUA_YIELD is set later from L->status if applicable.
Title: Re: Shot Histogram Request
Post by: waterwingz on 22 / April / 2013, 22:51:17
I camped out in a wet, windy blizzard on Friday night hoping that the weather would clear the next day as the forecast promised.  It did, and I did several time lapses, including sunrise Saturday morning, and all night Saturday night.
Off topic but I have to acknowledge being impressed.  My kids go camping in Northern Ontario Provincial Parks in the dead of winter but its always a "big deal" to get prepared and organized.  You just seem to casually hike up a mountain and sleep in the snow just so you can get a unique timelapse.  Simply amazing.
Title: Re: Shot Histogram Request
Post by: lapser on 23 / April / 2013, 00:08:09
You just seem to casually hike up a mountain and sleep in the snow just so you can get a unique timelapse.  Simply amazing.
"Seem to" is the operative word here. All the preparation was "off topic."

Having lived in Michigan, the winter temperatures in Ontario are brutal compared to Oregon. The coldest night I've camped in here was 0 Fahrenheit, which is a mild spring day in Ontario.
Title: Re: Shot Histogram Request
Post by: philmoz on 25 / April / 2013, 00:28:42
0x310252 is the Lres value (confirmed in the script log). "resume yield" means resume is resuming from a yield (rather than starting the script).

Taking the lua load address as 0x309178, this makes the lres 0x70da in the lua module, which is not the same as before, but not far off. According to lua.elf.objdump, this would correspond to
Code: [Select]
000070d8 <luaD_reallocstack>:
    70d8: b5f0      push {r4, r5, r6, r7, lr}
    70da: 6a03      ldr r3, [r0, #32]

There is a 36 byte header loaded as part of the module so you need to go back 36 bytes in the dump to get to the address.

The code at 70da is in the luaD_rawrunprotected function @ 70b6 in the dump:
Code: [Select]
    70b4: b01c      add sp, #112 ; 0x70
    70b6: 6e18      ldr r0, [r3, #96] ; 0x60     <---- here
    70b8: bc10      pop {r4}

So Lres contains the address of the instruction that is loading the status return value into r0  ???

Phil.
Title: Re: Shot Histogram Request
Post by: reyalp on 27 / April / 2013, 00:49:10
There is a 36 byte header loaded as part of the module so you need to go back 36 bytes in the dump to get to the address.
Good to know. Thinking about this, module code should probably be 32 bit aligned. 2 byte alignment should be fine for thumb, but modules can have ARM too (setjmp in Lua, for example)

I don't think this is the cause of the script problem though, since it's been happening from before Lua was a module.

edit:of course it is.
Quote
So Lres contains the address of the instruction that is loading the status return value into r0  ???
This must be a clue, but damned if I know what it means...
Title: Re: Shot Histogram Request
Post by: swimmer727 on 05 / May / 2013, 11:21:31
Hey Lapser, great work.

I've been digging into the CHDK stuff this week before a trip to Juneau (hoping it'll only rain 80% of the time I am there), and I'd be interested in trying this out on my SX260_100b and S100_101b.

I'm planning to run some testing the next couple nights. I can see if I run into the same issue you have been.

Keep up the good work!
Title: Re: Shot Histogram Request
Post by: lapser on 09 / May / 2013, 23:22:00
I'd be interested in trying this out on my SX260_100b and S100_101b.

I'm planning to run some testing the next couple nights. I can see if I run into the same issue you have been.
I think Phil found the bug we were working on and fixed it. The attached CHDK builds should have the fix included. I'll post the latest script in the next message.
Title: Time Lapse Script
Post by: lapser on 09 / May / 2013, 23:33:51
Here's the script that works with the CHDK builds in the last post.

Most of the defaults should work OK. You can change the interval to as short as 500 msec. Try setting the log file parameter to 0 if the camera can't keep up. I usually set the focus to 1 (hyperfocal distance) for sunset time lapsing.

Try putting the camera in manual focus mode before starting the script if you have focus trouble, or the S100 crashes with the first picture.

Put the camera in continuous drive mode for faster shooting, and to see the pictures on the screen between shots. It works best in Av mode, since the script doesn't change the aperture.

The script starts out by setting the metering areas. You press <display> to go to the next meter, or <menu> to start taking pictures. Just press menu if you want a single, centered meter.

I hope you have time try the script before you have to leave. Good luck!
Title: Re: Shot Histogram Request
Post by: swimmer727 on 10 / May / 2013, 01:16:50
S100 is happily taking photos in a first test, but SX260 is giving me "Fail to load lua.flt: bad import symbol". I haven't seen much on the forums about fail to load errors for ideas about what may have caused that error. *.bas scripts run ok, but nothing *.lua will run with that build on the SX260.

I tried using the lua.flt file from the S100 build, but same error (not sure if that was a useless troubleshooting effort if that's a file that's generated from the build for a specific camera). I remember seeing something about needing to boot from the SD card rather than from the load firmware option for your builds... I used STICK to create the build on this card, then deleted the modules folder and replaced with the one in your file, but the card didn't boot on the SX260 (I used the same method on the S100 and it booted to the card without issue).

A note on the S100... I was only able to move the first metering area. on the S100 the display button is down on the circle (the buttons outside the circle are ring func, movie record, playback, and menu). I tried other buttons to figure which might change metering areas, but did not have much luck. I didn't see a list of possible keys in the CHDK scripting page on the WIKI for that function to update the script for a different button, such as the ring/func?

Thanks for the builds!


Title: Re: Shot Histogram Request
Post by: philmoz on 10 / May / 2013, 01:31:38
S100 is happily taking photos in a first test, but SX260 is giving me "Fail to load lua.flt: bad import symbol". I haven't seen much on the forums about fail to load errors for ideas about what may have caused that error. *.bas scripts run ok, but nothing *.lua will run with that build on the SX260.

Make sure you've copied the entire contents of the build (including the CHDK/MODULES folder) to the SD card.

Phil.
Title: Re: Shot Histogram Request
Post by: swimmer727 on 10 / May / 2013, 02:06:13
I have tried copying the entire modules folder from the .zip onto the card. I have also tried deleting the CHDK/Modules folder on the card, then copying the entire MODULES folder from the unzipped CHDK folder. Both methods gave me the same error. Is there a different way I should copy or anything I need to do to the files before copying? ( I have a vague recollection of an "@something" that macs append that needs to be removed, but I can't remember what the issue was or if it was related to .zip files, I'll try to keep searching tomorrow).

Title: Re: Shot Histogram Request
Post by: lapser on 10 / May / 2013, 02:48:36
A note on the S100... I was only able to move the first metering area. on the S100 the display button is down on the circle (the buttons outside the circle are ring func, movie record, playback, and menu). I tried other buttons to figure which might change metering areas, but did not have much luck. I didn't see a list of possible keys in the CHDK scripting page on the WIKI for that function to update the script for a different button, such as the ring/func?
It's never simple, is it? Here's the key map for the S100 that's in CHDK:
Code: [Select]
// Keymap values for kbd.c. Additional keys may be present, only common values included here.
static KeyMap keymap[] = {
    { 0, KEY_ERASE           ,0x00000001 },
    { 0, KEY_DOWN            ,0x00000002 }, // Found @0xff45373c, levent 0x05
    { 0, KEY_DISPLAY         ,0x00000002 },
    { 0, KEY_LEFT            ,0x00000004 }, // Found @0xff453744, levent 0x06
    { 0, KEY_MENU            ,0x00000008 }, // Found @0xff45374c, levent 0x09
    { 0, KEY_SET             ,0x00000020 }, // Found @0xff45375c, levent 0x08
    { 0, KEY_UP              ,0x00000040 }, // Found @0xff453764, levent 0x04
    { 0, KEY_RIGHT           ,0x00000080 }, // Found @0xff45376c, levent 0x07
    { 0, KEY_ZOOM_OUT        ,0x00008000 }, // Found @0xff4537ac, levent 0x03
    { 0, KEY_ZOOM_IN         ,0x00010000 }, // Found @0xff4537b4, levent 0x02
    { 0, KEY_VIDEO           ,0x00000100 },

    { 1, KEY_PRINT           ,0x00800000 }, // ALT menu on PLAYBACK button
    { 1, KEY_PLAYBACK        ,0x00800000 },
    { 1, KEY_SHOOT_FULL      ,0x00300000 }, // Found @0xff4537dc, levent 0x01
    { 1, KEY_SHOOT_FULL_ONLY ,0x00200000 }, // Found @0xff4537dc, levent 0x01
    { 1, KEY_SHOOT_HALF      ,0x00100000 }, // Found @0xff4537d4, levent 0x00

    { 0, 0, 0 }
};
I don't see a ring function key in there. It doesn't seem useful to have the CHDK display and down buttons map to the same key. On the G1X, the CHDK display button maps to the lower left key.  Wouldn't it be better to map KEY_DISPLAY to the ring function key, similar to the G1X?

You can edit the script to change the key, with a text editor. You need to change line 147, which currently reads:

    elseif (is_key("display"))then

Try
    elseif (is_key("erase"))then
Or
    elseif (is_key("video"))then

As for the sx260 loading problem, I suggest you erase all the files off the card and download the latest Full version of CHDK for the camera. Set the write protect tab, and make sure it auto boots.

Then unzip my build, select all the files and folders in my build, and drag them to the root of the SD card. Choose the option to overwrite everything. Set the write protect tab and auto boot with my build.

Title: Re: Shot Histogram Request
Post by: swimmer727 on 12 / May / 2013, 17:11:07
Thanks for the help! I have everything working now.

The "erase" key is the same as the ring/func key and changing that as you suggested allowed me to switch between metering windows on the S100.

I set my SX260 card to bootable from the CHDK menus then re-copied the autobuild to get it to auto-boot, then copied your build onto the card and it worked. Not sure exactly where I went wrong the first couple times, but I have created a second card that works using and then copying Lapser's build on top.

I tried a couple 'sunrises.' The script worked nicely on the change from dark to light, but my city view is pretty boring,cloudy, and full of lights. I did manage to get a group of pics for Star Trails last night.

Looks pretty Rainy for the trip, but if I get a clear night, I'll let you know how it came out.
Title: Re: Shot Histogram Request
Post by: ahull on 04 / July / 2013, 10:10:06
lapser, did your revised code ever get merged back in to the development branch?

I was going to try a bit of time lapse on a Ixus 115 HS or perhaps my Ixus 60, but wasn't sure if I still needed a bespoke build to use your enhancements.
Title: Re: Shot Histogram Request
Post by: reyalp on 04 / July / 2013, 16:03:25
lapser, did your revised code ever get merged back in to the development branch?
No, lapsers code was never merged into the trunk.

There is certainly some good ideas there that would be nice to have. I'm not averse to having it in CHDK in principle, though it would probably be for 1.3 as 1.2 getting very close to release.

A bit of explanation of why I haven't made effort to get this into the trunk:
The last versions that I saw, the code had a lot of different, not very closely related changes. Some of them were related to working around the lua bug, which has since been fixed. I am much more likely to accept patches that are in clearly defined, digestible chunks. Code dumps of "here's a bunch of cool stuff I did" are not something I want to spend my limited CHDK development time on. I also greatly prefer clear interfaces, even if it doesn't give you the absolute maximum performance or efficiency, and prefer to provide building blocks for scripts rather than have entire features hard coded in the core. In the past I've have accepted things I felt were too ugly but didn't have the time to sort out, and I have almost always come to regret it later. If someone wants to take the features lapser developed and work them into patches with the characteristics outlined above, I'd definitely be happy to consider including them.

Isn't this what the development branch is for, can't we just put in whatever is useful no matter how much of a mess it is? In a word: No. It is acceptable to have a mess in the trunk, but only if there is a clear path to making it something that is eventually acceptable for release and someone committed to doing that work.
Title: Re: Shot Histogram Request
Post by: lapser on 05 / July / 2013, 18:00:03
lapser, did your revised code ever get merged back in to the development branch?

I was going to try a bit of time lapse on a Ixus 115 HS or perhaps my Ixus 60, but wasn't sure if I still needed a bespoke build to use your enhancements.
Sorry, I've been doing a lot of travelling, and we've had family visitors, etc. etc. I haven't had a chance to obsess on CHDK for awhile.

It will take a lot of cleanup to get all the changes into the trunk, as reyalp described. I plan to work on that as soon as the rest of my world settles down again. In the meantime, I can compile you a specific build for a camera/firmware revision as before.

I'm way behind on the trunk changes, but the time lapse script and code changes so far are working great. Let me know your camera info and I'll see if I can get something compiled for you.

Here's a few of the time lapses I've done recently:

http://www.youtube.com/watch?v=BK6Aqpn1zoY#ws (http://www.youtube.com/watch?v=BK6Aqpn1zoY#ws)

http://www.youtube.com/watch?v=UITD9c6c3Rk#ws (http://www.youtube.com/watch?v=UITD9c6c3Rk#ws)

http://www.youtube.com/watch?v=zwGXXJSRPxA#ws (http://www.youtube.com/watch?v=zwGXXJSRPxA#ws)

http://www.youtube.com/watch?v=DEU8l2mCMBY#ws (http://www.youtube.com/watch?v=DEU8l2mCMBY#ws)

http://www.youtube.com/watch?v=nTzLeq-9z1A#ws (http://www.youtube.com/watch?v=nTzLeq-9z1A#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 08 / July / 2013, 20:33:44
Attached are the two builds for @ahull

I'll attach the Lua script that goes with them in the next message.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / July / 2013, 20:48:27
I attached the script that goes with the above builds.

You can try setting the focus to 1 for hyperfocal distance. That's what I use for my cameras, but it may crash older cameras.

I'm way behind on the build number, but at least the Lua bug that interrupted the script randomly was fixed in this build. I haven't had any script stoppages since then.

Here's the time lapse I did last night at the lake. I talk about the flashes as the sun goes down in the YouTube description. I think they're caused by shutter speed inaccuracy at 1/4000 on the G1X. I haven't seen it on other cameras with shutter speed max set at 1/3200.

http://www.youtube.com/watch?v=bPYX9keMisk#ws (http://www.youtube.com/watch?v=bPYX9keMisk#ws)
Title: Re: Shot Histogram Request
Post by: ahull on 09 / July / 2013, 03:32:42
 :D Thanks for that lapser, I will give them a try, hopefully tonight.
Title: Re: Shot Histogram Request
Post by: hwntw on 09 / July / 2013, 05:33:28
Hello, @lapser, can you extract the shot histogram/meter bits from this and code them in to CHDK so we can use this interesting development of yours apart from time lapses?

Colin
Title: Re: Shot Histogram Request
Post by: lapser on 09 / July / 2013, 11:57:55
Hello, @lapser, can you extract the shot histogram/meter bits from this and code them in to CHDK so we can use this interesting development of yours apart from time lapses?
The shot histogram changes aren't finished, and they're integrated with the shot meter changes at the moment.

However, if you just want the increased precision in
  get_histo_range(from, to [,scale])
I may be able to do that, although reyalp has to approve putting it into the trunk.
Title: Re: Shot Histogram Request
Post by: reyalp on 09 / July / 2013, 16:56:47
I may be able to do that, although reyalp has to approve putting it into the trunk.
Or one of the other developers.

As I've said before, if changes are in small digestible chunks, I am much likely to spend time on them. Even if there is something I don't like in a patch, if I can understand what is supposed to be doing I may be able to turn it into something I do find acceptable.
Title: Re: Shot Histogram Request
Post by: hwntw on 10 / July / 2013, 04:51:57
Hello,
A good way to start is with Lapser's shot meter feature? Then possibly the shot histogram bit?
Colin
Title: Re: Shot Histogram Request
Post by: ahull on 14 / July / 2013, 16:04:22
Lapser, I'm running a test on the a2200, its currently strapped to a fence post in my "quick weatherproof camera box" (http://chdk.setepontos.com/index.php?topic=10284.0) fitted with a polariser..

I'll post the results if and when I get them. The A2200 was a little quirky to set up, but I got it going.

Title: Re: Shot Histogram Request
Post by: ahull on 14 / July / 2013, 18:21:26
The first results are in... Lots of blunders on my part, I should have taken more time setting up the metering, not shot all the images at the full resolution of the camera, and offset the path of the sun to avoid some of the nasty flare. Youtube has also added a bit of mosaicing which is not in the original, but all in all, not bad for a first attempt..

Sunset in the Trossachs July 2013 (http://www.youtube.com/watch?v=QHzk9eJ_0U4#)

Title: Re: Shot Histogram Request
Post by: lapser on 14 / July / 2013, 23:06:17
@ahull,

Looks great! It's really hard to get a good picture with the sun in the frame, especially with clouds moving in front of it.  My 3 cameras all have an ND filter, although only the G1X is documented by Canon. It would be nice to have the script control the ND filter, which I plan to do soon. The sun tends to max out the shutter speed, so the ND filter would help.

When bright and dark areas are in the frame, there always seem to be video compression artifacts in the dark areas, even with commercial video. The main thing is that the script seems to be smoothing out the exposure changes in your video, so there isn't any "fluttering" of exposure like I used to get.

I'm looking forward to seeing your next video.
Title: Re: Shot Histogram Request
Post by: lapser on 27 / July / 2013, 15:24:14
I was able to get my time lapse mods working with the latest trunk revision today.
set_console_layout() is working now (thanks Phil). I also removed the Lua bug code since that one is fixed (THANKS Phil).

I'm interested in doing something with the new filewrite hook. Is there a thread or some documentation about it somewhere?

I discovered that the shutter time gets a little inaccurate on the SX50 when it's less than about 1/1600 second. It goes all the way to 1/3200, second but when shooting multiple pictures the exposure varies by about 15/96 ev between pictures. This leads to "flashing" in a time lapse video. This also happens slightly with multiple pictures without CHDK taken at 1/2000 second, so I don't think it's a CHDK issue. It DOESN'T happen with the SX260 at 1/3200 second.

Here's an example. The time lapse starts out with the sun in the frame, and 1/3200 shutter time. It flashes until the sun goes down and the shutter time reaches about 1/1600. The rest of the video looks very smooth. By the way, CHDK is not doing any exposure changes at the beginning. The exposure is a constant 1/3200 during the flashing.

http://www.youtube.com/watch?v=NLSbSRq3JhY#ws (http://www.youtube.com/watch?v=NLSbSRq3JhY#ws)


Below is a more interesting time lapse from the same spot, which shows flashing at the beginning and very smooth exposure changes later.

http://www.youtube.com/watch?v=3RPLgJYyNCA#ws (http://www.youtube.com/watch?v=3RPLgJYyNCA#ws)

The next time lapse was done with the SX260 starting at 1/3200 sec, and ending at 1/154 sec, with no flashing:

http://www.youtube.com/watch?v=AvflNryCscw#ws (http://www.youtube.com/watch?v=AvflNryCscw#ws)

The G1X doesn't have any flashing at 1/4000 second, but it did show some single flashes as the sun went down in this video. I'll have to do some more testing on this one, but I think it may be related to inaccurate shutter time when changing exposure. It's possible I changed the exposure during the shot or something :

http://www.youtube.com/watch?v=bPYX9keMisk#ws (http://www.youtube.com/watch?v=bPYX9keMisk#ws)

By using the ND filter and stopping down to F16, the G1X starts at 1/558 sec in this video without any flashing. My script can't change Av or the ND Filter yet, so the shutter time goes to 3.17 seconds at the end. I stayed until 2200 this night, so you can see Venus appear at the end of the video:

http://www.youtube.com/watch?v=CDpFKfmS0Sk#ws (http://www.youtube.com/watch?v=CDpFKfmS0Sk#ws)
Title: Re: Shot Histogram Request
Post by: waterwingz on 08 / August / 2013, 22:59:10
Okay - so over the last couple of days I've tried the various drivelapse and carlapse scripts.

Frankly - while they mostly work,  the resulting videos pretty much suck.

At highway speeds,  one frame per second is the minimum standard for a reasonable timelapse video and none of the current scripts give you that. 

And driving under underpasses makes the next shot wildly over exposed.

So,  jamming the camera in continuous shooting mode seems to be the order of the day.   Except doing that locks the exposure on the first shot ... which just made a mess of the end of my 30 minute commute home today as the sun started to set.

So lapser,  we need your mods!  Please.  Would you like me to work with you on a "releasable" version to the trunk ?

Title: Re: Shot Histogram Request
Post by: lapser on 09 / August / 2013, 02:05:20
So lapser,  we need your mods!  Please.  Would you like me to work with you on a "releasable" version to the trunk ?
That sounds great. I've got a lot of travel and camping trips planned over the next 6 weeks, hopefully getting some nice time lapses. I'm leaving for a 3-4 day trip tomorrow morning. I'm hoping to get some good shots of the Perseid meteors.

I'll try to have a new diff file and time lapse script for you by the end of the week. I haven't tried it in a moving car for awhile, but it should work well. Here's some of my favorite recent time lapses:

http://www.youtube.com/watch?v=7Wym42H7S7Y#ws (http://www.youtube.com/watch?v=7Wym42H7S7Y#ws)

http://www.youtube.com/watch?v=96hGKyxMavQ#ws (http://www.youtube.com/watch?v=96hGKyxMavQ#ws)

http://www.youtube.com/watch?v=Mr1SguBQ-eo#ws (http://www.youtube.com/watch?v=Mr1SguBQ-eo#ws)

http://www.youtube.com/watch?v=odKcq9HqLwc#ws (http://www.youtube.com/watch?v=odKcq9HqLwc#ws)
Title: Re: Shot Histogram Request
Post by: waterwingz on 09 / August / 2013, 09:55:10
I'll try to have a new diff file and time lapse script for you by the end of the week.
You sound busy.  Just send me what you have now?
Title: Re: Shot Histogram Request
Post by: lapser on 09 / August / 2013, 11:32:49
OK, here's what I have that was working for me. The diff is for 1.3, and won't work with 1.2. I'll attach a diff for 1.2 to the next message.
Title: Re: Shot Histogram Request
Post by: lapser on 09 / August / 2013, 11:34:00
I'll attach a diff for 1.2 to the next message.

OK, my ride is here.. gotta go. Good luck.
Title: Re: Shot Histogram Request
Post by: waterwingz on 09 / August / 2013, 21:04:51
OK, here's what I have that was working for me. The diff is for 1.3, and won't work with 1.2. I'll attach a diff for 1.2 to the next message.
OK, my ride is here.. gotta go. Good luck.
Did a bit of cleanup on the 1.3.0 patch file - converted to a patch file for an svn local repository and removed everything not related to shot_histogram_request (including the Lua bug chasing code and backlight control).  Seems to run well with your script - I'll do a simpler script for car lapse shooting I think.    Once I put more mileage on the code and cleanup the patch file a bit more,  I'll post a final patch file here.   

Hopefully reyalp, philmoz and srsa_4c (and anyone else who cares) can take a look and comment at that point.
Title: Re: Shot Histogram Request
Post by: lapser on 11 / August / 2013, 19:31:23
Did a bit of cleanup on the 1.3.0 patch file - converted to a patch file for an svn local repository and removed everything not related to shot_histogram_request (including the Lua bug chasing code and backlight control).  Seems to run well with your script - I'll do a simpler script for car lapse shooting I think.    Once I put more mileage on the code and cleanup the patch file a bit more,  I'll post a final patch file here.   
Thanks. I had actually removed the lua bug code once, but a bug in CHDK shell overwrote the whole trunk I was working on. CHDK shell needs to be updated for 1.3. It won't change the active trunk any more, so it always starts on 1.2.

I still need to work some more on the shot histogram part of the code. Right now it uses the full bit depth, but I'm not sure that's necessary. I also haven't tested it very much, so I'm not sure it's bug free.

The shot meter part is very stable, and I recently made it more accurate by correcting the rounding for negative values. The time lapse part works great with continuous mode, but the script has to hand shake properly with the C code. I also have a new set exposure routine that sets everything at once using propcases. That's part of the script handshaking. Anyway, I need to write all that up so you can understand how it works.

Did you notice the Apex96 conversion routines in luascript.c? The time lapse script uses them for input and display.

There's also a small print_screen modification that sets a different output file name for input >9999.

I just got back from a 2 night backpack trip in the mountains with thousands of new time lapse pics to process. There was a lot of rain, lightning and thunder both afternoons but I didn't want to risk the cameras, so I don't have pics of that. Lightning hit pretty close to my tent, and a really loud thunderclap arrived less than a second later. Great fun!

Also 2 very bright meteors streaked by quite low, which I think were early Perseids. I missed those with the cameras too, I think. I was hoping to get some meteor pictures tonight, but I'm pretty wiped out. I'll definitely have cameras going all night tomorrow, the peak of the meteor shower. The forecast is for clears skies here, to if I can find a dark spot, I should get some good pics. After that, I'll have some time for CHDK programming.
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / August / 2013, 19:44:57
I still need to work some more on the shot histogram part of the code. Right now it uses the full bit depth, but I'm not sure that's necessary. I also haven't tested it very much, so I'm not sure it's bug free.
Not sure I understand the difference between shot_meter and shot_histogram.

Quote
The shot meter part is very stable, and I recently made it more accurate by correcting the rounding for negative values. The time lapse part works great with continuous mode, but the script has to hand shake properly with the C code.
It would be good to get a definition of what each of these functions does, what parameters it expects, what it returns and maybe how they are used (they seem to interlock) :

    set_shot_interval()   
    shot_meter_enable()
    get_shot_meter()   
    get_shot_ready()
    get_shot_data()


Quote
I also have a new set exposure routine that sets everything at once using propcases. That's part of the script handshaking. Anyway, I need to write all that up so you can understand how it works.
I saw that and separated it out (along with the backlight_off code and the APEX96 code).  Its separate from the shot_meter stuff and there was a discussion in IRC with reyalp about how this should be handled.  It comes down to "SET_NOW" versus "SET_LATER" in the shooting code and this might not be the best way to handle it.

Quote
Did you notice the Apex96 conversion routines in luascript.c? The time lapse script uses them for input and display.
umm .. yes :  http://chdk.setepontos.com/index.php?topic=10459.msg103918#msg103918 (http://chdk.setepontos.com/index.php?topic=10459.msg103918#msg103918)


Attached is a patch file that just includes the shot_meter / shot_histogram stuff.  I'm currently trying to understand the interaction between set_shot_interval() and capt_seq.c - if you use it and do a shoot() rather than press & release of full shoot the camera hangs for example.


Title: Re: Shot Histogram Request
Post by: lapser on 12 / August / 2013, 02:04:21
Not sure I understand the difference between shot_meter and shot_histogram.
The shot histogram is what's already there. I've modified it to create a larger array based on bit depth instead of bit shifting, added a scale factor for greater accuracy, and added the ability to get a histogram of a rectangular area in the raw buffer.

The shot meter is similar to the camera meter, but you can specify the metering area. That's what my script does at the beginning. get_shot_meter() returns an Apex96 value that is the difference between the measured brightness and the optimum brightness. You can add this value to your exposure to correct the exposure for the next shot.

Quote
It would be good to get a definition of what each of these functions does, what parameters it expects, what it returns and maybe how they are used (they seem to interlock) :
Yes, I'll work on that when I can.
Quote
Quote
I also have a new set exposure routine that sets everything at once using propcases. That's part of the script handshaking. Anyway, I need to write all that up so you can understand how it works.
I saw that and separated it out (along with the backlight_off code and the APEX96 code).  Its separate from the shot_meter stuff and there was a discussion in IRC with reyalp about how this should be handled.  It comes down to "SET_NOW" versus "SET_LATER" in the shooting code and this might not be the best way to handle it.
The problem is that in continuous mode, my interval delay has to wait until the script sets the exposure before it takes the next shot. By setting all the exposure parameters at once, I can then let the camera take the next shot. I worked for months getting all this to work right.

Another problem I found is that set_sv96() is a mess. I got some glitches (flashing in the video) that I think were related to this. I simplified it, and it seems to work correctly in all my cameras.
Quote
I'm currently trying to understand the interaction between set_shot_interval() and capt_seq.c - if you use it and do a shoot() rather than press & release of full shoot the camera hangs for example.
There's a handshake in continuous mode that may be the culprit. set_shot_interval() has an optional 2nd parameter that turns off this handshake. Were you using shoot() in continuous mode?

I've got some documentation in the comments in the C code before most of the functions you're talking about.

I appreciate you trying to get this into the trunk by separating it out at reyalp's request. But a lot of this stuff is very closely interwoven to get it to work at high speed in continuous mode. I tried separating things out including the Apex96 conversion and the set_backlight() fix, but I never got anything past reyalp.

Fixing set_backlight() is very important to me and a lot of other posters. My fix works, is simple, and doesn't take significant time or memory. I gave up trying to get anything into the trunk when this was vetoed. My script uses it and it works (press <set> while script is taking pictures). It eliminates flashing in single shot mode, and minimizes it in continuous.

Maybe it would be better to make shot_histogram.c a module that I have control of for now, and make the interface to CHDK as simple as possible. It wouldn't be loaded unless someone tried to call one of my new functions, so it should be safer.
Title: Re: Shot Histogram Request
Post by: waterwingz on 12 / August / 2013, 10:43:57
The shot meter is similar to the camera meter, but you can specify the metering area. That's what my script does at the beginning. get_shot_meter() returns an Apex96 value that is the difference between the measured brightness and the optimum brightness. You can add this value to your exposure to correct the exposure for the next shot.
That's the part I was looking for most immediately.

Quote
Quote
It would be good to get a definition of what each of these functions does, what parameters it expects, what it returns and maybe how they are used (they seem to interlock) :
Yes, I'll work on that when I can.
Thanks - reading someone else's comments in code that has grown over time is a slow way to figure things out. Knowing what you intended each function to do will be a big help - especially give the interactions you mention.


Quote
The problem is that in continuous mode, my interval delay has to wait until the script sets the exposure before it takes the next shot. By setting all the exposure parameters at once, I can then let the camera take the next shot. I worked for months getting all this to work right. Another problem I found is that set_sv96() is a mess. I got some glitches (flashing in the video) that I think were related to this. I simplified it, and it seems to work correctly in all my cameras.
We can certainly discuss this - the idea has merit and the need is there.  Its not only an issue for intervalometers jammed into continuous shooting mode - hence reyalps interest in generalizing it.

Quote
Quote
I'm currently trying to understand the interaction between set_shot_interval() and capt_seq.c - if you use it and do a shoot() rather than press & release of full shoot the camera hangs for example.
There's a handshake in continuous mode that may be the culprit. set_shot_interval() has an optional 2nd parameter that turns off this handshake. Were you using shoot() in continuous mode?
I understand why its doing it - I was looking for an explanation of how to setup the handshake. What sequence of commands are needed to make this work right?

Quote
I appreciate you trying to get this into the trunk by separating it out at reyalp's request. But a lot of this stuff is very closely interwoven to get it to work at high speed in continuous mode. I tried separating things out including the Apex96 conversion and the set_backlight() fix, but I never got anything past reyalp.
You have done a lot of good work here and both philmoz & reyalp have made comments to me about "needing to get lapser's stuff into the core".   In their defense,  I believe they would like to see an organized discussion about each of the mods and anything that becomes really interwoven and codependent is going to be a "hard sell".  Frankly,  as I followed your various threads I could not keep track of everything you were doing and I don't think anyone else could either.   So I believe we now have the opportunity to discuss this in an organized fashion - at least that has been reyalp's offer.

Quote
Fixing set_backlight() is very important to me and a lot of other posters. My fix works, is simple, and doesn't take significant time or memory. I gave up trying to get anything into the trunk when this was vetoed. My script uses it and it works (press <set> while script is taking pictures). It eliminates flashing in single shot mode, and minimizes it in continuous.
Same comment as above.

Quote
Maybe it would be better to make shot_histogram.c a module that I have control of for now, and make the interface to CHDK as simple as possible. It wouldn't be loaded unless someone tried to call one of my new functions, so it should be safer.
Given the mods in other files necessary to make this work,  I'm not sure that will fly.

Let's take this in order as I suggested and if we can't work it out then you & I will both be using custom builds going forward.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / August / 2013, 13:43:16
There's only a month or two when summer backpacking in the Oregon cascades is bearable. Most of the summer, the mosquitoes will drive you nuts, and winter snows close all the mountain roads in November or December. Tonight, I want to catch some meteors, but I promise to work on CHDK while I'm scratching mosquito bites, and when I get the time.

Here are some of the time lapses I got last weekend:

This is my favorite. You can see smoke from us starting the campfire, and our headlamps moving around after it gets dark:
http://www.youtube.com/watch?v=Sl3Sl1gELTU#ws (http://www.youtube.com/watch?v=Sl3Sl1gELTU#ws)

This is an all night time lapse starting Saturday around 1800. The last part is just fog, but it's kind of interesting. I should have let it run a little longer to watch the fog burn off.
http://www.youtube.com/watch?v=P6jrJuI8xZs#ws (http://www.youtube.com/watch?v=P6jrJuI8xZs#ws)

This one was taken with the SX50 starting at the same time as the first video:
http://www.youtube.com/watch?v=5WzzfBEd_Zw#ws (http://www.youtube.com/watch?v=5WzzfBEd_Zw#ws)

And a foggy sunrise on the SX260
http://www.youtube.com/watch?v=1Ya474jgUJg#ws (http://www.youtube.com/watch?v=1Ya474jgUJg#ws)

Title: Re: Shot Histogram Request
Post by: waterwingz on 13 / August / 2013, 22:15:56
Fixing set_backlight() is very important to me and a lot of other posters. My fix works, is simple, and doesn't take significant time or memory.
Here's the fix for the backlight issue in a separate patch file (against the 1.3.0 trunk).

It works better in that the  script does not need to turn the backlight off again after each shoot!  Technically, there is a brief flash when the Canon firmware turns the backlight back on and CHDK immediately turns it off again.   I guess I can live with that.

 8)
Title: Re: Shot Histogram Request
Post by: reyalp on 14 / August / 2013, 01:10:22
Fixing set_backlight() is very important to me and a lot of other posters. My fix works, is simple, and doesn't take significant time or memory.
Here's the fix for the backlight issue in a separate patch file (against the 1.3.0 trunk).

It works better in that the  script does not need to turn the backlight off again after each shoot!  Technically, there is a brief flash when the Canon firmware turns the backlight back on and CHDK immediately turns it off again.   I guess I can live with that.
Thanks for splitting this out into a patch. I agree that would be better than the current behavior, but I think I may have found a better solution: http://chdk.setepontos.com/index.php?topic=10551.msg104054#msg104054 (http://chdk.setepontos.com/index.php?topic=10551.msg104054#msg104054)
Title: Re: Shot Histogram Request
Post by: lapser on 16 / August / 2013, 02:02:24
If your actually do have a little time,  taking an hour to document the function calls in shot_histogram would be really helpful ...
I'm sure there are many typos, but I'll attach the documentation I have so far.

One thing that is completely separate from everything else is the Apex96 conversion functions. They're pretty simple to use with the default values, but also very flexible with the optional scale parameter. The functions are all in luascript.c. I could separate them into a diff file and we could work on them if you want.

It would be harder, but I could probably separate out the shot interval timing functions from the shot meter functions. I assume you would want to add the shot meter first. The new histogram changes are intertwined with the shot meter, so they have to come in together. I'd like to do some more changes and testing of the histogram functions before putting them in the trunk, though.

Anyway, I hope the documentation helps you figure out how to use the functions, and what Tlapser.lua is doing.
Title: Re: Shot Histogram Request
Post by: waterwingz on 16 / August / 2013, 09:37:27
I'm sure there are many typos, but I'll attach the documentation I have so far.
Thank you for this.  I took a quick read through and it will really help a lot.  I'll post questions as I run into thing I still don't understand if I can't figure them out from the source code.

Quote
One thing that is completely separate from everything else is the Apex96 conversion functions. They're pretty simple to use with the default values, but also very flexible with the optional scale parameter. The functions are all in luascript.c. I could separate them into a diff file and we could work on them if you want.
As I posted above,  I already seperated them out and posted elsewhere for discussion.   Right now the discussion is between adding the functionality as a lua library  < e.g.  require("apex96convert")  > or adding to the core so that they can be accessed from uBASIC as well.


Quote
It would be harder, but I could probably separate out the shot interval timing functions from the shot meter functions. I assume you would want to add the shot meter first. The new histogram changes are intertwined with the shot meter, so they have to come in together. I'd like to do some more changes and testing of the histogram functions before putting them in the trunk, though.
I also separated out the set_exp96(tv96[,sv96,av96,nd]) function.  Seems possible to do in Lua as it looks like it just basically does set_prop() calls in C rather that Lua.    There was discussion on IRC about the shooting functions and the need to be able to do a "SET_NOW" in addition to the current functions that does a "SET_LATER".  I'm not certain how that will be resolved.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / August / 2013, 14:34:56
I also separated out the set_exp96(tv96[,sv96,av96,nd]) function.  Seems possible to do in Lua as it looks like it just basically does set_prop() calls in C rather that Lua.    There was discussion on IRC about the shooting functions and the need to be able to do a "SET_NOW" in addition to the current functions that does a "SET_LATER".  I'm not certain how that will be resolved.
First of all, my mods already include the capability of using SET_NOW in half shoot. This is from luascript.c
Code: [Select]
//when() function allows scripts to set exposure (tv,sv,av) values with half shoot
//  pressed that take effect immediately. Without when() function, changes won't
//  take place until the NEXT half_shoot. This requires double metering of each
//  shot, which slows down rate (by half) for multiple shots.
//  av96 & nd_filter may require a delay after setting, for mechanical reasons
static int when()
{
//  if(now_flag&&shooting_in_progress())return SET_NOW;
  if(shooting_in_progress())return SET_NOW;
  return SET_LATER;
}
I think we have a basic difference in how we look at CHDK. I see it more as a platform for writing Lua functions. This is similar to the way smart phones are set up, i.e. as a platform for apps. Simple C functions that make it easier to program scripts in Lua are very worthwhile.

I started out using propcases from Lua, and it took quite awhile to figure it out. Because you CAN do something in Lua, doesn't mean it's not worthwhile to greatly simplify doing it with a C function. I think we need to optimize the Lua programming environment as a priority over the C environment (within reason).

The other reason I wrote set_exp96() is that the code for set_sv96() doesn't work correctly all the time. I had several large glitches in the exposure when using set_sv96(). The code for set_sv96() is very complicated, computing a base sv96 that isn't necessary. This is the simple way to do it, that works well with all my cameras:
Code: [Select]
    shooting_set_prop(PROPCASE_DELTA_SV,
      sv96-shooting_get_prop(PROPCASE_SV)+shooting_get_prop(PROPCASE_DELTA_SV));
    shooting_set_prop(PROPCASE_SV,sv96);
I think we could simplify set_sv96 to use this code and remove all the current mess. Maybe we could write a test Lua script that uses propcases and test it on older cameras?

Another important thing that set_exp96 does is signal chdk to abort the post shot script delay and let the camera go on to the next shot in continuous mode. I could do this by adding a parameter to get_shot_ready() so it aborts the delay without resetting the ready flag, but this is a little confusing.

I spent a lot of time getting the maximum speed out of continuous mode, while writing the log file. The shot data is buffered so you can be writing the log of the last shot while taking a new shot. This is how I do it in my script:
Code: [Select]
  sp=string.format("%d %d %d %d %2d %2d %d %s %-6d",
    get_shot_data(2),get_shot_data(3),get_shot_data(6),
    sv96_to_iso(sv+svdiff),tvd0,tvd,get_vbatt(),seconds(tv),ptime)
  set_exp96(tv,sv,0,nd) -- camera goes on to next shot
  tick0=get_tick_count()
  print(sp) -- writes log file
  ptime=get_tick_count()-tick0
until done
Title: Re: Shot Histogram Request
Post by: lapser on 16 / August / 2013, 18:34:28
Here's the time lapses I got while I was up at McKenzie Pass (Dee Wright Observatory) overnight during the meteor shower.

I used external power adapters for the SX50 and G1X. I also set up the SX260 with external power using a USB battery overnight. I accidentally unplugged it and had to restart it again. Then I left it on all night, until the external battery shut down. When I got home, I discovered that all of the pictures with the camera powered by the external battery WERE LOST! I don't remember this ever happening with the G1X, but that external battery lasts so long I've never had it shut down. I don't think it even has a shut down, so maybe the camera shuts itself down normally when the voltage gets too low.

Has anyone else lost all their pictures with a sudden loss of external power. I wonder if that happens if you open the battery door after taking some pictures. But here's what I did get:

http://www.youtube.com/watch?v=E08y-vxlnhI# (http://www.youtube.com/watch?v=E08y-vxlnhI#)

http://www.youtube.com/watch?v=XppcIvjW1cw# (http://www.youtube.com/watch?v=XppcIvjW1cw#)

http://www.youtube.com/watch?v=Kqsq1BZQO2Y# (http://www.youtube.com/watch?v=Kqsq1BZQO2Y#)

There's an interesting, small moving white object in the lower left corner just before the end of the video. It lasts for about 20 minutes in real time, so it's not a meteor. I'm pretty sure it's an airplane reflecting the setting sun.
http://www.youtube.com/watch?v=96Qivk4qKDc# (http://www.youtube.com/watch?v=96Qivk4qKDc#)

http://www.youtube.com/watch?v=b6PKGP28czs# (http://www.youtube.com/watch?v=b6PKGP28czs#)
Title: Re: Shot Histogram Request
Post by: waterwingz on 16 / August / 2013, 19:27:36
I think we have a basic difference in how we look at CHDK. I see it more as a platform for writing Lua functions. This is similar to the way smart phones are set up, i.e. as a platform for apps. Simple C functions that make it easier to program scripts in Lua are very worthwhile.
I don't think I have ever suggested anything that contradicts what you have said here,  and I don't believe we have a basic difference in how we look at CHDK.   We might be at odds on the definition of "simple" though.

Quote
The other reason I wrote set_exp96() is that the code for set_sv96() doesn't work correctly all the time.  I had several large glitches in the exposure when using set_sv96().
I've seen those glitches too - the exif info is normal and consistent with the previous and following shot.  But the image itself is massively overexposed.

However, in my previous response, I did not suggest using the set_xx96() functions.  I did however point out that your set_exp96() function just does a sequence of set_prop() commands in C rather than in Lua. Nothing gained there over just implementing the function in Lua  (except for the one line of code that sets your wait_script semaphore at the end of the function - more on that below).

Quote
Another important thing that set_exp96 does is signal chdk to abort the post shot script delay and let the camera go on to the next shot in continuous mode. I could do this by adding a parameter to get_shot_ready() so it aborts the delay without resetting the ready flag, but this is a little confusing.
One fundamental belief I have about writing good functions (per your first point above) is to maximize cohesion and minimize coupling.  The use of wait_script in your various functions works,  but creates a lot of coupling between functions.

Where to from here then?  I think the shot_meter() concept is really good and will make a good extension to CHDK core.  As I posted elsewhere,  the APEX96 functions in some form needs to be made available to Lua and uBASIC.  And some method of managing "SET_NOW" vs "SET_LATER" needs to be considered.   How this gets coded is secondary to the best method to integrate this functionality into CHDK.


Title: Re: Shot Histogram Request
Post by: lapser on 16 / August / 2013, 20:27:43
I've seen those glitches too - the exif info is normal and consistent with the previous and following shot.  But the image itself is massively overexposed.
That's what I saw too. The propcase method I discovered (see above) has never shown any glitches. Why don't we throw away the entire current set_sv96(sv) and try my method?
Quote
However, in my previous response, I did not suggest using the set_xx96() functions.  I did however point out that your set_exp96() function just does a sequence of set_prop() commands in C rather than in Lua. Nothing gained there over just implementing the function in Lua  (except for the one line of code that sets your wait_script semaphore at the end of the function - more on that below).
This is what I think the difference between us is. To me, it's well worth it to add a short C function that sets the propcases in a camera independent manner, that's easier to understand and use. Using propcases in Lua is complicated, hard to figure out, memory inefficient, and slower. It works, but it makes for complicated scripts that are hard to follow.

But my when() function worked well for me, and was my preferred solution if set_sv96() is fixed. If we do that, I can get rid of set_exp96() and use a different semaphore. I initially was using get_shot_ready(0), or something like that. Adding the when() function and fixing set_sv96() would be better than set_exp96().

While we're at it, how about if we fix set_tv96() and set_av96(). They're useless now, because they do nothing if the input parameter isn't a valid camera dial setting. They should always set the exposure to something, i.e. the nearest valid camera setting? I would never use it myself, but it would make the actual exposure match the EXIF data, I suppose. Others might find that useful.
Title: Re: Shot Histogram Request
Post by: philmoz on 16 / August / 2013, 21:15:58
I've seen those glitches too - the exif info is normal and consistent with the previous and following shot.  But the image itself is massively overexposed.
That's what I saw too. The propcase method I discovered (see above) has never shown any glitches. Why don't we throw away the entire current set_sv96(sv) and try my method?

The ISO code has already been rewritten - http://chdk.setepontos.com/index.php?topic=10341.msg103282#msg103282 (http://chdk.setepontos.com/index.php?topic=10341.msg103282#msg103282)

Quote
Quote
However, in my previous response, I did not suggest using the set_xx96() functions.  I did however point out that your set_exp96() function just does a sequence of set_prop() commands in C rather than in Lua. Nothing gained there over just implementing the function in Lua  (except for the one line of code that sets your wait_script semaphore at the end of the function - more on that below).
This is what I think the difference between us is. To me, it's well worth it to add a short C function that sets the propcases in a camera independent manner, that's easier to understand and use. Using propcases in Lua is complicated, hard to figure out, memory inefficient, and slower. It works, but it makes for complicated scripts that are hard to follow.

But my when() function worked well for me, and was my preferred solution if set_sv96() is fixed. If we do that, I can get rid of set_exp96() and use a different semaphore. I initially was using get_shot_ready(0), or something like that. Adding the when() function and fixing set_sv96() would be better than set_exp96().

While we're at it, how about if we fix set_tv96() and set_av96(). They're useless now, because they do nothing if the input parameter isn't a valid camera dial setting. They should always set the exposure to something, i.e. the nearest valid camera setting? I would never use it myself, but it would make the actual exposure match the EXIF data, I suppose. Others might find that useful.

In progress.

Phil.
Title: Re: Shot Histogram Request
Post by: waterwingz on 16 / August / 2013, 21:54:05
Patch file for just the shot_meter & shot_histogram functions.   Stripped out the last of the NOW & LATER stuff - that belongs in a different patch.

I think this is "clean" now....   thanks once again to lapser for sharing this.
Title: Re: Shot Histogram Request
Post by: philmoz on 16 / August / 2013, 22:33:31
I think this is "clean" now....

Only had time for a quick look; but noticed the following:
- shot_histogram.h has lost the warning comment on use in modules/platform independent code
- wait_click behaviour is changed, wait_click(1) now does not wait at all (this may be ok; but may also break existing scripts, it also adds yet another magic number meaning to the function parameter)
- call to script_print_screen_statement(0) in lua_script_error is not needed (script_end already calls script_print_screen_end)

Phil.
Title: Re: Shot Histogram Request
Post by: waterwingz on 16 / August / 2013, 22:56:57
Only had time for a quick look; but noticed the following:
- shot_histogram.h has lost the warning comment on use in modules/platform independent code
- wait_click behaviour is changed, wait_click(1) now does not wait at all (this may be ok; but may also break existing scripts, it also adds yet another magic number meaning to the function parameter)
- call to script_print_screen_statement(0) in lua_script_error is not needed (script_end already calls script_print_screen_end)
Thanks - I guess "clean" is a relative term.  As in "compared to where I started" with this.  And lapser has never pretended for one moment that the patch file he posted at my request was anything but a "work in progress".

Still,  it gets us his "shot_meter" code - which is more useful for actual exposure control and adjustments of APEX96 values than the SDM readYUV (http://stereo.jpn.org/eng/sdm/ubasic.htm#ub11) "spot meter" function that I found linked here (http://chdk.setepontos.com/index.php?topic=9423.msg96712#msg96712).  That function turns out to be a wrapper of the standard motion detect code that reads the LCD buffer. A CHDK Lua or uBASIC version is a one line function.  Very handy to get relative values in real time but not much help with working with actual APEX96 exposure values from the RAW image data. Lapser's code lets you use the returned value directly in APEX96 calculations - very nice!
Title: Re: Shot Histogram Request
Post by: lapser on 17 / August / 2013, 01:36:41
I think this is "clean" now....
Thanks for working on this! I feel a little like you're tearing apart my baby, but if that's how you want to get it into the trunk, that's fine with me.
- shot_histogram.h has lost the warning comment on use in modules/platform independent code
Did I do that? That was unintentional
Quote
- wait_click behaviour is changed, wait_click(1) now does not wait at all (this may be ok; but may also break existing scripts, it also adds yet another magic number meaning to the function parameter)
That doesn't need to be there any more if you're worried about it. I put it in when you changed the behavior of wait_click(0), as I recall, but I don't use it now.
Quote
- call to script_print_screen_statement(0) in lua_script_error is not needed (script_end already calls script_print_screen_end)
While trying to trigger the "Lua bug", I left the camera running until the battery ran down. After a lua error, the error message sits there with Lua still running, so it never closed the log file and I lost the error message when the battery died. Of course, if the battery dies with Lua running without an error, the log isn't closed either, but there's not much to do about that.
Title: Re: Shot Histogram Request
Post by: waterwingz on 17 / August / 2013, 08:27:56
Thanks for working on this! I feel a little like you're tearing apart my baby, but if that's how you want to get it into the trunk, that's fine with me.
When you have a minute, you might find this interesting :

the ten commandments of egoless programming (http://www.codinghorror.com/blog/2006/05/the-ten-commandments-of-egoless-programming.html)

Its been reprinted many times online and still holds true many decades later.
Title: For Siavash Kanani
Post by: lapser on 18 / August / 2013, 03:43:51
Attached is a custom CHDK build with the time lapse mods, and the Tlapser.lua script that works with it.

Unzip the CHDK build and copy it to the root of your SD card that already has CHDK. Make sure you copy all the files and folders, overwriting any files and folders that are already there.

Your version of CHDK is pretty old, but this should update it to a more recent version. You have to set the write protect tab on the card before inserting it into the camera so it auto-boots, for the modified version to load (not the firmware update method of loading). If this doesn't work, try loading the latest CHDK full version 1.3 from the main website, and then add the attached custom version.

Then, try running the Tlapser.lua script. Hopefully, you can figure out what the input parameters mean and how to set the metering areas. I haven't gotten to documenting it yet.

Mr. Kanani found out about the time lapse mods from YouTube:

http://www.youtube.com/watch?v=E08y-vxlnhI# (http://www.youtube.com/watch?v=E08y-vxlnhI#)
Title: Re: Shot Histogram Request
Post by: waterwingz on 18 / August / 2013, 09:57:19
@lapser :   a couple of questions about the shot_meter_enable() &  get_shot_meter() functions ?


Thanks.
Title: Re: Shot Histogram Request
Post by: lapser on 18 / August / 2013, 14:03:53
@lapser :   a couple of questions about the shot_meter_enable() &  get_shot_meter() functions ?
1. Yes, that's a mistake in the script I'll correct. Thanks for pointing it out. I initially tried to set the exposure and do the smoothing in the C code so it could keep up in continuous mode, but I decided that was too inflexible. But then I had to add a delay for the script to finish setting the new exposure before taking the next shot. Waiting isn't necessary in single shot mode since the script triggers the next shot.

2. Each shot meter returns an Apex96 value that you can add to the current exposure to to get to optimum exposure. I think this is 2  ev (192 apex96) below a meter reading of 50% linear, which approximates the built in camera meter. But the Bv value for the meters also depends on the exposure settings of the shot (Av, Tv, Sv). These settings are the same for all the meters. get_shot_meter(0) returns an Apex96 value that you add to each meter to get the individual Bv96 reading for that meter, as you stated.

You don't really need the Bv96 values most of the time, since you can adjust for optimum exposure with just the shot_meter values. But in my script, I wanted to underexpose the shots as it gets darker, so I use bv96 to tell how dark it is. My script adds an underexposure adjustment (specified in a parameter) which varies linearly from bv96= +500 to -500.

3. This is because I convert the x1,y1,x2,y2 percent input values from the script into absolute x,y,w,h for the shot meter calculation and use the same variable names.
Code: [Select]
  //convert from %(x1,y1,x2,y2) to actual (x1,y1,w,h)
  x1=(CAM_ACTIVE_AREA_WIDTH*x1)/100;
  w=(CAM_ACTIVE_AREA_WIDTH*w)/100 - x1; //w is input width now
  x1+=CAM_ACTIVE_AREA_X1; //x1 is input left position
 
  y1=(CAM_ACTIVE_AREA_HEIGHT*y1)/100;
  h=(CAM_ACTIVE_AREA_HEIGHT*h)/100 - y1; //h is input height now
  y1+=CAM_ACTIVE_AREA_Y1; //y1 is input top position

I should have some time to work on it for the next few weeks. But I've been reviewing the code, and I don't think separating out the shot meter/histogram part from the time lapse part is as easy as it sounds. The exposure values, and the calculated shot meter values are stored in a buffer that is initialized in capt_seq_hook_set_nr() (time lapse part) right before shutter open.   get_shot_meter reads its results out of the buffer. In continuous mode, this means you can be reading valid values even though the next shot has already started. I spent months getting all this to work right.

The tearing apart my baby analogy isn't so much an ego thing, although I appreciate your link. It's just very difficult to take a fully debugged, working program and split it up into different parts, and then have to debug the individual parts. Presumably, we'll want to add the time lapse part again, and have to put it back together and debug it all over again. I designed all this to work together, and it does that pretty well now.

So rather than spending a lot of time splitting up the shot meter/histogram and time lapse parts, I'd rather use the time to finish and test the shot histogram part more. I also want to add ND filter control to the script and Bv calculation. I'm happy to get rid of the set_exp96() function and use the current exposure functions modified to work in half_shoot, and with set_sv96() corrected. The apex96 conversion functions are also a separate issue.

I'm glad you're starting to understand and appreciate the power of the shot meter. I think I can do a similar thing with the histogram, i.e. return an exposure adjustment value for optimum exposure based on the histogram for each meter.

But I'm not sure anyone appreciates how powerful the time lapse part is, i.e. set_shot_interval. First of all, the timing of the shots is absolutely perfect, or as close as you can get. A script can't be this precise on its own, and it's pretty complicated to set up the timing correctly in a script.  Also, the script can trigger an immediate shot with set_shot_interval(1), and then reset the interval back. The script has precise control of when the shot is taken, so you could trigger synchronized shots with multiple cameras based on anything the script wants, rather than just the current PTP sync method. And of course, it works in continuous mode at maximum speed (more that 2 shots per second for most cameras).

So would it be possible for everyone to agree to work on adding the time lapse/shot meter modifications together? I've tried to set it up so there's only 2 function calls hooked into the current code, that simply return if you haven't called set_shot_meter() or set_shot_interval().  It shouldn't interfere with old scripts or CHDK features.
Title: Re: Shot Histogram Request
Post by: waterwingz on 18 / August / 2013, 14:55:37
And of course, it works in continuous mode at maximum speed (more that 2 shots per second for most cameras).
I've been doing a lot if drivelapse shooting over the last week.  Can't get better than 1 shot / second in continuous mode with my SD940.   Discrete shooting mode is slower than 2 seconds per shot.    Unlike sunsets,  drivelapse has rapidly changing exposures as you face in and out of the sun.  Driving beneath an underpass is also a challenge - by the time the exposure is set your are back out in bright sunshine again.   Driving slow is better and making smooth turns requires you to drive really slow.  But 1 frame per second is about as slow as you can go and have a viewable video when you are done.

I think the best solution is to move to Belgium or Denmark,  where it is always grey and overcast.

Quote
So would it be possible for everyone to agree to work on adding the time lapse/shot meter modifications together? I've tried to set it up so there's only 2 function calls hooked into the current code, that simply return if you haven't called set_shot_meter() or set_shot_interval().  It shouldn't interfere with old scripts or CHDK features.
I suspect there will be some concern about the interlocks between functions that you needed to use in your code to make this all work. 

But focusing just on the shot histogram stuff and on continuous shooting mode (for fastest frame rate and therefore smoothest time lapses),  these seem to be the high level requirements :


Did I miss anything important ?
Title: Re: Shot Histogram Request
Post by: lapser on 18 / August / 2013, 16:41:44
I've been doing a lot if drivelapse shooting over the last week.  Can't get better than 1 shot / second in continuous mode with my SD940.
Oops, it looks like the spec for that camera is 0.8 fps:
http://www.usa.canon.com/cusa/support/consumer/digital_cameras/powershot_sd_series/powershot_sd940_is#Specifications (http://www.usa.canon.com/cusa/support/consumer/digital_cameras/powershot_sd_series/powershot_sd940_is#Specifications)

The sx260 goes to 2.4 fps. Interestingly, it's 0.8 fps with autofocus on, so it sounds like the SD940 is always doing autofocus in continuous mode? But I think you need to try a different camera for drivelapsing. This is a test I did a long time ago with a 1.33 shot per second rate (750 msec interval).
http://www.youtube.com/watch?v=b_nVZbV-MR4#ws (http://www.youtube.com/watch?v=b_nVZbV-MR4#ws)
If you want to use my script for drive lapse, try setting the glitch and smoothing parameters to 0. Here's how they work:

Glitch: ignores first exposure change > glitch value. It takes 2 in a row. This handles a lightning flash going off at night, for example.

Smoothing: Limits exposure changes to 1 ev96 within plus or minus smoothing value. I usually use 32 ev96, so the exposure result is within 1/3 ev of optimum. This eliminates fluttering from inaccuracies in small exposure changes, i.e. at fast shutter speeds. It might help with a drivelapse.
Quote
I suspect there will be some concern about the interlocks between functions that you needed to use in your code to make this all work. 

But focusing just on the shot histogram stuff and on continuous shooting mode (for fastest frame rate and therefore smoothest time lapses),  these seem to be the high level requirements :

  • Allow a mechanism for "shot meter" style measurements of illumination (in Bv96 values) from the raw image buffer while shooting in continuous mode
  • Allow more detailed information from the "shot meter" for histogram type analysis
  • Allow adjustment of exposure settings  ( Tv, Av, Sv, ND filter) while shooting in continuous mode with the ability to ensure that adjustments are only made between shots.
  • Allow the ability to pause continuous mode shooting so that additional processing can occur prior to taking the next shot.

Did I miss anything important ?
That sounds basically right. Take a look at shot_histogram_shot_delay(). When not shooting a time lapse, it still saves the exposure values in the shot data buffer so they can be used later by the shot meter for bv96 calculation.

The rest of the shot data buffer is filled after the raw buffer is ready, in shot_histogram_do_histo(). Without the shot data buffer, it doesn't work right in continuous mode since exposure and meter data aren't guaranteed to refer to the same shot.

Again, I've got all this working and debugged. I don't see any advantage in trying to split it up.
Title: Re: Shot Histogram Request
Post by: waterwingz on 18 / August / 2013, 17:25:27
The sx260 goes to 2.4 fps. Interestingly, it's 0.8 fps with autofocus on, so it sounds like the SD940 is always
doing autofocus in continuous mode?
Nope - my script locks focus at infinity (AFL shows on the Canon OSD).  Its an older camera and one of the smallest Canon has every made.  You don't get something for nothing.

Quote
But I think you need to try a different camera for drivelapsing
The SD940 is just a really nice & light image stablized pocketable camera (shirt pocket - not cargo pants side pocket).  Not sure I want to hang my G10 or SX50 on a suction cup windshield mount.  One fps is good enough for archiving the drives I want to remember some day.

Quote
If you want to use my script for drive lapse, try setting the glitch and smoothing parameters to 0. Here's how they work:
Well, I have my own script - I seem to have written a few - and playing with your own code is way more fun that just using somebody elses.   But thanks for the offer !

Quote
Quote
Did I miss anything important ?
That sounds basically right. Take a look at shot_histogram_shot_delay().
Good - thanks.

Quote
Again, I've got all this working and debugged. I don't see any advantage in trying to split it up.
A highly customized piece of code working and debugged to suit your exact requirements is a great accomplishment.  I salute you.   But when this is all over,  I expect we wil end up with a more generalized solution suitable for multiple scripting applications and the complete range of 112 or so cameras we support.  Pretty much every patch I have posted beyond the trivial bug fixes has been improved by reyalp, philmoz, msl, srsa_4c or someone else.  So please try to remember rules 2 & 3 as we go along for the ride.

Title: Re: Shot Histogram Request
Post by: lapser on 18 / August / 2013, 18:28:10
A highly customized piece of code working and debugged to suit your exact requirements is a great accomplishment.  I salute you.   But when this is all over,  I expect we wil end up with a more generalized solution suitable for multiple scripting applications and the complete range of 112 or so cameras we support.  Pretty much every patch I have posted beyond the trivial bug fixes has been improved by reyalp, philmoz, msl, srsa_4c or someone else.  So please try to remember rules 2 & 3 as we go along for the ride.
I like to think of what I've written in C as more generalized than customized. I tried to make sure everything works in single shot, and with the shot meters enabled or disabled, and that it doesn't break any old scripts. Phil pointed out awhile back that a few cameras don't have capt_seq_hook_set_nr() implemented. I think I can include a workaround for that problem within the current code structure if that's important. But why not start with the current code and capabilities that I've already done and have everyone see what they can do to generalize and improve it, if needed?

Also, I don't think you want the shot meters to just return bv96. Then you would need the av, sv and tv values for that shot to compute the next exposure change, and they're not always available in continuous mode. I could have the meters return the suggested exposure change AND bv96 as a second Lua return value if that's easier.

And I welcome all help and improvements, including totally re-writing everything if that's what people want to do. But if the "improvements" take away the continuous mode and other capabilities, then they're not really improvements.
Title: Re: Shot Histogram Request
Post by: reyalp on 18 / August / 2013, 19:27:16
Again, I've got all this working and debugged. I don't see any advantage in trying to split it up.
One big advantage is making it understandable to the people who will have to maintain it. It will also probably result in code that is more modular, and thus easier to maintain. As a maintainer "working" isn't the only thing that matters to me.

I've been trying to follow this thread but haven't had a chance to dig into the code enough to provide detailed feedback yet. From what I have seen, it seems both complicated and very tightly tied to your specific use case, but I'll have to look more to understand whether those impressions are justified. Waterwingz efforts to separate out the different aspects are certainly helpful.

I know you have spent a lot of time on this, and the value is clear. I would definitely like to have some form of it in CHDK, but I'm not in a hurry. I'd rather get things right than put in something that causes a lot of headaches later.
Title: Re: Shot Histogram Request
Post by: lapser on 19 / August / 2013, 02:21:06
I know you have spent a lot of time on this, and the value is clear. I would definitely like to have some form of it in CHDK, but I'm not in a hurry. I'd rather get things right than put in something that causes a lot of headaches later.
That sounds good. Let me see what I can do to make it more modular and easy to understand. I think that I can get rid of the shot data buffers, which work but are complicated. The script can buffer the data it wants in a string and then release the camera to take the next shot (in continuous). I'll make the code as modular and easy to understand as possible, but it's a design change. Trying to split up the current code won't work right. That's what has seemed rushed to me.

I want to ask you one more thing. I understand you're implementing a new file save hook. Is it possible to abort the jpg save after the raw buffer is ready? In addition to avoiding saving Canon jpgs with CHDK raw, it might be very useful in conjunction with the shot meter. I wonder what would happen in continuous mode if no jpg or raw files were being saved? I'm assuming it would speed up the shot rate, but I'm not sure. Is there a thread on the file save hook? Thanks.
Title: Re: Shot Histogram Request
Post by: waterwingz on 19 / August / 2013, 09:47:12
I think that I can get rid of the shot data buffers, which work but are complicated. The script can buffer the data it wants in a string and then release the camera to take the next shot (in continuous). I'll make the code as modular and easy to understand as possible, but it's a design change.
Before you start any recoding,   and referring to my previous post [ http://chdk.setepontos.com/index.php?topic=8997.msg104252#msg104252 (http://chdk.setepontos.com/index.php?topic=8997.msg104252#msg104252) ],  I think it would be good to discuss the mechanism to be used to sync exposure settings and continuous mode "pausing" under script control.  Getting that generalized, the timing understood, with a clean script interface,  and the actions coordinated is probably the biggest challenge.   Your work with the histogram & shot meter code seems to be good enough for now (given that all code can usually be improved if you want to invest the time).
Title: Re: Shot Histogram Request
Post by: lapser on 19 / August / 2013, 11:49:15
I think it would be good to discuss the mechanism to be used to sync exposure settings and continuous mode "pausing" under script control.  Getting that generalized, the timing understood, with a clean script interface,  and the actions coordinated is probably the biggest challenge.   Your work with the histogram & shot meter code seems to be good enough for now (given that all code can usually be improved if you want to invest the time).
Thanks for all the input. I understand what needs to be done to simplify the code and get it into the trunk in an organized manner now. I can eliminate the shot data buffers and get rid of a lot of code and complexity. Also, it will decouple the shot meter and histogram functions from the time lapse part. We can put each into the trunk separately like everyone wants.

You caught me at the stage where I just got everything working, including Phil fixing that nasty "Lua bug." But the code really wasn't ready to turn over yet. Let me spend this week working on it, and I think I can have something ready for you to look at, and for everyone to modify as they wish.

As for the timing code and script delay, that's not as big a problem as it appears. The get_shot_ready() function already aborts the wait for script delay in continuous mode, on the first call after it returns true. If you want to abort the script delay and do more processing, all the script needs to do is save the get_shot_ready() return value. There's no need for another function to abort the script delay (like set_exp96). This complete time lapse script explains what I mean:

Code: [Select]
set_shot_meter(1 [,metering area])
set_shot_interval(1000)
press("shoot_full")
repeat sleep(10) until get_shooting()
tv=get_tv96()
ready=false
repeat
  if(not ready)then
    repeat sleep(10) until get_shot_ready()
  end
  sp=string.format("tv=%d",tv) -- save string to print later
  tv=tv+get_shot_meter(1)
  set_tv96_direct(tv) -- assumes it work in half_shoot
-- the next part is optional
  ready=get_shot_ready() -- aborts script wait delay and saves ready status
  print(sp) -- print log file without delaying next shot
until false
A little background... In my testing with continuous mode, I discovered that writing a log file while the camera was also saving jpg files as fast as it could, sometimes resulted in long delays in the print or write statement. I fixed this by buffering the shot data, including the shot meters. The buffers allow you to read the meters from the last shot even while calculating the meters for the next shot. That solved the print delay problem nicely.

Eliminating the buffers means you have to process all the meter data before starting the next shot. But part of that processing can be saving the log file in a string (using string.format). The lua string becomes the buffer, so the shot data and meters don't need to be buffered. That makes the C code a lot simpler. That's what I'll be writing this week.

[edit] After thinking about it a little more, I don't think you really even need to save the ready flag in the second call to get_shot_ready(). At that point, get_shot_ready() had just returned true, and CHDK is waiting for the script to call get_shot_ready() again before continuing. But another shot can never become ready during the wait for script delay.
Title: Re: Shot Histogram Request
Post by: reyalp on 19 / August / 2013, 16:35:27
I know you have spent a lot of time on this, and the value is clear. I would definitely like to have some form of it in CHDK, but I'm not in a hurry. I'd rather get things right than put in something that causes a lot of headaches later.
That sounds good. Let me see what I can do to make it more modular and easy to understand.
Note that we aren't necessarily asking you to re-write it. Code passing through several authors often ends up better for it.

Quote
I want to ask you one more thing. I understand you're implementing a new file save hook. Is it possible to abort the jpg save after the raw buffer is ready? In addition to avoiding saving Canon jpgs with CHDK raw, it might be very useful in conjunction with the shot meter. I wonder what would happen in continuous mode if no jpg or raw files were being saved? I'm assuming it would speed up the shot rate, but I'm not sure. Is there a thread on the file save hook? Thanks.
This was done for the USB remote capture feature (discussed starting around http://chdk.setepontos.com/index.php?topic=4338.820 (http://chdk.setepontos.com/index.php?topic=4338.820) released in 1.2). It is only implemented on a few cameras at the moment (see filewrite task nafrafs table http://chdk.wikia.com/wiki/User:Nafraf/csv2wiki (http://chdk.wikia.com/wiki/User:Nafraf/csv2wiki)) . Currently there is no way to disable jpeg outside of the remote capture process, but it would be relatively simple to add. Continuous mode generally works with remote capture, so not saving an image would be OK.

The remote capture thing is a good example of some code that both srsa and myself re-wrote several times. It is also related to what you are doing in that it makes hooked tasks wait for specific conditions.

This is a slight tangent, but one of the things I see in your code is that this hook waiting is very specifically tied to the shot_meter/shot_histogram stuff. It seems to me if this was done in a very general way exposed to script, it could allow implementing the same thing you have done while also opening up a bunch of other options.

What I envision is script being able say "make capt_seq wait at X" where X could be the the override hook, the NR hook, the raw hook when the raw buffer is valid, etc. The script could then poll or block until the condition is met, and take whatever action it wanted, and then tell the hook when it's ok to proceed. So for example, a script that wanted to get values from the raw buffer could do something like

Code: [Select]
hook=hooks.raw_ready -- hooks have a standard interface
hook.enable() -- tell hook to block when reached
...
press('shoot_full')
...
hook.wait() -- wait until hook is reached, could also have a hook.is_ready() for scripts that want to use a repeat / sleep loop and do something while they wait.
... get meter values ...
hook.continue() -- raw hook it can move on
Note that this would enable a lot more than just metering from the raw buffer in continuous mode. You could also write to the buffer (people have often asked for date stamps on cameras that don't support them), or perform whatever kind of analysis they want on the raw buffer. Bulk data processing (like histogram or shot meter) would be done in C functions that are only valid when a particular hook is active.

For applications that don't actually need to block, a count of how many times a particular hook was reached would be useful.

A hook in the override code would make fiddling with exposure values in the shooting process (the set_now vs set_later) thing a lot more predictable.

I know you've said that putting too much in script prevents you form getting the performance that you need, but without playing with a more script-oriented implementation, I'm not really convinced. Again, I'm not asking you to re-write it this way, this is something I would like to experiment with which could potentially generalize some of the things you have done.
Title: Re: Shot Histogram Request
Post by: lapser on 19 / August / 2013, 19:44:29
Note that we aren't necessarily asking you to re-write it. Code passing through several authors often ends up better for it.
I agree, but I want to get it to a point where I'm satisfied with it before turning it over. I never really polished it up for release, and I have a lot of ideas now thanks to Waterwingz and you.
Quote
(see filewrite task nafrafs table http://chdk.wikia.com/wiki/User:Nafraf/csv2wiki (http://chdk.wikia.com/wiki/User:Nafraf/csv2wiki)) . Currently there is no way to disable jpeg outside of the remote capture process, but it would be relatively simple to add. Continuous mode generally works with remote capture, so not saving an image would be OK.
It looks like all my cameras have the filewrite task except for the D20 I just bought. I did get CHDK 1.3 and my mods and script installed on the D20 and it works fine. Good job on the port, nafraf!

If anyone feels like adding the filewrite task to the D20, that would be great. I haven't tried remote capture yet, but it sounds interesting. Would it be possible to add a Lua script function to turn jpg files on or off in cameras with filewrite task, or do you think that's a good idea?
Quote
This is a slight tangent, but one of the things I see in your code is that this hook waiting is very specifically tied to the shot_meter/shot_histogram stuff. It seems to me if this was done in a very general way exposed to script, it could allow implementing the same thing you have done while also opening up a bunch of other options.
Interesting ideas. Actually, I'm going to totally decouple the shot_meter/histogram part from the hook delays now. You'll be able to read the shot meter for the last shot at any time, just like the current shot histogram.

For half_shoot in single shot mode, all that's needed is the get_shot_ready() function, which lets the script wait until the histogram and/or shot meters are ready. There's no good way to do that at the moment.

Continuous mode is where you need the two delays: Pre-shot right before shutter open to so you can slow down continuous shooting to the desired interval, and post-shot, to give the script time to set the exposure for the next shot. These functions will be very simple after the shot data buffer part is removed.

The delays are set up as function calls in capt_seq.c, and raw.c. The two functions that are called are in shot_histogram.c. After I get it working, you could generalize it by changing the address of the functions that are called from a script, if you wanted.
Quote
I know you've said that putting too much in script prevents you form getting the performance that you need, but without playing with a more script-oriented implementation, I'm not really convinced.
Actually, I think you're right about scripts now.  I tracked down the major script delays I was having to writing the log file and jpg files at the same time. The script keeps up nicely for setting exposure in continuous mode, usually taking under 10 msec. Lua seems to be very fast.
Title: Re: Shot Histogram Request
Post by: reyalp on 19 / August / 2013, 21:56:11
If anyone feels like adding the filewrite task to the D20, that would be great. I haven't tried remote capture yet, but it sounds interesting. Would it be possible to add a Lua script function to turn jpg files on or off in cameras with filewrite task, or do you think that's a good idea?
I think it's a good idea if there is a use case for it ;)

I'm not sure whether it should be a script option, or a menu setting (which you could set from script with set_config_value) or some combination. My inclination would be to make it menu option, without a separate script function.

The most common reason for people to want to turn off jpeg is to just shoot raw, but in practice I don't think this is much of a win. The smallest/lowest quality jpeg doesn't take much space or time to save, and if you save only raw, you cannot review at all on camera.

Note that our filewrite hook doesn't disable jpeg processing, it just ignores the writes to disk. I suspect that processing the data is a substantial part of the jpeg shooting time. Based on my observations in http://chdk.setepontos.com/index.php?topic=4338.msg103907#msg103907 (http://chdk.setepontos.com/index.php?topic=4338.msg103907#msg103907) the actual file writing happens in the background, and can be delayed long after the shot was taken. In fact it may not even start until the *next* shot has been exposed.
Title: Re: Shot Histogram Request
Post by: lapser on 19 / August / 2013, 23:00:39
I think it's a good idea if there is a use case for it ;)
Thanks for that info and link. What I'd like to do is take 2 shots at a time. The first shot would be only for metering, and I'd use get_shot_meter() to set the exposure for the second shot. I wouldn't need to save the first shot.

I think the bottleneck in continuous mode is filling up the file write buffer. Yes, it might be a few shots ahead, but eventually, I think the speed limiting factor is how fast the jpg files can be saved to disk.

Have you tested how fast you can take multiple shots in continuous mode without saving the jpgs? I assume it would be faster, but I wonder how much faster it is?

As for a script or menu interface, I would be happy with just a C function for now so I can test out how to use it, and if it's worthwhile doing. Can you give me an idea how to implement this for testing? No rush, thanks.
Title: Re: Shot Histogram Request
Post by: reyalp on 20 / August / 2013, 00:25:48
I think the bottleneck in continuous mode is filling up the file write buffer. Yes, it might be a few shots ahead, but eventually, I think the speed limiting factor is how fast the jpg files can be saved to disk.
On my a540, there is no discernible slowdown after a particular number of images. There are occasional hitches but for the most part it just shoots at the same rate indefinitely. See this thread: http://chdk.setepontos.com/index.php?topic=10488.msg103780#msg103780 (http://chdk.setepontos.com/index.php?topic=10488.msg103780#msg103780)
Quote
Have you tested how fast you can take multiple shots in continuous mode without saving the jpgs? I assume it would be faster, but I wonder how much faster it is?
I have not tested this.
Quote
As for a script or menu interface, I would be happy with just a C function for now so I can test out how to use it, and if it's worthwhile doing. Can you give me an idea how to implement this for testing? No rush, thanks.
You should theoretically just be able to call filewrite_set_discard_jpeg(1) before each shot. However, the filewrite code will currently clear it (enabling write for the next image) when the write completes (generic/filewrite.c filewrite_jpeg_complete). The delay issues I mentioned earlier mean that re-setting it for each shot would be tricky. For a quick test you could comment out the code that resets it, or make it some value other than 1 mean "don't reset"
Title: Re: Shot Histogram Request
Post by: danx88 on 20 / August / 2013, 00:59:13
Hi Lapser,
I'm Sia (Siavash), thanks for putting the CHDK build and the script here for me to test.
I've successfully set up the new CHDK on bootable mode and everything worked fine, then I made some tests with the script to familiarize myself with the parameters, some of them are obvious and I'm gonna try other ones to find out how exactly they work, but I'm still confused about these ones:

Shots per Interval: Can we just set the desired interval, or this does something else?

Focus: What does this do? Does it mean that for being able to focus on something not too far away we have to experiment with this value with numbers between 0 and 1 to find the correct focus? or is it enough to manual focus the camera before starting the script?

Smoothing and Glitch: I was confused about these but found some explanations in your previous post.
 
Show Meters: I set this to 1 but nothing happened during the shooting, screen was black between shots (tested with 5 sec, 2 sec and also 1 sec  intervals)

Meter Areas: I think I roughly know that we can set 4 areas to be metered before starting the script, I'd appreciate if you let me know how exactly these areas work, for example, does is help if I put an area for ground and a separate area for sky? and maybe an area containing the places that sun will move on the frame during sunset?

Shutter->ISO (msec): ?

by the way what is the reason for the first shots that is overexposed?

I have to say it's a really good script and I figured out that you've done something with core CHDK that enables it to take shots faster than normal scripts, and set exposures more accurately between shots, I can't exactly understand some of the technical stuff that you guys talk about here but overall it looks great! As soon as I can figure out how to set it up I'll take a sunset time lapse with it and will post it here.

Thanks again

Sia

Title: Re: Shot Histogram Request
Post by: danx88 on 20 / August / 2013, 01:07:56
The shot meter exposed the 2nd shot perfectly, matching the shot with the ND filter IN at the end of the first sequence.  The exposure change was about 2.75 EV when the ND filter went out. You can see the glitch at 1:11 in the video. There's a noticeable color change, so I guess the ND filter isn't quite ND.

I'm wondering why did you stop the script and changed the ND filter status while you were expecting the exact same exposure at the next shot (and possibly the shots after that?), was there any reason not to use ND after that point? cause this has introduced the glitch in there in both colour and the smooth movement of the cloud, and also with ND you can expect longer shutter speeds that are more accurate (compared to the shorter ones like 1/500sec etc) that prevents flickering in your movie.

I can understand if it was just for experiment, but in a real situation would you do this in the middle of a time lapse shot?
Title: Re: Shot Histogram Request
Post by: lapser on 20 / August / 2013, 01:52:36
You should theoretically just be able to call filewrite_set_discard_jpeg(1) before each shot. However, the filewrite code will currently clear it (enabling write for the next image) when the write completes (generic/filewrite.c filewrite_jpeg_complete). The delay issues I mentioned earlier mean that re-setting it for each shot would be tricky. For a quick test you could comment out the code that resets it, or make it some value other than 1 mean "don't reset"
Thanks! I tried commenting out the reset code and it worked. Then I tested the SX260 camera in continuous mode holding down the shutter button. The spec on the camera is 2.4 shots per second, and that's what I got, both with filewrite disabled, and not disabled. My script did adjust the exposure properly without writing the jpg files, but maximum shot rate was unchanged. My script only does 2.0 shots per second maximum, probably because of the script handshake and shot_meter delays.

I suspect that the camera is hard wired for 2.4 shots per second in continuous mode, whether you're saving files or not. So there's no speed benefit in skipping the jpg saving.

By the way, nafraf already sent me a build for my new D20 with the filewrite task. I was able to do remote captures with it, which I'll have to admit, is pretty cool! Good work. The jpgs didn't show up on the camera either, so I assume nafraf did it right.
Title: Re: Shot Histogram Request
Post by: lapser on 20 / August / 2013, 02:48:42
Shots per Interval: Can we just set the desired interval, or this does something else?
That's great that you got it working!

You can keep this at 1 normally. It's actually the number of un-delayed shots per interval. I designed it for longer intervals where you want to do a shot or two to get the exposure right. Try setting the interval to 10,000 with 2 shots per interval, and you'll see what it does.
Quote
Focus: What does this do? Does it mean that for being able to focus on something not too far away we have to experiment with this value with numbers between 0 and 1 to find the correct focus? or is it enough to manual focus the camera before starting the script?
For sunsets, I always set it to 1. The script will calculate the "hyperfocal distance" and focus there. This is the closest you can focus and still have infinity in focus. You don't have to worry about focusing then, and foreground objects should be in focus as well as the sunset and clouds. It works pretty well.

If you set it to 0, the camera will do autofocus on the first shot, and hold that focus.
Quote
Smoothing and Glitch: I was confused about these but found some explanations in your previous post.
 
Show Meters: I set this to 1 but nothing happened during the shooting, screen was black between shots (tested with 5 sec, 2 sec and also 1 sec  intervals)
What this does is write lines on the first shot to show the metering areas. The first shot uses the camera meter for exposure, so it's usually overexposed on sunset time lapses. Writing the meter areas on it ruins it as a picture, but it's a good record of the meters.

If you want to see the meter areas on the screen while shooting, press the RIGHT key.
Quote
Meter Areas: I think I roughly know that we can set 4 areas to be metered before starting the script, I'd appreciate if you let me know how exactly these areas work, for example, does is help if I put an area for ground and a separate area for sky? and maybe an area containing the places that sun will move on the frame during sunset?
This is one of the most powerful features of the script. It looks at all the meters and picks the brightest so no area is overexposed. My early time lapse test of sunset over the city resulted in the city lights being way over exposed after the sky got dark. Skip to the very end of this video to see the effect:
http://www.youtube.com/watch?v=MQah7sksQaw#ws (http://www.youtube.com/watch?v=MQah7sksQaw#ws)

But in this video, I put one of the meters on the a part of the city where I knew the lights would get brighter. I held the first frame so you can see the metering areas at the beginning. Then skip to the end and see how different the city lights are after dark.
http://www.youtube.com/watch?v=qhkVtBtY3t0#ws (http://www.youtube.com/watch?v=qhkVtBtY3t0#ws)

This last one is one of my favorites for using the meters. I put one meter on the sky and another very small rectangular meter on Willamette street. The small meter took over after dark and I zoomed in on the street to see the cars better (with movie software). At the very end, I showed the metering area by stopping the script and immediately starting it again to take a picture with the metering areas, and then stopping it.
http://www.youtube.com/watch?v=pozFliELR4w#ws (http://www.youtube.com/watch?v=pozFliELR4w#ws)
Quote
Shutter->ISO (msec): ?
The script will vary the shutter time until it gets to this value, using the minimum ISO. Then it holds this value and varies the ISO until it reaches the maximum. Then it goes back to increasing shutter time until that reaches maximum.
Quote
by the way what is the reason for the first shots that is overexposed?
The exposure of the first shot is set by the camera. If the shot meter area is the same as the camera meter area, they would be exposed the same. Usually, I put the shot meter on the brightest part of the sky, so the 2nd shot gets a lot darker.

The bvDelta parameter is the amount of underexposure at -500 (night). It starts at +500 (day). A change of 96 is 1 fstop, so 192 is 2 fstops underexposed after it gets dark.
Quote
I have to say it's a really good script and I figured out that you've done something with core CHDK that enables it to take shots faster than normal scripts, and set exposures more accurately between shots, I can't exactly understand some of the technical stuff that you guys talk about here but overall it looks great! As soon as I can figure out how to set it up I'll take a sunset time lapse with it and will post it here.
Don't forget to set up the camera before starting the script. I usually use Av mode. Turn everything off that you can, especially "safety manual focus." Make sure it's in continuous drive mode also. It's faster, and the pictures will be visible on the screen.

I look forward to seeing what you come up with. Good luck.
Title: Re: Shot Histogram Request
Post by: lapser on 20 / August / 2013, 03:00:09
I'm wondering why did you stop the script and changed the ND filter status while you were expecting the exact same exposure at the next shot (and possibly the shots after that?), was there any reason not to use ND after that point? cause this has introduced the glitch in there in both colour and the smooth movement of the cloud, and also with ND you can expect longer shutter speeds that are more accurate (compared to the shorter ones like 1/500sec etc) that prevents flickering in your movie.

I can understand if it was just for experiment, but in a real situation would you do this in the middle of a time lapse shot?
The shutter speed maxes out at 3200 for the sx260. On really bright days, or with the sun in the frame, it's nice to extend that with an ND filter. The SX50 and SX260 both have undocumented ND filters that CHDK can control.

Yes, this was a test and I would never do this unless I was testing. I need to test some more so I can find the precise density of the filter and change the exposure by this amount when I set the filter in or out. That's on my to do list, but I'm worried that it will be noticeable. We'll see.

I've found that varying ISO is very precise and works great. Varying the shutter time isn't as precise, and at really fast shutter speeds, the exposure overshoots or undershoots what it's supposed to be. The next shot may sense this and over-correct the other way, leading to "fluttering" of exposure in the time lapse. The ND filter may help keep the shutter times longer to avoid this fluttering. The SX50 has this problem worse than the G1X. The SX260 doesn't seem to have the problem.
Title: Re: Shot Histogram Request
Post by: lapser on 22 / August / 2013, 16:34:35
I found the Canon D20 at Costco for $249, which is $40 less than the current Amazon price, so I couldn't resist. It seems to be a pretty good camera. My time lapse mods worked on nafraf's new port, so I was able to take my first time lapse with the D20 last night on Spencer's Butte.

Something was off in the first few pictures. The exposure was flashing up and down almost 1 fstop until my smoothing routine kicked in after 5 pictures. I'll have to check that out. But the smoothing routine in the script is designed to smooth that kind of variation out, and it worked great.

One thing I like about the camera for sunsets is that the lens is very simple, contained entirely within the camera to make it waterproof. It's only 5X zoom, but I'm usually doing wide angle with time lapse anyway. The short, simple lens didn't show any lens reflections from the sun like all the other cameras. In the video, there's a small reflection right under the sun, but that's a building with a shiny roof, not a lens reflection.

Here's the D20 time lapse video, complete with a group of people walking in front of the camera:

http://www.youtube.com/watch?v=3dGj4CRDeqw# (http://www.youtube.com/watch?v=3dGj4CRDeqw#)
Title: Re: Shot Histogram Request
Post by: ahull on 23 / August / 2013, 17:42:07
 :D   The first thing that has made me smile after a particularly hard day. 
        By the way lapser, what is the music?
Title: Re: Shot Histogram Request
Post by: lapser on 23 / August / 2013, 18:53:37
        By the way lapser, what is the music?
Here's the music link:
http://www.jamendo.com/en/track/709234/demande-au-ciel (http://www.jamendo.com/en/track/709234/demande-au-ciel)

I just used the first minute of the song. The rest of it is very pretty too.

I'm pretty excited about using the D20 for time lapses. Since it's waterproof, I should be able to use it in storms. We had some really nasty thunderstorms with hail and lightning on the Hand Lake backpacking trip, but I was too chicken to leave the G1X out in it, even wrapped in plastic film.
Title: Continuous vs Single Shot mode discoveries
Post by: lapser on 24 / August / 2013, 12:36:17
I tried the D20 with an overnight time lapse powered by an external, A/C supply (Chinese cheapo). The power kept cutting off for some reason. The connectors all seemed OK, so maybe the voltage regulation or filtering in the power supply is bad, or the D20 is more sensitive to power fluctuations. Anyway, I found out some interesting things about the camera.

In continuous mode, all the pictures taken by the time lapse script are LOST if the external power suddenly shuts off while the script is running. In single shot mode, only the last picture is lost. This happened on the D20 and the SX260. I haven't tested it on the G1X, but I'm sure glad my G1X external battery lasted the whole night on my backpack trips!

With fast shutter speeds, you can take pictures at almost 2 shots per second in continuous on the SX260. In single shot, it drops to a little slower than 1 shot per second. So I set up my overnight time lapse with a 2 second interval, and put it in single shot to avoid losing all the pictures if the power failed.

The power did fail after about an hour, but I had all the pictures until that point. However, single shot isn't as good for two reasons:

1: In single shot, the screen doesn't display the pictures as they come in. The screen is blank during a long exposure, so you can't see the log data, except briefly in between pictures. In continuous mode, the last picture, and log data is on the screen until it is replaced by the next picture. This makes it easier to see what's happening.

2. In single shot, the time in between pictures is about 1000 msec PLUS the shutter time. At night, the shutter time frequently exceeds the interval time, so the camera is taking pictures as fast as possible. So in single shot, there is a 1000 msec gap between exposures at night.

In continuous mode, the time between pictures is about 300 msec PLUS the shutter time. So there is only a 300 msec gap between pictures. This should make for smoother video or star trails, and you'll catch more meteors.

But if you're using continuous mode, it's important to make sure the battery doesn't shut down or you'll lose all the pictures. I think the script could do a release shoot_full_only and then hold it down again every so often. That should save all the pictures taken up until that point. Doing this every 30 minutes or hour would insure against the total catastrophe of losing all the pictures (that happened to me with the SX260 during the Perseid meteor shower).

I'm a little disappointed that the D20 didn't run all night on A/C external power. I'll try it with one of my big, external batteries after I solder up a cable for it. The D20 and the SX260 use nominal 3.7 volt batteries, but they run fine on USB power at 5 volts. A fully charged battery puts out about a volt more than its nominal voltage anyway, so the camera can easily handle this variation.

I set up the D20 behind my house last night pointed at the sky. I let the ISO go to 1600, and the shutter time up to 30 seconds. The shutter time only reached 25 seconds, so the exposure is pretty bright. I processed the pictures somewhat with Videomach, but Lightroom would do better. I tacked the orginal video on at the end.

http://www.youtube.com/watch?v=BjuEt1jnUng# (http://www.youtube.com/watch?v=BjuEt1jnUng#)
Title: New display off function
Post by: lapser on 25 / August / 2013, 13:46:01
Reyalp figured out a way to keep the screen display off without flashing. I added it to the script and tried it out last night. It worked great, and it was so nice not to have the camera screen on or flashing after it got dark. For more info, see this post:

http://chdk.setepontos.com/index.php?topic=10551.msg104446#msg104446 (http://chdk.setepontos.com/index.php?topic=10551.msg104446#msg104446)

Here's the two time lapses I made from last night's sunset and ISS flyover, and a cropped picture of the ISS:

http://www.youtube.com/watch?v=LstH_s4DBPk# (http://www.youtube.com/watch?v=LstH_s4DBPk#)

http://www.youtube.com/watch?v=dDqJpYiC4IU# (http://www.youtube.com/watch?v=dDqJpYiC4IU#)
Title: Re: Shot Histogram Request
Post by: lapser on 26 / August / 2013, 03:34:09
I tried out the Canon D20 for a rainy sunset on Skinner Butte, overlooking Eugene, OR. The camera takes pretty good pictures, and the time lapse looks smooth.

The D20 only has an ND filter, which is used as aperture. There's no aperture priority mode, only P mode, so I'll need to set an aperture with the script to make sure I don't have the ND filter in. I'll have to experiment with the camera a little here.

Philmoz recently improved the set_av96(n) function so it picks the nearest valid Canon aperture, rather than ignoring the call if you don't happen to pick a valid value. I wonder if this means I could set an aperture value of 1 (av96 equivalent) and end up with the widest possible (i.e. ND filter out). It's probably best to set aperture on this camera rather than try to control the ND filter directly.

I also discovered that the D20 doesn't work with my focusing routine. The other cameras have to be in manual focus mode for set_focus(d) to work. But the D20 crashes when you try to do this. I'll have to check this out more too. Fortunately, my script has an option to let the camera do its own focusing. So I can manually focus the camera before starting the script, and the script will hold this focus point. It worked for this time lapse.

Here's the time lapse:

http://www.youtube.com/watch?v=gUSApNkYRFA# (http://www.youtube.com/watch?v=gUSApNkYRFA#)
Title: Re: Shot Histogram Request
Post by: reyalp on 26 / August / 2013, 16:29:08
Philmoz recently improved the set_av96(n) function so it picks the nearest valid Canon aperture, rather than ignoring the call if you don't happen to pick a valid value. I wonder if this means I could set an aperture value of 1 (av96 equivalent) and end up with the widest possible (i.e. ND filter out). It's probably best to set aperture on this camera rather than try to control the ND filter directly.
In general, the aperture propcases do not control the ND filter (there may be some exceptions). You should use set_nd_filter for that.

Since d20 has CAM_HAS_IRIS_DIAPHRAGM is undefined, the set_av* functions should be NOOP.

Some further discussion of ND control http://chdk.setepontos.com/index.php?topic=10432.0 (http://chdk.setepontos.com/index.php?topic=10432.0)
Title: Re: Shot Histogram Request
Post by: straessi on 28 / August / 2013, 14:07:18
I finally was able to get my G1X (101a) running with the TLapse script. Great work, thanks a lot! I compiled the latest trunk 3034 (CHDK v1.3) after applying "shot_histogram.patch" and "backlight_off.patch", which I found as attachments in this forum thread. Not quite sure if that is the way to get to the most recent version. Let me know if there is a better way.

It works quite smooth, but there is one thing that I couldn't figure out so far. When it gets dark the exposure changes up and down quite fast, which results to massive flickering. I tried different metering placements but it doesn't really help.
I'm still trying to figure out what is causing that. My first guess is that it happens when max. shutter time is reached (after ISO is also at the maximum). But I have to confirm that... What happens in that case? It just stays there until it gets brighter again?

I have a few questions for debugging:
I have read the previous posts about glitch and smoothing parameters, but I'm not quite sure if I got it correctly. So let me try and explain what they are doing and I would be happy to know if that is correct.

Glitch: The glitch parameter is the maximum exposure difference to the previous picture in order to change exposure normally for the next picture. If that limit is overstepped it takes two shots. The second one with the same exposure as the picture before the glitch happend. So the higher this parameter is set, the more exposure difference is needed to detect a glitch and take a second picture.
What happens if this Parameter is set to 0? Is this function then deactivated?

Smoothing: Defines the maximum exposure difference allowed for the next picture. So the smaller the number, the slower the exposure will adjust, if it for example gets bright suddenly and it should be smoother.

Last question is about the log file. Everything is clear until the shots are taken. For every shot there are 9 parameters written on a line. This must be the code line that forms this string:

sp=string.format("%d %d %d %d %2d %2d %d %s %-6d",
    get_shot_data(2),get_shot_data(3),get_shot_data(6),
    sv96_to_iso(sv+svdiff),tvd0,tvd,get_vbatt(),seconds(tv),ptime)

I don't understand these parameters (well except the obvious ones... like the battery voltage). Could you briefly tell me what they represent?

Thanks for the help. I know that these questions can be answered by looking at the code, but it takes me ages and I want to get some time lapses :)

Cheers Daniel
Title: Re: Shot Histogram Request
Post by: lapser on 28 / August / 2013, 14:40:15
I added a new Lua function  to my CHDK mods that turns off all CHDK screen displays at once, including the OSD, console, and also the <ALT>  line at the bottom. The new function sets a flag that is read in main.c, which then skips gui_redraw(). Also, the current main.c (core_spy_task) skips gui_redraw() while taking a picture, unless the picture review is active. This assumes the screen is dark, but this is only true in single shot mode. In continuous mode, the last picture is displayed while taking the next picture. So I added a test to always do gui_redraw() except in single shot mode.

It works really well on all my cameras. The nice thing is that as soon as you reset the flag, the OSD and console appear fully updated. That is, whatever you wrote to the console while the OSD was off comes back when you turn it on again. I suppose you could also use the flag outside a script to get rid of the screen clutter temporarily.  I can post a separate .diff of the changes if anyone is interested.
=====
I also added reyalp's new method of turning off the display using eventprocs to my script. It worked great last night on 3 of my cameras. On the SX260, it turns off the display, but the camera turns it back on when it displays the next picture, just like set_backlight(0).

Finally, I added the <ALT> button script exit mod, which frees up the shoot_full button for script use. It works really well on all my cameras, is very easy to use, and only takes a few lines of code. I think it's a major improvement to CHDK, but there's a lot of inertia to keep things working the way they always have, so it doesn't look like it will make it into the trunk. Again, I can post a .diff if anyone is interested in using it in their own, custom version of CHDK.

I have two good tripods with really solid heads, and a 3rd cheapo tripod. I wanted to test the D20 zoom, so I set it up on the cheapo. I was playing with the new display on/off and OSD on/off in my script, which requires pressing camera buttons. The D20 shook a little every time I did this, because of the 5X (maximum) zoom, and cheap tripod. I didn't see any shake with the other two cameras, but they were zoomed out. I'll have to use the display on/off feature sparingly. I tried the anti-shake thing in YouTube, which zoomed the picture a little, and didn't work well after it got dark because of the motion blur in the original. It's pretty distracting in a time lapse, but might be useful as a last resort.

http://www.youtube.com/watch?v=beKZsxYiI8A# (http://www.youtube.com/watch?v=beKZsxYiI8A#)

http://www.youtube.com/watch?v=aAPbRlsh3ys# (http://www.youtube.com/watch?v=aAPbRlsh3ys#)

http://www.youtube.com/watch?v=be_T_DyWWLg# (http://www.youtube.com/watch?v=be_T_DyWWLg#)
Title: Re: Shot Histogram Request
Post by: lapser on 28 / August / 2013, 16:04:28
Not quite sure if that is the way to get to the most recent version. Let me know if there is a better way.
I'll attach the custom build and latest script so you know you've got exactly what I have.
Quote
When it gets dark the exposure changes up and down quite fast, which results to massive flickering.
That sounds like a problem with your build. It happens when the meter calculation is off. If you still have the problem with the attached build, it could be that the port for the G1X 101a isn't switching raw buffers properly. To check this, you could try saving two CHDK raw (dng) files, and see if they are different.
-------
Here's how smoothing and glitch work:

I spent months testing and improving the smoothing routine. I think it's about as perfect as it can be. To understand how it works, I'll use an analogy.

Imagine you are driving down a road. The smoothing parameter is the width of the road (+-32 ev96). If you are within 2 ev96 of the center of the road, the script doesn't change exposure. If you are on the road, but more than 2 from the center, the script will move you 1 ev96 towards the center every few shots (faster if you're moving away from the center). But if you start to go off the edge of the road (32ev96), the script always moves you back to the edge, so you never go off the road. So you will turn very slowly until you get to the edge of the road, then yank the wheel as hard as necessary to stay on the road.

I've found this technique eliminates small oscillations in exposure caused by small inaccuracies in the desired shutter time. You say increase the shutter by 1 ev96, but it actually increases by 1.5 ev96, for example. The next shot is off the other direction and tells you to decrease by 1 ev96. It shows up as "fluttering" in the dark areas of the picture. The smoothing technique makes sure you only change exposure in 1 direction, so it eliminates the problem nicely.

The glitch parameter is much simpler than you're describing. A value of 0 is disabled (script converts it to 999999). This should probably be the default. The first measurement that is more than the glitch value is ignored. The next 5 values are assumed not to be glitches.

I take a lot of my time lapses near a road, with cars going by at night. Glitch prevents the bright, headlight flash in 1 picture from messing up the exposure of the next picture. A lightning flash would do the same thing. If you know you're not going to have sudden exposure changes,  set glitch=32 (or try other values). If you're expecting sudden changes, like in a moving car, set glitch=0.

Here's is the code in shot_histogram.c that defines the get_shot_data(n) results depending on n:
Code: [Select]
enum
{
  SHOT_COUNT=0, //1
  EXP_COUNT,    //2
  PRE_DELAY,    //3
  INTERVAL,     //4
 
  HISTO,        //5
  SCRIPT_DELAY, //6
  SHUTTER_TO_RAW, //7
 
  TICK_SHUTTER_READY, //8 tick at start of pre shot delay
  TICK_SHUTTER_OPEN, //9 tick at end of pre shot delay
 
  SHOT_TV96,    //10
  SHOT_AV96,    //11
  SHOT_SV96,    //12
  SHOT_ND,      //13
 
  SHOT_METERS,  //14 meter 1
  //4 METERS HERE //15 16 17 meter 2,3,4
  NUM_SHOT_DATA=SHOT_METERS+NMETERS,
};
Quote
Last question is about the log file.
Here's a log file I posted somewhere back in this thread that shows what the numbers mean. I should probably print them in every log.
Exposure # is the number of the image file, i.e. IMG_nnnn

pre-shot delay is the time waiting to take the next shot, which is always < the interval time. If it's negative, it shows that you missed the interval, and the camera isn't keeping up with the desired shot rate. This is usually because the shutter time is getting longer than the desired interval, but occasionally writing the log file is slow. I can handle 1 slow log write, but two in a row sometimes overwhelms the buffers and you miss the shot interval for 1 shot. This was another several months of testing to get the timing to work.
Code: [Select]
Sat Mar 30 19:50:19 2013
platform:  g1x 100g
version:  CHDK 1.2.0-2619  built on  Mar 28 2013 18:03:42
30 =t tvmin= -470 10 =m n= 1 ev= 0
1 0 0 100 57
Focus 2787
Result 2762
false =single  Drive mode= 1
Press <MENU> to exit

[EDIT]
1 shot per second, ISO 100 to 1600, 30 sec max shutter time
Meter set to top 57% of raw image, focus at hyperfocal distance

exposure #, pre-shot delay, script time to set exposure, ISO Market,
   unsmoothed EV96 change, smoothed change, battery voltage, shutter time,
   log print time

769 0 0 100 106 106 8103 1/3.41 0
770 0 30 100 -5 -1 8123 1/3.38 10
771 360 20 100 -6 -1 8103 1/3.36 30
772 370 20 100 -7 -1 8123 1/3.33 10
773 370 20 100 -6 -1 8103 1/3.31 10
774 370 20 100 -6 -1 8113 1/3.29 10
775 360 30 100 -7 -1 8103 1/3.26 20
776 370 30 100 -4 -1 8093 1/3.24 20
777 370 20 100 -5 -1 8103 1/3.22 10
778 360 20 100 -5 -1 8103 1/3.19 10
779 370 20 100 -4 -1 8093 1/3.17 10
780 360 20 100 -3 -1 8064 1/3.15 340
781 370 20 100 -4 -1 8093 1/3.12 290
782 350 20 100 -1  0 8103 1/3.12 10
783 360 20 100 -2  0 8113 1/3.12 10
784 360 20 100 -3 -1 8093 1/3.10 10
785 360 20 100 -3 -1 8093 1/3.08 10
786 360 20 100 -3 -1 8103 1/3.06 10
787 360 20 100 -1  0 8093 1/3.06 10
788 350 20 100 -1  0 8084 1/3.06 200
789 350 20 100 -1  0 8103 1/3.06 260
790 350 20 100 -2  0 8093 1/3.06 10
791 350 20 100 -2  0 8093 1/3.06 10
792 350 20 100 -2  0 8103 1/3.06 10
793 350 20 100 -2  0 8093 1/3.06 10
794 350 20 100 -2  0 8093 1/3.06 10
795 350 20 100 -3 -1 8084 1/3.04 20
796 350 20 100 -3 -1 8084 1/3.01 430
797 350 20 100 -4 -1 8093 1/2.99 200
798 350 20 100 -1  0 8093 1/2.99 10
799 340 30 100 -2  0 8093 1/2.99 10
800 340 20 100 -3 -1 8103 1/2.97 10

... snipped to fit in post...

2454 -28680 20 1602 -33 -17 7663 29.7 10
2455 -28680 20 1602 -38 -22 7683 29.7 10
2456 -28680 20 1602 -43 -27 7653 29.7 200
Menu Key Pressed
2457 -28670 20 1602 -47 -31 7653 29.7 10
*** FINISHED ***
When you reach the maximum shutter time and ISO, the exposure setting holds there. You can see this at the end of the log above, where the ISO is stuck at 1602, and the shutter is 29.7, which corresponds to the input parameters of 1600 ISO and 30 seconds max shutter.

Incidentally, on the G1X, using a shutter time of 1/4000 doesn't give consistent exposure between pictures, even without CHDK. It's best to limit it to 1/3200 or less. Using the ND filter is on my to do list, which should help with this problem.

The new script has added functions for the <set> <left>, <right>, and <up> keys. Try them while the script is taking pictures to see what they do. Also, you should exit with <menu>, not abort with <ALT>.
Title: Re: Shot Histogram Request
Post by: straessi on 29 / August / 2013, 10:14:52
Thanks, especially for the nice explanations. That helps a lot!
I will do some testing and report how it goes.
Title: Re: Shot Histogram Request
Post by: lapser on 29 / August / 2013, 17:40:09
Thanks, especially for the nice explanations. That helps a lot!
I will do some testing and report how it goes.
Thanks for your interest, and I hope you get it to work for you.

By the way, if you press the <display> key while the script is running, it toggles the ND filter in or out. It changes the exposure for the next shot, but then the script corrects for it. However, I haven't adjusted for the Bv96 change yet, so the script thinks it's suddenly darker out, and lowers the exposure. It's a work in progress, but it's interesting to try out.

I did a short time lapse on Spencer's Butte last night. Clouds blocked the sun, but the time lapse was still interesting. I tested out my new wide angle lens attachment for the G1X, and did some panning and zooming with my video edit program to make it more interesting.

http://www.youtube.com/watch?v=wcI_jIY69yI# (http://www.youtube.com/watch?v=wcI_jIY69yI#)
Title: Re: Shot Histogram Request
Post by: lapser on 30 / August / 2013, 04:09:44
The sun was streaming through small holes in moving dark clouds in this sunset time lapse video. The meter I had on the sky averaged everything out and ended up blowing out the small bright spots. This would be a good time to use a histogram based exposure compensation function, which I plan to add soon.

http://www.youtube.com/watch?v=kc2CeWEkRuc# (http://www.youtube.com/watch?v=kc2CeWEkRuc#)
Title: Re: Shot Histogram Request - ND Filter Tests
Post by: lapser on 30 / August / 2013, 16:43:50
In general, the aperture propcases do not control the ND filter (there may be some exceptions). You should use set_nd_filter for that.

Since d20 has CAM_HAS_IRIS_DIAPHRAGM is undefined, the set_av* functions should be NOOP.

Some further discussion of ND control http://chdk.setepontos.com/index.php?topic=10432.0 (http://chdk.setepontos.com/index.php?topic=10432.0)
Thanks for that info. Do you know an easy way to read the status of the ND filter when the script starts?

My script toggles the ND filter state when you press <display> during a time lapse. I don't include the ND filter in my Bv calculation because I need the density. But I just realized that I can set my smoothing parameters to 0 and accurately measure the density with my current script.

The ND density I get with the SX260 is 312 EV96, or 3.25 f-stops. That's using my post shot meters from the raw buffers while taking pictures of my favorite blank wall. Has anyone else measured it using the camera meter? I think you could take two pictures (or two half-shoots) in Av mode with fixed ISO and compare the get_tv96() values with ND in and ND out.

I'll try measuring ND density with the rest of my cameras. I'm hoping it will be 3.25 for all of them.
Title: Re: Shot Histogram Request - ND Filter Tests
Post by: reyalp on 30 / August / 2013, 16:53:24
Thanks for that info. Do you know an easy way to read the status of the ND filter when the script starts?
edit: fixed quote.
I don't know about easy, but that's the subject discussed in the thread I linked.

Quote
The ND density I get with the SX260 is 312 EV96, or 3.25 f-stops. That's using my post shot meters from the raw buffers while taking pictures of my favorite blank wall. Has anyone else measured it using the camera meter? I think you could take two pictures (or two half-shoots) in Av mode with fixed ISO and compare the get_tv96() values with ND in and ND out.
For cameras without an iris, these are normally determined from propcase values and entered in platform/<camera>shooting.c aperture_sizes_table. See http://trac.assembla.com/chdk/browser/trunk/platform/d10/shooting.c (http://trac.assembla.com/chdk/browser/trunk/platform/d10/shooting.c) for example.

I'm not sure how it is with cameras that have both, the values aren't recorded in aperture_sizes_table, but I would expect there is still a propcase somewhere that reflects the nd+aperture value.
Title: Re: Shot Histogram Request
Post by: straessi on 01 / September / 2013, 13:10:07
I still have the flickering issue. I uploaded a time lapse to show the problem... The log file is also attached.

Marsai Mara Time Laps - CHDK time lapse flickering issue (http://www.youtube.com/watch?v=G3wtMe1UFZ0#)

Is there a way to see if the ND filter was in or out from the EXIF data of a photo?
Title: Re: Shot Histogram Request
Post by: reyalp on 01 / September / 2013, 14:19:45
Is there a way to see if the ND filter was in or out from the EXIF data of a photo?
I'm not sure how this works on cameras that have both an ND and an adjustable filter, but I would expected it to be recorded somehow if the Canon firmware selected. Some digging with exiftool would probably clarify things. I'd take test shots where you know the ND is in or out and then compare the output.
Title: Re: Shot Histogram Request
Post by: lapser on 01 / September / 2013, 14:39:00
I still have the flickering issue. I uploaded a time lapse to show the problem... The log file is also attached.
Is there a way to see if the ND filter was in or out from the EXIF data of a photo?
It looks like everything worked great until you got to IMG_1704. This image was 2 f-stops brighter than IMG_1703. Will you look at those 2 pictures and confirm that the second one is a lot brighter than the first?

As the cows walked in front of the sun, the meter reading changed by 1 f-stop. The script handled that ok, and you'll notice that the ground in front of the cows briefly gets brighter while the cows block the sun.

However, the sudden 2 f-stop change is what messed things up. Specifically, the bvdelta parameter is designed to gradually underexpose the images as it gets darker. But it doesn't take into account the ND filter. So if the ND filter suddenly went in, the script would think it got suddenly darker.

Anyway, the flickering would be explained if you pressed the <display> key right before IMG_1704, and the ND filter is about 2 f-stops. Did you press display?

I'm not sure if the ND filter state is in the EXIF. I don't think so, at least when it's set from a script or CHDK menu. But from the shutter speed while the sun was in the frame, it looks like the ND filter was IN when you started. Maybe you pressed <display> after it got dark? That won't quite work yet, but I'll add ND filter control soon.

Thanks for doing the video. Other than the end, it's a great time lapse!
Title: Re: Shot Histogram Request
Post by: waterwingz on 01 / September / 2013, 15:06:28
I'm not sure if the ND filter state is in the EXIF. I don't think so, at least when it's set from a script or CHDK menu.
I've tested it and can confirm that the EXIF will indicate if Canon firmware used (or wanted to use) the ND filter.  CHDK override of ND filter does not get recorded in the EXIF.
Title: Re: Shot Histogram Request
Post by: lapser on 01 / September / 2013, 16:39:48
I've tested it and can confirm that the EXIF will indicate if Canon firmware used (or wanted to use) the ND filter.  CHDK override of ND filter does not get recorded in the EXIF.
Thanks, that's nice to know.

I wonder if there's a propcase that indicates the ND filter state for writing to the Exif, similar to the extra tv96 propcase. In other words, is there a way that we could get the nd filter state to appear in the EXIF when set by CHDK?
Title: Re: Shot Histogram Request
Post by: straessi on 02 / September / 2013, 15:49:41
It looks like everything worked great until you got to IMG_1704. This image was 2 f-stops brighter than IMG_1703. Will you look at those 2 pictures and confirm that the second one is a lot brighter than the first?

I attached the two pictures. I would say they are about the same brightness. Things mess up with IMG_1706, which is darker (and the ISO drops from 400 to 320 for this picture only) and IMG_1707 is way brighter.

I just noticed that the EXIF data of the pictures and the log file data is always shifted by one picture. So in reality IMG_1706 is the one where the ISO drops to 320 for only one picture, but the log file tells its IMG_1705.
To get back to your question about IMG_1703 and IMG_1704... if that is also shifted by one picture, it doesn't make a difference, because IMG_1705 is about the same brightness as the two previous pictures.

Anyway, the flickering would be explained if you pressed the <display> key right before IMG_1704, and the ND filter is about 2 f-stops. Did you press display?

I was not quite sure, so I did an other test today and made sure not to touch anything this time and I had the same issue of flickering. As soon as it gets dark the exposure jumps around like crazy.

By the way, should the display go completely dark when pressing the <SET> button? It doesn't seem to make a change when I press it. The image is flashes up every time the camera takes a picture.
I can toggle the information string by pressing the <UP> button and the <RIGHT> button toggles the displaying of the meters. But the <LEFT> and the <DOWN> button don't seem to make a change.

I'm still experimenting with the build and script you attached for me...
Title: Re: Shot Histogram Request
Post by: lapser on 02 / September / 2013, 19:44:37
I attached the two pictures. I would say they are about the same brightness. Things mess up with IMG_1706, which is darker (and the ISO drops from 400 to 320 for this picture only) and IMG_1707 is way brighter.
Thanks a lot for all the testing. I noticed that the trouble started right after the shutter time reached 1 second. That's 0 tv96 units. Over 1 second is negative tv96, and under is positive. So the problem shows up when going from positive to negative tv96 and vice versa. Here's the relevant part of your log file:
Code: [Select]
1700 650 60 401 -33 -1 7595 1/1.022 10   
1701 710 50 401 -34 -2 7614 1/1.007 10   
1702 660 60 401 -33 -1 7585 1.000 10   
1703 650 60 401 -34 -2 7585 1.015 10     first picture over 1 second shutter time (tv96<0)
1704 680 50 401 165  0 7595 1.015 10    glitch detector prevented exposure change
1705 680 60 313 164 132 7585 1/2.00 10    glitch detector off for next 5 shots
1706 710 50 401 -239 -207 7605 1.744 10    tv96 going from positive to negative
1707 1090 50 401 185 153 7585 1/1.731 10   
1708 -20 50 401 -195 -163 7585 1.874 10   
The log prints the calculated exposure change measured from the current shot, which is then applied to the next shot after smoothing and glitch detection. The problem is that the picture taken with 1.015 second shutter time was much brighter than the picture taken with 1.000 shutter time. My get_shot_meter() function could be measuring wrong, but I don't have the measurements in the log data. I'll attach a new script and build which might help me figure out what happened, if you can get it to happen again.

I also noticed you're using exposure compensation. It looks like the exposure may be off by about that amount. Try running the test with it set to 0 and see if that makes a difference.

I would like to see the logs from any other times it happened to see if they also show it starting at 1 second shutter time.

I doesn't look like the ND filter had anything to do with it. The "display" key is what controls the ND filter while the script is taking pictures, not the <left> key as I said previously. I corrected it in the post.

The <set> key turns the screen off and on. I just finished a new version that keeps it off without flashing. Also, the <left> key should now toggle the CHDK OSD and console displays, so all you see is the picture. Up toggles the data line on top, and right toggles the meter area display. The active meter is green. If you want it to be red, press <set> while you're setting up the meters, then <menu> to start taking pictures.
Title: Re: Shot Histogram Request
Post by: straessi on 03 / September / 2013, 11:07:35
I also noticed you're using exposure compensation. It looks like the exposure may be off by about that amount. Try running the test with it set to 0 and see if that makes a difference.
Okay, I'm currently capturing a new time lapse. By the way, what settings do you use on the camera? Which mode do you choose? Maybe I'm just setting it up wrongly. I'm currently using Av mode, because I can choose the aperture and that is probably one of the only things that the script doesn't override.

I would like to see the logs from any other times it happened to see if they also show it starting at 1 second shutter time.
Here you go... It is just as you expected, it messes up after it reaches a shutter time of 1 sec.
Code: [Select]
3605 -280 50 600 -34 -2 7174 1/1.106 10   
3606 -310 50 600 -32  0 7184 1/1.106 10   
3607 -340 60 600 -35 -3 7184 1/1.083 10   
3608 -310 60 600 -33 -1 7194 1/1.075 10   
3609 -360 60 600 -35 -3 7174 1/1.052 10   
3610 -340 50 600 -33 -1 7184 1/1.044 10   
3611 -380 60 600 -35 -3 7184 1/1.022 10   
3612 -390 60 600 -33 -1 7184 1/1.015 10   
3613 -410 60 600 -32  0 7184 1/1.015 10   
3614 -440 60 600 -34 -2 7184 1.000 360   
3615 -420 60 600 -36 -4 7184 1.029 10   
3616 -440 60 600 146  0 7184 1.029 10   
3617 -430 50 542 146 114 7194 1/2.00 10   
3618 -370 50 600 -233 -201 7174 1.929 0     
3619 40 60 600 170 138 7194 1/1.404 10   
3620 -1290 50 600 -174 -142 7184 1.986 10   
3621 -180 60 600 171 139 7174 1/1.374 10   
3622 -1330 60 600 -176  0 7174 1/1.374 10   
3623 -110 50 600 -177 -145 7184 2.07 10   
3624 -170 50 600 172 140 7174 1/1.325 10   
3625 -1420 50 600 -181 -149 7174 2.21 80   
3626 -190 50 600 174 142 7174 1/1.260 10   
3627 -1590 60 600 -176 -144 7174 2.24 10   
3628 -240 50 600 174  0 7174 2.24 10   
3629 -1690 50 600 174 142 7194 1/1.242 80   
3630 -1620 50 600 -188 -156 7174 2.48 10   
3631 -260 60 600 177 145 7174 1/1.147 10   
3632 -1880 50 600 -182 -150 7174 2.57 10
The <set> key turns the screen off and on. I just finished a new version that keeps it off without flashing. Also, the <left> key should now toggle the CHDK OSD and console displays, so all you see is the picture. Up toggles the data line on top, and right toggles the meter area display. The active meter is green. If you want it to be red, press <set> while you're setting up the meters, then <menu> to start taking pictures.
Thanks. I found out why my display didn't blank completely... I still had a 2 sec review in the original canon menu settings. It seems like chdk doesn't override that :)
Title: Re: Shot Histogram Request
Post by: straessi on 03 / September / 2013, 12:12:45
Okay, I'm currently capturing a new time lapse.

The result is still the same... Attached is the log file. I saw that you added some information to the log.
Title: Re: Shot Histogram Request
Post by: lapser on 03 / September / 2013, 14:49:11
The result is still the same... Attached is the log file. I saw that you added some information to the log.
Thanks, that's very helpful. According to the log:

IMG_6282 has tv96=0 (1.000 sec) and the meter reading is normal
IMG_6283 has tv96=4 (1.029 sec) and the meter reading says it much brighter than IMG_6282

Will you check those two pictures for me and see if that's the case? If not, what was the first image that was suddenly much brighter.

6282 -360 60 400 -36 -4 7409 1.029 10   
_2 -327 -184 -294 -539 | -275 148 0 603
6283 -340 50 400 102  0 7409 1.029 10   
_2 -27 -14 -25 -33 | -109 116 -4 603

I checked the logs for my G1X, and I've had several times where I passed through 1 second shutter time without a problem. I also can't find an error in the script. So I'm thinking it may be a camera setting that you're using that I'm not. The camera does do different things starting at 1 second, including dark frames. I always set dark frames OFF in the CHDK menu.

Go through all the <set> menu Canon settings and make sure everything is OFF. Set the White Balance to cloudy. Make sure DR Correction and Shadow correct are OFF. Then go through the Canon record menu and set all that to off, including IS and whatever else you can set to off. Basically, you don't want the camera doing anything automatically. All the CHDK overrides should be OFF too. Just go through every menu you can get to and try to turn everything off. Also, it looks like your clock isn't set right, so it would help to set it to the correct date and time, unless it's actually October on your planet :)

Incidentally, you can set the max ISO for the G1X to 1600 and still get really good pictures. If you do that, the shutter time will stay under 1 second, and it won't trigger the bug (unless you keep going until it gets REALLY dark. But for testing, it would be nice to stick with 400 max, if you find a camera setting that may be the cause.

Good luck.
Title: Re: Shot Histogram Request
Post by: straessi on 03 / September / 2013, 16:17:46
IMG_6282 has tv96=0 (1.000 sec) and the meter reading is normal
IMG_6283 has tv96=4 (1.029 sec) and the meter reading says it much brighter than IMG_6282

Will you check those two pictures for me and see if that's the case? If not, what was the first image that was suddenly much brighter.

That is not the case IMG_6282 and IMG_6283 are about the same brightness. IMG_6283 even is slightly darker. The first image that is much brighter is IMG_6286.

Okay I will try to play around with the camera settings... when it is dark enough it starts flickering right away when I start the script, so it is quite well reproduce able the problem.

It seems to be quite systematic the brightness changes. I took a couple of photos when it was quite dark outside. And when I looked at the photos, I realized that it is always the same number of pics between the brightest pictures. So I stiched together only the brightest photos to see if they match... The result is attached.

Thanks for your great support. I will be away for a couple of days, but I will report if I found something new.
Title: Re: Shot Histogram Request
Post by: lapser on 04 / September / 2013, 18:33:51
IMG_6282 has tv96=0 (1.000 sec) and the meter reading is normal
IMG_6283 has tv96=4 (1.029 sec) and the meter reading says it much brighter than IMG_6282
Will you check those two pictures for me and see if that's the case? If not, what was the first image that was suddenly much brighter.
That is not the case IMG_6282 and IMG_6283 are about the same brightness. IMG_6283 even is slightly darker. The first image that is much brighter is IMG_6286.
Hmm, well the meter readings seem reasonable, just 2 EV brighter for all the meters. I'm reading the raw buffer, so if it got suddenly brighter but the jpg looked the same, it sounds like the camera is doing something automatically for negative tv96 (shutter time >1 second), then compensating for it when it makes the jpg.

I know Canon did some tricks to get lower noise at high ISO for the G1X. Maybe this is one of them. I recall a menu setting for Noise reduction at high ISO. I set it to "normal". See what you have it set to.

When I get some time, I'll try experimenting by taking pictures at tv96 of +1 and -1 and compare meter readings to see if I can get my camera to duplicate what you've discovered. If you get a chance, maybe you can set the camera to manual exposure mode, and set the shutter to 1 second. Find a relatively dark, constant lit scene (closet?), and pick an aperture and ISO so the exposure looks right.  Then set CHDK to save dng raw files, and take a picture with one notch (1/3 ev?) above 1 second and 1 below. Then, compare the 2 jpg and 2 dng files. I suspect the jpgp files will be similar, but the dng files will have much different brightness.

The regular oscillations in brightness come from the difference in meter readings over and under one second shutter time. Apparently, this difference is a constant.
Title: Re: Shot Histogram Request
Post by: lapser on 04 / September / 2013, 18:51:51
I caught a really pretty sunset last night with the G1X:
http://www.youtube.com/watch?v=utGA60nspfo# (http://www.youtube.com/watch?v=utGA60nspfo#)

I also set up the SX50 at the same spot, zoomed in on the paper mill with a 2nd meter just on the tower that lights up the brightest at night. This meter took over after dark and kept the right exposure for the tower. Usually, lighted buildings are overexposed in night shots. I had the tripod extension tube up, so touching the camera buttons caused some shaking with the high zoom setting.
http://www.youtube.com/watch?v=_kZqszU6FMQ# (http://www.youtube.com/watch?v=_kZqszU6FMQ#)

I tried out a wide angle lens attachment on the G1X. It clips the corners (extreme vignetting) unless you zoom in a little, which kind of defeats the purpose of the wide angle lens. So I left the clipped corners on the bottom and cropped the top so I could see the widest area of sky possible.  It's a pretty interesting effect.
http://www.youtube.com/watch?v=nQuEBx0vF7Q# (http://www.youtube.com/watch?v=nQuEBx0vF7Q#)

This uses the wide angle lens, but zoomed until the vignetting isn't obvious:
http://www.youtube.com/watch?v=K-Ri0xQf714# (http://www.youtube.com/watch?v=K-Ri0xQf714#)
Title: Re: Shot Histogram Request
Post by: lapser on 05 / September / 2013, 15:34:29
I'm really beginning to like the Canon D20 for sunsets. The simple lens has fewer lens reflection with the sun in the frame. I was able to crop the single lens reflection out of this video, except for a short time at the beginning. Pointing at the sun, the camera starts with the ND filter in, and it was able to expose the sun correctly so it's a circle instead of the usual blown out area.

Once I add ND filter control, I should be able to go smoothly to total darkness with stars showing using the D20. Here's a photo and the time lapse video I took last night from the top of Spencer's Butte with the D20.

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fphotos4.meetupstatic.com%2Fphotos%2Fevent%2Fd%2F4%2F3%2F2%2Fhighres_279714322.jpeg&hash=8b2a4a30bfc628667a80ee9261873528)

http://www.youtube.com/watch?v=jUAeO3LctT8# (http://www.youtube.com/watch?v=jUAeO3LctT8#)
Title: Re: Shot Histogram Request
Post by: lapser on 08 / September / 2013, 12:55:30
I've been trying out my time lapse script after dark lately. I used it to capture an Iridium flare the last two nights.

The first picture shows the Iridium flare I captured 2 nights ago with the G1X. It's a 5 second exposure at 1600 ISO. Unfortunately, the flare ended up split between two pictures. I stacked the pictures together but there's still a gap in the flare between shots.

So last night I set the maximum shutter time to 25 seconds and captured the entire flare in one shot. Then I noticed that there was another, dim "flare" about 2 minutes before the Iridium flare that only appeared in one frame. It must be another satellite that also caught the glint of the sun so it got a little brighter and became visible.
Title: Re: Shot Histogram Request
Post by: lapser on 08 / September / 2013, 16:24:16
@lukeiron

Attached is a custom CHDK build for your camera. You need to copy all the files in the zip, including the subfolders, onto your SD card, replacing the files that are there. The way I do it with Windows is: download zip, double click it, press ctrl+A ctrl+C, go to root of your SD card, press ctrl+V, choose overwrite all folders and files.

The new USBLapse.lua requires this CHDK custom build. I added a maximum interval parameter which takes over if the USB doesn't trigger (this is the time out). It defaults to -1, which is no time out.

The script should open the shutter within 10 msec of the time it gets the USB trigger. Let me know if you have problems, or get it working. Good luck!


Title: Re: Shot Histogram Request
Post by: lapser on 08 / September / 2013, 19:52:46
Okay I will try to play around with the camera settings... when it is dark enough it starts flickering right away when I start the script, so it is quite well reproduce able the problem.
One thing that you can do that would be a big help is to turn on CHDK raw saving in DNG format. Hopefully, you have a program that can display the DNG files. Before starting Tlapser, try setting bvDelta to 0. Then the flickering, if it still happens, is all from the incorrect meter readings. Look at the jpg and dng files with the same file number and see if they always have the same brightness. The dng file should be showing what my meter read its brightness from.

To test the 1 second shutter time theory, I wrote a script that takes pictures at tv96 of -1 and +1 (0 is 1 second). It prints out the meter readings for the 2 pictures, and the difference in meter readings. Try pointing the camera at a blank wall for the test. The difference in meter readings should be small. It's always small on my camera. If it's a large difference on your camera, we'll be one step closer to figuring out the cause.

Before running the test script, set the camera to Tv, shutter priority, mode with a shutter speed of 1 second. Leave all the other settings the same as the ones where it flickered. Hopefully, we can figure it out. Thanks.
Title: Re: Shot Histogram Request
Post by: straessi on 09 / September / 2013, 16:07:52
Before starting Tlapser, try setting bvDelta to 0. Then the flickering, if it still happens, is all from the incorrect meter readings.

The flickering is gone when I set bvDelta to 0. What does that mean?
Thanks for the testing script, I will try looking at the DNG raw files.
Title: Re: Shot Histogram Request
Post by: lapser on 09 / September / 2013, 16:59:30
The flickering is gone when I set bvDelta to 0. What does that mean?
Thanks for the testing script, I will try looking at the DNG raw files.
OK, if it doesn't flutter, does it get brighter for 1 or 2 pictures, and then correct back to normal exposure? Seeing the log file would be useful. It should show a sudden increase in the meter reading when the shutter time gets above 1 second.

Also, I need to check the way I do the brightness correction. The idea is to underexpose as it gets darker, but I didn't consider what happens with sudden brightness changes.

It sounds like the new G1X 101A firmware may be keeping the ND filter  IN with shutter time <=1 second. It may be related to starting the script in Av mode. I've noticed that the 1/4000 shutter time is inaccurate. Two pictures taken in continuous mode don't always come out the same brightness. I was going to add ND filter control to my script to keep the shutter times lower to avoid this. Maybe Canon already did it.

A useful test would be to start in Manual exposure mode. The Aperture setting is used for the entire script, so set it to the minimum F-stop if you're going to continue after it gets dark. The shutter and ISO are set by the script, so they don't matter that much. If the initial settings are overexposed, it takes a few extra pictures for the script to get the right exposure.

Thanks again for all the testing.
Title: Re: Shot Histogram Request
Post by: lapser on 10 / September / 2013, 14:46:26
Quote from: lukeiron
  i tried but i can't reach a costant interval between shots.
My goal is to shot a picture exactly every 2 sec because i've to log on the Arduino parameters in synch with the pictures.
I send to the USB, for example, this square wave: t0=5V t1=0V t2=0V with t0=0ms, t1=100ms and t2=3000ms but the camera shots every 3200ms, 2500ms, 3300ms...
I reached quite good results with the standard "USB remote" but i hope to improve them with your script and fw.
CHDK has built in USB remote menu options, including synch delay. I haven't used it, but it may be able to do what you want without using my time lapse mods. Maybe @waterwingz can help you? I'm thinking a simple script that just holds the shutter down in continuous drive mode combined with the right CHDK usb remote menu options might work:
Code: [Select]
press("shoot_full")
repeat until false
I'm not sure why my script didn't trigger. I'm looking for a change in USB power from on to off. Maybe it's not off long enough for the script to detect it. Anyway, if it's detecting the USB trigger built into CHDK, then I can detect it as a key click in a script.

Here's the script modified to sync to key clicks. You can press any camera key to trigger a picture, or trigger it through USB (if it works). Press <menu> to exit. Also, I modified the script abort key in my CHDK build. You press the <ALT> key to abort a script, instead of the shutter button.

Code: [Select]
--[[
@title USBLapse 130910
@param m Max Interval (msec)
@default m -1
--]]
--MUST BE IN CONTINUOUS MODE
if(m<0)then m=1234567890 end -- 2 week interval default
set_shot_interval(m,0) --Maximum interval, no script handshake delays
nshot=1
print("Holding shoot_full")
print("Press <menu> to exit")
press("shoot_full") -- continuous mode
repeat
  wait_click(10)
  if(not is_key("no_key")) then
    set_shot_interval(-1) --takes one shot immediately with any key click or usb remote
  end
  if(get_shot_ready())then
    print(nshot,get_shot_data(4)) -- shot #, interval from last shot
    nshot=nshot+1
  end
until is_key("menu")

By the way, the interval using my set_shot_interval() function is very precise. If you want a 2 second interval, set the Max Interval parameter in the script to 2000. The script could then send a USB power output pulse to your board in between pictures, so you could pan the camera without messing up a shot, if that's what you're up to. In other words, instead of triggering the camera with the external board, you can trigger the board with the camera.

[edit] I just noticed that you asked about USBLapse.lua in another topic, where it started. Sorry for the confusion. We may as well keep it in this topic now. For reference, the initial USBLapse discussion topic is here:
http://chdk.setepontos.com/index.php?topic=9188.msg105038#msg105038 (http://chdk.setepontos.com/index.php?topic=9188.msg105038#msg105038)
Title: Re: Shot Histogram Request
Post by: lukeiron on 10 / September / 2013, 16:11:41
Trigger the board with the camera can be a very good idea!
I was close to ask to you the same thing :-)

But I'd like also to be able to start to shoot remotely, is it possible to use the USB for I/O at the same time?
Which is the command to send a pulse on the USB in output from the camera?

Thank you!
luca
Title: Re: Shot Histogram Request
Post by: straessi on 10 / September / 2013, 16:33:09
It looks like there is something wrong with the G1 X 101a firmware port.

First, I can't run your test script "Tv0test.lua" sucessfully. It prints *** STARTED *** on the LCD and takes one picture, but nothing happens afterwards.

Anyway, I had a look at the DNG files. There seems to be an issue there. Some of them look quite pink.
I uploaded some sample pictures (dng and jpeg files plus the log file).
https://dl.dropboxusercontent.com/u/55970719/Sample_raw_files.rar (https://dl.dropboxusercontent.com/u/55970719/Sample_raw_files.rar)

It is not quite true that the flickering is completely gone with bvDelta set to 0. I did a test and I still had some flickering just as the shutter time reached 1 second, but it was not so bad and disappeared again after a couple of oscillations. I placed all the data of that test in a rar file and uploaded it also.
https://dl.dropboxusercontent.com/u/55970719/20130910.rar (https://dl.dropboxusercontent.com/u/55970719/20130910.rar)

I guess I have to return my G1 X to the Canon Vendor and tell them CHDK is not working properly on it :)
Title: Re: Shot Histogram Request
Post by: lapser on 10 / September / 2013, 18:07:10
It looks like there is something wrong with the G1 X 101a firmware port.
I posted your reply over on the G1X porting thread. Hopefully, philmoz will figure it out. See this post for more info:

http://chdk.setepontos.com/index.php?topic=7934.msg105145#msg105145 (http://chdk.setepontos.com/index.php?topic=7934.msg105145#msg105145)
Title: Re: Shot Histogram Request
Post by: lapser on 10 / September / 2013, 18:22:04
Trigger the board with the camera can be a very good idea!
I was close to ask to you the same thing :-)

But I'd like also to be able to start to shoot remotely, is it possible to use the USB for I/O at the same time?
Which is the command to send a pulse on the USB in output from the camera?
http://chdk.wikia.com/wiki/Lua/PTP_Scripting#write_usb_msg (http://chdk.wikia.com/wiki/Lua/PTP_Scripting#write_usb_msg)
I haven't used the usb part of CHDK much, but yes you can write data to the usb port from Lua. Check out the above link.

I think the script could start taking pictures when your external computer turns on the USB power. The script could send a data pulse between pictures when it's safe to pan the camera.

Maybe your board is leaving the USB power on and sending data pulses, instead of turning the power off and back on. My initial script checked for the power going off, not the data.

reyalp is the expert on USB and CHDK, so maybe he can shed some light on this.
Title: Re: Shot Histogram Request
Post by: lukeiron on 10 / September / 2013, 18:46:03
The camera is connected to an Arduino board and so I just sending a +5V or 0V to the USB port, not serial data streaming.

Thank you for the link but I prefer just receive a 5+V or 0V instead of a real data streaming... it's easier to handle this with the arduino board.

I tried to use the script without the USB triggering and the timing is perfect.
I just need to receive on the USB a pulse to obtain the sync with the board.

 
Title: Re: Shot Histogram Request
Post by: lapser on 11 / September / 2013, 00:19:41
The camera is connected to an Arduino board and so I just sending a +5V or 0V to the USB port, not serial data streaming.

Thank you for the link but I prefer just receive a 5+V or 0V instead of a real data streaming... it's easier to handle this with the arduino board.

I tried to use the script without the USB triggering and the timing is perfect.
I just need to receive on the USB a pulse to obtain the sync with the board.
The USB connector has a data line, and a power line (red wire). Normally, the power line is always 5 volts. The power comes from the external computer, not the camera. The camera, and CHDK, can sense if the power is on, without any data being transmitted. I suspect that you're leaving the power on, and sending pulses over the data line. My original script looks for changes in the power line, not the data line, so it wouldn't be triggered. I think there's a way to shut the USB power off and on with the board, but I'm not sure how.

But I think the CHDK remote trigger can also sense a change in the data line, so it would work the way you're doing it, like you said. My modified script senses the CHDK remote, so it should trigger the way you're doing it. Did you try the new script? I didn't change the file name, but the I put the date in the script name at the bottom of the screen.

CHDK can only send data on the data lines, and can't change the power lines since the power is supplied by the computer (your board). But you wouldn't need to read the actual data with the Arduino, just sense when there WAS data. The script could just send a byte of garbage data between shots.

Title: Re: Shot Histogram Request
Post by: lapser on 11 / September / 2013, 02:07:28
I've been out taking time lapses a lot lately, while the weather is still good for a few more weeks. I noticed that 2 Iridium flares were coming up near my house, so I set up to photograph them. Here's the two time lapses I made with the flares in them. More info is in the descriptions on YouTube:

http://www.youtube.com/watch?v=Ap38PBGcSX8# (http://www.youtube.com/watch?v=Ap38PBGcSX8#)

http://www.youtube.com/watch?v=7NQ0ZSFHFK0# (http://www.youtube.com/watch?v=7NQ0ZSFHFK0#)

I set up the SX50 to watch the city get dark after sunset, while the G1X was watching the Iridium flare.
http://www.youtube.com/watch?v=dRnDoNcUDOY# (http://www.youtube.com/watch?v=dRnDoNcUDOY#)

Last night, I tried out the D20(wide) and the SX260(zoomed) on the same sunset. I really like the color changes. The D20 lasted a lot longer than the SX260.

http://www.youtube.com/watch?v=WGfDP9PMmbs# (http://www.youtube.com/watch?v=WGfDP9PMmbs#)

http://www.youtube.com/watch?v=iUZVhwvobuw# (http://www.youtube.com/watch?v=iUZVhwvobuw#)
Title: Re: Shot Histogram Request
Post by: lukeiron on 11 / September / 2013, 04:21:01
Quote
The USB connector has a data line, and a power line (red wire). Normally, the power line is always 5 volts. The power comes from the external computer, not the camera. The camera, and CHDK, can sense if the power is on, without any data being transmitted. I suspect that you're leaving the power on, and sending pulses over the data line. My original script looks for changes in the power line, not the data line, so it wouldn't be triggered. I think there's a way to shut the USB power off and on with the board, but I'm not sure how.

I've the data sheet of the cable and I connected the +5V from the Arduino board to the red wire.
Effectively with the standard remote triggering CHDK it works.

Another strange behavior is this: the camera is on (remote triggering OFF), I don't start the script, I connect the cable and the shutter start to open/close (without capture pictures).

I tried the new script, it works with the keys but not with USB.

Maybe we can try using the USB +5V just to start to take pictures every x second (without waiting for USB) and sending a byte of garbage on the data out after every shot. I'll try to read that signal from the Arduino.

Thanks

Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / September / 2013, 08:52:37
Another strange behavior is this: the camera is on (remote triggering OFF), I don't start the script, I connect the cable and the shutter start to open/close (without capture pictures).
Many Canon P&S cameras will switch to playback mode when USB power is applied if CHDK remote mode is disabled.  The lens will also retract if and extended retract delay has not been selected in the Canon menus.  Could this be what you are seeing?

I tried the new script, it works with the keys but not with USB.
Quote
Maybe we can try using the USB +5V just to start to take pictures every x second (without waiting for USB) and sending a byte of garbage on the data out after every shot. I'll try to read that signal from the Arduino.
I might be wrong but I suspect the CHDK USB commands for sending data messages will only work if a valid host / slave relationship has been negotiated between the camera and PC.
Title: Re: Shot Histogram Request
Post by: lukeiron on 11 / September / 2013, 09:13:57
Another strange behavior is this: the camera is on (remote triggering OFF), I don't start the script, I connect the cable and the shutter start to open/close (without capture pictures).

Many Canon P&S cameras will switch to playback mode when USB power is applied if CHDK remote mode is disabled.  The lens will also retract if and extended retract delay has not been selected in the Canon menus.  Could this be what you are seeing?

The camera doesn't retract the lens but can be something of similar... the screen switch continuously between black and the live view.
Quote
I tried the new script, it works with the keys but not with USB.

Maybe we can try using the USB +5V just to start to take pictures every x second (without waiting for USB) and sending a byte of garbage on the data out after every shot. I'll try to read that signal from the Arduino.

Quote
I might be wrong but I suspect the CHDK USB commands for sending data messages will only work if a valid host / slave relationship has been negotiated between the camera and PC.

I hope you're wrong but we've to try... :-)
Title: Re: Shot Histogram Request
Post by: lapser on 11 / September / 2013, 16:07:51
The camera doesn't retract the lens but can be something of similar... the screen switch continuously between black and the live view.
It does sound like it's taking pictures. If new pictures aren't appearing on the card, maybe it's a bug in the new remote capture feature that uses the filewrite hook?
Quote
I might be wrong but I suspect the CHDK USB commands for sending data messages will only work if a valid host / slave relationship has been negotiated between the camera and PC.
reyalp probably knows more about it. It seems like you should be able to output 1 byte to the usb port without a negotiated connection. After all, there has to be a way to negotiate a connection.

Maybe you should start a new topic, "Using Arduino with CHDK". Someone who has done it can probably help you better.
Title: Re: Shot Histogram Request
Post by: straessi on 12 / September / 2013, 10:18:25
@lapser: I also have a SX210 IS (100c). Could you attach a build for that camera, so I can try if I run into the same problems like with my G1 X?
That would be great. Thanks!
Title: Re: Shot Histogram Request
Post by: lapser on 13 / September / 2013, 14:03:28
@lapser: I also have a SX210 IS (100c). Could you attach a build for that camera, so I can try if I run into the same problems like with my G1 X?
That would be great. Thanks!
Will do. I'll have to test single shot mode in all my cameras too. Thanks for helping to find this problem. Here's the answer to the questions you brought up in the G1X thread:

Sorry, very stupid question... I figured it out. It's just the setting in the canon menu :)
But it's interesting: I've always shot time lapses in single shot mode. Now I tested in the continuous mode and it works perfectly.

So what is actually the difference between these two modes (except that you loose all pictures when you run out of power in continuous mode)?
90% of my questions are "stupid". And if I don't feel stupid after figuring something out, I probably haven't really figured it out.

I'm really glad you tested it in single shot mode, since I haven't used single shot very much. I tested the script on my G1X in single shot and it brings out the problem for me too!

There are no real advantages of single shot mode with my time lapse script, except the possibility of losing pictures with an external battery. The solution to that problem isn't to use single shot mode though. It's to stop the script when the external battery gets near its low voltage cutoff.

A script just simulates pushing the shutter button to take pictures. You push the shutter yourself, without a script, to see what happens.

In single shot mode, the script pushes the shutter all the way down, and lets it up half way between pictures.  The advantage of letting it up only half way is that the camera doesn't re-focus and measure exposure before each shot. All the pictures are taken with the same exposure as the first shot.

In continuous mode, the script holds the shutter all the way down for the entire time. The focus and exposure behavior is the same as single shot, but the shot rate is about twice as fast. In addition to the faster shot rate, the minimum time between shots is about .25 seconds in continuous mode, and .75 seconds in single shot. This is great for night shots, because you don't miss as many brief events, like meteors.

My CHDK build includes a shot meter function that measures the brightness of 4 different image areas after the shot, from the raw image when it's in memory. It's this raw image that was color shifted, and caused the bad meter readings and fluttering. The script uses the meter readings to set the exposure of the next shot, in 1/96 F-stop (ev) units.

In-camera real time shot metering is something that I don't think has ever been done before. It's much more accurate, and faster, than the built in camera exposure meter, especially at low light levels. The disadvantage is that you don't know the meter reading until after the shot. But if you're willing to take multiple shots, like with a time lapse, there are lots of possibilites, like optimum exposure bracketing and HDR with a minimum of shots. The multiple metering areas are quite useful too.

But the most exciting use of shot metering to me is doing smooth exposure adjustments in day to night time lapses. This is the so called "Holy Grail" of time lapse photography. My script produces pictures that can be converted to a time lapse straight out of the camera, with no post processing of the images. I don't think there's any other way to do this. The only thing comparable is "bulb ramping" where an external controller holds the remote shutter down. There's are smartphone apps coming out that control the camera through PTP and can adjust exposure between shots. I assume they use the phone as an exposure meter, but I haven't tried them. I think you still have to post process the images to get rid of the flickering.

The other major addition to CHDK in my build is the set_shot_interval(interval) function. What this does is hold the camera at the point immediately before it opens the shutter until the time from the last shot is equal to the specified interval. The time between shots is perfectly accurate. When I take time lapses with 2 different cameras at the same time, they stay perfectly in sync with each other as long as the shutter time is at least ~300 msec less than the interval. This has real potential for multi-camera synchronization without requiring usb cables connected to each camera.

[EDIT]
Another big advantage of continuous over single shot mode is that the pictures are displayed on the screen between shots, as you've probably noticed. In single shot, the screen is blank most of the time.

New build is attached now:
Title: Re: Shot Histogram Request
Post by: Microfunguy on 13 / September / 2013, 14:50:10
.
Title: Re: Shot Histogram Request
Post by: lapser on 16 / September / 2013, 15:27:00
I captured some fast moving clouds at sunset last night from a bridge over the Willamette River. Like a lot of the time lapse videos I make, there are a lot of pixelation artifacts in the very dark areas of the pictures. I always thought this was from the mp4 compression, which it may be, but I had another idea.

I have a linear underexposure fudge factor that starts at +500 Bv96, and underexposes by 2 EV at -500 Bv96. This makes the time lapses look more natural as the light fades. Without the underexposure, everything gets way too bright after dark.

However, this greatly reduces the precision of the low light shots. It's the opposite of ETTR. It might be better to let the camera expose the dark scenes normally, and fix it on the computer later, i.e. with Lightroom. The problem is varying the brightness of the pictures smoothly as it gets darker. There's a program called LRTimelapse that can do this, but the number of pictures I take would overwhelm it, and it would take about 2 days of computer time to process all the photos.

One possibility would be to take every other shot at 2 EV brighter, and blend them together as 2 tracks in the video, fading one to the other. This is kind of like HDR, but it would decrease the shot rate quite a bit at longer shutter times.

Anyway, here's the video from last night:
http://www.youtube.com/watch?v=u1yy1qXU-WU# (http://www.youtube.com/watch?v=u1yy1qXU-WU#)



Title: Re: Shot Histogram Request
Post by: straessi on 17 / September / 2013, 16:00:38
There are no real advantages of single shot mode with my time lapse script, except the possibility of losing pictures with an external battery. The solution to that problem isn't to use single shot mode though. It's to stop the script when the external battery gets near its low voltage cutoff.

That's nice.

I now always use the continuous mode and it works quite smoothly.
I didn't do much testing recently, because it's raining a lot here in Switzerland... But we hope to get a couple of nice Autumn days soon.

@lapser: Thanks again. I really appreciate the awesome work you did!
Title: Re: Shot Histogram Request
Post by: lapser on 17 / September / 2013, 19:37:35
I now always use the continuous mode and it works quite smoothly.
I didn't do much testing recently, because it's raining a lot here in Switzerland... But we hope to get a couple of nice Autumn days soon.
That's good news. I'm excited to see what you come up with. Switzerland is such a beautiful country.

The extra print statement I added to print more log data causes an extra delay about every 10th shot. I think the camera is filling up a memory buffer with pictures in continuous mode, and then writing them out all at once. The camera keeps on taking pictures while it's writing, but when the script tries to write a log at the same time, it seems to block until the pictures are written first. I like the extra log data, but I need to re-do the script so it writes all the data in one print statement instead of two.

I think I figured out a way to vary the white balance and brightness, and everything else, smoothly during the video without going through LRTimelapse and Lightroom (and the 24 hours or more of computer time that takes). I first turn all the pictures into a video clip with VideoMach. Then I use the TMGENC encoding program to turn the clip into a finished mp4 video file.

TMPGENC can adjust colors and brightness of a clip, but the adjustment is the same for the entire clip. But you can put the same clip on 2 different tracks, and fade between them. So I just need to create a duplicate clip and adjust the white balance for it based on the end of the video. Then I can gradually fade from the original clip to the duplicate (white balance adjusted) clip. I'll try it for the next video.

It rains all winter here, so I've had to figure out a way to protect the G1X in the rain. The underwater housing is way too expensive, and I'm not planning to take it diving. I got an underwater bag, but it can't be mounted to a tripod. So here's what I came up with.

Unroll a long piece of plastic wrap and place it flat on a table. Turn the display facing out. Place the camera, display side down, on the plastic wrap. Then fold the wrap around the camera, and put a rubber band around the base of the lens, holding the plastic in place. Then cut the excess plastic wrap off so it doesn't cover the lens.

If you're using an external battery, Scotch tape the wrap around the cable. Now screw the tripod attachment through the wrap into the bottom of the camera. Place the camera on the tripod, turn it on, and line up the shot. Use a lens hood if you have one, since it helps keep sprinkles off the lens. Now tear off a 2nd, narrow piece of plastic and wrap it around the lens barrel. Tape the wrap to the lens hood.

Now, the entire camera, except the front of the lens, is covered in plastic, and water resistant. It also holds in the heat of the camera enough to keep the lens from fogging up, at least under the conditions I've used it so far. I left the G1X out all night using this set up to get this video:

http://www.youtube.com/watch?v=luIXZWJUFvw#ws (http://www.youtube.com/watch?v=luIXZWJUFvw#ws)


Here are two more recent videos that came out pretty interesting:

http://www.youtube.com/watch?v=u1yy1qXU-WU# (http://www.youtube.com/watch?v=u1yy1qXU-WU#)

http://www.youtube.com/watch?v=-2JqVZzniz8# (http://www.youtube.com/watch?v=-2JqVZzniz8#)
Title: Re: Shot Histogram Request
Post by: lapser on 18 / September / 2013, 18:59:23
I changed the script to use "write" instead of print_screen and print to see if I could write 2 lines of log data at a time faster. It worked OK on the SX50, but caused lots of >1000 msec delays on the G1X for some reason. The Lua system handles a "write" to SD, but CHDK does the file writing with print, so CHDK must be a little faster. Back to the drawing board, I guess.

The title of this topic is Shot Histogram Request, but I still haven't finished the shot histogram functions, other than making the existing function more accurate. I want to use the shot histogram to adjust exposure, like the shot meters, so I need to return Apex96 values, like the meters. I also want to get the full accuracy of the 14-bit sensor on the G1X, but that takes 16 times the memory, or 32K for the full histogram, instead of 2K for the current, bit shifted histogram.

My idea today is to compute the  histogram in logarithmic, Apex96 units instead of linear. That way, I'll only need 500 or 600 values to store the histogram, without losing any accuracy with 12 or 14 bit sensors. It may take a little longer to calculate what Apex96 value corresponds to each pixel value, but it should be doable with integers using bit shifts and table lookups. I'll experiment with it in the near future.

For the time lapses last night, I set the underexposure at -500 Bv to 0, instead of the usual 192. Then I used my video rendering program to fade the video using set points to try to get it to look right. It came out ok, but I think the slight "fluttering" is still there, although maybe not as noticeable as with 192. The disadvantage is that the shutter times get longer quicker, speeding up the end of the video. Plus, part of the picture where the sun set ended up overexposed and blown out, so it couldn't be corrected by lowering the brightness. So I'll probably go back to using 192 for now. When I get the histogram feature working, maybe I can try again without blowing out the pictures.

Here's the two videos from last night:

http://www.youtube.com/watch?v=2SPOG_qbgtA# (http://www.youtube.com/watch?v=2SPOG_qbgtA#)

http://www.youtube.com/watch?v=2SPOG_qbgtA# (http://www.youtube.com/watch?v=2SPOG_qbgtA#)

Before turning off the SX50, I turned it at the moon and did a time lapse of the moon going through a shot meter area box. As the moon moved out of the metering area, it got brighter slowly until it was blown out. But on the way, I caught this perfect exposure (attached)
Title: Re: Shot Histogram Request
Post by: lapser on 19 / September / 2013, 15:15:38
I did another time lapse with the sun in the frame, causing the shutter time to hit the minimum 1/3200 seconds. That pesky fluttering at high shutter speed is still visible. My idea of overexposing a little and turning down the brightness in post wouldn't work here. It doesn't really work for dark scenes either, since after you turn down the brightness, the variation in exposure is still there.

I recently added the 4 meter readings to the log when I was trying to track down the G1X major flickering problem. That turned out to be a problem with the G1X ports we haven't tracked down, but it doesn't happen in continuous mode, so it's on the back burner for now. But the extra log data has proven interesting.

While the D20 was at 1/3200, you can see the fluttering in the video, and the meter data shows it. All 4 meters change by the same amount, about 7 ev96 units. This shows that it's a problem with the actual exposure. The camera isn't quite accurate enough to time a 1/3200 second exposure perfectly every shot. So this kind of exposure variation could be corrected in post with Photoshop Lightroom, and a program like LRTimelapse.

I tried my moon going out of the meter box method of exposure bracketing (kind of) last night, and it worked pretty well. The moon gets a lot brighter when it's full, and loses some contrast, so the detail isn't quite as good as last night, but it was still pretty good. I was hoping to get a time lapse of the full moon rising, but the sun hadn't quite set when the moon rose, so it was too light out to get a clear moon shot (maybe next month).

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fphotos3.meetupstatic.com%2Fphotos%2Fevent%2F5%2Fe%2Ff%2F8%2Fhighres_284904312.jpeg&hash=5636a9ad8d050296ceb1b980ab5955ae)

http://www.youtube.com/watch?v=b1RL49rgfY0# (http://www.youtube.com/watch?v=b1RL49rgfY0#)
Title: Re: Shot Histogram Request
Post by: lapser on 28 / September / 2013, 00:03:19
The rainy season in Oregon is starting again, so I'm planning to get some good use out of the waterproof D20. The problem isn't the camera getting wet, it's the droplets on the lens. The wind, and rain, usually come out of the West here, so the lens is usually pointed into the wind for a sunset.

When it's raining, I need to wipe the lens off every once in awhile. But if I take a picture while wiping, the script thinks it got suddenly darker, and overexposes the next picture, causing a flash. I have a "glitch" detector that ignores one picture with a large exposure change. But if you're wiping for 2 pictures, look out. I need to modify my glitch detector to ignore more than 1 photo.

In this time lapse, I caused a flash in the D20 when wiping the lens. I removed a few frames so the flash isn't visible, but the clouds jump suddenly. I wiped faster in the 2nd part of the video (SX260), and didn't trigger a flash.

http://www.youtube.com/watch?v=Sx1exJJHepw# (http://www.youtube.com/watch?v=Sx1exJJHepw#)

I took the SX50 and G1X to a pretty new place for the next video. I set the shutter minimum to 1/2000. This worked great on the G1X, but the SX50 showed flickering until the shutter time got to 1/500. I've been measuring the ND filter density, and trying to figure out how to automatically shift it in and out without a visible change. This way, I can keep the shutter times slower, and hopefully prevent the flickering. Here's the video. The flickering SX50 starts half way through.

http://www.youtube.com/watch?v=-3osLQs6uHE# (http://www.youtube.com/watch?v=-3osLQs6uHE#)
Title: Re: Shot Histogram Request
Post by: Microfunguy on 09 / October / 2013, 11:26:51
Well Mr.Lapser,

I am exhausted after reading this entire thread.

Bottom line is, do we have to request a custom build from yourself or can we compile it ourself ?

Please tell me which of the 43 pages is the most relevant to this.

Thanks.


David
Title: Re: Shot Histogram Request
Post by: waterwingz on 09 / October / 2013, 12:01:34
Bottom line is, do we have to request a custom build from yourself or can we compile it ourself ?
He posted a patch file here :
http://chdk.setepontos.com/index.php?topic=8997.msg103871#msg103871 (http://chdk.setepontos.com/index.php?topic=8997.msg103871#msg103871)
I cleaned it up a bit and posted that immediately after in the same thread.
Title: Re: Shot Histogram Request
Post by: Microfunguy on 09 / October / 2013, 12:17:50
He posted a patch file here :

Thanks, I will check it out.

The main question is does averaging the values of an equal number of R,G,B pixels accurately relate to scene brightness ?

I think early on in the thread Reyalp (or Phil) suggested they do not, the values need de-bayering and 'gamma correction' curves applied.

Title: Re: Shot Histogram Request
Post by: lapser on 09 / October / 2013, 18:22:42
The main question is does averaging the values of an equal number of R,G,B pixels accurately relate to scene brightness ?

I think early on in the thread Reyalp (or Phil) suggested they do not, the values need de-bayering and 'gamma correction' curves applied.
In practice, it's proven extremely accurate. It's much more accurate at low light levels that the built in camera meter. The get_shot_meter function returns an apex96 value that is used to compute the exposure for the next picture. As long as there are no blown pixels in the metering area, and the shot isn't severely underexposed, the next picture is usually right on the money.

Remember, the goal isn't to measure the absolute brightness of the image. It's to measure the exposure change needed, which is the difference in brightness between two images. This is best done on the raw pixels, since doubling the shutter time, for example, doubles the linear value of all the raw pixels.

The first shot in my time lapses is, by necessity, metered by the camera. Then the second shot is adjusted based on the get_shot_meter() reading of the first shot. In this video, I held the first two shots for 5 seconds. Note that the exposure changes quite a bit on the second shot, but then stays steady after that. This means that the second shot was exposed correctly based on the first shot.
http://www.youtube.com/watch?v=MQah7sksQaw#ws (http://www.youtube.com/watch?v=MQah7sksQaw#ws)
Title: Re: Shot Histogram Request
Post by: Microfunguy on 10 / October / 2013, 05:23:07
Thanks.

Whether the exposures are technically correct I am not sure.

However, the result is effective.

It is a very difficult problem.

I have a similar location a short walk away (in Wales) though overlooking a town rather than a city and with hills in the background.
I will ask the farmer for permission to leave my equipment setup for a few hours.

Wonder if taking the exposure reading from a grey card at a corner of the view would be better ?



David
Title: Re: Shot Histogram Request
Post by: lapser on 10 / October / 2013, 22:45:18
I have a similar location a short walk away (in Wales) though overlooking a town rather than a city and with hills in the background.

I will ask the farmer for permission to leave my equipment setup for a few hours.

Wonder if taking the exposure reading from a grey card at a corner of the view would be better ?
I thought about grey cards when I was writing the shot_meter functions. But I ended up adding up to 4 different meters, each with its own metering area. I thought that was overkill when I did it, but it's turned out to be quite useful.

I'd love to see a time lapse done with my script in a new location. I've made a bit of progress since posting that patch. If you'd like to try out my script, it would be easiest just to post a custom build for your camera/firmware, and the latest script for you to try out.

The video in my last post was done before I added the script function to adjust the metering areas. So the lights of the city are badly overexposed at the end, as the script tries to keep the sky the same brightness based on where the meter was. Once I could adjust the location and size of the meters, I could set one of them on one of the streets in the city, and another on the sky. After it gets dark, the script switches to the street meter. I showed the metering box at the end of this video:

http://www.youtube.com/watch?v=pozFliELR4w#ws (http://www.youtube.com/watch?v=pozFliELR4w#ws)
Title: Re: Shot Histogram Request
Post by: lapser on 10 / October / 2013, 23:22:38
I caught the ISS last night from the top of Spencer's Butte with the SX50, as well as a pretty sunset with the G1X.

One of the biggest headaches I've had with my script is writing the log. I have a timer for the print statement that writes the log, and most of the time it takes 10 msec or less. However, sometimes it takes much longer, especially at the start of the time lapse. In this time lapse, the print statement took over 3 seconds one time! I'm pretty sure this happens because the camera is saving pictures as fast as it can in continuous mode. Sometimes, the log file has to wait its turn.

I was thinking about adding code to save the log to memory and then writing it out all at once when the script ends. However, it looks like the script console is already saved to memory, and can be viewed with "misc/console/display last console". It shouldn't be too hard to add a new script function:

write_console(filename)

By the way, I triggered an out of memory error by writing too much data to the console (with another script). I'm not sure it's worth fixing at this point. It took a LOT of data.

Here's the time lapse from last night with the sunset and the ISS:

http://www.youtube.com/watch?v=GQEilawZeOo# (http://www.youtube.com/watch?v=GQEilawZeOo#)
Title: Re: Shot Histogram Request
Post by: Microfunguy on 11 / October / 2013, 05:20:34
If you'd like to try out my script, it would be easiest just to post a custom build for your camera/firmware, and the latest script for you to try out.

Thanks.

SX20is 100f.


David
Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 05:37:44
SX20is 100f.
Build and script are attached. It's a work in progress, but it works. Let me know how you do, and thanks for trying it.
Title: Re: Shot Histogram Request
Post by: Microfunguy on 11 / October / 2013, 10:34:10
Well, it seems a simple enough request but the farmer is so busy gathering grass for silage that I will have to return Monday to discuss it.

There is also a consideration of which fields the cows are in, it can change even during a single day.

Anyway, the view is great.


David
Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 13:42:23
There is also a consideration of which fields the cows are in, it can change even during a single day.
Ha! I'll have to write a cow test into the script. :D

I'm trying to see if I can distribute custom builds with Google drive. Uploading all the files is just dragging and dropping them to a "Google Drive" sub folder. Sharing them is easy to set up. You get a link that anyone can use to see the folders and files you specify. So far so good. But when someone clicks on a file to download, it's pretty confusing. I don't know how Google could get everything else right, and mess up a simple thing like downloading the file.

Anyway, see if you can download your custom build, and the Tlapser.lua file from the link below. It works if you find the right button to click, but it's hard to tell that it worked. Still, it might be a good way to distribute custom builds. [EDIT] Download works better with Firefox than Google Chrome.

https://drive.google.com/folderview?id=0B3woLhMB_tdqWmozT3hheXBzSms&usp=sharing#list (https://drive.google.com/folderview?id=0B3woLhMB_tdqWmozT3hheXBzSms&usp=sharing#list)
Title: Re: Shot Histogram Request
Post by: Microfunguy on 11 / October / 2013, 16:08:20
I see no way to download it.

I assume you have to sign into a Google account.

I have absolutely no trust in Google,Facebook,Skype, Microsoft or any American file-hosting companies.

Your Information and  surfing habits will be added to the NSA haystack and shared with GCHQ and the so-called state of Israel.

It is not ideal but how about DropBox or similar ?

Title: Re: Shot Histogram Request
Post by: ahull on 11 / October / 2013, 16:13:47
I see no way to download it.

I assume you have to sign into a Google account.

I have absolutely no trust in Google,Facebook,Skype, Microsoft or any American file-hosting companies.

Your Information and  surfing habits will be added to the NSA haystack and shared with GCHQ and the so-called state of Israel.

It is not ideal but how about DropBox or similar ?

Ahh don't worry about it, if they rely on Google for their information,  the NSA think I'm a 34 year old penguin from Idaho.
Title: Re: Shot Histogram Request
Post by: Microfunguy on 11 / October / 2013, 16:42:14
 :)

The massive data centre in Utah is so vast it keeps blowing the electrical power circuits.

Talk about finding a needle in the haystack ... only after the 'event' probably.

(I know you are a 34 year old penguin from Scotland).
Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 17:58:08
I see no way to download it.

I assume you have to sign into a Google account.
No, you don't need to sign in. Find your camera firmware and click on it. The download button is a tiny down arrow in the extreme lower right corner. Pretty stupid, eh? Will you try again? Also, see if you can download Tlapser.lua too. Thanks.

You only need a Google account to upload. Uploading is great. I just finished uploading all the cameras.

And don't worry. NSA only breaks into your house and takes you away to an undisclosed location if you type something stupid, like "Osama bin Laden" ....... uh ... oops?
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 18:38:35
Uploading is great. I just finished uploading all the cameras.
So we now have a second official CHDK spin-off.  Good job! 

Do you have a name for your project? LHDK? LDM ? The mind boggles ...  :xmas

Quote
And don't worry. NSA only breaks into your house and takes you away to an undisclosed location if you type something stupid, like "Osama bin Laden" ....... uh ... oops?
Worrying about the NSA by avoiding "American" web sites is kind of pointless.  What would make someone  think the NSA restricts its activities to "American" web sites?  If you are online anywhere in the world,  they have you.
Title: Re: Shot Histogram Request
Post by: Microfunguy on 11 / October / 2013, 19:13:47
The download button is a tiny down arrow in the extreme lower right corner.

Very discrete.

Yes, both files download OK.

Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 19:28:50
So we now have a second official CHDK spin-off.  Good job - do you have a name for your project? LHDK?
LDM ? The mind boggles ...
I keep getting requests from my YouTube videos from people who want to run the time lapse script on their cameras. This way, I can post a link with instructions on how to do it, instead of custom compiling for each request.

This is just a way to post my patches in compiled form for testing. It's not a spin-off like SDM.
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 19:37:48
So we now have a second official CHDK spin-off.  Good job - do you have a name for your project? LHDK?
LDM ? The mind boggles ...
I keep getting requests from my YouTube videos from people who want to run the time lapse script on their cameras. This way, I can post a link with instructions on how to do it, instead of custom compiling for each request.

This is just a way to post my patches in compiled form for testing. It's not a spin-off like SDM.
While I asked that question somewhat "tongue in cheek",  its actually something I've thought about too. 

How does one provide a "customized" version of CHDK without going back to the early days of  "Allbest" vs "juiciphox" vs "cail" vs  ...?   The idea of building and maintaining a custom repository does not appeal to me much.  But copying what some linux sites do and letting you build a ZIP file for your camera and f/w against the current trunk with a patch file applied,  that you then download,  seemed like different option if you are not expecting a lot of load. 

The ability to provide a .flt module that can be added to the existing CHDK distribution seems interesting too.  The standard build links in file called "custom.flt" with a bunch of generic hooks built-in.  You then provide your own "custom.flt" file that people can download and substitute.  Sort of like a script file,  but coded in C and able to access & maybe override lower level functions.



Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 20:18:35
While I asked that question somewhat "tongue in cheek",  its actually something I've thought about too. 

How does one provide a "customized" version of CHDK without going back to the early days of  "Allbest" vs "juiciphox" vs "cail" vs  ...?
I thought I would have to set up a complicated web site, but it actually ended up being incredibly simple. I had it working in about 30 minutes.

Just go to google.com, sign in to a google account,  and install google drive. That adds a folder on your computer that syncs with google's online storage. You get 5 GB for free.

From the google drive web page, create a new folder and share it as public. You get a URL for the folder. Anyone who goes to the URL with their browser sees the shared folder, which is synced to the identical folder on your computer.

To upload, just drag files to that folder on the computer. You can create new folders in the shared folder, and everything shows up online too.

I then just used the BATCH mode in CHDK shell to compile all the cameras at once. All the zip files end up in the bin folder for that trunk. When it's done, just drag all the files over to the Google drive folder. That's all there is to it.

Every once in awhile, I create a diff file with my current patches, and apply it to the latest trunk. Then all I need to do is batch compile all the cameras for that trunk and drag the bin/zip files to the google drive on my computer. That updates them on the web download page too.
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 20:34:42
I thought I would have to set up a complicated web site, but it actually ended up being incredibly simple.

Yes ... but you've stumbled precisely into the "maintaining" half of what I said :
The idea of building and maintaining a custom repository does not appeal to me much. 

At some point, manually rebuilding against the latest trunk and uploading will get tiring.  Not that I have a better solution though ....
Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 20:51:26
At some point, manually rebuilding against the latest trunk and uploading will get tiring.  Not that I have a better solution though ....
With CHDK Shell, it's really not any harder than what I'm doing now for one camera. I build one camera, upload the zip to that camera, and test it on that camera.

To update the web site, I check two boxes in CHDK shell, build all the cameras with one click, and drag all the zip files to the Google drive. It's so simple, it's hard to comprehend!
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 20:58:26
To update the web site, I check two boxes in CHDK shell, build all the cameras with one click, and drag all the zip files to the Google drive. It's so simple, it's hard to comprehend!
Do you plan to do that every night after the trunk updates?
Title: Re: Shot Histogram Request
Post by: lapser on 11 / October / 2013, 22:15:35
Do you plan to do that every night after the trunk updates?
I think it will only be necessary when I have something new to test, or there is something new in the trunk that is important to include, like a new camera. It's nice to have because it makes it possible for anyone with CHDK to use a new patch, instead of just people who can compile from a diff file. I think it will prove useful. Of course, you need to compile with CHDK shell.
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 22:34:54
Do you plan to do that every night after the trunk updates?
I think it will only be necessary when I have something new to test, or there is something new in the trunk that is important to include, like a new camera.
I was just thinking about that too and came to the same conclusion.  Especially if you build your repository against the 1.2.0 stable rather than 1.3.0 dev trunks.

Quote
Of course, you need to compile with CHDK shell.
Or you need to be able to write simple bash scripts  :P
(Hint :  that autobuild does not use CHDK-Shell)
Title: Re: Shot Histogram Request
Post by: waterwingz on 11 / October / 2013, 23:11:17
One final thought .. to spare us some long tech support forum threads ....it would be good if you patch your top level makefile.inc from

Code: [Select]
ifndef OPT_DE_VERSION
    VER=CHDK
    ifndef OPT_DEFAULT_LANG
        OPT_DEFAULT_LANG=english
    endif
else
    VER=CHDK_DE
    ifndef OPT_DEFAULT_LANG
        OPT_DEFAULT_LANG=german
    endif
endif
to

Code: [Select]
VER=LAPSER
ifndef OPT_DEFAULT_LANG
    OPT_DEFAULT_LANG=english
endif

Thanks!
Title: Re: Shot Histogram Request
Post by: lapser on 12 / October / 2013, 03:24:17
Code: [Select]
VER=LAPSER
ifndef OPT_DEFAULT_LANG
    OPT_DEFAULT_LANG=english
endif
Thanks, that's a good idea. The splash screen and misc/build info say "LAPSER" now, so you can blame everything on me.

I thought about using the 1.2 build, but I don't think being a a little out of date on the 1.3 version will be a problem. I'm planning to use 1.3 functions in my scripts too.  And someday, I might even talk you guys into putting something from my build into the 1.3 trunk.  :o

I'm making a conscious effort not to learn too much about ARMs and thumbs and bashes and all that stuff. I spent 10 years in my basement writing machine code during my ill spent youth, and I don't want to get hooked like that again. I'll leave it to you guys :haha I'll be out watching sunsets... with my custom CHDK build and script purring away on a few cameras, of course.

And doesn't this animated stuff drive you nuts?
Title: Re: Shot Histogram Request
Post by: srsa_4c on 12 / October / 2013, 08:22:14
One of the biggest headaches I've had with my script is writing the log. I have a timer for the print statement that writes the log, and most of the time it takes 10 msec or less. However, sometimes it takes much longer, especially at the start of the time lapse. In this time lapse, the print statement took over 3 seconds one time! I'm pretty sure this happens because the camera is saving pictures as fast as it can in continuous mode. Sometimes, the log file has to wait its turn.
Since most or all your cameras have the file write hook, you could start experimenting with writing the log file before or after a jpeg file is written (place a hook into fwt_open or fwt_close, before the open() or after the close() call). Of course you'll need to buffer the log output for this.
Title: Re: Shot Histogram Request
Post by: lapser on 12 / October / 2013, 13:44:37
Since most or all your cameras have the file write hook, you could start experimenting with writing the log file before or after a jpeg file is written (place a hook into fwt_open or fwt_close, before the open() or after the close() call). Of course you'll need to buffer the log output for this.
I thought about using the file write hook but couldn't figure out a good way to do it. That's a good suggestion.

It might still be possible to write from the script (keyboard) task, and avoid buffering, by having the script wait until fwt_close, and delaying fwt_open while the script is writing. I think that could be done in the script_console_add_line() function just for cameras with the file write hook:

Code: [Select]
void script_console_add_line(long str_id)
{
    const char* str = lang_str(str_id);
    console_add_line(str);
    if (print_screen_p && (print_screen_d >= 0)) {
        char nl = '\n';
        // TODO this should be uncached memory

//set flag to delay fwt_open
//wait until fwt_close (if fwt_open was called)
        write(print_screen_d, str, strlen(str) );
        write(print_screen_d, &nl, 1);
//clear flag to delay fwt_open
    }
}
I don't understand the comment about uncached memory. Would this cause a problem with using this idea?

Title: Re: Shot Histogram Request
Post by: reyalp on 12 / October / 2013, 16:45:44
Every once in awhile, I create a diff file with my current patches, and apply it to the latest trunk. Then all I need to do is batch compile all the cameras for that trunk and drag the bin/zip files to the google drive on my computer. That updates them on the web download page too.
If you distribute CHDK binaries, you also need to provide the source that was used to build them. Including the patch in the download directory would meet this requirement.

Quote
I don't understand the comment about uncached memory. Would this cause a problem with using this idea?
This refers CPU cache. The camera RAM is accessible through two different address ranges, one that goes through the CPU cache and write buffer, and one that does not. Low level functions like write() only work 100% correctly using uncached memory, presumably because the actual writing is done with DMA, which doesn't know about the CPU cache. In practice, you can often get away with ignoring this.

So in the quoted case, if the nl = '\n' had not been flushed, you might get some other random character instead of a new line.

See  http://chdk.wikia.com/wiki/CHDK_Coding_Guidelines#Memory_allocation (http://chdk.wikia.com/wiki/CHDK_Coding_Guidelines#Memory_allocation) and http://chdk.setepontos.com/index.php?topic=1910.msg42829#msg42829 (http://chdk.setepontos.com/index.php?topic=1910.msg42829#msg42829)

Note that none of this has to do with disk caching or file buffering, so it's not directly related to your log problem.

srsa's suggestion of buffering and doing it in filewrite is seems like a good one. You might also probably do it in the raw hook, since everything else is pretty much blocked at this point. Another alternative would be to use one of the cameras built in logging systems, like uart redirection. http://chdk.wikia.com/wiki/Debugging#UART_redirection_.28DryOS.29 (http://chdk.wikia.com/wiki/Debugging#UART_redirection_.28DryOS.29)

Some kind of buffered logging for script seems like a good idea, but keep in mind that it will make debugging harder if you crash. In this case, logging to the camera log is useful, since recent messages will be recorded with the romlog.
Title: Re: Shot Histogram Request
Post by: Microfunguy on 18 / October / 2013, 10:38:54
I will have to return Monday to discuss it.

Which I did and that is sorted out.
Just have to wait for suitable weather.

Anything that I need to know about camera settings and using the script ?

Title: Re: Shot Histogram Request
Post by: lapser on 18 / October / 2013, 12:05:40
Anything that I need to know about camera settings and using the script ?
Try testing the script inside to see how it works. Most of the default settings should be OK. I set the interval to 1000 msec, but that's up to you.

I need to work some more on the focusing part of the script. It doesn't work on all cameras. I like to set the focus parameter to "1", which focuses at the hyperfocal distance. You may need to start the script with the camera in manual focus mode for it it work.

The most reliable way to set the focus on any camera is to set the focus parameter to 0, and start the script in manual focus mode with the focus set where you want it beforehand. The D20 requires this method.

The script starts out with the meter location function. I usually put one meter on the brightest part of the sky so the sky is exposed correctly. You can put a second meter on a building that is going to light up after dark, if want the building exposed correctly. The meter locations are saved in a file, so the next time you start the script you can get them back by pressing <display> for each meter. Also, while entering meter locations, you can start over by pressing half shoot. That goes back to just 1 meter, in the location you specified. Pressing <display> goes to the next meter, etc. Pressing half shoot twice puts all the meters in the center, the default.

Camera settings should be as simple as possible. That is, turn every automatic feature off that you can. I usually set the white balance to "cloudy". Be sure not to use auto or the color changes will cause flashing during the time lapse. I use AV mode, and set the aperture as wide as possible for sunsets.

You should set "review" to 0 seconds, or off. Then, you'll be able to press <set> while the time lapse is running to turn off the display. This saves battery, and the camera will run about 15% longer.

The script sets the ISO, but I usually set it to 100 with the camera, instead of AUTO. I'm not sure this matters. The script reads the exposure compensation and uses it, so be sure to set it to 0 unless want the entire time lapse exposed differently. I always use continuous mode, which allows faster shot rates, and shows the pictures on the screen as they are taken so you can see what's happening.

In particular, make sure "safety MF" and "IS" are off. Go through all the camera settings and turn off everything you can, too. The main thing is to test run the script and make sure the pictures are coming out right. You might want to do a sunset or two from your porch, or out the window, to see if it works. Good luck!
Title: Re: Shot Histogram Request
Post by: Microfunguy on 24 / October / 2013, 14:23:42
Hmmm  ....  endless bad weather.
Title: Found the core!
Post by: MedicineMan4040 on 23 / December / 2013, 00:38:12
Lapser must be Dr.Lapser from youtube (I searched youtube for G1X, timelapse) and this confirms it!:
'I keep getting requests from my YouTube videos from people who want to run the time lapse script on their cameras. This way, I can post a link with instructions on how to do it, instead of custom compiling for each request.'
Other than finding the core knowledge of the G1X/CHDK I think I've found a sound bunch of humorous photographers, this confirmed by sayings such as these!:
'And don't worry. NSA only breaks into your house and takes you away to an undisclosed location if you type something stupid, like "Osama bin Laden" ....... uh ... oops?
'the NSA think I'm a 34 year old penguin from Idaho.'
'Your Information and  surfing habits will be added to the NSA haystack and shared with GCHQ and the so-called state of Israel.'
HA! Yep def. found a happy home here.
Didn't see an 'intro' page. Me, just a photographer....
So glad I found the forum....now off for hours of study....ironically I don't even have the G1X yet!
Title: Re: Found the core!
Post by: lapser on 23 / December / 2013, 01:19:49
Lapser must be Dr.Lapser from youtube (I searched youtube for G1X, timelapse) and this confirms it!:

Yes, you found me. I hope you don't work for NSA!  :) For the record, I'm also DrHiker on YouTube.

I haven't posted much here lately because I've been getting my sled invention ready for snowshoe season. Here's a photo of the sleds I'm working on, taken earlier today:
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fphotos3.meetupstatic.com%2Fphotos%2Fevent%2F9%2Fa%2F0%2F8%2Fhighres_318039432.jpeg&hash=08d27362d87a8753a8cbde6378ce5c34)

I was coming back from an overnight in the mountains. The weather was bad, but I did a time lapse anyway. The nice thing about time lapses is that each frame is a full resolution picture. I took over 4,000 pictures last night, mostly of fog, but this one stood out:
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fphotos2.meetupstatic.com%2Fphotos%2Fevent%2F4%2Fa%2Fe%2F4%2Fhighres_318079172.jpeg&hash=77c97174c53ae880cba316612aea4bbf)

The full time lapse is here, with lots of weather going through.
Fuji Shelter 131222 Canon G1X (http://www.youtube.com/watch?v=X-LFVxP_7Do#ws)

And one of my favorite, recent time lapses was from Skinner Butte overlooking the city of Eugene, OR. You can watch it here:
Skinner Butte 131116 Canon G1X (http://www.youtube.com/watch?v=AmTHdfzFn-A#ws)
Title: Re: Shot Histogram Request
Post by: MedicineMan4040 on 23 / December / 2013, 02:34:08
Arrrg...here in the hospital...firewall. I'll admire the sledcreations when I get out of here. Could see the pics-very very nice. I've spent a bit over 6 weeks in the PNW exploring here and there. You are blessed in location.
Now should I add the G1X?
I'm hoping to create a lightweight backpackable astro kit...the G1x + Ioptron Skytracker + Berlebach Mini.
CHDK removes the need for the external intervalometer and I'm thinking once I can really dive into the CHDK threads I'll find a script what honors bulb ramping (or something close).
All that is left is to figure out how you did the external battery (or did you yet).
I see the ongoing quest to defeat the manual focus lost to autofocus once the screen is turned off BUT with the lightweight nature of lithium batteries why not just give in and carry the extra larger external battery and be done with it?
p.s. the plastic bag trick for weather proofing was brilliant!
Title: Re: Shot Histogram Request
Post by: lapser on 23 / December / 2013, 08:24:54
Now should I add the G1X?

I'm hoping to create a lightweight backpackable astro kit...the G1x + Ioptron Skytracker + Berlebach Mini.
CHDK removes the need for the external intervalometer and I'm thinking once I can really dive into the CHDK threads I'll find a script what honors bulb ramping (or something close).
CHDK scripts can go a lot further than bulb ramping. In addition to directly setting the shutter time, a script can set the ISO, aperture, and control the G1X built in ND filter.

My CHDK mods also can measure the brightness of an image while it is still in the camera and use it to set the exposure of the next shot. I call it shot metering.
Quote
All that is left is to figure out how you did the external battery (or did you yet).
I used this battery: http://www.bixnet.com/mumiexbapaki1.html (http://www.bixnet.com/mumiexbapaki1.html)
It was about 1/2 discharged after powering the G1X for 10 hours on my last trip
Quote
I see the ongoing quest to defeat the manual focus lost to autofocus once the screen is turned off BUT with the lightweight nature of lithium batteries why not just give in and carry the extra larger external battery and be done with it?
p.s. the plastic bag trick for weather proofing was brilliant!
reyalp and philmoz figured out how to turn the display off from a script without losing autofocus. My script turns the display on and off when you press <set> on the G1X. It would be useful to trigger this with a shortcut key outside of a script, but this hasn't been implemented yet.

It started to rain pretty hard at about 2:30 a.m. so I got up and took the camera into my tent. There was some water on the screen that got through the "weather proofing".  I wrapped the camera in plastic wrap in a hurry on my lap in the tent, so I don't think I did the best job. Next time, I'll wrap it at home first.
Title: Genius applied
Post by: MedicineMan4040 on 23 / December / 2013, 15:15:06
OK, close to 3 hours invested in sponging through the forum(s).
You Lapser, Waterwingz, Philmoz are all genius level.
I've toyed with Magic Lantern on a 6D....the overall presentation of CHDK=in how to approach it, get it, load it, use it is beyond ML. This site is far more user friendly; in organization, accessibility, and most importantly the approach to the noobie.

The battery you link too-sweeet. As a backpacker/cyclist/paddler first thing I looked for was weight ? Does double duty via USB power, nice. 10 hour shoot at 1/2 power=could run two cameras.

If you are bored (somehow I doubt that), a timelapse from my Sony days (last year, just sold all my Sony alpha mount stuff), just to show I love timelapse....sadly nothing close to a Holy Grail, and obviously something I learned as I went:
12,000 Pictures in 7 Minutes (http://www.youtube.com/watch?v=OFWxT4xYIa8#ws)

Yep the G1X is in my future....
I assume your refined script is included in the latest builds for the G1X? and the non-genius simple minded end-user (ME) only has to enable scripts when running CHDK?

Title: Re: Shot Histogram Request
Post by: MedicineMan4040 on 23 / December / 2013, 16:07:09
Just watched the two vid you posted above. Watched not as a photographer nor anyone doing a critique but as someone worn out from work needing a therapeutic release--both vids provided well! In fact many many of your vids on youtube timelapsing provide something for the soul=Orion passing by, shooting stars, the ISS, the always beautiful clouds-esp the pink ones scalloping over Eugene.
I swore I was over timelapse after my 'big' one, many miles hiked to get to some of those spots; not counting the driving and the fear of amassing so many shutter clicks BUT you don't seem worried with multiple thousands of clicks on your G1X.
So looks like I'm back in when I add the Powershot.
Pulking? Yep we tried, here 20 secs in me with a pulk in tow (turn down music or the bagpipes will ruin your hearing):
RoanTheHighKnobHangWinMed (http://www.youtube.com/watch?v=KJ9j7h8JueE#)
We decided that the Appalachian Trail overall was too steep/rocky/rooty for pulking :(
Title: Re: Shot Histogram Request
Post by: waterwingz on 23 / December / 2013, 16:37:45
.. and the fear of amassing so many shutter clicks BUT you don't seem worried with multiple thousands of clicks on your G1X.
I tend to believe that shutter clicks - even by hard core CHDK users - do not kill many P&S camera.  Dust infiltration onto the sensor,  lens errors from jammed gears, and the release of new&better models every year probably relegate more cameras to the back of the closet that actual wear and tear on the shutter.  And I do have a little experience (http://chdk.setepontos.com/index.php?topic=9049) to back up that statement.   So my advice is to enjoy these little machines as much as you can now and push them to their limits like lapser does - they are not a life-time investment.
Title: Re: Shot Histogram Request
Post by: jmac698 on 31 / August / 2014, 14:15:47
Lapser,
I could only skim the thread but it looks like you've done some amazing work here.  I did notice you did some nice moon shots with your SX50 which I also do.  I have questions and tips for you;

-Did you ever get the histogram/metering features into trunk? If not, where can I get a build for SX50? Also your timelapse script.

-I'm interested in exposing the moon properly as it moves across the entire frame, so what I was orginally searching for is a way to get a histogram for the entire frame (based on the RAW buffer), and in fact I have no stuck pixels that I can detect so I want *every* pixel to be less than 3968 (the measured saturation on my camera)

-Your problems with whitebalance are easy to solve in an Avisynth script, I could make that for you.  Interpolation between white balances between start and end frames can be done with the animate command.

-You may also be interested in what I do further with my moon shots, it's called stacking, a common technique in astrophotography.  I find the simplest program is Astrostakkert!.  Basically drag the 25 shots or so of the moon moving across frame, and it lines them up, including pixel-by-pixel as it waves due to atmospheric disturbence.  The stacking accomplishes sharpening and noise reduction.  The result is quite amazing!

-There is also a planetcrop.avs script in Avisynth that centers each moon image, for some other stacking programs that have trouble locating the moon anywhere across the frame.

-Finally I'm interested in the full frame histogram to do extreme HDR, to make sure there's a shot with no blown highlights and some lower limit for the shadows.  At night I've had to exposure up to 8 minutes. (and I have no hot pixels).

-I'd also like a real normal daytime exposure mode that makes sure no highlights are missing.  As long as the sky is not in the shot :)  In fact in some cases I really hate the sky looking all white instead of blue.
Title: Re: Shot Histogram Request
Post by: lapser on 01 / September / 2014, 21:42:47
-Did you ever get the histogram/metering features into trunk? If not, where can I get a build for SX50? Also your timelapse script.
Thanks for posting. Sorry, I've been pretty busy time lapsing and haven't posted much to the CHDK forum. If you'd like to catch up on what I've been doing lately, look at my YouTube channel, including the description section for the videos:

https://www.youtube.com/user/DrLapser/videos (https://www.youtube.com/user/DrLapser/videos)

I'm way behind on the latest CHDK updates, but you can download the custom CHDK build I'm using, and the Tlapser.lua script here:
https://drive.google.com/folderview?id=0B3woLhMB_tdqWmozT3hheXBzSms&usp=sharing (https://drive.google.com/folderview?id=0B3woLhMB_tdqWmozT3hheXBzSms&usp=sharing)
Quote
-I'm interested in exposing the moon properly as it moves across the entire frame, so what I was orginally searching for is a way to get a histogram for the entire frame (based on the RAW buffer), and in fact I have no stuck pixels that I can detect so I want *every* pixel to be less than 3968 (the measured saturation on my camera)
I haven't gotten to the histogram processing functions in my CHDK build yet, but I'm planning to do that soon. But my current script has the ability to adjust exposure bias on the fly. What I do for SX50 zoomed moon shots is set a single metering area that covers the entire frame, so the moon is always in the metering area as long as it's in the frame. Then I adjust the exposure with the up and down arrow keys until it looks right on the screen. A histogram would be more accurate, but this way works pretty well, especially with raw files.

I used this method to time lapse the April 15 Lunar Eclipse:

https://www.youtube.com/watch?v=1C6zLG5os8Y (https://www.youtube.com/watch?v=1C6zLG5os8Y)

More recently, I was able to track the moon better and caught a close up of it setting behind a ridge (starts around 1:50):

https://www.youtube.com/watch?v=yv0TKcgiooA (https://www.youtube.com/watch?v=yv0TKcgiooA)
Quote

-Your problems with whitebalance are easy to solve in an Avisynth script, I could make that for you.  Interpolation between white balances between start and end frames can be done with the animate command.

-You may also be interested in what I do further with my moon shots, it's called stacking, a common technique in astrophotography.  I find the simplest program is Astrostakkert!.  Basically drag the 25 shots or so of the moon moving across frame, and it lines them up, including pixel-by-pixel as it waves due to atmospheric disturbence.  The stacking accomplishes sharpening and noise reduction.  The result is quite amazing!

-There is also a planetcrop.avs script in Avisynth that centers each moon image, for some other stacking programs that have trouble locating the moon anywhere across the frame.
Many thanks for those ideas. I've been handling white balance by fading between two tracks in the final video.  Here's a good example where I faded from Milky Way white balance to daytime so the RV is white at the end:
https://www.youtube.com/watch?v=itwzU0UWVPs (https://www.youtube.com/watch?v=itwzU0UWVPs)

I've been using VirtualDub with the DeShaker plugin for moon tracking. It doesn't always work well for the sun, since there are no features to match. Thanks for the tip with avisynth.
Quote
-Finally I'm interested in the full frame histogram to do extreme HDR, to make sure there's a shot with no blown highlights and some lower limit for the shadows.  At night I've had to exposure up to 8 minutes. (and I have no hot pixels).

-I'd also like a real normal daytime exposure mode that makes sure no highlights are missing.  As long as the sky is not in the shot :)  In fact in some cases I really hate the sky looking all white instead of blue.
I think I can do this once I get the histogram part done. I need to shift into obsessive programming mode for awhile. Right now, I'm in obsessive time lapsing mode, especially in the summer when the skies are clear. There's another total lunar eclipse on October 8-9 that I'm gearing up for, so I might try to do something before then. It would be nice to have histogram based metering of the moon with raw files on the SX50 for that eclipse. Lately, though, I've been working on getting the tracking right.
Title: Re: Shot Histogram Request
Post by: jmac698 on 01 / September / 2014, 22:42:33
Some follow-up references

Avisynth whitebalance
http://avisynth.nl/index.php/WhiteBalance (http://avisynth.nl/index.php/WhiteBalance)
http://avisynth.nl/index.php/Animate (http://avisynth.nl/index.php/Animate)

Avisynth Planetcrop
http://forum.doom9.org/showthread.php?t=165479 (http://forum.doom9.org/showthread.php?t=165479)

Planetary stacking
http://www.autostakkert.com/ (http://www.autostakkert.com/)

Examples of stacking with SX50 - you can image Mars, Jupiter, Saturn, Venus with just a camera!
http://www.tool-box.info/blog/archives/1445-Saturn-near-opposition.html (http://www.tool-box.info/blog/archives/1445-Saturn-near-opposition.html)