CHDK Forum

CHDK Development => General Discussion and Assistance => Topic started by: mweerden on 08 / October / 2009, 18:35:31

Title: CHDK PTP interface
Post by: mweerden on 08 / October / 2009, 18:35:31
Hi all,

The last couple of days I've been working on a PTP extension for the CHDK that allows various remote operations (e.g. memory inspection/manipulation, function calls, uploading/downloading, switching to record mode and LUA script execution). I've also made an ad-hoc command-line tool to use it (based on ptpcam).

Have a look here for patches and documentation of what I did: http://www.mweerden.net/chdk_ptp.html (http://www.mweerden.net/chdk_ptp.html)
Title: Re: CHDK PTP interface
Post by: HarpoMa on 08 / October / 2009, 19:39:46
wow - I will be checking this out tonight.  Wonderful work.
Title: Re: CHDK PTP interface
Post by: fe50 on 09 / October / 2009, 03:21:59
Great stuff !
...will have a look to this, too - but first i need to apply the LongDay patch to extend my available CHDK-ing time from Day24h to Day32h   :-[
Title: Re: CHDK PTP interface
Post by: hudson on 09 / October / 2009, 11:02:55
I've added some similar functions to Magic Lantern (http://magiclantern.wikia.com/) for the 5D Mark II.  It looks like we duplicated each others efforts in reverse engineering the PTP context structure and callback interface.  I added fine grained focus control for interfacing with remote focus controllers like the Impero (http://www.viewfactor.net/index.php/products/impero.html).

One of my other goals was to build a command console that would work over the PTP interface.  Perhaps it would allow arbitrary Lua commands to be sent, and use the USB as the stdout.  And as an outside goal, I wanted to add a gdb interface so that extensions could be more easily debugged.
Title: Re: CHDK PTP interface
Post by: mweerden on 09 / October / 2009, 12:28:34
I've added some similar functions to Magic Lantern (http://magiclantern.wikia.com/) for the 5D Mark II.  It looks like we duplicated each others efforts in reverse engineering the PTP context structure and callback interface.
First time I even hear of Magic Lantern. ;) Fortunately the PTP part wasn't much work, but it would be nice if we can avoid duplication in the future. As I've said before, there is a lot of knowledge floating around these project, but most of it is inaccessible.

By the way, I just tried to find your functions (for comparison) but had no luck; can you give a me pointer?


Quote
One of my other goals was to build a command console that would work over the PTP interface.  Perhaps it would allow arbitrary Lua commands to be sent, and use the USB as the stdout.
This shouldn't be hard. I'm not sure if it's clear, but my "LUA script execution" means you can already execute arbitrary commands (e.g. "lua shoot();" with "ptpcam --chdk"). What I haven't looked at is something to preserve context between executions. Sending of output should be fairly simple (e.g. with a simple hook).

Quote
And as an outside goal, I wanted to add a gdb interface so that extensions could be more easily debugged.
Do you think this is possible? It seems to me that this requires support from the OS to provide tracing and breakpoints and what not. Has anything like this been found?
Title: Re: CHDK PTP interface
Post by: ewavr on 09 / October / 2009, 16:04:05
Great!
How about developers under Windows, can they use libptp or something else?
Title: Re: CHDK PTP interface
Post by: mweerden on 09 / October / 2009, 17:56:14
How about developers under Windows, can they use libptp or something else?
A quick search gave me the following: http://code.assembla.com/CuteCanonCapture/subversion/nodes/libptp2?rev=30 (http://code.assembla.com/CuteCanonCapture/subversion/nodes/libptp2?rev=30) This seems to be the libptp2-1.1.10 that I used with some minor changes to make it work on Windows. I don't think my code uses anything Linux specific. I currently don't have the right configuration around to try it out, however.
Title: Re: CHDK PTP interface
Post by: hudson on 09 / October / 2009, 23:09:43
First time I even hear of Magic Lantern. ;) Fortunately the PTP part wasn't much work, but it would be nice if we can avoid duplication in the future. As I've said before, there is a lot of knowledge floating around these project, but most of it is inaccessible.
Since I'm working solely on the 5D Mark II and 7D cameras and focusing almost entirely on the cinematography features, there isn't a whole lot of overlap with the CHDK dev team.  I hope there will be more cross-pollination in the future, however.

Quote
By the way, I just tried to find your functions (for comparison) but had no luck; can you give a me pointer?
ptp.h (http://bitbucket.org/hudson/magic-lantern/src/tip/ptp.h).  It isn't near as complete as your implementation; I plan to hack your hacked ptpcam program to work for me, as well work on a AVR PTP library so that the Impero can talk to the 5D.

Quote
I'm not sure if it's clear, but my "LUA script execution" means you can already execute arbitrary commands (e.g. "lua shoot();" with "ptpcam --chdk"). What I haven't looked at is something to preserve context between executions. Sending of output should be fairly simple (e.g. with a simple hook).
Neat.  I hadn't realized that.  ML doesn't have Lua yet, although we do have a simple embedded Python.  I've been meaning to port the Lua library patches so that we can put Lua into it.

Quote
Quote
And as an outside goal, I wanted to add a gdb interface so that extensions could be more easily debugged.
Do you think this is possible? It seems to me that this requires support from the OS to provide tracing and breakpoints and what not. Has anything like this been found?
I see things that look like a debugger interface in the command shell inside DryOS.  As you had found, there are equivalents to ps, top, and a few other programs.  We also have control of the scheduler, so we might be able to do some simple profiling.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 10 / October / 2009, 04:48:43
Have a look here for patches and documentation

This is a bit too advanced for my basic knowledge.

Could you list the steps that I have to take to compile and patch the various softwares (under Windows) and run the command line for testing ?

Assume that I do not know anything.

If I manage to get that working, I will see if I can support my A620.

It would be VERY tedious to support all cameras.


David
Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 07:48:57
Quote
By the way, I just tried to find your functions (for comparison) but had no luck; can you give a me pointer?
ptp.h (http://bitbucket.org/hudson/magic-lantern/src/tip/ptp.h).  It isn't near as complete as your implementation; I plan to hack your hacked ptpcam program to work for me, as well work on a AVR PTP library so that the Impero can talk to the 5D.
Thanks, I somehow completely missed that file.

Quote
I see things that look like a debugger interface in the command shell inside DryOS.  As you had found, there are equivalents to ps, top, and a few other programs.  We also have control of the scheduler, so we might be able to do some simple profiling.
Hmmm, I'm not sure I'm as positive about the possibilities, but who knows? ;)
Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 08:16:23
This is a bit too advanced for my basic knowledge.
Sorry about that.

Quote
It would be VERY tedious to support all cameras.
I don't know about that. Of course, every feature that relies on previously unused functions from the firmware requires each and every firmware to be inspected, but that is inherent to the CHDK. Perhaps it is possible to find a few generic signatures that can be used instead. Otherwise you can just give empty definitions by default and override them only for some cameras (as is done with other "optional" functionality).

The only thing that is really needed is the address of add_ptp_handler. For specific features (shutdown/reboot and mode switching) you need a few more.

Quote
Could you list the steps that I have to take to compile and patch the various softwares (under Windows) and run the command line for testing ?
Sure, but I'm not sure about the Windows part as I can't test it. Also, I haven't looked at VxWorks, so that might also be a bit different.

For the CHDK you need the following:


The platform function need not have anything as body, unless you want the appropriate functionality to work. In the latter case you also need the following:


To get libptp/ptpcam you should download the latest version (1.1.10) or, in case of Windows, I'd download the sources linked to before in this thread. Then apply my patch (I think it should work for the Windows variant as well) and compile it. I'm not sure which compilers work for Windows and whether or not you need libusb as well.

I think that should be it. Let me know how things work out.

Edit: added creation of init_chdk_ptp as task to todo list.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 10 / October / 2009, 08:32:23
Many thanks for that.

I will do a few chores and start this later.

I am sure I will have problems, I will contact you directly  :)


David
Title: Re: CHDK PTP interface
Post by: whim on 10 / October / 2009, 09:23:28
@mweerden

many thanks for this, great project !

Quote
I'm not sure which compilers work for Windows
are you using the same compiler setup for this as for compiling CHDK ?  and which native/ARM GCC versions do you use ?

TIA,

wim
 

Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 09:55:41
Quote
I'm not sure which compilers work for Windows
are you using the same compiler setup for this as for compiling CHDK ?  and which native/ARM GCC versions do you use ?
Yes. For CHDK I'm using 4.3.3 and for libptp/ptpcam 4.3.3-12 (Debian).
Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 13:16:11
In conversation with Microfunguy I realised that getting things done on Windows isn't always as easy. I've created a zip with sources for Windows (here (http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip)). This works for me with MinGW and libusb for Windows (http://libusb-win32.sourceforge.net/) (filter binary). You'll probably have to adjust some paths in the Makefile to make things work for your system.

One problem I noticed on Windows is that with certain request (as the ones Windows automatically makes) the camera goes into a deeper mode of sleep (if you will). In this mode not everything works as otherwise (e.g. shutdown and mode switching; edit: you shouldn't test another function if the previous has already crashed the camera). Edit: it seems that mode switching first makes the camera stay in the current mode. Perhaps a wrapper around PTP_OC_OpenSession that calls set_control_event(0x902) should be used.

I also noticed that my ptpcam patch had a small bug (the last #endif should have been just before the preceding else). This has been fixed.
Title: Re: CHDK PTP interface
Post by: ewavr on 10 / October / 2009, 17:03:58
I've created a zip with sources for Windows (here (http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip)). This works for me with MinGW and libusb for Windows (http://libusb-win32.sourceforge.net/) (filter binary).
I also noticed that my ptpcam patch had a small bug (the last #endif should have been just before the preceding else). This has been fixed.

Oh, many thanks, now ptpcam.exe works (sometimes), still w/o CHDK
I had to turn off "Canon Camera Access Library 8" service for more stable work.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 10 / October / 2009, 17:10:13
now ptpcam.exe works

Is that with A710IS ?

Nothing happens with my A460 or A620.

I have disabled external programmes starting when the 'Camera Connected' event happens.

ptpcam -L  just waits forever.
Title: Re: CHDK PTP interface
Post by: ewavr on 10 / October / 2009, 17:35:07
Is that with A710IS ?
Yes.
Quote
ptpcam -L  just waits forever.
How about disable "Canon Camera Access Library" service (and in extreme case, WIA service) in services applet?
Title: Re: CHDK PTP interface
Post by: Microfunguy on 10 / October / 2009, 17:53:11
How about disable "Canon Camera Access Library" service (and in extreme case, WIA service) in services applet?


Whoaaah  ....   that works !

Is there any way the ptpcam code can do that  ?


David
Title: Re: CHDK PTP interface
Post by: ewavr on 10 / October / 2009, 19:02:16
Is there any way the ptpcam code can do that  ?

Maybe you can do this in batch file:
Code: [Select]
net stop CCALib8
ptpcam --chdk
net start CCALib8

p.s. For a710 NHSTUB(add_ptp_handler, 0xFFE59FE4) - and transfer works! But uploading/downloading of files fails - ptpcam reports about unexpected result code, then camera shuts down.
Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 19:14:37
So I guess VxWorks really only supports one session at a time.

How about disable "Canon Camera Access Library" service (and in extreme case, WIA service) in services applet?
Is there any way the ptpcam code can do that  ?
I think so (see here (http://msdn.microsoft.com/en-us/library/ms686335(VS.85).aspx)), but I'm not sure it's the right place. Why not just use a command like 'sc' to do it?

Then again, I'm not sure what the (CHDK extension of) ptpcam is supposed to be. For me it was just a quick and easy way to get something to work. I've been thinking that for a serious interface it is probably better to just link the library functions (in ptp.c) to something like python. This way you are way more flexible and even get a free and advanced interactive prompt.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 10 / October / 2009, 19:14:46
I have looked at the changes for ixus870 101a, they do not look too bad.

Time for bed ... so I will try to add A620 later.
Title: Re: CHDK PTP interface
Post by: mweerden on 10 / October / 2009, 19:22:22
p.s. For a710 NHSTUB(add_ptp_handler, 0xFFE59FE4) - and transfer works!
Great!

Quote
But uploading/downloading of files fails - ptpcam reports about unexpected result code, then camera shuts down.
Hmm.. If the code is something like 0x2ff it usually means the camera has crashed; 0x2002 means a less critical error (e.g. alloc failed). Perhaps the functions passed to the handler work a bit different for VxWorks. I deduced their workings by looking at how they were used by handlers for things like PTP_OC_GetObject.
Title: Re: CHDK PTP interface
Post by: ewavr on 10 / October / 2009, 19:29:41
--deleted--
Title: Re: CHDK PTP interface
Post by: ewavr on 11 / October / 2009, 15:36:48
Hmm.. If the code is something like 0x2ff it usually means the camera has crashed; 0x2002 means a less critical error (e.g. alloc failed). Perhaps the functions passed to the handler work a bit different for VxWorks. I deduced their workings by looking at how they were used by handlers for things like PTP_OC_GetObject.

It was my stupid error - remote filename must begin with 'A/' (not with 'a/') ;)
 
Title: Re: CHDK PTP interface
Post by: mweerden on 11 / October / 2009, 15:52:17
It was my stupid error - remote filename must begin with 'A/' (not with 'a/') ;)
Yeah, I fell for that one too... However, it shouldn't really cause a crash. It is likely a problem caused by the fact that one side still expects to send/receive data. Interestingly enough I found that in these cases another function (that comes after get_data_size in ptp_data) than send_resp is used in the A620 firmware (and not in the IXUS 870 IS firmware, as far as I can tell). This might be a solution, but I haven't tried anything out yet.
Title: Re: CHDK PTP interface
Post by: ewavr on 11 / October / 2009, 16:24:38
Yeah, I fell for that one too... However, it shouldn't really cause a crash. It is likely a problem caused by the fact that one side still expects to send/receive data.

No, in my a710
FILE* f=fopen("a/1.txt","wb");
really crashes the camera (and "A/1.txt" not).
Title: Re: CHDK PTP interface
Post by: Microfunguy on 11 / October / 2009, 16:36:29
On my A620 this worked :-

download A/DCIM/100CANON/IMG_0002.jpg    F:/TEST.JPG

Title: Re: CHDK PTP interface
Post by: mweerden on 11 / October / 2009, 16:47:26
No, in my a710
FILE* f=fopen("a/1.txt","wb");
really crashes the camera (and "A/1.txt" not).
Ah.. I guess that is the same with my camera then. I think I assumed adding NULL checks would fix it and didn't actually check. I didn't consider the possibility that fopen actually crashes stuff. Perhaps it would be a good idea to add some check in its definition so it behaves more naturally.
Title: Re: CHDK PTP interface
Post by: RaduP on 11 / October / 2009, 17:19:28
Yeah, I fell for that one too... However, it shouldn't really cause a crash. It is likely a problem caused by the fact that one side still expects to send/receive data.

No, in my a710
FILE* f=fopen("a/1.txt","wb");
really crashes the camera (and "A/1.txt" not).

On my SD980, anything not starting with A/ crashes the camera. That's why I modified open() in wrappers.c to be like this:
Code: [Select]
int open (const char *name, int flags, int mode )
{
if(name[0]!='A')return -1;//on the SD980, it will crash if a file path doesn't start with A
    return _Open(name, flags, mode);//hmm
}
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 04:58:08
It was my stupid error - remote filename must begin with 'A/' (not with 'a/') ;)

Does ptpcam work in Record mode on your A710 ?

Title: Re: CHDK PTP interface
Post by: ewavr on 12 / October / 2009, 08:45:45
Does ptpcam work in Record mode on your A710 ?
I'll try this evening.


Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 09:45:42
I'll try this evening.

rec2PB abd PB2rec do not work on many cameras.

So, this is what I have :-

void switch_mode(int mode)
{
  if ( mode == 0 )
  {
 PostLogicalEventForNotPowerType(0x1061); // playback
  } else if ( mode == 1 )
  {
   PostLogicalEventForNotPowerType(0x1061); // playback first !
   msleep(10);
   PostLogicalEventForNotPowerType(0x1065); // then record
   msleep(10);
  }
}

ptpcam command 'mode 0' when you are already in playback does not produce an error.

'mode 1' switches to record, lens extends and camera turns-off immediately.
From previous experience, the playback mode command when switching to record was needed , I cannot remember why, I will remove it.

For cameras that have a playback pushbutton, I have used the following for PostLogicalEventForNotPowerType :-

RECORD 0x1001
PLAYBACK 0x1003
Title: Re: CHDK PTP interface
Post by: mweerden on 12 / October / 2009, 09:59:15
For cameras that have a playback pushbutton, I have used the following for PostLogicalEventForNotPowerType :-

RECORD 0x1001
PLAYBACK 0x1003
I like the use of PostLogicalEventForNotPowerType (also for soft shutdown with 0x1005); it's seems a lot safer than directly calling functions that hopefully do the same. Unfortunately switching to playback this way causes the PTP connection to be closed (just like really pressing the button), while calling Rec2PB doesn't. On the other hand, it is just a minor inconvenience.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 10:28:56
So, on the ixus870, does that switch to record mode and does ptp continue to work ?

Title: Re: CHDK PTP interface
Post by: mweerden on 12 / October / 2009, 10:33:49
So, on the ixus870, does that switch to record mode and does ptp continue to work ?
Yes. That is, together with the call to set_control_event.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 10:50:45
together with the call to set_control_event.

As I do not seem to have that on the A620, I wonder if I should replace with connect and disconnect USB functions ?

Title: Re: CHDK PTP interface
Post by: mweerden on 12 / October / 2009, 11:09:36
together with the call to set_control_event.

As I do not seem to have that on the A620, I wonder if I should replace with connect and disconnect USB functions ?
I don't know. I tried several things (including PostLogicalEventForNotPowerType(0x10A6); for you it seems 0x1086 is needed), but they typically resulted in actually disconnecting USB connections.
Title: Re: CHDK PTP interface
Post by: ewavr on 12 / October / 2009, 14:10:18
Ok, it seemt that for A710 this simple code:
Code: (c) [Select]
void switch_mode(int mode) {
  if ( mode == 0 ) {
   _PostLogicalEventForNotPowerType(0x1003, 0); //PressPBButton
  }
  else if ( mode == 1 ) {
    _PostLogicalEventForNotPowerType(0x1001, 0); //PressRecButton
  }
}
works very well. No crashes, no USB disconnect when camera toggles record<->playback.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 15:05:36
Ok, it seemt that for A710 this simple code:
works very well. No crashes, no USB disconnect when camera toggles record<->playback.

It works on the A620 as well.

It should work on most or all cameras.

I guess _ExitTask needs declaring in lolevel.h.

Edit: it is declared but still get implicit declaration warning.

Time for a cup of tea after that   :)
Title: Re: CHDK PTP interface
Post by: mweerden on 12 / October / 2009, 15:57:51
I guess _ExitTask needs declaring in lolevel.h.

Edit: it is declared but still get implicit declaration warning.
According to lolevel.h it should only be used in platform code. To fix it it would be best to add a wrapper ExitTask to platform/generic/wrappers.h (and declaration to include/platform.h) and use that function. Can't remember getting this warning, though; perhaps I'm using different compiler flags or something. (edit: I'm blind.)
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 16:08:54
I will play with this a bit and then study the code.

I wonder if you can (in principle) upload files that the Canon firmware will not report over PTP ?
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / October / 2009, 16:22:03
That is great !
Taking a photo and uploading image in record mode works fine.

Is there any way ptpcam can talk to two cameras ?

Title: Re: CHDK PTP interface
Post by: mweerden on 12 / October / 2009, 16:57:58
I wonder if you can (in principle) upload files that the Canon firmware will not report over PTP ?
Sure you can, the normal PTP and CHDK PTP functionalities are completely independent.

Is there any way ptpcam can talk to two cameras ?
I think it should be possible with two instances of ptpcam. You can use the options --bus and --dev when starting an instance to indicate which device you want to connect to. You should be able to see the right values with 'ptpcam -l'.
Title: Re: CHDK PTP interface
Post by: ewavr on 12 / October / 2009, 20:29:17
BTW, transfer of live image over USB 2.0 is quite fast (20-25 fps; 720*230*6/4=248400 bytes @ each frame).
Title: Re: CHDK PTP interface
Post by: Microfunguy on 13 / October / 2009, 17:33:09
transfer of live image over USB 2.0 is quite fast

Every time I reconnect I get a Windows message saying a faster USB connection is available.
If you click on the message, ROOT HUB is in bold type and there are  meant to be six USB 2.0 connections.

Four are at the back and I am plugged into one of those via a four-port hub.

The remaining two are at the front but I 'blew' them a few days ago after accidentally shorting.

Anyway, the four at the back should still be working at high speed.

Title: Re: CHDK PTP interface
Post by: fudgey on 27 / October / 2009, 18:31:39
a570 100e needs this stub:
NHSTUB(add_ptp_handler, 0xffd9b9d8 ) // via ptp handler table 0xffda8f70

Couldn't quite figure out where I task creation should go so I just dropped it in platform/generic/main.c after SpyTask creation:

Code: [Select]
void CreateTask_init_chdk_ptp() {
        _CreateTask("InitCHDKPTP", 0x19, 0x2000, init_chdk_ptp, 0);
};

static void task_start_hook(
    long p0,    long p1,    long p2,    long p3,    long p4,
    long p5,    long p6,    long p7,    long p8,    long p9)
{
    _CreateTask("SpyTask", 0x19, 0x2000, spytask, 0);
    task_prev(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 );
   
    CreateTask_init_chdk_ptp();
}
hald in Ubuntu causes a little bit of trouble (first invocation if ptpcam always fails to connect but it works on the second attempt...I didn't try without hald yet):

./ptpcam --chdk
ERROR: Could not open session!
<    > q
./ptpcam --chdk
<conn> upload ptp.o A/ptp.o
<conn> download A/ptp.o foo
<conn> q
diff foo ptp.o

It works!

./ptpcam --chdk
<conn> lua shut_down
<conn> q
ERROR: Could not close session!

So that Lua part works too (the camera did shut down).

All this was in PLAY mode, I didn't try tackling the REC mode stuff yet  but DisableNotificationPTP() and PB2Rec() ought to do it since they have before but didn't have those in this first build. I did have reyalp's levent patches added, so I tried

lua set_levent_script_mode(1); post_levent("PressRecButton"); post_levent("UnpressRecButton"); set_levent_script_mode(0)

but that didn't have any effect. This is not surprising, because the REC switch actually shuts down the camera if USB cable is plugged in (even without CHDK).
Title: Re: CHDK PTP interface
Post by: ewavr on 27 / October / 2009, 19:17:14
the REC switch actually shuts down the camera if USB cable is plugged in (even without CHDK).
The same for a710.
Quote
lua set_levent_script_mode(1); post_levent("PressRecButton"); post_levent("UnpressRecButton"); set_levent_script_mode(0)
but that didn't have any effect.
post_levent_to_ui("PressRecButton")
This script works on a710 :o. Very strange...

edit: If someone interested, I write simple GUI program for Windows for remote shooting (see screenshot), using slightly modified mweerden's code.

Title: Re: CHDK PTP interface
Post by: reyalp on 27 / October / 2009, 19:38:47
How about  ConnectUSBCable, DisconnectUSBCable ? Or possibly the Cradle ones (or is cradle something different than USB ?)

Or perhaps, using the eventproc code UiEvnt_StartDisguiseCradleStatus UiEvnt_StopDisguiseCradleStatus  ?
Title: Re: CHDK PTP interface
Post by: fe50 on 27 / October / 2009, 20:43:24
Hello ewavr,
edit: If someone interested, I write simple GUI program for Windows for remote shooting (see screenshot), using slightly modified mweerden's code.
...very interested  8)
Could you publish the code ?
Title: Re: CHDK PTP interface
Post by: ewavr on 27 / October / 2009, 20:51:35
Could you publish the code ?
Yes, I'll do a few days (currently only a710 is supported, but I'll try tomorrow port PTP extension for SX10).
Title: Re: CHDK PTP interface
Post by: an0n on 27 / October / 2009, 21:04:57
edit: If someone interested, I write simple GUI program for Windows for remote shooting (see screenshot), using slightly modified mweerden's code.
Hi ewavr, good work, I too am interested, but I have A720 - possible for A720?  With code maybe I could compile
for Mac OSX?
thanks.
Title: Re: CHDK PTP interface
Post by: fe50 on 27 / October / 2009, 21:12:53
Could you publish the code ?
Yes, I'll do a few days (currently only a710 is supported, but I'll try tomorrow port PTP extension for SX10).
Great  :xmas
Take it easy, i'll need also some more days to test & play with all the new, nice stuff, PTP & reyalP's events (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fwww.greensmilies.com%2Fsmile%2Fsmiley_emoticons_bufferoverflow.gif&hash=0d8968b2501fb516f843e5d4482473a0) (http://www.greensmilies.com/)
Title: Re: CHDK PTP interface
Post by: Aged on 28 / October / 2009, 07:52:40
@ewavr
 If someone interested, I write simple GUI program for Windows for remote shooting (see screenshot), using slightly modified mweerden's code.


 Can GUI be added to S3is (camera is listed as remote capture by Canon)  ?
Title: Re: CHDK PTP interface
Post by: ewavr on 28 / October / 2009, 15:59:05
How about  ConnectUSBCable, DisconnectUSBCable ? Or possibly the Cradle ones (or is cradle something different than USB ?)

Or perhaps, using the eventproc code UiEvnt_StartDisguiseCradleStatus UiEvnt_StopDisguiseCradleStatus  ?

For SX10, any event does not help to switch PB/rec mode if USB cable is connected  :(
But I have good news - mweerden's code (with PB2Rec) works perfectly.
Title: Re: CHDK PTP interface
Post by: fudgey on 28 / October / 2009, 17:47:01
I screwed up the previous experiment a bit, forgot to actually define post_levent.

lua post_levent=post_levent_for_npt;set_levent_script_mode(1); post_levent("PressRecButton"); post_levent("UnpressRecButton"); set_levent_script_mode(0)

actually switched the cam (a570) to REC mode a couple of times (although a successive command "lua shoot" crashed the camera...as does "lua foo" or any other unknown lua command, btw...).

post_levent_to_ui() for the same event didn't do anything even once, and I can't seem to get *npt to work one more time either...will have to add PB2Rec stuff later, I think it used to work fine before.
Title: Re: CHDK PTP interface
Post by: ewavr on 28 / October / 2009, 19:48:35
Take it easy, i'll need also some more days to test & play with all the new, nice stuff, PTP & reyalP's events [

src&bin for Win, a710 and sx10 1.01a (pre-alpha) here - http://ewavr.nm.ru/chdk/for_test/ (http://ewavr.nm.ru/chdk/for_test/)
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 28 / October / 2009, 21:43:27
Is PTP supported by the CANNON SX120 and SX200 IS ?
Title: Re: CHDK PTP interface
Post by: RaduP on 28 / October / 2009, 22:21:19
It should be supported by all the Canon cameras, that's how the pictures are transfered to the PC.
Title: Re: CHDK PTP interface
Post by: fe50 on 28 / October / 2009, 22:45:22
src&bin for Win, a710 and sx10 1.01a (pre-alpha) here - http://ewavr.nm.ru/chdk/for_test/ (http://ewavr.nm.ru/chdk/for_test/)
Wow, that was fast !

Started with testing, playback connection is ok, ~ 4 to 5 fps.
Script execution works, e.g. set_led(9,1) to turn on the AF lamp

Didn't find out how to switch to rec mode yet, will look deeper after some hours of sleep.

BTW: atm i use an unmodified libusb-win32-filter-bin-0.1.12.2 package; are the patches from mweerden still needed ?
Title: Re: CHDK PTP interface
Post by: ewavr on 29 / October / 2009, 05:57:00
Started with testing, playback connection is ok, ~ 4 to 5 fps.
This depends on computer speed and camera model (I have 12 fps for SX10 and 7 fps for A710 with overlays) - GDI drawing is not too fast.

Quote
BTW: atm i use an unmodified libusb-win32-filter-bin-0.1.12.2 package; are the patches from mweerden still needed ?
No, libusb and ptpcam are different things. To recompile libusb-win32, DDK is required.

And hint: use numeric keypad (with numlock=on) to walk camera menus (when camera in record mode).
Title: Re: CHDK PTP interface
Post by: whoever on 29 / October / 2009, 15:23:39
Thrilling! Don't quite get though how the numeric keypad is supposed to work, but maybe I just patched wrong. Then again, I don't have any numeric keypad on the laptop.
   And how nice! With ReyalP's levents I can even run
Code: [Select]
set_levent_script_mode(1)
post_levent_to_ui("PressRecButton")
post_levent_to_ui("UnpressRecButton")
sleep(2000)
post_levent_to_ui("ModeDialToP")
set_levent_script_mode(0)
in the script box, which switches to "manual" mode, and then take a shot with the "Shoot" button!
   It feels like the ultimate unlimited power, MU-HA-HA!
Well, almost... Has anyone succeeded in switching to movie without disconnecting PTP?
Title: Re: CHDK PTP interface
Post by: fudgey on 29 / October / 2009, 15:26:43
On a570 play->rec->play switching works from mweerden's PTP interface if I do this:

1) boot up cam to play mode without USB cable
2) call DisableNotificationPTP() from a script (I set it to autostart). Without this call the camera would on USB cable attach go to a mode where it powers off the LCD, retracts the lens if it's open and prevent switching to REC mode until powered off.
3) attach USB cable
4) <conn> lua PB2Rec()

and we're in REC mode.

'lua Rec2PB()' then works too for REC->PLAY switching, and 'lua shoot()' works as well.

It's not a good idea to call PB2Rec() while in REC mode (cam crashes, need to wait for watchdog or remove batteries). Calling Rec2PB in PLAY mode does not seem to be that bad, but should be prevented as well of course -- doing that from an autorun script in PLAY mode I did manage to get the cam to a mode where it and CHDK seem to work, but power button and rec switch have no effect.

The a570 100e stubs I used:
NHSTUB(DisableNotificationPTP, 0xffd8df04)
NHSTUB(PB2Rec, 0xffc119b8)
NHSTUB(Rec2PB, 0xffc119f8)


Further, looks like it's also possible to do this stuff without having to touch the USB cable:

1) boot up cam to REC mode with USB cable already attached.
2) run script that calls DisableNotificationPTP() and Rec2PB() -- maybe for this one the event stuff would work in place of Rec2PB since PTP isn't active until we're in PLAY mode...but I didn't try it.
3) from PTP interface, we can now call stuff like 'lua PB2Rec(); sleep(1000); shoot()'

This way the PLAY/REC switch is physically in correct position for REC mode and probably shouldn't confuse CHDK quite as much for shooting related stuff as when booting to PLAY mode (basically we need to go to PLAY mode once while the USB cable is plugged in to get Canon FW to fire up all its PTP stuff...maybe it's would be possible to make that happen without PLAY mode too, but I suppose that's not necessary).

If that little script is set autostart, things work pretty smoothly (as long as you never want to boot to PLAY mode). It may even be possible to fully remote control the cam with the mechanically-prevent-power-button-from-getting-unpressed-and-then-switch-power-with-external-PSU hack (the controlling PC will of course need some simple custom electronics to switch the external PSU at will).

I gave this a quick try and I think it works as long as the camera is shut down cleanly with lua post_levent_to_ui("PressPowerButton")... I first tried just switching to play mode and then disconnecting the PSU, but after that the autostart script failed to switch to PLAY mode and thus PTP stuff never started. My finger got tired pressing the power button before I could test it ehough :haha.

Title: Re: CHDK PTP interface
Post by: ewavr on 29 / October / 2009, 16:54:09
Has anyone succeeded in switching to movie without disconnecting PTP?

May be post_levent_to_ui("ModeLeverMovieRec") ?
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / October / 2009, 17:19:55
Has anyone succeeded in switching to movie without disconnecting PTP?

May be post_levent_to_ui("ModeLeverMovieRec") ?
Or maybe exec_event_proc("UIFS_SetDialMovieRec")

(you probably have to exec_event_proc("UI_RegistDebugEventProc") first)
Title: Re: CHDK PTP interface
Post by: fudgey on 29 / October / 2009, 17:32:04
May be post_levent_to_ui("ModeLeverMovieRec") ?

edit: oops, misread that one...ModeLeverMovieRec has no effect. post_levent_to_ui("ModeDialToMovie") is what works for me (but only if...)

That works for me, but only if the camera was booted to PLAY mode. When camera was booted to REC mode, I can't get any mode change (including movie) to stick (camera announces the change on LCD, but then it changes back to whatever it was). In the mode dial thread http://chdk.setepontos.com/index.php/topic,3228.45.html (http://chdk.setepontos.com/index.php/topic,3228.45.html) reyalp's solution for this particular problem is to set set_levent_script_mode(1) first but it doesn't seem to help when PTP is active.

(in both cases DisableNotificationPTP() and and PB2Rec() were called, in REC mode boot also Rec2PB() as described in my previous post).
Title: Re: CHDK PTP interface
Post by: ewavr on 29 / October / 2009, 21:09:43
Program for PC is updated: added focus slider and 9 buttons for your favorite scripts.
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / October / 2009, 22:54:27
When camera was booted to REC mode, I can't get any mode change (including movie) to stick (camera announces the change on LCD, but then it changes back to whatever it was). In the mode dial thread http://chdk.setepontos.com/index.php/topic,3228.45.html (http://chdk.setepontos.com/index.php/topic,3228.45.html) reyalp's solution for this particular problem is to set set_levent_script_mode(1) first but it doesn't seem to help when PTP is active.
set_levent_script_mode() is only half the solution. The other half is set_levent_active("ModeDailTo...",false) on all the mode dial position events *except* the one you want to use, and  set_levent_active("ModeDailToMovie",true)
Title: Re: CHDK PTP interface
Post by: whoever on 30 / October / 2009, 03:45:48
Has anyone succeeded in switching to movie without disconnecting PTP?
May be post_levent_to_ui("ModeLeverMovieRec") ?
Or maybe exec_event_proc("UIFS_SetDialMovieRec")
(you probably have to exec_event_proc("UI_RegistDebugEventProc") first)
post_levent_to_ui("ModeLeverMovieRec") is ignored.

UIFS_SetDialMovieRec in the sequence exec_event_proc("UI_RegistDebugEventProc"); exec_event_proc("UIFS_SetDialMovieRec") half-crashes (turns off) the cam.

ModeDialToMovie in the sequence such as set_levent_script_mode(1); post_levent_to_ui("PressRecButton"); post_levent_to_ui("UnpressRecButton"); sleep(2000); post_levent_to_ui("ModeDialToMovie"); set_levent_script_mode(0) changes the mode and disconnects. While fudgey's stays connected in this circumstance, as far as I understand. Also, the Ixus950 connects at all only if started in play mode.

Almost every camera is somehow different in this respect, it seems. Funny. Why would they bother to change the logic every time?
Title: Re: CHDK PTP interface
Post by: fudgey on 30 / October / 2009, 05:21:41
Almost every camera is somehow different in this respect, it seems. Funny. Why would they bother to change the logic every time?

A large part of this comes from actual differences in the camera UI... e.g. some cameras have a separate rec/play switch, most use buttons.. some cameras have a video button, while most have video on the mode dial.
Title: Re: CHDK PTP interface
Post by: fudgey on 01 / November / 2009, 16:45:51
set_levent_script_mode() is only half the solution. The other half is set_levent_active("ModeDailTo...",false) on all the mode dial position events *except* the one you want to use, and  set_levent_active("ModeDailToMovie",true)

Ah, of course. I put that stuff in a library so that I wouldn't need to paste it to the PTP interface and it now works fine:

Code: [Select]
set_levent_script_mode(true)
set_mode_exclusive(modename)
post_levent_to_ui(modename)
sleep(ModeSwDelay)
set_levent_script_mode(false)

ModeSwDelay above is necessary, otherwise mode will bounce right back to the original dialmode position (even if previously overrided mode was something else) just like it did without set_mode_exlusive(). The delay required is probably fairly equal to the length of mode switching animations that happen on screen. In my short experiments 400 ms was sometimes not enough and 500 ms was always enough (I'd probably use no less than 1000 ms unless it's critical to optimize this... and usually it isn't since you probably don't have to exit levent_script_mode until the end of your Lua script).
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / November / 2009, 17:19:38
FWIW, as far as I can tell, there's no particular need to turn off script mode. You probably want to turn it off before you return to manual operation, but I haven't noticed any problems just turning it on at the start of the script and off at the end.
Title: Re: CHDK PTP interface
Post by: ADamb on 02 / November / 2009, 14:53:49
src&bin for Win, a710 and sx10 1.01a (pre-alpha) here - http://ewavr.nm.ru/chdk/for_test/ (http://ewavr.nm.ru/chdk/for_test/)
Support for sx200is 100c, wrong aspect for overlay...
Title: Re: CHDK PTP interface
Post by: ewavr on 02 / November / 2009, 16:26:20
Support for sx200is 100c, wrong aspect for overlay...

Ok, I found in gui_draw.c this comment for SX200:

>we have a 720x240 efective memory buffer (in a 960x270 physical memory buffer)

and try to make corrections in my code tomorrow.
Title: Re: CHDK PTP interface
Post by: ewavr on 03 / November / 2009, 07:31:42
and try to make corrections in my code tomorrow.
Done. But I can't test how it works on SX200 :).
Title: Re: CHDK PTP interface
Post by: Microfunguy on 03 / November / 2009, 08:48:00
>we have a 720x240 efective memory buffer (in a 960x270 physical memory buffer)

Does that mean we have to write a pixel to the bitmap buffer twice in the 'x' direction to memory locations (y*960)+(x*2)  and (y*960)+(x*2)+1 ?

Is the size of the live viewport buffer 360x240x3  bytes ?

Title: Re: CHDK PTP interface
Post by: ewavr on 03 / November / 2009, 09:32:19
Does that mean we have to write a pixel to the bitmap buffer twice in the 'x' direction to memory locations (y*960)+(x*2)  and (y*960)+(x*2)+1 ?
Maybe this question is for 'SX200 porting' thread. Maybe yes, but drawing functions for sx200 in dui_draw.c are not too easy to understang  :).
Quote
Is the size of the live viewport buffer 360x240x3  bytes ?
More precisely, 720*240*6/4 (in playback mode).
In record mode, actual image width and height depends on shooting mode and digital zoom value, buffer width always is 720.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 03 / November / 2009, 09:40:02
drawing functions for sx200 in dui_draw.c are not too easy to understang  

No, I am not convinced they are correct.

Later this week I will try the procedure that I suggested.

Title: Re: CHDK PTP interface
Post by: ADamb on 03 / November / 2009, 14:30:57
@ewavr
Thanks for your work, but there is no improvement...
Tried to patch source, but ptp.c is missing in your patch.
Binary version gave this (the same picture as previous).
Title: Re: CHDK PTP interface
Post by: ewavr on 03 / November / 2009, 16:08:16
Tried to patch source, but ptp.c is missing in your patch.

Oops! I also missed this file :(.
Could you upload ptp.c from my previous patch?

Quote
but there is no improvement...
It seems this was error in PC client program. Corrected now.
Title: Re: CHDK PTP interface
Post by: fudgey on 03 / November / 2009, 16:22:58
Could you upload ptp.c from my previous patch?
Your first (I think) ptp_patch.zip attached.
Title: Re: CHDK PTP interface
Post by: ewavr on 03 / November / 2009, 18:24:59
Your first (I think) ptp_patch.zip attached.
Many thanks! I forgot about this (http://my-trac.assembla.com/chdkde/browser/branches/fe50/core/ptp.c).
Now I restored all changes from memory, new patch is uploaded.
Title: Re: CHDK PTP interface
Post by: ADamb on 04 / November / 2009, 04:36:45
Thanks, now it is OK.
Title: Re: CHDK PTP interface
Post by: msl on 07 / November / 2009, 19:24:27
Hi ewavr,

great work!

It would be nice if you could also create a version for the A720. I would like to test the PTP functions.

Thx msl
Title: Re: CHDK PTP interface
Post by: ewavr on 08 / November / 2009, 20:10:09
It would be nice if you could also create a version for the A720. I would like to test the PTP functions.

Unfortunately, there is no universal method of software switching camera to record mode when USB cable is connected.
Because a720 has a slide mode switch, try run this lua script on fresh CHDK version (in playback mode, USB cable must be connected):
Code: (lua) [Select]
post_levent_to_ui("PressRecButton")If the lens comes out, it would be great.

Title: Re: CHDK PTP interface
Post by: msl on 09 / November / 2009, 05:48:44
Thanks for your answer, ewavr.

When  your script line is starting with autostart method in play mode, the camera switches in the record mode (lens comes out). The PC detect the camera USB connection.

I've also tested a manual script start when print menu is displaying. It was not possible switching to record mode. I've tried different commands with reyalp's testlev script.

msl
Title: Re: CHDK PTP interface
Post by: RaduP on 10 / November / 2009, 21:04:30
There is this very cheap computer with WiFi called Zipit Z2.
It is intended as a way to use messenger programs such as YIM, MSN and so on away from the computer.
The nice thing is that you can run Linux on it, and it only cost 50 bucks.
It does not come with an USB connector, however there are some USB pins in the back connector. And there is some work at a kernel that will support USB host mode.

If someone gets it to work in conjunction with the PTP interface, the possibilities are endless. You can control you camera remotely from your PC and use it as a security webcam and all kind of cool stuff, by writing a relatively simple client/server that uses TCP/IP.
Title: Re: CHDK PTP interface
Post by: ewavr on 11 / November / 2009, 16:02:52
@msl:
Ok, I almost made test version for a720, but I cannot understand how works palette in this camera.
Could you made dump of RAM (debug menu->alt +/- debug action = DmpRAM, then press +/- in <alt> mode, dump is stored in DCIM/100CANON/IMG_0001.JPG) and upload zipped dump somewhere?
Title: Re: CHDK PTP interface
Post by: msl on 11 / November / 2009, 16:46:26
No problem, here is the dump: http://drop.io/chdk_de_II/asset/ramdumpa720-zip (http://drop.io/chdk_de_II/asset/ramdumpa720-zip)

And thanks for your tireless work.

msl
Title: Re: CHDK PTP interface
Post by: ewavr on 11 / November / 2009, 18:52:17
No problem, here is the dump:

And here are files:
http://ewavr.nm.ru/chdk/for_test/CHDK-a720-100c-0.9.8.zip (http://ewavr.nm.ru/chdk/for_test/CHDK-a720-100c-0.9.8.zip)
http://ewavr.nm.ru/chdk/for_test/chdkcam_exec.zip (http://ewavr.nm.ru/chdk/for_test/chdkcam_exec.zip)

and don't forget to install libusb-win32 executables (can not work under Vista/Seven).
Title: Re: CHDK PTP interface
Post by: msl on 12 / November / 2009, 06:28:28
Thanks for your great job.
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Ffc06.deviantart.com%2Ffs43%2Ff%2F2009%2F110%2F6%2Fc%2FRainbow_8D_by_MyrthJ.gif&hash=195820f96fd3471c1dff4f26ad1d531c)

The programm is working perfect. All functions are available. The average frame rate is 6 fps. Scripts are also ok.

The CHDK PTP interface and the logical event functions are a quantum leap in the history of CHDK!

msl
Title: Re: CHDK PTP interface
Post by: msl on 14 / November / 2009, 16:36:13
rudi from the german chdk forum was so impressed by the PTP interface that he has made a version for the A590 101b.

And then there's a small thing:

The chdkcam program has a small incompatibility to the trunk version.
set_capture_mode -> trunk version
set_capture_mode_type -> necessary for PTP version
Title: Re: CHDK PTP interface
Post by: ewavr on 14 / November / 2009, 20:22:16
set_capture_mode -> trunk version
set_capture_mode_type -> necessary for PTP version
Thanks, corrected.
Title: Re: CHDK PTP interface
Post by: msl on 19 / November / 2009, 18:02:36
PTP interface for A610 100e by CHDKLover (german CHDK forum)
Title: Re: CHDK PTP interface
Post by: ewavr on 19 / November / 2009, 19:34:35
Title: Re: CHDK PTP interface
Post by: msl on 20 / November / 2009, 06:23:49
Thanks for the explanations.

I've checked the unnamed events for the a720 and found the right events for keyboard unlock: 0x1184 and 0x1185 (with blocked power button)

edit: For the A590 we can also use 0x1184.
Title: Re: CHDK PTP interface
Post by: whoever on 21 / November / 2009, 06:40:28
But we can unlock it using simple script (value is only for a710):
post_levent_to_ui(0x1144)  // unnamed event, only for a710
0x1143 value also unlocks keyboard, but blocks power button.
Unbelievable... How did you find out?! (I cannot find it, even knowing what to look for...)
Title: Re: CHDK PTP interface
Post by: ewavr on 21 / November / 2009, 07:47:11
Unbelievable... How did you find out?! (I cannot find it, even knowing what to look for...)
Using script with loop, something like:

for i=0x1100, 0x1200 do
 print(i)
 sleep(1000)
 post_levent_to_ui(i)
 click("menu")
end

If camera menu opens, goal is reached. If camera reboots, or shutdowns with "E00" message, or low battery icon starts (stops) blinking, goal is near.
Title: Re: CHDK PTP interface
Post by: whoever on 21 / November / 2009, 11:46:57
Thanks, I got it after all (for the record, it's also 0x1184 on this little Ixus).

It'd never cross my mind to expect, and look for an unnamed (!) event that would mysteriously unlock (!!) the keys! I start to think -- and maybe I suspected it before -- that even the "H" in someone's signature is not all there is to it...

P.S. Regretfully, the later versions of chdkcam don't like my little camera and refuse to connect -- I must've patched something wrong. Strangely enough, mweerden's ptpcam connects flawlessly...
Title: Re: CHDK PTP interface
Post by: PhyrePhoX on 21 / November / 2009, 12:49:01
havent read everything but this seems to be great stuff :)
really gotta get back here more often
Title: Re: CHDK PTP interface
Post by: msl on 22 / November / 2009, 07:25:15
PTP support for a610 100f and sx10 102b by CHDKLover
Title: Re: CHDK PTP interface
Post by: whoever on 22 / November / 2009, 12:29:46
Before too late, I'd suggest to conduct a little discussion on how we actually want it, and whether we want it at all. CHDK PTP, that is. In other words, to formulate a standard if you wish. Does CHDK PTP go into the mainstream, or only remains in personal builds? If it makes it to the trunk, then in which shape? Etc.

(My personal point of view is pretty close to mweerden's: I'd suggest his well-documented implementation to become standard, with small modifications on both the camera side and in ptpcam. Note that ptpcam is easily portable to any platform, and that the basic implementation on the camera side only requires one function address.)
Title: Re: CHDK PTP interface
Post by: ewavr on 28 / November / 2009, 08:07:06
@msl:
I successfully tested my program under Win7 32-bit.
Libusb-win32 installation instructions under Vista - http://lejos.sourceforge.net/forum/viewtopic.php?t=541 (http://lejos.sourceforge.net/forum/viewtopic.php?t=541)
Unfortunately, in this case the libusb-win32 driver completely replaces the standard Windows PTP driver.
To intall webcam driver under Win7, UAC system must be disabled at the time of installation of the driver.
Title: Re: CHDK PTP interface
Post by: msl on 01 / December / 2009, 06:55:56
Thanks for this informations, ewavr.

rudi (from german CHDK forum) has made a not tested a590 100e version for a better compiler compatibility because of the exceptions in camera.h.
Title: Re: CHDK PTP interface
Post by: rudi on 04 / December / 2009, 15:50:41
Today, I tested the newest CHDKCAM and ewavr's BIN, but the "Shooting mode"-Box are empty.

Hint:
Answer "modes_script" form "main.cpp": > 0000000000000017631c30b7e <

Can you check this? Thanks!
Title: Re: CHDK PTP interface
Post by: ewavr on 04 / December / 2009, 17:28:00
Today, I tested the newest CHDKCAM and ewavr's BIN, but the "Shooting mode"-Box are empty.
Hint:
Answer "modes_script" form "main.cpp": > 0000000000000017631c30b7e <
Can you check this? Thanks!
Maybe delay for script execution was too small for your camera  :(
Now I uploaded PC client with bigger delay, try it.
At present we cannot read script execution state, but this is planned.
Title: Re: CHDK PTP interface
Post by: rudi on 04 / December / 2009, 18:10:21
Thanks for your fast answer.

Now I tested the new chdkcam. Usually I start the PC client at first and then the camera. In this moment show me the client an error-box without any message. After "OK" it works. I looking for cause - the messagebox is show after each turn on the camera.
Then I tested your previous client-version (03.12.09) again and it works also!?!

I'm sorry. It was a mistake on my part!

Now I know: "start at first the camera and then the application"

OK, the previous client-version is the better one.
Title: Re: CHDK PTP interface
Post by: ewavr on 04 / December / 2009, 18:28:24
In this moment show me the client an error-box without any message. After "OK" it works.
Oops! Fixed (maybe).
Quote
Now I know: "start at first the camera and then the application"
Just after connecting PC client executes some scripts in camera to read its capabilities (maximum zoom value and available shooting modes). Maybe we need some delay between these events.
p.s. In your camera script autostart is off?
Title: Re: CHDK PTP interface
Post by: rudi on 05 / December / 2009, 13:47:54
Quote from: ewavr
p.s. In your camera script autostart is off?
Yes, it is.
Title: Re: CHDK PTP interface
Post by: m.rump on 06 / December / 2009, 07:41:10
First of all: Thanks mweerden for the great work!

I located the PTP functions in the G9 1.00d firmware, if anyone else is interested:

NHSTUB(add_ptp_handler, 0xFF8D897C) // via ptp handler table
NHSTUB(get_ptp_handler_entry, 0xFF8D8F98)   // via add_ptp_handler
NHSTUB(get_ptp_handler, 0xFF8D8B10)   // directly below get_ptp_handler_entry
NHSTUB(rem_ptp_handler, 0xFF8D8A68) // directly below add_ptp_handler

Title: Re: CHDK PTP interface
Post by: leedsgreen on 08 / December / 2009, 18:17:10
I really don't know how you guys do it. But thanks so much for doing it! It never ceases to amaze me what you come up with  :o

I've dreamt of buying camera with Remote Capture ability but now I don't need to, my a710is can do it all! Just loaded up tonight and got it working  :xmas

Thanks again (and again),

Nick

Title: Re: CHDK PTP interface
Post by: ynaig on 08 / December / 2009, 18:23:14
Is there a chdk build for A550 that I can test the PTP functionality?

Ynaig
Title: Re: CHDK PTP interface
Post by: leedsgreen on 08 / December / 2009, 20:42:29
If I may ask a couple of questions?

1. Is it possible to flick through taken images in 'playback' mode without physicaly touching the camera?

2. Is it possible to zoom into an image during 'playback' mode without touching the camera? For example, is there anyway of manipulating the 'zoom slider' so that a taken image can be looked at in more detail?

The reason I ask is that I use my camera afocally on telescope and the less in can be touched the better (i.e. to maintain alignment etc).

Thanks very much,

Nick
Title: Re: CHDK PTP interface
Post by: ewavr on 09 / December / 2009, 05:26:25
1. Is it possible to flick through taken images in 'playback' mode without physicaly touching the camera?
2. Is it possible to zoom into an image during 'playback' mode without touching the camera? For example, is there anyway of manipulating the 'zoom slider' so that a taken image can be looked at in more detail?

You can use keys on numeric keypad for this (with numlock on):
4,8,6,2,5 as arrow keys and "set"
0 as "video" (for sx10)
"+" and "-" as zoom keys
9 and 3 as "shoot_half" and "shoot_full"
"." as "menu"
"*" as "*/erase"
"/" as "disp"

and you have 12 programmable keys (F1-F12) to run user scripts.
Title: Re: CHDK PTP interface
Post by: leedsgreen on 09 / December / 2009, 05:51:46
Wow! Thanks ewavr.

If not too much trouble, can you tell me how to load user scripts into system. I was pressing F keys last night but couldn't work how to connect to my different scripts.

Thanks again,

Nick
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 09 / December / 2009, 15:52:05
Does anybody knows the entry pont of the SX200 PTP functions ?
Title: Re: CHDK PTP interface
Post by: leedsgreen on 11 / December / 2009, 19:38:23
Dear All,

I've managed to enter basic scripts into the editor of chdkcam as well as assign them to a programmable key. However, whilst some commands appear to work, others don't. For example:

press "shoot_half"
press "shoot_full"
release "shoot_full"
release "shoot_half"

Enables a single shot to be taken. However when I add a 'sleep' command, the editor doesn't appear to accept it or make use of it. Other uBasic commands (such as n=1 to 10) appear to be misunderstood.

Is this expected or do I need to write code slightly differently to my normal scripts?

Thanks for any help,

Nick
Title: Re: CHDK PTP interface
Post by: whoever on 12 / December / 2009, 03:41:08
Other uBasic commands (such as n=1 to 10) appear to be misunderstood.
Ewavr's builds (used to) only interpret Lua thru PTP, not uBasic. Therefore, you have to use pure Lua. Not sure about 'press "shoot_half"' though -- isn't Lua supposed to understand that? Otherwise try press("shoot_half") instead. Hope that helps.
Title: Re: CHDK PTP interface
Post by: leedsgreen on 12 / December / 2009, 07:19:21
Thanks so much Whoever, have now sorted out scripts with Lua code. Fantastic!

Nick
Title: Re: CHDK PTP interface
Post by: whoever on 12 / December / 2009, 12:05:45
have now sorted out scripts with Lua code. Fantastic!
Nick
Great to hear that your astrophotography setup gets perfect shape, Nick!
Would you consider submitting a short write-up on your setup and results to "Creative uses" or elsewhere? It'd inspire the folks. And it'd bring more attention to this CHDK PTP hack, which is unjustly overlooked by most, while being -- as I believe -- a major breakthrough.
/Alex
Title: Re: CHDK PTP interface
Post by: leedsgreen on 12 / December / 2009, 12:40:56
Whoever,

I will happily do that and post in 'Creative uses'. I have actually posted there a few times in the past (after I first got continuos shooting script working) but this, as you say, is another step forward. Clouds, the bane of the astrophotographer's life*, are currently 'sitting' on top of Leeds, but when they shift and the moon is back up (my primary target), I'll post some results.

BTW I've noticed that when I reopen CHDKcam, the scripts I have assigned F keys no longer work. That is, only the first 'line' of the script is saved, the rest is deleted. Do you know how to stop this? (Save me re-typing each time).

Nick

*Of course, enjoying landscape phototgraphy as well, I do like clouds!
Title: Re: CHDK PTP interface
Post by: whoever on 12 / December / 2009, 13:46:49
BTW I've noticed that when I reopen CHDKcam, the scripts I have assigned F keys no longer work. That is, only the first 'line' of the script is saved, the rest is deleted. Do you know how to stop this? (Save me re-typing each time).
That's a question to ewavr ;)
Title: Re: CHDK PTP interface
Post by: ewavr on 12 / December / 2009, 19:41:43

BTW I've noticed that when I reopen CHDKcam, the scripts I have assigned F keys no longer work. That is, only the first 'line' of the script is saved, the rest is deleted.

Oops! You can enter several lines of text in macro editor? How?
This editor is designed for single-line short scripts. You can separate several lua operators in one line by semicolon ( ; ).
Title: Re: CHDK PTP interface
Post by: leedsgreen on 13 / December / 2009, 12:11:02
ewavr,

Thanks. Your right, I can't enter multiple lines. What happened was when I copied all lines from the script builder window (bottom left) they appeared as a long string, seperated by || (thingies, only bolded). However, when I went back in, anything after the first || dissapered. However, I have now used semicolon as you suggested and all is working.

Once again, thanks for all this development. Much appreciated etc.  :D

Nick
Title: Re: CHDK PTP interface
Post by: JMD on 14 / December / 2009, 13:33:59
Wow! This is great stuff.  I would love to try this with my SX1, version 2.01a.  Does anyone have a build for the SX1.

Thanks!
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 15 / December / 2009, 16:27:32
I have included PTP code for SX200 camera and try to start it. Nothing happens.
 When I connect the USB cable and CHDK is loaded the screen stay blank and the PTP USB device in windows is not enumerated. When I do not load CDK (unlocking the SD card) the PTP device is enuareted and I can use PTPCAM.

Can anybidy have a clue on what may be happening ?

Thanks
Title: Re: CHDK PTP interface
Post by: ewavr on 15 / December / 2009, 18:01:43
@Marcio Lima:

Under Windows?
Screen should not become a black when USB cable is connected (this means that standard PTP driver already connected to camera and libusb driver cannot connect to it). Try to disable all event handlers in camera properties in windows explorer and also "Canon camera access library" service.
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 21 / December / 2009, 12:43:40
Title: Re: CHDK PTP interface
Post by: Microfunguy on 21 / December / 2009, 13:19:35
For firmware 100c I think it is 0xFFA125D4.

Which firmware do you have ?

David
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 21 / December / 2009, 13:49:41
David

It worked! Thanks!

Marcio
Title: Re: CHDK PTP interface
Post by: ADamb on 21 / December / 2009, 15:11:49
Marcio,

What exactly are you trying to do?
SX200IS 100c is already included in PTP patch (http://ewavr.nm.ru/chdk/for_test/), overlay colors are wrong, but everything else is OK.
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 22 / December / 2009, 05:02:53
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 23 / December / 2009, 08:49:42
Title: Re: CHDK PTP interface
Post by: Microfunguy on 23 / December / 2009, 14:55:10
I recently got this from the published DIFF file:

NHSTUB(PB2Rec, 0xFF87D780)                       // via aAcPb2rec
NHSTUB(Rec2PB, 0xFF87EE50)                       // via aAcRec2pb


David
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 23 / December / 2009, 15:43:22
It seems not to work after aplying the patch. How can I be sure it works ?
Title: Re: CHDK PTP interface
Post by: fe50 on 24 / December / 2009, 08:12:55
It seems not to work after aplying the patch. How can I be sure it works ?

It works for the SX200 1.00c:
Thanks, now it is OK.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / December / 2009, 22:05:23
First try at a540 support.

Note, I added add_ptp_handler to sig_ref_vxworks_1.txt, seems to be a good match.

Live view works, switch to rec (using post_levent...) worked.
Trying to shoot after switch to rec crashed the cam.
Code: [Select]
ASSERT!! OperTrns.c Line 594
Occured Time  2009:12:24 19:05:20
TCB: 00212218
Task: tPTPSessio
SP: 0x002120C0
StackDump:
0x00000000
...
(at FFE4EB1C)


I am thinking about making a PTP branch in the main SVN. It would make it easier to keep in sync with the trunk (I have no problem with merging my trunk checkins to a branch). Or just put it in the trunk and make it compile time optional ?

edit:
I did manage to take a picture without crashing, turning off live view and bitmap updates first.
Title: Re: CHDK PTP interface
Post by: fe50 on 25 / December / 2009, 06:20:40
I am thinking about making a PTP branch in the main SVN. It would make it easier to keep in sync with the trunk (I have no problem with merging my trunk checkins to a branch). Or just put it in the trunk and make it compile time optional ?

Since it seems that this will have no negative side effects for the CHDK main functionality (at least i didn't notice any), i'd prefer to have it in the trunk, compile time optional - sooner or later PTP will be also another "usual" feature beside all others, so IMO it's simply consequent to have it in the main source tree as early as possible.

BTW - some things i've noticed while testing/using PTP on the SX10 101a (Win XP sp3, no Canon services):

Title: Re: CHDK PTP interface
Post by: Marcio Lima on 25 / December / 2009, 07:11:13
Title: Re: CHDK PTP interface
Post by: fe50 on 25 / December / 2009, 07:41:41
Title: Re: CHDK PTP interface
Post by: msl on 25 / December / 2009, 07:57:14
@Marcio Lima
Use you the windows program chdkcam (http://ewavr.nm.ru/chdk/for_test/) from ewavr' site? You must also install a usb driver libusb (http://libusb-win32.sourceforge.net/).

@reyalp
PTP service should be added optional in trunk. It works ok for me. Sometime I have a little instabil usb connection. The webcam function is also ok. I have included ptp interface in my branch (http://my-trac.assembla.com/chdkde/browser/branches/msl) of chdk_de svn server. Binary files are available here (http://drop.io/chdk_de).

For the A540 is a small correction necessary - see attachment. Without this the compiler displays a warning.
Title: Re: CHDK PTP interface
Post by: ewavr on 25 / December / 2009, 08:07:33
connected directly (on board USB, nVidia GeForce 8200 chipset) it behaves very instable, the connection mostly get lost after some seconds.
I saw the same thing with SX10 and some computer (I don't remember chipset model). When camera is switched to USB 1.1  ("B") mode, connection is stable, but frame rate is 1..2 fps ;). On the same computer connection with A710 and IXUS700 is perfect.
Title: Re: CHDK PTP interface
Post by: ewavr on 25 / December / 2009, 10:58:36
Trying to shoot after switch to rec crashed the cam.
RAW saving is off?
Title: Re: CHDK PTP interface
Post by: whoever on 25 / December / 2009, 12:18:51
Note, I added add_ptp_handler to sig_ref_vxworks_1.txt, seems to be a good match.
Gives good match (though <100%) and finds the function correctly here, too (Ixus950): NSTUB(add_ptp_handler, 0xFF9EC59C).

So, if findsig can be trained to find add_ptp_handler() on (all) other cameras, I don't see any obstacle to including the basic PTP handling stuff to the autobuild right away.

There remains the mode switching stuff, for which I'd hard-code the "logical events" PressRecButton/PressPBButton -- if I read Microfunguy correctly, this works on most (all) cameras that he supports. It may not work correctly with PTP (e.g., may disconnect), but shouldn't crash the camera.

Then, I'd bundle mweerden's ptpcam as a basic PC-side client (ewavr's extensions require much more attention for each camera and computer).

Such minimal implementation, together with reyalp's Lua additions (levents, call by name/address, etc.), already gives a powerful interface.

It may be useful to make PTP extensions run-time-optional, although it is not obvious how to do that neatly (PTP handler registration happens in a task that is not synchronized with reading of config).

EDIT: Almost forgot... Merry Christmas! Und guten Rutsch, etc.!
Title: Re: CHDK PTP interface
Post by: ewavr on 25 / December / 2009, 14:13:47
There remains the mode switching stuff, for which I'd hard-code the "logical events" PressRecButton/PressPBButton -- if I read Microfunguy correctly, this works on most (all) cameras that he supports.
It seems that this works only on some VxWorks cameras (a540, a710, ixus700, a610). On DryOS (SX10) "PressRecButton" event has no effect if USB cable is connected.
Title: Re: CHDK PTP interface
Post by: yvesson on 25 / December / 2009, 16:21:21
Hej,
well as I'm not too much into using patches and stuff, I'll just wait for it is in a built...

By the way, wouldn't this help in one of the most wanted CHDK feature request, camera acting like a card reader ?
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2009, 16:57:58
There remains the mode switching stuff, for which I'd hard-code the "logical events" PressRecButton/PressPBButton -- if I read Microfunguy correctly, this works on most (all) cameras that he supports.
It seems that this works only on some VxWorks cameras (a540, a710, ixus700, a610). On DryOS (SX10) "PressRecButton" event has no effect if USB cable is connected.
Maybe the functions used on the other cameras can be found with the sig finder. I was hoping to find an eventproc that did the same thing, but I haven't yet.

I'm not sure about putting it in the autobuild yet, I think we want room to break things for a while until we work out the best way to put it all together. Turning making the PTP stuff a runtime option shouldn't be too hard. I've had quit a few crashes/hangs just playing with script stuff in ewavrs chdkcam

@yvesson
both ewavrs chdkcam and the modified ptpcam lets you upload/download any file, although it doesn't act like a drive. With fuse we could do this quite easily on linux :)

also another most wanted feature, use camera like web cam :)
Many thanks tow mweerden and ewavr!
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 26 / December / 2009, 08:46:34
Guys

It worked on the SX200 but I used the binaries from ewavr. I would like to have the worked sources (trunk, patch, etc) because I want to add new features and also to port to SX120. Can Anybody tells me where I can download it ?

Guys Great work!
Title: Re: CHDK PTP interface
Post by: fe50 on 26 / December / 2009, 12:58:14
It worked on the SX200 but I used the binaries from ewavr. I would like to have the worked sources (trunk, patch, etc) because I want to add new features and also to port to SX120. Can Anybody tells me where I can download it ?
Hmmm - what are you missing ?
There's the diff against the official CHDK trunk (rev. #863) and also the complete source code for the Windows app (Borland C++ Builder 6) on ewavr's site (http://ewavr.nm.ru/chdk/for_test/)...

So just load trunk #863 from here (http://tools.assembla.com/chdk/browser/trunk?rev=863) (DL link for the zip file is at the bottom), apply the diff & compile it !
On Windows i suggest do use the CHDKShell
Title: Re: CHDK PTP interface
Post by: m.rump on 28 / December / 2009, 08:22:10
There remains the mode switching stuff, for which I'd hard-code the "logical events" PressRecButton/PressPBButton -- if I read Microfunguy correctly, this works on most (all) cameras that he supports.
It seems that this works only on some VxWorks cameras (a540, a710, ixus700, a610). On DryOS (SX10) "PressRecButton" event has no effect if USB cable is connected.

I'm currently working on a solution for that (I'm using the G9). The problem is, that all the whole operating mode of the camera is different when the USB cable is connected. I'm still reverse engineering the firmware to understand the "ModeDial" system. I made some progress but my work isn't finished until now. If anyone works on similar stuff I would appreciate to collaborate.
Title: Re: CHDK PTP interface
Post by: JMD on 29 / December / 2009, 12:50:48
Thanks for everyone's hard work on this.  A special thanks to ewavr for making modes for the SX1 and getting chdkcam to work.  The SX1 works fairly well.  Everything seems to work except switching from record mode to play back.  That seems to be a common theme with this series of cameras.

What are the benefits of switching to play mode?  I will likely be downloading every picture in the camera anyway through the file transfer option in chdkcam (which works in record mode).  Would this work better in play mode?  Would it be faster?  Or would it allow me to mount the camera as a Windows removable storage and get faster downloads?  I'm just curious what this buys us.
Title: Re: CHDK PTP interface
Post by: m.rump on 30 / December / 2009, 03:53:00
The problem is, that the G9 for example (an I assume all other DryOS cams, too) start in PLAY mode and I have to switch to record mode first   :)
Title: Re: CHDK PTP interface
Post by: JMD on 30 / December / 2009, 20:35:28
But chdkcam correctly switches my SX1 from "play" to "record".  I thought the problem people were have was in switching back to "play".

Does the problem occur when the USB cable is plugged in?  I noticed that if I plugged in the USB cable after the CHDK had started on the camera that 4 out of 5 times the camera would switch to "disk" mode (for lack of a better term) and not accept commands and not come out of it until I opened the battery compartment.  This is how I fixed it:

1) put a normal SD card in the camera
2) turn it on and plug in the USB cable
3) open "My Computer" in Windows
4) find the "Canon Camera" among your drives and right click
5) select "properties"
6) click on the "Events" tab
7) select "Take no action"
8 ) click "OK"

This keeps windows from trying to start a program to talk to the camera.  I found that this interfered with chdkcam and put the camera in a bad state.  Since I made this change to windows my camera never freezes up unless I click on "play" mode in chdkcam.
Title: Re: CHDK PTP interface
Post by: ewavr on 02 / January / 2010, 16:27:00
Everything seems to work except switching from record mode to play back.
If camera hangs, the problem maybe located in CHDK function:
Code: (c) [Select]

void switch_mode(int mode)
{
  if ( mode == 0 )
  {
    _Rec2PB();
    _set_control_event(0x80000902); // 0x10A5 ConnectUSBCable
  } else if ( mode == 1 )
  {
    _set_control_event(0x902); // 0x10A6 DisconnectUSBCable
    _PB2Rec();
  }
}
It seems that Rec2PB() address and magic number 0x80000902 are correct... Sorry, I can't find solution remotely, developer with SX1 wanted.
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 23 / January / 2010, 15:08:56
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 24 / January / 2010, 10:12:43
The problem is that after shooting the camnera always disconnects. If you reconnect again it works fine.
Is this a bug or it is the way the firmware was supposed to work ?

I can control the Zoom but the focus seems not to work whatever value I set.
I am trying also to set ansd reset the flash with set_pro 16 and it also seems not to work.
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 24 / January / 2010, 10:14:58
Title: Re: CHDK PTP interface
Post by: eman on 24 / January / 2010, 15:40:19
Is there a chdk build for A570 IS that have  PTP functionality?
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 28 / January / 2010, 20:31:12
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 10 / February / 2010, 04:46:13
Title: Re: CHDK PTP interface
Post by: EmilCzech on 11 / February / 2010, 16:02:06
Helo. I am camera a590IS. Test chdkcam.exe. Problem connecting camera WinXP to random.
Stop in the control panel scanner and camera connecting ok 100%.
Seems malfunctioning stabilizer.
Title: Re: CHDK PTP interface
Post by: JMD on 17 / February / 2010, 12:32:05
Special application and some general observations.  I have attached my SX1 via a USB cable to an ethernet to USB server.  That way I can make my SX1 part of my local network.  I have actually tried two different kinds of ethernet to USB servers, the results were different, but similar.

1) The frame rate and network utilization is different between the two servers
2) If I turn off the "live image" and the "overlay" the CPU usage of ChdkCam jumps way up.  With one of the servers the network utilization stayed very high even without the live feed.  With the other server the network utilization dropped to close to 0, but the CPU utilization was higher.

I'm guessing that this behavior is do to the delay in the ethernet to USB server.  Obviously, I am not getting as fast of a connection as I do when the camera is connected directly to the USB port on my computer.  Perhaps ChdkCam is polling the camera on a regular basis, but with a very short time out.  When it doesn't get a response in time it keeps polling, chewing up CPU cycles and ethernet bandwidth.  It would appear that ChdkCam needs a bit more optimization for this type of application to work well.

Ewavr, I think I can compile ChdkCam.  Do you have any suggestions on what I might change in the code to make this work better.

Thank you.
Title: Re: CHDK PTP interface
Post by: marstav on 26 / February / 2010, 09:25:04
Hello,

 I'm very interested in making PTP working on G9, but I'm stuck on the mode switching. I'm using 100g version fw. I've tried all 3 methods I found, i.e. the one with set_control_event, method with sending a disconnect event via post event and even ForceQuitPTPMode. None of them does really work, the posting of event disconnects camera, while the set_control_event simply blocks camera and the only way to get out of the state is to remove a camera battery.

Here are the function locations I've extracted.

NHSTUB(add_ptp_handler, 0xFF8D897C) // via ptp handler table
NHSTUB(set_control_event, 0xFF872C2C) // via eventproc_export_IsControlEventActive (last call)
NHSTUB(PB2Rec, 0xFF876664) // via aAcPb2rec
NHSTUB(Rec2PB, 0xFF875024) // via aAcRec2pb

NHSTUB(ForceQuitPTPMode, 0xFF83ED10)
NHSTUB(RefreshUSBMode, 0xFF83EC8C)

I've double checked outputs of "magic" transformation for set_control_event and the results are same as for the other cameras (0x902, 0x8........902).

Does anybody have an idea what else I could try in order to switch the mode?

Thank you
Title: Re: CHDK PTP interface
Post by: m.rump on 26 / February / 2010, 10:15:03
Please read my post a few pages back. Switchting mode is very tricky on G9. I'm currently reverse engineering the whole shooting process to set up an own mode switch. Until now I can run out the lens, activate the image system, set properties and start shooting. But somewhere inside the shooting process the camera comes into panic mode and switches off. I think I missed some preparating call and I did not find all the correct calls until now.
Title: Re: CHDK PTP interface
Post by: marstav on 26 / February / 2010, 10:53:21
Please read my post a few pages back. Switchting mode is very tricky on G9. I'm currently reverse engineering the whole shooting process to set up an own mode switch. Until now I can run out the lens, activate the image system, set properties and start shooting. But somewhere inside the shooting process the camera comes into panic mode and switches off. I think I missed some preparating call and I did not find all the correct calls until now.

Thank you for your feedback. It seems you made a good progress so I'll hope you'll crack the problem. Let me know if you have some particular problem I may help you, though I'm not really fluent in ARM assembly, so I'm quite slow in reading the code.
Title: Re: CHDK PTP interface
Post by: enuro12 on 03 / March / 2010, 00:43:27
I was wondering if A460 and/or IXUS 960 will be supported by PTP?
Title: Re: CHDK PTP interface
Post by: Marcio Lima on 04 / March / 2010, 05:40:50
Does anybnody has haad anyprolem with the Zoom on the SX200IS usig PTP ?  he camera after some zooing shutdown.
Title: Re: CHDK PTP interface
Post by: HarpoMa on 13 / March / 2010, 02:07:44
I will say this about PTP it is great for debugging.  Thx for doing the initial implementation.  I added it to the SD780 and love it.

Harpo
Title: Re: CHDK PTP interface
Post by: yardleydobon on 28 / March / 2010, 18:28:32
I'm using Debian Lenny. I installed libusb-0.1.8 from source in /usr/lib. I patched and installed libptp2-1.1.10 from source.
I'm using the CHDK PTP build for A590 1.01b from ewavr's site. When I try ptpcam I keep getting:
ERROR: Could not open session!

I've tried using ptpcam --bus=BUS-NUMBER --dev=DEV-NUMBER with bus-number and dev-number taken from lsusb. I still get the same error.

I also have the libusb.0.1-4 installed that's part of Debian.

Could someone tell me what's going wrong?

Edit:
Mweerden helped me figure out the problem was that my camera was talking to the Debian libusb and not the libusb I installed from source, which libptp was dependent on. Uninstalling libusb-0.1.8 and installing the Debian package libusb-dev, then recompiling and reinstalling libptp got everything working.

Here are step by step instructions for getting a patched version of libptp going on Debian Lenny:
$ su -c "apt-get install libusb-dev"

$ mkdir libptp_chdk
$ cd libptp_chdk
$ wget http://www.mweerden.net/download/chdk-ptp/chdk-ptp.patch (http://www.mweerden.net/download/chdk-ptp/chdk-ptp.patch)

download libptp2-1.1.10.tar.gz from:
http://sourceforge.net/projects/libptp/files/libptp2/ (http://sourceforge.net/projects/libptp/files/libptp2/)
and save it in libptp_chdk

$ tar xvzf libptp2-1.1.10.tar.gz
$ patch -p0 < libptp-chdk.patch
$ cd libptp2-1.1.10/
$ ./configure
$ make
$ su -c "make install"

I had to run ldconfig so ptpcam could see libptp2.
To see if ptpcam can find libptp2 run this: $ ldd `which ptpcam`
If it says "not found", run:
$ su -c "ldconfig"


Title: Re: CHDK PTP interface
Post by: mweerden on 31 / March / 2010, 12:53:51
Glad to see the continued activity here.

As a result of yardleydobon trying to get CHDK PTP to work on his camera (and specifically him not being able to download JPEGs), I noticed that there is a file size limit to the files that can be downloaded with my original patch/download functionality. I got a maximum of 251312 while experimenting, which seems to relate to USB packet sizes of 256k. As I couldn't find any other mentioning of it, I figured I'd add it here. I guess ewavr also noticed it, seeing his PTP patch.

One additional thing about this: given Microfunguy's post (http://chdk.setepontos.com/index.php/topic,4338.msg41449.html#msg41449) it seems as if this limit does not hold for his camera (or perhaps VxWorks). Or perhaps he just had a pretty small photo?


As for the discussion whoever tried to start (http://chdk.setepontos.com/index.php/topic,4338.msg43676.html#msg43676) (and sort of started later (http://chdk.setepontos.com/index.php/topic,4338.msg44963.html#msg44963)), I would suggest adding CHDK PTP to the trunk in a minimal form. Having a central "standard" interface should avoid too much divergence in patches and tools as well as increase visibility, usage and improvements.

The main question then becomes "what is this minimal form?" Which I'd split into the following questions (mainly based on the patches of ewavr and myself).

Add upload/download?
This seems to me as one of the essentials as it provides functionality that isn't available through the firmware PTP on many cameras and is one of the main reasons to extend PTP. Edit: Regarding downloads and file size limits, there are two options: either use ewavr's method of repeatedly getting parts of the file or, and this would be much nicer if possible, figuring out how the send_data function really works to enable repeated calls (similar to how uploading works).

Add script execution?
As this instantly provides access to a great part of CHDK functionality, this also seems a no-brainer. There are two additional questions here, though. First of all, LUA or uBASIC? I'd originally did LUA because it seemed to be the easiest to make and I got the impression that LUA is preferred. However, I've been told that uBASIC is easier for "non-hackers". If someone knows (or makes) a easy way to execute a string containing uBASIC, then I'd think it's easy and cheap to allow both (change PTP_CHDK_ExecuteLUA to PTP_CHDK_ExecuteScript and use param2 to indicate the language).

The other question is regarding the output. Is having it scroll over the camera screen sufficient or do you want to be able to read it out via PTP? In case of the latter, do you store all output in camera memory first or do you send a PTP event for every line (should be nicest, but haven't looked at such functionality).

Add "debugging" features?
This includes reading/writing memory, remote calling of functions (by address) and retrieval of props and params. I'm in favour of at least keeping the first two. Both for actual debugging and possibly providing tools with an easy way to extend functionality not available otherwise without having to change CHDK itself (albeit camera specific, unless we have/add a way to resolve function names). For the other two see "Add specific functionality" below.

Add mode switching?
I'm not entirely sure about this one, but I suspect it is also covered under the "Add specific functionality" part below.

Add shutdown/reboot?
See "Add specific functionality."

Add video settings retrieval?
See "Add specific functionality."

Add directory reading?
See "Add specific functionality."

Add specific functionality?
To minimise extending CHDK PTP indefinitely with more and more useful functionality, I think it is preferable to only do this when there is absolutely no other way. I'm hoping that most of these things can be better implemented as LUA functions and accessed as such via PTP. I think this is at least the case for things like mode switching, shutdown/reboot and directory access.

The only downside to doing things via scripts is that values have to be constantly converted to and from strings. On the other hand, how much data does one expect to be transferred in this way? Big chucks of memory can better be obtained using CHDK PTP "get memory" functionality (meaning some script functions should return pointers).

When should CHDK PTP be enabled?
I think the amount of code is pretty small and the code is only used when specific CHDK PTP commands are received. The only side effects are an extra short task at initialisation and one extra entry in the PTP handlers list. I don't really see any objection to having it enabled all the time. That is, as long as it's supported by the camera, which means controlling its addition with defines in camera.h.

Also, I'd suggest ensuring that CHDK PTP can be enabled with a minimal amount of effort. For example by just adding add_ptp_handler and the one define in camera.h. The rest of the camera specifics could be covered by trivial default wrappers that just return something such that CHDK PTP knows the functionality isn't implemented. I think this might also be very helpful when porting; one of the first things you do is add the CHDK PTP task and you can already remotely inspect memory and call functions. Add file-operation stubs and you can easily upload new CHDK images without constantly removing and inserting cards.


Well.. that's a bit more text than I anticipated.. ;) To summarise: I'd suggest adding CHDK PTP to the trunk, enabled via camera.h and consisting of just upload/download, read/write memory, function call and script execution (LUA and uBASIC and preferably with per line output PTP events). The rest (e.g. mode switching, video conf) I'd move to LUA and/or uBASIC.
Title: Re: CHDK PTP interface
Post by: yardleydobon on 31 / March / 2010, 19:56:47
I'd like to report that for my A590 IS with 1.01b:
  lua post_levent_to_ui("PressRecButton")
  lua shoot()
works for capturing images over PTP. Pressing the <Alt> button unlocks the other buttons and zoom.

I don't really know enough to comment knowledgeably on what the CHDK PTP interface should be. However, I think you've just laid out a very clear description of a clean and simple interface. Mode switching seems to be so varied between cameras I think it is best to leave that to a script. I think the interface should be easily built upon by other programs; for example I'd really like to see a remote capture GUI for Linux, and a CLI that has command history and can read and execute scripts saved as files.

I think it should definitely be in trunk. I sure don't get why the hell this thread is fading and CHDK PTP isn't getting more attention! Perhaps many people don't realize that this effectively adds computer control to CHDK.
Title: Re: CHDK PTP interface
Post by: reyalp on 31 / March / 2010, 20:51:04
Agree with mweerden.

I don't personally see any reason to add ubasic support. If you restrict yourself to doing the things that ubasic can do, an equivalent lua script isn't really more complicated.

Executing ubasic shouldn't be too hard, but you'd need to do something about the one statement per cycle business (so you'd need a loop running ubasic_run until it finished). The PTP handler should probably just pass a message to the kbd task to run the script in the normal way, otherwise we will run into problems with long running scripts, not to mention things running in a different task than they expect to.

A further (somewhat OT) thought I've had on scripting is to allow PTP to communicate with an already running script, rather then sending a full script to be executed each time. If you also added a way to send messages back, you'd have a very flexible interface with very little code required.
Title: Re: CHDK PTP interface
Post by: an0n on 01 / April / 2010, 04:26:50
Title: Re: CHDK PTP interface
Post by: JMD on 01 / April / 2010, 15:31:43
I have a question about adding code to the trunk.  When you add code to the trunk, is there a policy that all of the cameras that support the new code have to be updated? i.e. Does someone need to go in and modify all of the platforms and all of the firmware versions within the trunk, or will that be done piece meal?  Just curious.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / April / 2010, 15:54:39
I have a question about adding code to the trunk.  When you add code to the trunk, is there a policy that all of the cameras that support the new code have to be updated?
No, features can be only enabled for certain cameras. Extra long exposures are and example.

Of course, the goal is to support each feature on every camera capable of supporting it.
Title: Re: CHDK PTP interface
Post by: JMD on 01 / April / 2010, 18:19:17
Thanks reyalp

I posted this a couple of weeks ago and didn't get a response, do you have any insight as to how I could make this application work more efficiently.

Quote
Special application and some general observations.  I have attached my SX1 via a USB cable to an ethernet to USB server.  That way I can make my SX1 part of my local network.  I have actually tried two different kinds of ethernet to USB servers, the results were different, but similar.

1) The frame rate and network utilization is different between the two servers
2) If I turn off the "live image" and the "overlay" the CPU usage of ChdkCam jumps way up.  With one of the servers the network utilization stayed very high even without the live feed.  With the other server the network utilization dropped to close to 0, but the CPU utilization was higher.

I'm guessing that this behavior is do to the delay in the ethernet to USB server.  Obviously, I am not getting as fast of a connection as I do when the camera is connected directly to the USB port on my computer.  Perhaps ChdkCam is polling the camera on a regular basis, but with a very short time out.  When it doesn't get a response in time it keeps polling, chewing up CPU cycles and ethernet bandwidth.  It would appear that ChdkCam needs a bit more optimization for this type of application to work well.

Ewavr, I think I can compile ChdkCam.  Do you have any suggestions on what I might change in the code to make this work better.

Thank you.
Title: Re: CHDK PTP interface
Post by: mweerden on 01 / April / 2010, 20:09:08
..., I noticed that there is a file size limit to the files that can be downloaded with my original patch/download functionality. I got a maximum of 251312 while experimenting, which seems to relate to USB packet sizes of 256k.
Quote
Regarding downloads and file size limits, there are two options: either use ewavr's method of repeatedly getting parts of the file or, and this would be much nicer if possible, figuring out how the send_data function really works to enable repeated calls (similar to how uploading works).

Today I intercepted a firmware handler to see how send_data is normally used. It turns out that of the two "size" parameters the first should be the size of the block that is sent with a given call and the second should be the total size. This isn't surprising and I'm pretty sure I tried it, but the trick is that the second size should only be given with the first call (and it should be 0 afterwards). With this it is now possible to nicely download big chunks of data.

B.t.w., I haven't checked it explicitly, but the file size limit I encountered is more likely due to the fact that malloc fails. The code suggest that this should result in a different error code, but it seems that either USB or the libptp2 code doesn't pass it on.

The two parameters after size appear to be a function/data pointer pair. In the case I tested the function was at 0xff8d222c, which basically consists of a call to GiveSemaphore. I guess it is called when the transfer is finished. I haven't looked into this any further.


I don't personally see any reason to add ubasic support. If you restrict yourself to doing the things that ubasic can do, an equivalent lua script isn't really more complicated.

Perhaps we can just implement the PTP_CHDK_ExecuteScript and only support LUA at first. This only adds a simple if and if the need for uBASIC really arises it can be added then.

Quote
A further (somewhat OT) thought I've had on scripting is to allow PTP to communicate with an already running script, rather then sending a full script to be executed each time. If you also added a way to send messages back, you'd have a very flexible interface with very little code required.

I've also tried to find a way to send back events today, but was not entirely successful. I did find a function that almost certainly is used for sending events, but I couldn't get it to work. I found it by searching for 0x0000c008. For my IXUS870IS (1.01a) it's at 0xff9f138c. It can also be found by picking the right PTP handler; for example at the end of the PTP_OC_SendObjectInfo (0x100C) handler.

The first parameter is most likely the "Event DataSet" (with 4-byte code): struct { int code, sess_id, trans_id, param1, param2, param3; }. The second parameter seems to hold flags; the two least significant bits each result in a specific function call if set. I've seen the values 2 and 3 for this parameter (mostly 2).


Truly OT: Why aren't we using a DVCS (http://chdk.setepontos.com/index.php/topic,2304.msg48125.html#msg48125)
Title: Re: CHDK PTP interface
Post by: mweerden on 05 / April / 2010, 06:15:36
I made an initial attempt for the minimal CHDK PTP interface. In addition to the suggestions I made previously I also added a way to request a version to be able to ensure both parties understand each other. Apart from one thing, I think it is already something that could be included in the trunk. The "one thing" is the name of the new Lua function switch_mode; as there already seem to be functions to switch mode under normal conditions, this name should probably reflect its USB-connection requirement.

As I'm playing with git and GitHub, I've made it available on the latter (http://github.com/mweerden/CHDK/tree/ptp). You can view the changes here (http://github.com/mweerden/CHDK/compare/master...ptp) (unfortunately not (yet) downloadable as patch; if anyone wants it, just ask).

The thing that remains is script feedback. There are two parts, I think. One is getting the "console" output (like in ewavr's tool) and the other is getting return values of a script. I think the first would be excellent for events, if we can figure those out. Until that time I'd suggest getting the info (i.e. all text, a single line or a pointer to memory) using Lua.

For the return values I was thinking about the following. Use a PTP parameter for flags and include the flags "wait for script termination" and "store (first) return value in TempData" (the latter requiring the first). Do the same for the PTP_CHDK_TempData command for the flags "download" (instead of the current upload) and "remove/free data".

With the storing of the return value you'd return the type of the data put in TempData (no data, nil, boolean, number, string; the rest I'd ignore for now) and possibly its size. I only talk about one return value (instead of the arbitrary number of values that might be available) because I'm assuming that this is almost always what you need. It also makes things a bit easier (e.g. making TempData point to the const char* returned by Lua for strings).
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / April / 2010, 08:36:19
I did play with this a few months ago with the A620 and SDM but have been concentrating on other features since then.

I am not sure what percentage of users will actually use this, clever though it is.

I am certainly not adding Lua support, that will terrify SDM users.

How much does the filesize increase with this compile-option enabled ?


David
Title: Re: CHDK PTP interface
Post by: mweerden on 05 / April / 2010, 14:01:48
I am not sure what percentage of users will actually use this, clever though it is.

What I'd expect is that "normal" users would be interested in:
This interface makes these tools possible.

Quote
I am certainly not adding Lua support, that will terrify SDM users.
And you have every right not to. However, adding Lua support doesn't mean people have to use it themselves or that they can't use uBASIC (assuming support for it is implemented at some stage).

Especially with the possibility to obtain the return values, I believe the Lua support is ideal for tool makers. I don't know if the same would hold for uBASIC, simply because I know nearly nothing about it.

Quote
How much does the filesize increase with this compile-option enabled ?
This is what I get when building for the IXUS870IS:
DISKBOOT.BINPS.FI2
full support259337153424
no CHDK PTP (undef in camera.h)258097152528
no CHDK PTP and no support in platform257865152448
clean (i.e. current CHDK trunk)257633152320
That's +0.66% for DISKBOOT.BIN and +0.72% for PS.FI2 when you compare clean vs. full support.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / April / 2010, 14:07:37
Thanks.

The comments about Lua are because of the amount of memory it consumes that I could use for other purposes.

Actually, my current code for the A620 does contain some of your basic ptp code.

As I recall, I get a compiler warning about implicit declaration of _ExitTask.


David
Title: Re: CHDK PTP interface
Post by: zeno on 05 / April / 2010, 18:07:47
David - I'd be interested in doing the necessary uBasic additions for SDM (and CHDK) for this.
Title: Re: CHDK PTP interface
Post by: mweerden on 05 / April / 2010, 18:10:33
Actually, my current code for the A620 does contain some of your basic ptp code.

As I recall, I get a compiler warning about implicit declaration of _ExitTask.
Although the warning isn't anything serious, the solution I described here (http://chdk.setepontos.com/index.php/topic,4338.msg41513.html#msg41513) is what I've been using everywhere since pretty much that moment.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / April / 2010, 18:53:34
@mweerden
I had forgotten that I had even mentioned that previously.

@zeno

Carry on, I am having a rest so that I have more time to take photos.
Title: Re: CHDK PTP interface
Post by: JMD on 06 / April / 2010, 17:46:18
Has anyone here built CHDKCam recently.  If so I would appreciate some advice on how to set up the build environment.  How difficult is it?  Is there a sort of plug and play build tool that will make it simple?

Thanks
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / April / 2010, 18:24:26
Has anyone here built CHDKCam recently.  If so I would appreciate some advice on how to set up the build environment.  How difficult is it?  Is there a sort of plug and play build tool that will make it simple?
I've only looked at the code briefly, but it seems to be build with (and requires) Borland C++ Builder (v6.0). If you have it (or can get it) then that's pretty much a "plug-and-play build tool".
Title: PTP Patch for A650 IS on build 885
Post by: lauer on 11 / April / 2010, 21:52:25
Thank for muck's help.
The patch for A650 IS 100d tested on build 885
Title: Re: CHDK PTP interface
Post by: msl on 20 / April / 2010, 07:44:45
Hi ewavr,

I could test a few days the SX200.The ptp interface works very well for this cam. But the color of overlay display could be improved.Thatswhy I asked rudi to analyzing this problem.

Here is a chdkcam screenshot: (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fs1.postimage.org%2F6KOm9.jpg&hash=5d421ed256a69de579677d6f54d40ebc) (http://www.postimage.org/image.php?v=gx6KOm9)

And this are he color palettes of the SX200 (play and record)
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fs4.postimage.org%2FslkfJ.jpg&hash=afe2dbddec311e69dffab97f1684d01d) (http://www.postimage.org/image.php?v=aVslkfJ) (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fs1.postimage.org%2F6LoMi.jpg&hash=28daaefd8401061819465648ad8fc0d1) (http://www.postimage.org/image.php?v=gx6LoMi)

Here is the Ramdump SX200 (http://chdk.bplaced.net/extra/ram_dump_sx200.zip) (play and record).

This has written rudi:

***********************************************************************************
we have two variants of color palettes.

At first the calculated varinat from 4x 16 byte as VUYA, you named it syspal. It is used by VxWorks- and older DryOS-cams (tested on IXUS80, A590, A610, A620, A710, A720).
The maincolors are diagonal arranged.

transparent-byte:
I found $FF > $7F(or $80),$3F > $00 (full transparent > middle > not transparent)

luminance-byte:
This value are never over $E0. This is 7/8 from a byte value. So I have a different calculation routine. Please try it.

my favorite calculation routine:
        y:=(c1.Y+c2.Y)div 2;
        y:=y*8 div 7;
        if y>$ff then y:=$ff;
        c.Y:=y;
        c.U:=(c1.U+c2.U) div 2;
        c.V:=(c1.V+c2.V) div 2;
        c.A:=(c1.A+c2.A) div 2;



At second a full palette variant with 4x 256 byte as AYUV. It is used by newer DryOS-Cams (tested on SX200).
In this case the colors are in a line arranged.

transparent-byte:
found $03 > $02,$01 > $00 (full transparent > middle > not transparent)

my routine to adapt:
        case c.A of
          01: c.A:=$3f;
          02: c.A:=$7f;
          03: c.A:=$ff;
          else c.A:=$00;
        end;


---------------------------------------------------
For color arrange see CHDK palette viewer.

---------------------------------------------------
I have written a ColorTab-Viewer (http://chdk.bplaced.net/extra/ColorTab.zip).

You can open extracted color tables with 64 or 1024 byte, a RAM-Dump or a firmware-dump (PRIMARY.BIN). I found only on DryOs-firmware build-in color tables.
On RAM-Dumps the program looks-up for pointer address to color table (displayed only the first found address), look at status bar.

To idendify colortables: first color must be a full transparent color and last color must be black without transparency.

You can change the color decoder routine for calculated color tables in menu "decoder".

Also you have a preview function by mouse-over in color field (tranparent colors have a gray frame all other a black frame).  The preview area on left side show additional color information and under it is a sorted color list.

rudi
***********************************************************************************

Maybe you can use this knowledge to improve the overlay colors in chdkcam.

msl
Title: Re: CHDK PTP interface
Post by: mweerden on 28 / April / 2010, 12:09:04
I've just implemented the return-value feedback for script execution (see here (http://github.com/mweerden/CHDK/compare/master...ptp)). With this I think we have a pretty nice initial implementation to add to the trunk. Let me know what you think.

I also figured out how to send events (http://www.mweerden.net/chdk_ptp2.html), but I don't really see an obvious and nice way to use it to get script output. Last time I seem to have conveniently forgotten the fact that events don't "carry" data (apart from three integer parameters). You can use them as notifications, but then you have to store output until it is retrieved by the client. Another option could be to use the parameters to store 4 characters and use as much events per line as necessary, but I'm not sure they'll arrive in order and thus far I've only been able to transmit one parameter per event.
Title: Re: CHDK PTP interface
Post by: c10ud on 02 / May / 2010, 08:36:20
I've just implemented the return-value feedback for script execution (see here (http://github.com/mweerden/CHDK/compare/master...ptp)). With this I think we have a pretty nice initial implementation to add to the trunk. Let me know what you think.
great, i'm looking forward a merge with trunk, so every camera can easily benefit of this super addition!
I also figured out how to send events (http://www.mweerden.net/chdk_ptp2.html), but I don't really see an obvious and nice way to use it to get script output. Last time I seem to have conveniently forgotten the fact that events don't "carry" data (apart from three integer parameters). You can use them as notifications, but then you have to store output until it is retrieved by the client. Another option could be to use the parameters to store 4 characters and use as much events per line as necessary, but I'm not sure they'll arrive in order and thus far I've only been able to transmit one parameter per event.
i think events could be useful for some chdk custom ptp capture (they could carry a capturefinished event and/or some object handle so one can easily retrieve/delete/whatever the just captured image(s) when they're ready) but i think this is not trivial to do..
Title: Re: CHDK PTP interface
Post by: JMD on 18 / May / 2010, 19:10:45
Is it possible to limit the live image frame rate in the CHDK code?  I'm running in a rather unusual configuration (through a ethernet to USB server), and I believe the server is choking on UDP packets.

Thanks
Title: Re: CHDK PTP interface
Post by: waldo on 20 / May / 2010, 19:32:10
The ability to get a screen image via USB is great!  Is it possible to pass the screen bitmap image through the camera's JPEG compressor?  This might allow faster FPS or lower bandwidth transfers to the PC.
Title: Re: CHDK PTP interface
Post by: c10ud on 01 / June / 2010, 05:59:53
i wanted to find ptp entry points for other cameras as well, do i have to follow the "standard" procedure for finding entry points or is there a faster version? :P
Title: Re: CHDK PTP interface
Post by: whoever on 01 / June / 2010, 13:17:23
i wanted to find ptp entry points for other cameras as well, do i have to follow the "standard" procedure for finding entry points or is there a faster version? :P
Sort of, by using the signature finder, (http://chdk.wikia.com/wiki/Signature_finder) which is a standard way to find most functions. This proved to work well on a few VxWorks cameras (flip back a few pages and look for reyalp's patch). You can try the same approach for DryOS, which probably is your target. For a start, take the reference A720 firmware, where add_ptp_handler address is known (see ewavr's patch back in the thread), use "gensig" to generate a signature, and try "finsig" with that signature on a different firmware. Of course, you will have to "manually" verify (by visual inspection and/or experiment) that the result is correct. Yes, human intellect still counts...
Title: Re: CHDK PTP interface
Post by: ledelectronics on 01 / June / 2010, 21:36:45
Is it possible to compress liveview image into JPEG before transferring it through USB to PC?
Title: Re: CHDK PTP interface
Post by: ballloons on 05 / June / 2010, 23:21:45
Forgive the list of questions -- of which I have alot being so new. But, I am trying to implement a "photobooth" as I describe here:

http://chdk.setepontos.com/index.php/topic,5282.new.html (http://chdk.setepontos.com/index.php/topic,5282.new.html)

Given that this PTP mode seems to give me the remote control I was looking for (I'm still amazed!), I have a few questions to finish the implementation. Note I am using linux.

How are you getting the live feed from the camera?
How can I get the return values from a lua script?
Is it possible to execute a script on the camera (merely for ease of use) or must I submit the entire script to be run from the command line?
Finally, I've been playing with ptpcam, but see mention and screenshots of chdkcam. Where can i get this software? It appears to be windows only -- does there need to be pc-side tools developed for this for mac and linux?
Answering myself for the benefit of others: http://ewavr.nm.ru/chdk/for_test/ (http://ewavr.nm.ru/chdk/for_test/) and yes it appears there is a need. I will begin examining the code for chdkcam

I apologize if these have been answered already. Thanks!
Title: Re: CHDK PTP interface
Post by: whoever on 09 / June / 2010, 12:21:41
Note I am using linux.
There's no publicly known linux client so far.
Quote
How are you getting the live feed from the camera?
By repeatedly reading, through "custom" PTP requests, a chunk of camera memory that hosts the live view buffer (it is in YUV format). So far, there is no synchronization or such.
Quote
How can I get the return values from a lua script?
Read the latest mweerden's posts up this thread and implement his ideas.
Quote
Is it possible to execute a script on the camera (merely for ease of use) or must I submit the entire script to be run from the command line?
Nobody bothered so far, but it is pretty straightforward to implement.

Good luck! Please post about your successes.
Title: Re: CHDK PTP interface
Post by: ballloons on 27 / June / 2010, 22:18:21
Thank you for the answers. Because of time constraints, I did not pursue a full linux client, but instead used python and expect to wrap around ptpcam. It's kludgy, but it worked. You can find the code here:

Please note this is my first time coding in python as well as gtk.  :-[

http://code.google.com/p/chdkphotobooth/ (http://code.google.com/p/chdkphotobooth/)
Title: Re: CHDK PTP interface
Post by: jmgummes on 01 / July / 2010, 14:29:05
Hi all,

I am having trouble getting the PTP interface working on an a590 101b camera and linux.  ballloons has already listed off the steps to do this at http://chdk.setepontos.com/index.php/topic,5282.new.html: (http://chdk.setepontos.com/index.php/topic,5282.new.html:)

(1) Patch libptp2 using mweerben's ptp patch
(2) use custom build for CHDK a590 (in testing folder)
(3) connect camera in playback mode
(4) run ptpcam --chdk

But I have followed these steps without success.  After I connect the camera to my computer via usb (in playback) mode, the screen goes blank and all of the buttons on the camera become unresponsive.  (At this point the top LED above the camera screen is lit, but I don't see anything else interesting happening with the camera.)  When I try to issue the "shutdown-hard" or "reboot" commands, I get the following error: "unexpected return code 0x2001".  Also, when I run "lua shoot()" the camera doesn't do anything and I get no output on the terminal.

I am pretty confident that I followed steps (1), (3) and (4) correctly, but I am not sure that I used the correct CHDK build in step (2). I took the build from here: http://ewavr.nm.ru/chdk/for_test/. (http://ewavr.nm.ru/chdk/for_test/.)

Does anyone have any idea what is going wrong?  I would appreciate any insights here.

Jim
Title: Re: CHDK PTP interface
Post by: ewavr on 01 / July / 2010, 14:42:38
When I try to issue the "shutdown-hard" or "reboot" commands, I get the following error: "unexpected return code 0x2001".` I took the build from here: http://ewavr.nm.ru/chdk/for_test/. (http://ewavr.nm.ru/chdk/for_test/.)
This build is not fully compatible with mweerben's ptp patch: "shutdown-hard" or "reboot" commands are not supported.

edit:
Quote
when I run "lua shoot()" the camera doesn't do anything and I get no output on the terminal.
Try "mode 1" command for switching camera to record mode.
Title: Re: CHDK PTP interface
Post by: jmgummes on 01 / July / 2010, 15:03:22
Quote
Try "mode 1" command for switching camera to record mode.

The command seems to have no effect.  (I don't get any output on the terminal and the camera doesn't do anything).  Here's what my terminal looks like:

<conn> mode 1
<conn> lua shoot()
Title: Re: CHDK PTP interface
Post by: jmgummes on 01 / July / 2010, 16:26:15
I feel that the unresponsiveness of the camera is due to windows interfering as described here (taken from page 11):

Quote
I noticed that if I plugged in the USB cable after the CHDK had started on the camera that 4 out of 5 times the camera would switch to "disk" mode (for lack of a better term) and not accept commands and not come out of it until I opened the battery compartment.

I am running linux in a windows virtual box that, so when I plug in the USB cable the camera first talks to windows before I can capture it into the linux machine.  Could the communications with windows be the problem here?
Title: Re: CHDK PTP interface
Post by: jimb on 01 / July / 2010, 21:36:37
So where would one start porting the patches to an A560?
Title: Re: CHDK PTP interface
Post by: c10ud on 04 / July / 2010, 09:55:58
so, i was experimenting a bit with the viewfinder image lurking ewavr's code in order to make the yuv-to-rgb conversion OS agnostic.

Code: [Select]
    char* liveb = NULL; 
    unsigned char* buf1= NULL;
    int WIDTH = 720;
    int HEIGHT = 480;
    int BUFWIDTH = 720;
    long int SIZE = (BUFWIDTH*HEIGHT*6)/4;
    liveb = ptp_chdk_get_memory(ADDRESS, SIZE, &params, &params.deviceinfo);
    if (liveb == NULL)
        return NULL;
    buf1=(unsigned char*)liveb;
    unsigned char* nastybuf =(unsigned char*) malloc (sizeof(unsigned char*)*SIZE);
    if (nastybuf == NULL)
        return NULL;
    memcpy(nastybuf, liveb, SIZE);
    int* col = (int*)nastybuf;
    int x = 0; int y = 0;
    for (y=0; y<HEIGHT; y++) {
    for (x=0; x<BUFWIDTH; x+=4, buf1+=6) {
        if ( x < WIDTH) {
            *col++=get_pixel_yuv(buf1[1],  buf1[0], buf1[2]);
            *col++=get_pixel_yuv(buf1[3],  buf1[0], buf1[2]);
            *col++=get_pixel_yuv(buf1[4],  buf1[0], buf1[2]);
            *col++=get_pixel_yuv(buf1[5],  buf1[0], buf1[2]);
        }
    }
    }   
    free(liveb);
    return nastybuf;
the current code returns a nice uchar* with raw rgb data. using the Qt toolkit i can magically convert this to whatever image format i want with two simple lines
Code: [Select]
    QImage img(nastybuf, WIDTH, HEIGHT, QImage::Format_RGB32);

    img.save("converted_image.bmp");
however a cool thing would have been returning "complete" image data instead of raw rgb without involving the use of a complete toolkit in orderd to be fast and more platform-independant as possible (i see ewavr uses Windows' GDI+ for converting the image data in his chdkde tool). I was thinking on linking some c library like libjpeg, what do you think? Is there a simpler solution in your opinion?

greets
Title: Re: CHDK PTP interface
Post by: c10ud on 05 / July / 2010, 04:35:26
great reply from reyalp: http://chdk.setepontos.com/index.php/topic,5415.0.html (http://chdk.setepontos.com/index.php/topic,5415.0.html)
Title: Re: CHDK PTP interface
Post by: ballloons on 06 / July / 2010, 20:01:16
jmgummes -- you need to send the following lua command to force the camera back into shooting mode. Until then no commands will respond.


lua post_levent_to_ui("PressRecButton")


then, things like
lua shoot()

should operate correctly.. Can you read python? If so you'll find the wedding photobooth code helpful as an example of crudely controlling the camera in this manner.
Title: Re: CHDK PTP interface
Post by: 3pointedit on 09 / July / 2010, 01:04:45
I'm very new to this and don't understand what to do to get my a720 recognised by Win XP? I have latest chdk build and libusb for windows installed and CHDKCAM too. I cannot get my a720 to become available to the PC at all now, where at least it used to be seen by the Canon pc transfer app before. Of course CHDKCAM cant see it either.

I really would like to use it for an animation trigger via usb. Thanks for any advice (btw, I love chdk!), keeps me from buying a 550D ;)
Title: Re: CHDK PTP interface
Post by: fe50 on 09 / July / 2010, 01:28:47
Hello & welcome, 3pointedit !

I'm very new to this and don't understand what to do to get my a720 recognised by Win XP? I have latest chdk build and libusb for windows installed and CHDKCAM too. I cannot get my a720 to become available to the PC at all now, where at least it used to be seen by the Canon pc transfer app before.
The PTP stuff is not integrated in the standard CHDK builds from the Autobuild server; there are compiled binaries (i.e. "ready-to-use") for some cameras...

--> http://chdk.wikia.com/wiki/User:Fe50#PTP_stuff (http://chdk.wikia.com/wiki/User:Fe50#PTP_stuff)
Title: Re: CHDK PTP interface
Post by: 3pointedit on 09 / July / 2010, 06:47:34
I have downloded and applied the CHDK-a720-100c-0.9.9.zip, which contained a .bin and PS.FI2 files. I added these to my SD card and CHDK booted ok but my PC still cant see the camera. Is there something about Libusb I should be doing? I installed it from the win32 build site at sourceforge, but couldnt get the latest build to install. I tried a slightly earlier Vers. It seemed to give me all the right install windows during the wizard.

I assume that it sees the camera ok, should I be registering the device somehow?
Title: Re: CHDK PTP interface
Post by: fudgey on 09 / July / 2010, 12:14:40
I may be wrong, but my best guess is you need to disable CHDK USB remote shutter feature from CHDK settings for PTP to work.
Title: Re: CHDK PTP interface
Post by: 3pointedit on 10 / July / 2010, 03:21:10
Thanks Fudgey, that did get the computer to correspond with the camera. But now the chdkcam app jams at start up. The egg timer appears until I switch off the camera or change to shoot mode.

When I go to close the program, I am warned that the program is not responding.

Thanks again, my deadline for capture approaches and I really hope to be able to do it remotely.
Title: Re: CHDK PTP interface
Post by: mwarning on 10 / July / 2010, 07:50:21
Hi,

I have downloaded the CHDK-sx200is-100d=100c-1.0.1_msl.zip prebuild and replaced the DISKBOOT.BIN
of my chdk installation.

When I plug the usb cable into my camera and start in play mode, no buttom on the camera reacts anymore (only on/off buttons). Therefore I plug in the usb cable after CHDK is manually loaded. (maybe that's the problem?)
When I start up the patched ptpcam on linux ("ptpcam --chdk") and enter the mode command:

<conn> mode 0
unexpected return code 0x2005
mode switch failed!


<conn> lua post_levent_to_ui("PressRecButton")
unexpected return code 0x2ff
execution failed!

^ this command turns my camera off.

Any ideas what could be wrong?
Title: Re: CHDK PTP interface
Post by: 3pointedit on 10 / July / 2010, 08:30:42
lucky you, i cant even interact with the software.
Title: Re: CHDK PTP interface
Post by: 3pointedit on 10 / July / 2010, 20:33:41
I ran chdkcam in win 98 compatability mode (on XP) and it worked but there is a window asking to select a program to use for my camera. The problem is that the program doesnt appear on the list so I cannot force it to use chdkcam. When I dismiss the window then the program looses control of the camera and it disconnects.
Title: Re: CHDK PTP interface
Post by: mwarning on 13 / July / 2010, 08:49:50
I wonder if it would work when I compile a fresh chdk (with ptp support) for my sx200.
But the chdk build environment won't compile (on debian, doesn't looks like a missing dependency).
Title: Re: CHDK PTP interface
Post by: JMD on 13 / July / 2010, 19:12:14
I ran chdkcam in win 98 compatability mode (on XP) and it worked but there is a window asking to select a program to use for my camera. The problem is that the program doesnt appear on the list so I cannot force it to use chdkcam. When I dismiss the window then the program looses control of the camera and it disconnects.

When that window pops up go to "My Computer", find the "Canon Camera" entry in the list of drives, right click on it, click on "Properties", click the tab "Events", select "Take no action".  It has been my experience that Windows tries to access the camera as some type of removable drive.  I believe it sends some sort of commands to the camera that confuses the PTP interface.  If you tell windows XP to take no action when it sees the camera, then you can simply open CHDKCAM and it will find the camera.
Title: Re: CHDK PTP interface
Post by: JMD on 13 / July / 2010, 19:15:36
Can I get someone's help in locating the NHSTUBs for an SX1, 2.00h.  I have CHDK Shell and, as long as the code is very close to the SX1 2.01A, I think I can make the other code changes.  I just don't have any experience with the STUBS.

Thanks
Title: Re: CHDK PTP interface
Post by: joseywales72 on 15 / July / 2010, 07:20:50
Hi,
I have two Canon cameras (A570IS and a SX10IS) and use Chdk with them since the day I bought them. Chdk really supercharged them. Anyway, I want to use the PTP interface of chdk with my SX10, but my firmware is 103a. Is there anything I can do to downgrade to 102b, which ewavr's chdk-ptp is built upon?
Also, is there a list of pt-codes that describe which code does what? I use exclusively Linux, and downloaded and installed libptp2, and can query my SX10is, but it says all the properties are UNKNOWN.
Thank you and sorry for my mistakes. I am not a native speaker.
Anil
Title: Re: CHDK PTP interface
Post by: mwarning on 16 / July / 2010, 21:55:06
How can I see/make sure that the loaded chdk has the PTP support?
Does it show some special identifier in the Build Info menu?
If not, could it be added please?
Title: Re: CHDK PTP interface
Post by: mwarning on 17 / July / 2010, 08:12:44
Hi again,

I finally managed to get PTP working on Linux with my sx200.  :D

The diskboot.bin from here (http://chdk.bplaced.net/content/download/summary/7/21.html) worked, as well as the one I've build myself from the  ptp branch (http://my-trac.assembla.com/chdkde/browser/branches/msl) of msl.
I used the ps.fi2 from the regular chdk download (http://chdk.wikia.com/wiki/SX200IS) for my camera, because I haven't managed to create my own.

The main issue was that I haven't started ptpcam as root.
Also, the usb cable need to be cannected after chdk has been manually started via the firmware update.
All buttons are blocked when I start the camera with the usb cable attached.
They can be enabled afterwards over ptp (e.g. by switching to "mode 1").

The chdkcam (for windows) starts up with wine
but doesn't connect to the camera. Same on windows.
Instead there is heavy CPU usage.

Unfortunately, file upload/download doesn't work:

Code: [Select]
<conn> download /dcim/100canon/test.jpg .
unexpected return code 0x2ff
download failed!

Any idea how I can debug file download?
How can I insert debug output in the chdk source?
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / July / 2010, 10:11:24
I ran chdkcam in win 98 compatability mode (on XP) and it worked but there is a window asking to select a program to use for my camera. The problem is that the program doesnt appear on the list so I cannot force it to use chdkcam. When I dismiss the window then the program looses control of the camera and it disconnects.
Although I've got no experience with this on Window, but I suspect Windows is interfering. There is some info on what to disable earlier in this thread.

Anyway, I want to use the PTP interface of chdk with my SX10, but my firmware is 103a. Is there anything I can do to downgrade to 102b, which ewavr's chdk-ptp is built upon?
Downgrading seems like overkill to me. How about asking ewavr to include the 1.03a version? Should be almost the same as 1.02b.

Quote
Also, is there a list of pt-codes that describe which code does what? I use exclusively Linux, and downloaded and installed libptp2, and can query my SX10is, but it says all the properties are UNKNOWN.
Do you mean the general PTP codes or the ones added for CHDK? The latter are described in the ptp.h header in the source and the former (partially) in the PTP specification.

How can I see/make sure that the loaded chdk has the PTP support?
Does it show some special identifier in the Build Info menu?
If not, could it be added please?
There's no way except connecting to with the modified ptpcam (with --chdk) or with CHDKCAM. Not sure what the "policy" is, but I don't see it happening (i.e. as permanent feature).

Unfortunately, file upload/download doesn't work:

Code: [Select]
<conn> download /dcim/100canon/test.jpg .
Try A/DCIM/100CANON/test.jpg. If I recall correctly the first A should always be capitalised. Also, specify a filename as destination; I don't remember putting in anything that derives the target filename from the source filename.

Quote
Any idea how I can debug file download?
Either write to a log file or print messages to the screen.
Title: Re: CHDK PTP interface
Post by: mwarning on 17 / July / 2010, 10:55:35
Quote
Try A/DCIM/100CANON/test.jpg. If I recall correctly the first A should always be capitalised. Also, specify a filename as destination; I don't remember putting in anything that derives the target filename from the source filename.

"download A/dcim/100canon/img_0012.jpg img_0012.jpg" works! Thanks!
Btw.: What is the meaning of A? Is it the first partionion?

But I can't download files exceeding a specific size, 115KB works, 248KB doesn't.
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / July / 2010, 11:08:38
Btw.: What is the meaning of A? Is it the first partionion?
I'm not sure it really has a meaning (as the firmware probably always assumes just one partition).

Quote
But I can't download files exceeding a specific size, 115KB works, 248KB doesn't.
That's a bug discussed earlier here. I've fixed it in my code, but it probably hasn't propagated to other places.
Title: Re: CHDK PTP interface
Post by: mwarning on 17 / July / 2010, 11:35:42
Quote
That's a bug discussed earlier here.
I've found it here (http://chdk.setepontos.com/index.php/topic,4338.msg48083.html#msg48083).  :)

Quote
I've fixed it in my code, but it probably hasn't propagated to other places.
Can you share it (maybe pm)? Or can it be found somewhere already?
I try to code one myself right now. But I assume you have a better/nicer solution compared to what what I might
produce ad hoc.

Thanks a lot for your work, ptp is a very valuable feature!  8)
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / July / 2010, 12:21:09
Can you share it (maybe pm)? Or can it be found somewhere already?
I try to code one myself right now. But I assume you have a better/nicer solution compared to what what I might
produce ad hoc.
Here (http://github.com/mweerden/CHDK/tree/ptp). Note that this is a version that is probably not fully compatible with the source you are using. However, the download part should be ok. You can always pm me if need some help with the details.
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / July / 2010, 13:03:33
B.t.w., I've taken some time to make a wiki page (http://chdk.wikia.com/wiki/PTP_Extension) for the PTP stuff.
Title: Re: CHDK PTP interface
Post by: fudgey on 17 / July / 2010, 14:18:35
How can I see/make sure that the loaded chdk has the PTP support?
Does it show some special identifier in the Build Info menu?
If not, could it be added please?
There's no way except connecting to with the modified ptpcam (with --chdk) or with CHDKCAM. Not sure what the "policy" is, but I don't see it happening (i.e. as permanent feature).

Would init_chdk_ptp be visible in CHDK debug menu task list if PTP support is there?
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / July / 2010, 14:33:07
Would init_chdk_ptp be visible in CHDK debug menu task list if PTP support is there?
Not likely; it's only to wait for a while until certain things are initialised. As soon as you can connect to the camera it's gone.
Title: Re: CHDK PTP interface
Post by: mwarning on 18 / July / 2010, 11:06:46
With some help, I finally got the ps.fi2 build and working. :)

The main problem were conflicting firmware files.
I had the old firmware renamed to "_ps.fi2",
that will still result in a conflict because the camera finds both files.
I thought the encryption keys were wrong.

If there is more than one file (regardless if they are valid firmware file or even empty) in the memory card root directory that has the string "fi2" after the last dot in it's name, then the manual firmware update option won't show up.

Anyway, mweerdens repository also has the file download size limitation fixed!

EDIT: the file matching problem is probably related to the (old DOS) 8.3 format.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / July / 2010, 11:57:00
B.t.w., I've taken some time to make a wiki page (http://chdk.wikia.com/wiki/PTP_Extension) for the PTP stuff.

Many thanks for this.
Your PTP feature was a major innovation for CHDK.
Unfortunately, none of the CHDK developers (whoever they are) took-up your suggestion to discuss a 'basic' PTP feature.

As usual, we are all busy and I have not had time to follow PTP development.
Do we know what aspects of PTP cause problems and which features are reported as working on all cameras tested ?

I see that you propose leaving-out mode switching, I assume there is no problem working in record mode, even for file uploading  ?

I guess liveview really needs USB 2.0.

We have discussed Lua support previously and in my opinion it attracts a 'certain type' of individual to CHDK.

The general public would not even be happy with uBasic, but at least some would.


I really must try to find time to try it.

On your Wiki, many people would not understand the comments about disabling services.


Title: Re: CHDK PTP interface
Post by: mwarning on 18 / July / 2010, 12:51:24
Quote
I guess liveview really needs USB 2.0.
Does chdk need to be fixed to use USB 2.0?
Anything I can do to help?
I did a little speed test for file downloading and got ~3.1MB/s.

Anyway, my camera turns off after some time (30s?).
This happens even while file transferring file.
Any idea what to do? (I use ptpcam on linux)

@mweerden: files seem to be loaded into RAM before written to disk.
This might cause problems for videos.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / July / 2010, 13:21:04
Does chdk need to be fixed to use USB 2.0?

No, I mean that EWAVR mentioned liveview is slow on the cameras that do not have USB 2.0.


David
Title: Re: CHDK PTP interface
Post by: mwarning on 18 / July / 2010, 13:33:47
I see. I have used a Class 6 (6MB/s read speed) SDHC card.
So it's probably that some internals slow transfer down.
Maybe the card isn't as fast as advertised, too.
Title: Re: CHDK PTP interface
Post by: mweerden on 18 / July / 2010, 14:29:27
Unfortunately, none of the CHDK developers (whoever they are) took-up your suggestion to discuss a 'basic' PTP feature.
That's not entirely true, but I guess the point is that there is nobody with the authority and responsibility to make "real" decisions. That's just the nature of this project.

Quote
Do we know what aspects of PTP cause problems and which features are reported as working on all cameras tested ?
I'm not aware of any actual PTP problems. For something like "my" minimal extension I'd say the only difficult issue is possibly the mode switching. I don't really have a good overview of the different methods in use and whether there's one that works for all cameras (or for all cameras one, for that matter).

There might be some additional issues for the CHDKCAM extensions, but from what I've seen I don't think there really are any.

Quote
I see that you propose leaving-out mode switching, I assume there is no problem working in record mode, even for file uploading  ?
Well, I propose moving mode switching from the PTP code to scripting. Again, I'm not aware of any problems, but that doesn't mean much.

Quote
We have discussed Lua support previously and in my opinion it attracts a 'certain type' of individual to CHDK.

The general public would not even be happy with uBasic, but at least some would.
With my proposal both could be supported and easily made compile-time conditional. I can't really see this as an issue.

Quote
On your Wiki, many people would not understand the comments about disabling services.
I just took that from this thread as I know nothing about it. Also, it's not mine, it's everybody's.

@mweerden: files seem to be loaded into RAM before written to disk.
This might cause problems for videos.
It's true that ptpcam stores the file in memory first. You should see the tool as a proof of concept; I just took whatever seemed easiest to make work. The original code only provided a function to get all data at once, so that's what I used.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / July / 2010, 15:14:34
I guess the point is that there is nobody with the authority and responsibility to make "real" decisions. That's just the nature of this project.


In that case, I vote for reyalp   :)
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / July / 2010, 19:27:17
I guess the point is that there is nobody with the authority and responsibility to make "real" decisions. That's just the nature of this project.
In that case, I vote for reyalp   :)
I would love to get this in CHDK, just been really busy and haven't had time to digest the different variants or proposals. I keep thinking I see the light at the end of the tunnel, but it turns into a train every damn time.

As long as it's a compile time option and has the appropriate camera.h control telling which cameras implement it, I don't see any reason not to. It would be nice to have things done in a way that doesn't give us huge compatibility headaches later, but it would be better to get it in now IMO.

If mweerden wants to post the definitive patch and have fe50 or myself commit it, that's fine with me. I'd also support giving him commit access if he wants to continue developing this.

Title: Re: CHDK PTP interface
Post by: mweerden on 18 / July / 2010, 20:47:13
I guess the point is that there is nobody with the authority and responsibility to make "real" decisions. That's just the nature of this project.
In that case, I vote for reyalp   :)
Not really what I meant. ;)

If mweerden wants to post the definitive patch and have fe50 or myself commit it, that's fine with me.
I'll look over it and make a patch, but I think it would be useful to have ewavr's opinion before adding anything. Especially w.r.t. the interaction with CHDKCAM - most likely the prime interface for most users - his view on the matter should have some weight.

Quote
I'd also support giving him commit access if he wants to continue developing this.
As I don't really see myself as an active party in this, I don't think that will be necessary.
Title: Re: CHDK PTP interface
Post by: joseywales72 on 20 / July / 2010, 02:03:43
@mweerden

Quote
Downgrading seems like overkill to me. How about asking ewavr to include the 1.03a version? Should be almost the same as 1.02b.

Then, if it is not too impolite for me to ask, and if ewavr is reading this, I would be very happy to have a 1.03a version of your SX10 port of chdk-ptp.

Quote
Also, is there a list of pt-codes that describe which code does what? I use exclusively Linux, and downloaded and installed libptp2, and can query my SX10is, but it says all the properties are UNKNOWN.

Do you mean the general PTP codes or the ones added for CHDK? The latter are described in the ptp.h header in the source and the former (partially) in the PTP specification.

Thank you for the heads up mweerden. I'll check them out.

Sorry for possible mistakes, not a native speaker.
Title: Re: CHDK PTP interface
Post by: joseywales72 on 20 / July / 2010, 02:18:17
@ewavr,

If is it possible for you, can you port chdk-ptp for SX10is 1.03a firmware too? I like to try it on my cam.

Thank you in advance.

Title: Re: CHDK PTP interface
Post by: mweerden on 20 / July / 2010, 18:03:25
Here's a patch with my proposed changes.
Title: Re: CHDK PTP interface
Post by: belahe on 04 / August / 2010, 11:30:55
Is there an implementation of PTP for SX120 ?
Title: Re: CHDK PTP interface
Post by: yvesson on 14 / August / 2010, 17:10:28
Here's a patch with my proposed changes.

Hej,
anything new about this ?
Title: Re: CHDK PTP interface
Post by: fudgey on 26 / August / 2010, 17:00:35
Maybe it's time to do something about this while the patch is still valid for current trunk :) ...some comments about the PTP proposal patch:

- http://chdk.wikia.com/wiki/PTP_Extension (http://chdk.wikia.com/wiki/PTP_Extension) lists memory read/write and remote function calls as excluded from the patch but they appear to be included in the proposal patch ptp.c anyway.

- I added a570 ptp startup to platform/generic/main.c and don't know how to do it any other way. The proposal patch adds code for ixus870_sd880 in each sub's boot.c because apparently some asm magic is required. I can only assume my addition interferes with it. How to deal with this?

- It would be easier to review the patch if tools/ptpcam stuff would be in a separate diff.

- Script command reboot() should be in a separate diff because it's not related to PTP.

- Maybe switch_mode_usb() lua command should be renamed to something like set_record_during_ptp or maybe set_record() could be given another option to signal that this alternative functionality is desired.

- What is PTP_CHDK_TempData?
Title: Re: CHDK PTP interface
Post by: fudgey on 26 / August / 2010, 17:03:19
I've built CHDK binaries of trunk 926 with PTP patches for a570 (both 100e and 101a). They are based on mweerden's PTP proposal patch, ported to a570. I didn't make a special vanilla build for publication so these binaries have some of my patches and selections applied to them in addition to the PTP stuff. Download (binaries+diffs) available at http://drop.io/a570_chdk_ptp (http://drop.io/a570_chdk_ptp).

The binaries were authored this way:

1) patch -p0 < ptp_proposal-20100721-mweerden.patch
The patch is for trunk rev 913 but it applies fine to trunk 926.

2) applied my old changes from http://chdk.setepontos.com/index.php/topic,4338.msg42384.html#msg42384 (http://chdk.setepontos.com/index.php/topic,4338.msg42384.html#msg42384) but this time I also wrote an implementation of the switch_mode_usb() rec/play switching command because set_record(true) in Lua seemed to cause a crash after shoot() command right after switching to rec if camera was originally powered on to rec mode with DNG enabled. So, I added entry points for PB2Rec, Rec2PB and DisableNotificationPTP for a570 100e and 101a to make it work and modified camera.h too. See a570_ptp.patch (to be applied after the ptp proposal patch).

3) added my localbuildconf.inc (removes curves, calendar, sokoban, mastermind, enables native calls in Lua):
# disabled components (overrides buildconf.inc)
OPT_GAME_SOKOBAN=
OPT_GAME_MASTERMIND=
OPT_CURVES=
OPT_CALENDAR=
# enabled components (overrides buildconf.inc)
OPT_LUA_CALL_NATIVE=1

4) added some of my patches (full zebra osd restore, add continuous mode tv adjustment, fix debug mem browser for vxworks cams, greatly reduce battery voltage display filtering) and built using gcc 3.4.6.


Example usage:

1) Power on camera with USB cable attached and rec/play switch in 'play' position.
2) Connect PTP from a PC using 'ptpcam --chdk'
3) send commands such as

upload something.lua A/CHDK/SCRIPTS/something.lua -- test file upload
lua set_record(true) -- switch to REC mode
lua shoot()
lua press("shoot_half"); sleep(2000); press("shoot_full"); sleep(10); release("shoot_half"); release("shoot_full")
lua set_record(false); sleep(3000); shut_down() -- switch to PLAY mode and power off

If you need to power on the camera remotely, you need to use the power button permanently taped down trick and toggle external power supply to power on.

In the patch there is an alternative command for rec/play switching:
lua switch_mode_usb(0) -- switch to PLAY mode
lua switch_mode_usb(1) -- switch to REC mode
These may or may not be required for crash free mode switching in some cases (possibly PLAY->REC switching if camera was powered on to REC mode instead of PLAY mode; you may want to do that if it turns out that playing around in REC mode with rec/play lever in play position causes trouble with some Canon or CHDK features). But these commands may also fail to work (they may bounce back to the mode you tried to get away from). More testing required.

Title: Re: CHDK PTP interface
Post by: mweerden on 27 / August / 2010, 08:44:54
- http://chdk.wikia.com/wiki/PTP_Extension (http://chdk.wikia.com/wiki/PTP_Extension) lists memory read/write and remote function calls as excluded from the patch but they appear to be included in the proposal patch ptp.c anyway.
Indeed. I corrected the wiki.

Quote
- I added a570 ptp startup to platform/generic/main.c and don't know how to do it any other way. The proposal patch adds code for ixus870_sd880 in each sub's boot.c because apparently some asm magic is required. I can only assume my addition interferes with it. How to deal with this?
There's no magic involved. ;) I just added it where SpyTask is created, but your methods seems to be fine as well (as long as it's platform independent, I guess). It seems a few different approaches are in use.

Quote
- It would be easier to review the patch if tools/ptpcam stuff would be in a separate diff.
I'm not sure I see why. In the patch itself all the non-ptpcam stuff comes first and if applied, it creates a new directory for ptpcam. But if you want I can split the file.

Quote
- Script command reboot() should be in a separate diff because it's not related to PTP.
Perhaps. I tend to see it as primarily useful in the context of (debugging via) PTP.

Quote
- Maybe switch_mode_usb() lua command should be renamed to something like set_record_during_ptp or maybe set_record() could be given another option to signal that this alternative functionality is desired.
W.r.t. consistency in naming you're absolutely right. Though set_record is a horrible name in my opinion. ;) I did use usb instead of ptp because the additional code seems to be USB specific and not so much directly related to PTP. Perhaps it's also useful in non-PTP communications some day.

Quote
- What is PTP_CHDK_TempData?
It's a command to temporarily store data or receive such data. It's useful in cases like downloading where you have to specify a filename but cannot transmit it in the same transaction as the actual download (due to the limited PTP arguments and the fact that each transaction can only send data in one direction).

Title: Re: CHDK PTP interface
Post by: fudgey on 29 / August / 2010, 05:15:32
- http://chdk.wikia.com/wiki/PTP_Extension (http://chdk.wikia.com/wiki/PTP_Extension) lists memory read/write and remote function calls as excluded from the patch but they appear to be included in the proposal patch ptp.c anyway.
Indeed. I corrected the wiki.
I think remote function calls should be disabled by default like they are in Lua, e.g. using buildconf.inc (OPT_PTP_CALL_NATIVE). Maybe even poke?

There's no magic involved. ;) I just added it where SpyTask is created, but your methods seems to be fine as well (as long as it's platform independent, I guess). It seems a few different approaches are in use.
I'm not an expert here I'm afraid but if the code in platform/generic works on many cameras and only some or none require platform or sub specific code, this definitely should be done in the generic code whenever possible, right?

Quote
- It would be easier to review the patch if tools/ptpcam stuff would be in a separate diff.
I'm not sure I see why. In the patch itself all the non-ptpcam stuff comes first and if applied, it creates a new directory for ptpcam. But if you want I can split the file.
I didn't know there wasn't any chdk stuff among the ptp files, which made reading the patch slow...(I use a text editor for this, no dedicated tools). When committing this stuff to svn, the changeset diff view in assembla web interface could suffer from the same problem.

Related to this, ptpcam sources should probably somehow state from which version of the original ptpcam it was forked. Committing the original in one patch and then your CHDK'ed ptpcam changes in another changeset would leave a cleaner track I suppose?


Quote
- Script command reboot() should be in a separate diff because it's not related to PTP.
Perhaps. I tend to see it as primarily useful in the context of (debugging via) PTP.

A reboot() command would be highly useful in long term (in time or in number of shots or both) timelapse use to get around problems with ticker wrapping and file table ROM hogging.

Quote
- Maybe switch_mode_usb() lua command should be renamed to something like set_record_during_ptp or maybe set_record() could be given another option to signal that this alternative functionality is desired.
W.r.t. consistency in naming you're absolutely right. Though set_record is a horrible name in my opinion. ;) I did use usb instead of ptp because the additional code seems to be USB specific and not so much directly related to PTP. Perhaps it's also useful in non-PTP communications some day.
Agreed...
Title: Re: CHDK PTP interface
Post by: mweerden on 29 / August / 2010, 08:36:12
I think remote function calls should be disabled by default like they are in Lua, e.g. using buildconf.inc (OPT_PTP_CALL_NATIVE). Maybe even poke?
This is something I'm not opposed to, but I do wonder why.

Quote
I'm not an expert here I'm afraid but if the code in platform/generic works on many cameras and only some or none require platform or sub specific code, this definitely should be done in the generic code whenever possible, right?
Ideally, yes. At the moment it seems the opposite is (mostly) the case.

Quote
I didn't know there wasn't any chdk stuff among the ptp[cam] files, which made reading the patch slow...(I use a text editor for this, no dedicated tools). When committing this stuff to svn, the changeset diff view in assembla web interface could suffer from the same problem.
Ok, I can see that this might not be clear. I guess I just assumed that it was clear that it's a completely separate tool (code wise). One could indicate it in the commit message, but I guess committing them separately would be clearer.

Quote
Related to this, ptpcam sources should probably somehow state from which version of the original ptpcam it was forked. Committing the original in one patch and then your CHDK'ed ptpcam changes in another changeset would leave a cleaner track I suppose?
If you wish to be able to distinguish the code I've written from the original, yes. Otherwise a line in README or the commit message should suffice. Personally I wouldn't (and didn't) bother because I'd call the link with the original ptpcam "accidental".
Title: Re: CHDK PTP interface
Post by: fudgey on 29 / August / 2010, 17:47:38
This is something I'm not opposed to, but I do wonder why.
Because having it enabled by default would make it possible for a psychopath to e.g. author a malicious program that clears the ROM of your camera once connected to a windows computer and distribute it on the internet under the name "l33t appz0r to double the mpiX3lz on ure powash00t lawl.exe". I.e. sort of the reason why it's disabled for Lua by default, but squared since you can actually review Lua scripts you run on your camera but you can't do that for binary malware that runs against your will.

Quote
Ideally, yes. At the moment it seems the opposite is (mostly) the case.
Okay, I suppose cams like a570 that can live with the generic code should then have something like #define PTP_GENERIC_STARTUP 1 in camera.h?



Btw, I added a command line interface to your CHDK-ptpcam. It's a quick&dirty hack of course, it does what the interactive interface does but always just one command that can be given on the command line. To start interactive version, you may still run 'ptpcam --chdk', but now you can also give one command as an argument to the chdk switch, for example 'ptpcam --chdk="lua shoot()"'.

My Ubuntu uses PTP for normal camera USB access, which interferes with ptpcam. Basically the first ptpcam connection attempt nearly always fails, but retrying solves this. So I changed ptpcam to retry before giving up.

I also changed the 'luar' command a bit. It used to be like the 'lua' command except that luar modified the script by placing 'return' in front of it. Unlike the 'lua' command, it then reads the return value from Lua. That means 'luar 2*21' returned 42. I found that to be rather limited, since you can't place complex scripts on a Lua return line. After my tiny little change you need to add that return statement yourself, but it since you can put it anywhere in the script, you can now do things like

ptpcam --chdk="luar a=10; b=20; c=a+b; return c"
or
ptpcam --chdk="luar propcase=require(\"propcase\"); return get_prop(propcase.USER_TV)"

The modified files are CHDK/tools/ptpcam/ptpcam.c and ptp.c. You can find them and a simple example usage shell script in http://drop.io/a570_chdk_ptp (http://drop.io/a570_chdk_ptp) file ptpcam-climod.zip.
Title: Re: CHDK PTP interface
Post by: mweerden on 29 / August / 2010, 19:55:21
Because having it enabled by default would make it possible for a psychopath to e.g. author a malicious program that clears the ROM of your camera once connected to a windows computer and distribute it on the internet under the name "l33t appz0r to double the mpiX3lz on ure powash00t lawl.exe". I.e. sort of the reason why it's disabled for Lua by default, but squared since you can actually review Lua scripts you run on your camera but you can't do that for binary malware that runs against your will.
I don't think those are very good examples. I'll keep it on security for the paranoid and the off chance that cameras with CHDK become so widely used that people will want to display ads on them or something. ;)

Quote
Quote
Ideally, yes. At the moment it seems the opposite is (mostly) the case.
Okay, I suppose cams like a570 that can live with the generic code should then have something like #define PTP_GENERIC_STARTUP 1 in camera.h?
Isn't this already taken care of by CAM_CHDK_PTP? (As far as I know the other cameras don't call task_start_hook.)

Quote
Btw, I added a command line interface to your CHDK-ptpcam.
Nice. This has been on my todo(-butnotlikelytoeverbedone)-list for some time.

Quote
My Ubuntu uses PTP for normal camera USB access, which interferes with ptpcam. Basically the first ptpcam connection attempt nearly always fails, but retrying solves this. So I changed ptpcam to retry before giving up.
If it works, great. I think it's also useful when rebooting; I've noticed that my just-wait-a-few-seconds approach didn't always work so well.

Quote
I also changed the 'luar' command a bit.
My intention was that you'd be able to type luar 2*21 and get 42 back without having to add return. If I understand the Lua semantics correctly, and I believe I tried it as well, without the return you don't get 42 back. Also, having more complex commands (or actually commands that take more time) can have undesired effects due to the fact that the PTP handler waits for completion.

I do understand the use of your version, but I'd probably either use (my) luar (function () body end)() (not tested) or make another command for it.
Title: Re: CHDK PTP interface
Post by: mweerden on 30 / August / 2010, 04:36:23
The modified files are CHDK/tools/ptpcam/ptpcam.c and ptp.c. You can find them and a simple example usage shell script in http://drop.io/a570_chdk_ptp (http://drop.io/a570_chdk_ptp) file ptpcam-climod.zip.
In ptp.c, the malloc/sprintf is now pretty useless; I'd remove that (together with the later free). As for ptpcam.c:
Title: Re: CHDK PTP interface
Post by: shiboob on 04 / September / 2010, 05:06:43
hello everybody
I am trying to write a value to the" PARAM_FILE_COUNTER"  by using  " set_parameter_data" but the camera crashes down ,
any idea why ?
Title: Re: CHDK PTP interface
Post by: fudgey on 05 / September / 2010, 05:00:20
Isn't this already taken care of by CAM_CHDK_PTP? (As far as I know the other cameras don't call task_start_hook.)

If that's true then it's all good. I didn't try building other platforms or studied the code closely enough.

Quote
If it works, great. I think it's also useful when rebooting; I've noticed that my just-wait-a-few-seconds approach didn't always work so well.

Actually this particular one probably doesn't help with rebooting because currently it exits if it can't find a suitable usb device at all. But that part could be retried just as well. The current way of restarting helped me overcome my connection issues, but I do have to wait a little while after powering up the camera for it to be enumerated in the PC's USB or ptpcam will just exit.

Quote
My intention was that you'd be able to type luar 2*21 and get 42 back without having to add return. If I understand the Lua semantics correctly, and I believe I tried it as well, without the return you don't get 42 back. Also, having more complex commands (or actually commands that take more time) can have undesired effects due to the fact that the PTP handler waits for completion.

I do understand the use of your version, but I'd probably either use (my) luar (function () body end)() (not tested) or make another command for it.

Actually...is there a reason for the lua command not to give a return value? Then your luar command could be left as is for faster command line debugging stuff like you intended. I've tried some commands and short scripts (without the return command) with my version of luar (which doesn't add return but does retrieve the return value) and they all worked fine, ptpcam just doesn't print a return value. In other words my version of the luar command seemed to work just the same as the lua command if the script didin't return anything.
Title: Re: CHDK PTP interface
Post by: fudgey on 05 / September / 2010, 05:09:44
In ptp.c, the malloc/sprintf is now pretty useless; I'd remove that (together with the later free).

I'm not 100% certain which one you mean...

Quote
  • Apparently you have some automatic style changer or something. Diffing your version with mine gives a lot more than one wishes. (Deja vu! J/k ;))

Yea, sorry. I was away from home when I started modifying it and ended up with a mixed tabs/space indenting mayhem that made me sick... ;)

Quote
  • It seems open_camera tries a (MAXCONNRETRIES+1)th time or, in case of success before, always calls ptp_opensession another time. Perhaps moving the call in the condition and the code after (and just before) the loop inside (into a "big" if) is a solution.

Did I say it was a quick hack? :P

Quote
  • How about just a char *buf = chdkarg; in chdk()?

I didn't look at the code today, but I do remember using duct tape and bubble gum wrappers with them buffers after gcc rudely complained about my coding skills.

Quote
  • Something to be aware of for the CLI is that the reboot commands try to reconnect after issuing the reboot. It's probably still the right behaviour as it gives you the result of the reboot (without having to look at the camera).
The reboot command is something I won't be able to test as there is no such thing for the vxworks cams.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / September / 2010, 07:52:06
The reboot command is something I won't be able to test as there is no such thing for the vxworks cams.


There is ExecuteFirmUpgrade  (or maybe LoadAndStartUpgrade) , but I have not managed to get it working so far.

On a G9, I have called reboot() from a script using a PS.FI2 file and an auto-start time-lapse script.

After extensive tests, the user reports it crashes after a random number of resets.

It does not seem to crash with an extremely simple test script.

I have no idea why  .....



David
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / September / 2010, 07:54:39
I am trying to write a value to the" PARAM_FILE_COUNTER"  by using  " set_parameter_data" but the camera crashes down ,
any idea why ?

I have tried that from a script (not using PTP) and it sort of works but requires a camera reset.

Cannot remember the details but the next-used image numbers where not as expected.


Incidentally, anyone know the difference between firmware functions 'remove' and 'DeleteFile_Fut' ?


David
Title: Re: CHDK PTP interface
Post by: shiboob on 06 / September / 2010, 10:02:29
for canon powershot G11 100j

NHSTUB(add_ptp_handler, 0xFFA4DE90)           
NHSTUB(set_control_event, 0xFF894CE8)         
NHSTUB(PB2Rec, 0xFF898460)       
NHSTUB(Rec2PB, 0xFF8984A0)   
NHSTUB(reboot_fw_update, 0xFFA89780) 
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / September / 2010, 10:50:36
Actually...is there a reason for the lua command not to give a return value?
The reason is that at the moment the task handling the PTP command will wait until the script is done to send back the return value and I'm unsure of the consequences of waiting for a long time. Perhaps it's completely harmless. An alternative is to make it asynchronous, having the camera send an event on completion or having a command to poll for a result.

In ptp.c, the malloc/sprintf is now pretty useless; I'd remove that (together with the later free).

I'm not 100% certain which one you mean...
I only get one change you made in ptp.c:

1933,1936c1933,1934
< //    char *buf = (char *) malloc(7+strlen(script)+1);
< //    sprintf(buf,"return %s",script);
<     char *buf = (char *) malloc(strlen(script)+1);
<     sprintf(buf,"%s",script);
---
>     char *buf = (char *) malloc(7+strlen(script)+1);
>     sprintf(buf,"return %s",script);

Title: Re: CHDK PTP interface
Post by: fudgey on 07 / September / 2010, 16:35:58
The reason is that at the moment the task handling the PTP command will wait until the script is done to send back the return value and I'm unsure of the consequences of waiting for a long time. Perhaps it's completely harmless. An alternative is to make it asynchronous, having the camera send an event on completion or having a command to poll for a result.

I played around with this a little bit and ended up restoring your "luar" (prefix script with result and retrieve lua return value) and naming mine "luaw" (do not modify script, retrieve result, w as in for "wait" for result) and leaving the "lua" as is (do not modify script, do not retrieve result).

Waiting for a result too long does seem to be a problem, at least for me
luaw sleep(4500);return(22+1) -- works
luaw sleep(5000);return(22+1) -- fails

I also believe I fixed the connection retry thing and added another retry loop to device finding meaning it now should not immediately fail if a command is started during power-on (tested via cli interface) and firmware reboot (not tested).

I also wrote a simple timelapse script (simple as in no good for serious timelapse work but fine for an example) in bash to show how to transfer the latest photo off the camera to the PC and delete it from the camera. It uses disk.lua from mattkime's lua libs package so if you don't have those installed (on the camera), you'll need to do something like this first:

ptpcam --chdk="upload disk.lua A/CHDK/LUALIB/disk.lua"

The new versions are available for download in ptpcam-climod-2.zip at http://drop.io/a570_chdk_ptp (http://drop.io/a570_chdk_ptp).
Title: Re: CHDK PTP interface
Post by: sneilan on 30 / September / 2010, 02:01:59
Please excuse me if this question has been asked.

I was wondering what bytes store the image on the LCD for the A590 IS. PTPCAM has the ability to read bytes which is quite useful. I want to stream whatever is on the LCD display live. I just don't know what bytes store the LCD display. What should I read to figure this out? Or, is it documented somewhere?

Thank you for your time.

-Sean
Title: Re: CHDK PTP interface
Post by: fudgey on 30 / September / 2010, 12:03:21
Please excuse me if this question has been asked.

I was wondering what bytes store the image on the LCD for the A590 IS. PTPCAM has the ability to read bytes which is quite useful. I want to stream whatever is on the LCD display live. I just don't know what bytes store the LCD display. What should I read to figure this out? Or, is it documented somewhere?

Doesn't ewavr's ptp builds+windows software do just that? If you can't use it for some reason (such as PC platform), you should be able to use his source code as an example.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 06 / October / 2010, 12:26:12
In theory, there is a Canon PTP operation code (0x901d) to send the 320x240 JPG viewfinder image.

Has anyone been able to read the values of Canon custom operation codes (9xxx)  ?

Type ptpcam -o to see the codes and ptpcam --show-property=9002    for example.

Title: Re: CHDK PTP interface
Post by: fudgey on 06 / October / 2010, 14:00:52
In theory, there is a Canon PTP operation code (0x901d) to send the 320x240 JPG viewfinder image.

Has anyone been able to read the values of Canon custom operation codes (9xxx)  ?

Type ptpcam -o to see the codes and ptpcam --show-property=9002    for example.

At least my a570 doesn't support opcode 0x901d. There are about 25 opcodes unknown to ptpcam in this camera's opcode list (but an opcode existing doesn't mean it actually does something, of course).

Properties != opcodes i.e. --show-property goes with ptpcam -p, not ptpcam -o. See ptpcam --show-all-properties.

To find out how to use unknown opcodes, one probably needs to search for the opcode's handler from disassembly. The Canon remote capture SDK could help, assuming they use similar commands in cameras that do not support ptp remote capture. Spying on USB connection using Canon's windows applications could also help, especially if it's known for some camera that those tools do more than regular camera PTP 'mass storage'-ish mount functinality.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / October / 2010, 23:43:40
I'm working on getting a version of this into the trunk. This will mostly be mweerden's proposal, with a few adjustments
- PTP is a build time option. If OPT_PTP is set in build conf, it is built for those cameras that have it enabled in camera.h
- PTP task starting is reworked so it requires no camera specific code.
- reboot stuff is merged with my reboot code.
- add_ptp_handler is added to sigs. This is the only thing strictly required for minimal PTP operation, so most cameras should be able to support PTP just by adding CAM_CHDK_PTP to camera.h. However, many will also need additional code to allow switching to rec and shooting.
- on dryos cameras, reboot_fw_update is also added to sigs. if reboot() is passed a filename that ends in .FI*, it will be loaded with this function. I haven't got around to adding the equivalent for vxworks, so reboot with an .FI* file it will just return.

OPT_PTP will be disabled by default initially. I don't see this as the definitive PTP implementation, rather as a starting point to get this moving again. Some outstanding issues
- I would really like to see ewavrs tool, or something like it compatible with the final version. The live view streaming is worthwhile, and should be supported in the core features somehow. Generally, it looks like we just need a way of returning the video buffer configuration. I think there could be default weak functions that work with most layouts based on existing lib.c functions, and cameras with different configurations could override them. Or maybe there's a native canon way to do it.
- the play/rec switching stuff should be unified, and if possible a portable way of doing this on newer cameras should be found. Maybe the pb2rec etc functions can be added to the sig finder, or maybe there are some event procs we can use. I'll be working on this since it applies to D10.
- scripting should be made a bit more flexible somehow, so you don't have to put the entire script in each command line.

Since this will be disable by default, I plan to commit it as soon as I've verified that there are no build-breaking sig finder failures. I haven't added all the individual camera specific patches yet, so initially only D10, A540 and ixus870_sd880 will be enabled in camera.h. I'll try to add the others later. For cameras that don't need specific mode switching code, just enabling it in camera.h may be enough. I probably won't go through and verify all the sig finder matches, so caution is advised before enabling it on your camera.

edit:
Checked in changeset 957 (http://tools.assembla.com/chdk/changeset/957) . I have not verified all the stubs, but I sampled a range of new and old cameras and all I checked were fine, including some low matches for reboot_fw_update
Title: Re: CHDK PTP interface
Post by: Microfunguy on 17 / October / 2010, 06:51:14
Is it worth adding the signature for set_control_event ?

Are you saying that the DRYOS-based cameras will work with PTP in Record mode without any mode switching from playback ?

My VxWorks A620 only works if connected in Playback mode and then switched to Record by a 'mode 1' command with ptpcam.

Title: Re: CHDK PTP interface
Post by: fudgey on 17 / October / 2010, 08:08:45
Goodie :)

Mode switching should indeed be handled better somehow. For a570 I tested it quite extensively a while back and the result was that normal mode switching commands in Lua work fine and that no matter how I choose to switch between modes, I must keep my hands off the rec/play lever while in PTP mode (typically causes PTP to stop working with no way to reconnect until camera reboot). I was unable to replicate the failed mode switchings I thought I saw in previous tests.

Are you saying that the DRYOS-based cameras will work with PTP in Record mode without any mode switching from playback ?

My VxWorks A620 only works if connected in Playback mode and then switched to Record by a 'mode 1' command with ptpcam.

My vxworks Digic III a570 doesn't start PTP services in REC mode either. But that's not a problem since I can run an autorun script that switches to PLAY. PTP will start. The reason I may choose to do it this way is that the mode lever will be in physically correct position after I command the camera back to REC mode using PTP.

Using current default Lua implementation of mode switching, I haven't experienced any problems with having the lever in incorrect position, though, but I haven't really used this much yet. My old implementation using _PB2Rec() / _Rec2PB() with _DisableNotificationPTP() performed worse in some tests (sometimes screen would go black and sometimes switching would appear to work but the cam immediately returned to the previous mode).
[/quote]
Title: Re: CHDK PTP interface
Post by: Microfunguy on 17 / October / 2010, 08:52:49
How about  :-

Code: [Select]
void switch_mode(int mode)
{
  if ( mode == 0 )
  {
    PostLogicalEventForNotPowerType(0x1003);
  } else if ( mode == 1 )
  {
   PostLogicalEventForNotPowerType(0x1001);
  }
}
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / October / 2010, 14:04:19
Is it worth adding the signature for set_control_event ?
If it's needed by many cameras, and matches reasonably well.
Quote
Are you saying that the DRYOS-based cameras will work with PTP in Record mode without any mode switching from playback ?
No. I'm saying that (some ? most ? all ?) dryos cams will need something more than PressRecButton (0x1001)/PressPBButton(0x1003), possibly involving set_control_event and/or pb2rec etc. so they can switch to record mode in PTP. Without this, shooting will not be available.

BTW, I'd suggest pairing each press with an Unpress.
Quote
My VxWorks A620 only works if connected in Playback mode and then switched to Record by a 'mode 1' command with ptpcam.
Title: Re: CHDK PTP interface
Post by: c10ud on 17 / October / 2010, 14:10:42
i tried mweerden's original patch with some dryos cameras, pb2rec and rec2pb along with set_control_event work pretty well, i think it could be worth it adding them to the sigfinder..
Title: Re: CHDK PTP interface
Post by: waldo on 17 / October / 2010, 15:06:46
FYI, I am adding PTP support to my S95 port and the S95 firmware is identical to the ixus870 firmware for the PTP code.  This includes the functions add_ptp_handler, set_control_event, PB2Rec, and Rec2PB. 
Title: Re: CHDK PTP interface
Post by: Microfunguy on 17 / October / 2010, 15:45:36
I have added PTP support to IXUS95 and have used   set_control_event(0x80000902) and set_control_event(0x902).

I am told it works.

@reyalp
If you have all the firmware dumps and can apply a set_control_event signature to them, it would be appreciated.

I really do not feel like manually checking all the DRYOS cameras.
Title: Re: CHDK PTP interface
Post by: yvesson on 17 / October / 2010, 16:10:01
Hej,
Well it's great news, except I couldn't make it work on my A540. :/
I compiled it with the option enabled and got the tool from ewrar website, I also needed some libusb but not sure if I got it right, anyway nothing happens when I start CHDKcam. :(
I feel kinda left-handed with all that, please someone could sum up again the steps to make it work, thanks.
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / October / 2010, 16:53:14
Hej,
Well it's great news, except I couldn't make it work on my A540. :/
I compiled it with the option enabled and got the tool from ewrar website, I also needed some libusb but not sure if I got it right, anyway nothing happens when I start CHDKcam. :(
I feel kinda left-handed with all that, please someone could sum up again the steps to make it work, thanks.
Unfortunately, the current version is not compatible with chdkcam. You have to use ptpcam patched with mweerdens code, and as mentioned before there's no support for chdkcams live view.

For libusb-win32, I used 1.2.2.0 filter, and used the filter wizard to add the cam.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 17 / October / 2010, 17:00:50
@yvesson

Need more information than that.

I do not know about the latest trunk build, let me tell you what I did with my own build.

With the camera connected, I ran  libusb.
That installed libusb0.dll in the \Windows\system32 folder.
I compiled my version of PTP and a 'special' version of mweerden's ptpcam.

I connect camera to PC and closed any window that popped up.

In MyComputer, I right-clicked on camera icon and in properties set 'do nothing' for the 'on-connect' event.

I do not have Canon Camera Services on my PC so did not have to disable with Windows Task Manager.

In playback mode, booted camera with the USB remote switch disabled.
Heard the 'on connect' event.

In a coomand console, navigated to ptpcam folder and typed ptpcam -r.

ptpcam responded with OK message.

Typed ptpcam --chdk

<conn> mode 1

switched to Record mode

Typed 'run time_lapse.bas'   (but that is another story)
Title: Re: CHDK PTP interface
Post by: yvesson on 17 / October / 2010, 17:21:25
Hej,
Okej guys thanks for the answer, there's what I missed : PTPcam. Is there a usable version downloadable somewhere ? I managed to compile CHDK with the help of whim's tool, but I don't think I'll go further than that. :/

How far are we from being able to use CHDKcam ?
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / October / 2010, 17:40:20
Hej,
Okej guys thanks for the answer, there's what I missed : PTPcam. Is there a usable version downloadable somewhere ? I managed to compile CHDK with the help of whim's tool, but I don't think I'll go further than that. :/
My build of ptpcam is here http://drop.io/reyalp_chdk/asset/ptpcam-mingw-reyalp-test-zip (http://drop.io/reyalp_chdk/asset/ptpcam-mingw-reyalp-test-zip)

the non-chdk functionality seems a bit broken, but maybe I just don't understand it. Some of the help messages in the CHDK section are also wrong.

ptpcam development seems pretty dead, we may want to fork our own CHDK specific version, or maybe just write our own tool. It would be nice to have something cross platform and easy to build. A library that others could build on would be ideal.
Quote
How far are we from being able to use CHDKcam ?
1) CHDKcam is written with Borland c++ builder, so people without that can't easily update it. I don't know if there is a free tool that can build this code (Borland released some of their command line compilers for free, but it's been a long time since I looked at this)
2) CHDKcam needs to be updated to talk to the current CHDK/ptp protocol
3) The current PTP implementation doesn't include the functions required by some features, e.g. live view. These shouldn't be too hard to add. In the original patches, this required camera specific code, but I think it could be generic for most.
Title: Re: CHDK PTP interface
Post by: hwntw on 17 / October / 2010, 18:39:13
1)
Quote
CHDKcam is written with Borland c++ builder, so people without that can't easily update it. I don't know if there is a free tool that can build this code (Borland released some of their command line compilers for free, but it's been a long time since I looked at this)
https://downloads.embarcadero.com/free/c_builder (https://downloads.embarcadero.com/free/c_builder)
Title: Re: CHDK PTP interface
Post by: fudgey on 18 / October / 2010, 12:56:36
My build of ptpcam is here http://drop.io/reyalp_chdk/asset/ptpcam-mingw-reyalp-test-zip (http://drop.io/reyalp_chdk/asset/ptpcam-mingw-reyalp-test-zip)
I tried to build my ptpcam mod with mingw (32-bit vista) once and finally got it to compile but wasn't able to connect to a camera. I'm pretty sure I didn't install enough/correct device drivers/whatever, so I have no clue what part isn't working so just gave up...I have next to no patience when it comes to things on windows, has anyone written a beginner's guide to getting this thing to work there? :'(

I was really just attempting to get ptpcam's autoconf stuff to work again so that chdk-ptpcam could be compiled on 32/64-bit Linux and mingw without modification.
Title: Re: CHDK PTP interface
Post by: whoever on 18 / October / 2010, 14:50:01
I have next to no patience when it comes to things on windows
Quite understandable. Although, IMHO, it is better to do exercise patience in the face of such a calamity.

Otherwise, ptpcam should easily compile under the normal CHDK win environment. I've just verified that, if I   (i) get patched ptpcam source here (http://chdk.setepontos.com/index.php?topic=4338.msg41386#msg41386), (ii) modify the paths in the makefile to match my environment, and (iii) run gmake in the ptpcam directory, then I get a working ptpcam.exe.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / October / 2010, 14:54:51
@fudgey

Have you followed the steps in message 272 above ?

Title: Re: CHDK PTP interface
Post by: yvesson on 18 / October / 2010, 15:00:31
Hej,
I gave up too, I got an error message when I wrote ptpcam --chdk. :(

Title: Re: CHDK PTP interface
Post by: fudgey on 19 / October / 2010, 17:15:07
Hmm I had somehow skipped mweerden's windows version source (had it on hdd but never tried it), it builds fine. But it -- just like my own build and reyalp's -- doesn't find ptp devices.

I guess my driver install was and still is the problem. I previously installed the non-filter one after reading the win32-libusb pages for a while and I suppose that did no good. So I now ran the filter version exe installer instead and let its filter wizard install a filter for my camera. Still no good, the camera has a yellow exlamation mark next to it in device manager, a closer look reveals error 10 (driver tab mentions libusb0.sys 1.2.2.0).

AFAIK, there are no Canon tools to disable on that computer, reboot didn't help.
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / October / 2010, 17:27:58
It appears to me that if you plug the camera into different USB ports, you have to set up the filter once for each one.

I also had trouble if I didn't set the action when the camera is connected to "none". This again has to be set for each port.

All of the above is on XP.
Title: Re: CHDK PTP interface
Post by: fudgey on 19 / October / 2010, 17:53:19
It appears to me that if you plug the camera into different USB ports, you have to set up the filter once for each one.
I also had trouble if I didn't set the action when the camera is connected to "none". This again has to be set for each port.

I used the same exact USB connector each time after installing the filter, and action was none even before installing the filter.
Title: Re: CHDK PTP interface
Post by: whoever on 20 / October / 2010, 12:44:27
A little observation on the function calls over PTP:
   PTP_CHDK_CallFunction in ptp.c just plunges into the foreign code like this:
Code: [Select]
ptp.param1=((int(*)(int,int,int,int,int,int,int,int,int,int))buf[0])(buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7],buf[8],buf[9],buf[10])
This will work with the functions that nicely return with "BX LR" or similar, but will likely crash at the often encountered MOV PC,LR, failing to return to thumb. Also, vararg functions cannot be called this way.

There used to be reyalp's call_vararg_func(), which could be used here like this:
   ptp.param1 = call_vararg_func(buf[0], &buf[1], 4);  // limit to 4 args, to save some hassle,
but I don't find it in the current trunk.

Has it changed, or is there a better way?

Edit 1: damn arm asm...

Edit 2: thanks, reyalp
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / October / 2010, 12:50:09
Yeah, this is something was going to change eventually. You can just use regular call_func_ptr

When I first started working on the native call stuff, I was under the mistaken impression that vararg calls used a different calling convention on arm, but on CHDK cameras at least, they do not.

If buff is big enough, you should be able to safely send extra args without any issue, they'll just end up on the stack and be ignored.
Title: Re: CHDK PTP interface
Post by: fudgey on 20 / October / 2010, 14:53:54
Does PTP really need its own native calls interface separate from Lua?
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / October / 2010, 15:57:07
Does PTP really need its own native calls interface separate from Lua?
Good question. There are currently a couple of differences
- PTP direct calls will be executed immediately in the context of the PTP task.
- PTP calls are currently always available whether or not native calls are enabled. I'm not sure if this is desirable.
- for development, it may be desirable to have direct calls, so you can use it before lua is fully functional.
Title: Re: CHDK PTP interface
Post by: hwntw on 20 / October / 2010, 17:03:55
Hej,
Well it's great news, except I couldn't make it work on my A540. :/
I compiled it with the option enabled and got the tool from ewrar website, I also needed some libusb but not sure if I got it right, anyway nothing happens when I start CHDKcam. :(
I feel kinda left-handed with all that, please someone could sum up again the steps to make it work, thanks.
Hello,
Install the USB driver (with install-filter.exe or wininstall-filter, whatever) without the cam booted to CHDK. That way, the correct driver (digital still camera) is available for installation.
After I do this, I can run ptpcam on my Ixus 95 CHDK-DE-443 home-brew and do some basic ptp commands:
e.g.
... >ptpcam.exe -i

Camera information
==================
Model: Canon DIGITAL IXUS 95 IS
  manufacturer: Canon Inc.
  serial number: '62DE4C8DB76749DC8CA5AA0CA74A0465'
  device version: 1-6.0.1.0
  extension ID: 0x00000006
  extension description: (null)
  extension version: 0x0064

What does not happen, is any response after I run ptpcam --chdk. The commands execute but no useful result ensues.
CHDKCAM does communicate with my Ixus 95, but only to power it down immediately.
Don't forget, the Ixus 95 is one of the cameras Canon removed remote capabilities from: so all of the preceding is actually great progress (by others- not me)!

Colin
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / October / 2010, 22:05:20
I'm not sure what's currently in CHDK-DE. In the trunk, PTP is not enabled for this camera, but just defining CAM_CHDK_PTP for it in camera.h should be enough if the functions were detected correctly.

Keep in mind that the version of ptpcam you are using much match the protocol implemented in your version of CHDK. The one I posted works the the code in the trunk (mweerden proposal protocol).
Title: Re: CHDK PTP interface
Post by: msl on 21 / October / 2010, 03:52:01
There is no PTP function for ixus95 in CHDK-DE trunk. The included functions are dummy functions (especially reboot_fw_update) for compiling of the autobuild. We are still looking for the right function for this camera (also for the SX120). Also the defining in camera.h in the ixus95 section is missing.

CHDK for the ixus95 in CHDK-DE is only a test version.

The CHDK PTP interface is a difficult topic. I think the mainstream users probably need an easy-to-use (Windows) GUI like ewavr's solution.
Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 22 / October / 2010, 23:16:22
I've added PTP stuff to my sd4000 port based on current trunk.
add_ptp_handler and reboot_fw_update sigfinder addresses are correct.

Installed libusb-win32 (http://sourceforge.net/projects/libusb-win32/) v1.2.2.0 driver for the camera on Windows 7 with inf-wizard.exe and used reyalp compiled ptpcam (http://drop.io/reyalp_chdk/asset/ptpcam-mingw-reyalp-test-zip) version.

Connection is fine. Most commands work (like memory, reboot)
looks like shutdown-hard does crash camera.
shutdown-soft does not work.
mode 1 does not work.

Is the patched ptpcam source available somewhere (didn't find anything besides original ptpcam source) ?
ptpcam execute some commands (like mode) as lua script. I want to look whats ptpcam actually does (or should do) to debug whats wrong (setrec and setmode scripts do work).

SD4000
Code: (c) [Select]
NHSTUB(get_ptp_handler, 0xFFA4EC7C)
//NHSTUB(add_ptp_handler, 0xFFA4EABC)                // sigfinder address ok
NHSTUB(remove_ptp_handler, 0xFFA4EBB0)
NHSTUB(PB2Rec, 0xFF898B40)                           // search String "AC:PB2Rec"
NHSTUB(Rec2PB, 0xFF897590)                           // search String "AC:Rec2PB"
NHSTUB(set_control_event, 0xFF8955C4)                // via eventproc_export_IsControlEventActive (last call), levent_table contains control event id's (Logical Event Table)
//NHSTUB(reboot_fw_update, 0xffa9b228)               // sigfinder address ok
Title: Re: CHDK PTP interface
Post by: fudgey on 23 / October / 2010, 03:38:13
Is the patched ptpcam source available somewhere (didn't find anything besides original ptpcam source) ?
You can find chdk-ptpcam source in mweerden's proposal CHDK patch, it goes in trunk/tools/ptpcam:
http://chdk.setepontos.com/index.php/topic,4338.msg52984.html#msg52984 (http://chdk.setepontos.com/index.php/topic,4338.msg52984.html#msg52984)

I've done some changes to that (connection retries and a command line interface to the CHDK features), source here:
http://drop.io/a570_chdk_ptp (http://drop.io/a570_chdk_ptp),
in ptpcam-climod-2.zip

For windows, the easiest route is this one (I'm not 100% sure if this matches proposal patch version functionally):
http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip (http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip)


edit: added attachment now that drop.io is dead
Title: Re: CHDK PTP interface
Post by: alorp on 01 / November / 2010, 18:25:47
Actualy there is no need for additional libraries/drivers to work with PTP on windows, it can be done using IWiaItemExtras::Escape function from Windows Image Acquisition API.
Title: Re: CHDK PTP interface
Post by: rudi on 04 / November / 2010, 14:38:18
Hello,

thanks for your good work on  PTP.

I have tested ptpcam with my A590. It works good, but sometimes there are fails on communication, but ptpcam.exe don't crash.

So, here my changes for PTP-comunication:
- disable "shutdown-hard" (I think we don't need it.)
- change helptext from "shutdown-soft" to "shutdown"
- add error handling for "lua(r)" syntax errors and others
- add result methode via a global var named "ptp_result" for "lua" command
- lua command also wait for script end (so you can't try to start a 2nd script)
- a solution for 5s-communications-timeout (try "lua sleep(20000)")

patches based on trunk 964
ptp-patch: for PTP-communication (ptpcam-folder on trunk/tools/ptpcam)
A590-patch: add only A590 PTP-functions (with mode-command)

rudi
Title: Re: CHDK PTP interface
Post by: fudgey on 05 / November / 2010, 14:09:56
A590-patch: add only A590 PTP-functions (with mode-command)

Added this one to trunk, rev 965.
Title: Re: CHDK PTP interface
Post by: rudi on 24 / November / 2010, 06:47:04
Hi,

I would to rewrite my "ptp_result"-version. I detect a problem on use eg. large for-loops (runtime over 5 sec.) without any sleep-command inside the loop. The timeout error come back. I think that the lua_script_wait()-routine in kbd.c works only on sleep comands and my timeout-code is not working. That's bad.

In current version I don't know is lua-script finished or not and I can't get a result eg. for read dir- or filenames.

Have anyone a solution?

rudi
Title: Re: CHDK PTP interface
Post by: ultimA on 24 / November / 2010, 10:56:58
In current version I don't know is lua-script finished or not

I have a solution for that. It is part of my next patch in a series to disable scripting in CHDK. Will be posting it soon.
Title: Re: CHDK PTP interface
Post by: fudgey on 24 / November / 2010, 14:10:26
I detect a problem on use eg. large for-loops (runtime over 5 sec.) without any sleep-command inside the loop. The timeout error come back.

On the other hand, isn't writing Lua code that doesn't yield regularly and often strongly discouraged anyway because it could cause odd behavior in the camera (or CHDK) because some other task might expect to get its turn to do something more lengthy or processor intensive regularly but doesn't because Lua hogs the CPU?
Title: Re: CHDK PTP interface
Post by: rudi on 25 / November / 2010, 06:19:28
@ fudgey
It is possible that not the script is the cause. Maybe the bus-timeout is only the effect of to many jobs for CPU. A sleep() give other processes more time for execute.

An other concept for ptp-console is "lua" runs without wait und I can get a "is finished" and "get_last_lua_result" (equal to "getLastError" on Windows-systems) for lua-script results or error messages.

I have a solution for that. It is part of my next patch in a series to disable scripting in CHDK. Will be posting it soon.
Thanks, that sounds good. I'm waiting for.

rudi
Title: Re: CHDK PTP interface
Post by: rudi on 29 / November / 2010, 01:42:38
Hi,

if we want get success from switch_mode_usb() in luaCB_switch_mode_usb() (core/luascript.c) I think we need this code on line 1193.

Code: [Select]
 lua_pushnumber(L, switch_mode_usb(mode));  //success to stack
  return 1;                                  //count of return value on stack

rudi
Title: Re: CHDK PTP interface
Post by: ultimA on 29 / November / 2010, 14:21:54
If I want to implement new PTP-query in the camera that returns only a single number or two, is my understanding of the code correct that I only need to do the following?

1) Add a new enum value to ptp_chdk_command
2) Extend the switch in handle_ptp(...)
3) Write ptp.num_param/.param1/.param2 with the return value
4) Do nothing else. PTP will return the params in the ptp structure "automatically" because of the data->send_resp( data->handle, &ptp ); line at the end of the function.
Title: Re: CHDK PTP interface
Post by: mweerden on 29 / November / 2010, 17:34:43
For windows, the easiest route is this one (I'm not 100% sure if this matches proposal patch version functionally):
http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip (http://www.mweerden.net/download/chdk-ptp/libptp2-chdk-win32.zip)
I'm pretty sure it doesn't match. I can't quickly build a new version at the moment, but let me know if it's needed. I'm guessing that others have more up-to-date versions.

If I want to implement new PTP-query in the camera that returns only a single number or two, is my understanding of the code correct that I only need to do the following?
It seems so, yes.
Title: Re: CHDK PTP interface
Post by: rudi on 29 / November / 2010, 18:28:19
Thanks for your informations, but I would give only a hint for return value of the lua-api function. I think the current implementation is wrong. We can't get the success result from "switch_mode_usb()". Sorry for my bad description.

For your information: We had on CHDK-DE version some problems with download/upload files (eg. on IXUS100 and A610). The reason is the constant buffersize. CHDKLover have written a solution. He calculate the max. RAM-buffersize. 50% from that is the ptp-buffersize. He found also a solution to make all vxworks-cams ptp-ready incl. mode-switching (see DE-Trunk 465 and up). But OPT_LUA_CALL_NATIVE is required.

EDIT:
I think, I found the answer for "switch_mode_usb()"-result. It is a tricky tri-state result (mode-val on stack for switching ok and nil for any error at switching). Is that correct?

rudi
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / December / 2010, 17:06:32
Some ptp changes here http://chdk.setepontos.com/index.php?topic=5793.msg58335#msg58335 (http://chdk.setepontos.com/index.php?topic=5793.msg58335#msg58335)

I've attached a win32 build of ptpcam, along with source patches. This isn't really useful as is but it shows how to use the new commands.

edit:
patches are against mweerdens github source.
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / December / 2010, 18:41:50
I think, I found the answer for "switch_mode_usb()"-result. It is a tricky tri-state result (mode-val on stack for switching ok and nil for any error at switching). Is that correct?
Seems so.

I think switch_mode_usb should not exist. set_record should know if PTP is active, and call C code switch_mode_usb if needed. Many older cameras don't need any special code.

(I agree set_record is a bad name, but I didn't want to confuse with shooting modes which already had get_mode and set_capture_mode...)
Title: Re: CHDK PTP interface
Post by: rudi on 20 / December / 2010, 12:57:41
Hello,

for mode-switching in ptp (mode-command) we use for VxWorks the canon event functions. Can we this also use for DryOS-cams?

successful tested with A590:
Code: [Select]
//equal levent_set_record();
<conn> lua post_levent_to_ui("PressRecButton");post_levent_to_ui("UnpressRecButton")

//for example make a shoot
<conn> lua shoot()

//equal levent_set_play();
<conn> lua post_levent_to_ui("PressPBButton");post_levent_to_ui("UnpressPBButton")

The best is, all cams use only one routine. We don't need to find entrypoints for set_control_event, PB2Rec and Rec2PB on DryOS-cams. I think the two methods are a little bit different and the event-method is a better way (feel stable on tests).
The downside is OPT_LUA_CALL_NATIVE is required for OPT_PTP, but for VxWorks-cams it is already required.

rudi
Title: Re: CHDK PTP interface
Post by: ultimA on 20 / December / 2010, 15:18:54
@reyalp: I saw the changes you made to the patch. While implementing, at first I also thought of using a bitfield. But the reason I didn't do that, and why I think it is not a good option right now, is that in my oppinion it complicates code for no foreseeable benefit. I understand that this theoretically makes adding new scripting languages possible, but as I have seen (I think it was this thread earlier) there is really no interest in adding UBasic support to PTP. And I also see no realistic chance of adding a third scripting language later on.

The reason it complicates code so much is that because you start supporting "scripting interfaces", as noted in the code comments. So to truely stay correct and open to future additions in the future, for every script-related PTP command you would need to supply a "target interface" as an argument (=an argument to state which scripting interface you are communicating to). This adds a lot of related problems, like what if there are multiple interface targets specified, how do you handle returning different errors in these cases and so on. And as stated, I cannot foresee supporting a scripting language in PTP other than LUA at the moment. So is this all worth it?

A relatively unrelated note: Maybe it would be better, instead of a ScriptSupport command, to have a general FeatureQuery command, that could return supported features of the current CHDK & camera in a bitfield. Not only for scripting, but games/zoom/native_calls/and other features.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / December / 2010, 16:37:24
The best is, all cams use only one routine. We don't need to find entrypoints for set_control_event, PB2Rec and Rec2PB on DryOS-cams. I think the two methods are a little bit different and the event-method is a better way (feel stable on tests).
The downside is OPT_LUA_CALL_NATIVE is required for OPT_PTP, but for VxWorks-cams it is already required.
I don't understand why native call is required, you can use without levent native call.

It looks like the code you are using is identical to lua set_record, which doesn't work on (most ?) dryos cameras when USB is connected. I know I tried a bunch of things on D10 and couldn't get it to switch using levent.

@ultimA it seemed to me there was some interest in ubasic support, there are already some constants there for it. ExecuteScript already takes a type option (which is just a constant, not a bitfield) PTP_CHDK_SL_LUA

One reason to use ubasic is cameras with very little memory. Once your scripting optional stuff is done, people will have the option of ubasic only, and might still want ptp.

The way things are now, the "supported" bit will be (1<< (executescript number)). I thought about changing ExecuteScript to use the bitmask values, but as you say it doesn't make sense to pass more than one.

I would assume that if multiple script interfaces are supported, you can only use one at a time, at least until a major protocol change.
Title: Re: CHDK PTP interface
Post by: hwntw on 20 / December / 2010, 17:13:18
Deleted by a craven coward
Title: Re: CHDK PTP interface
Post by: ultimA on 20 / December / 2010, 22:20:37
One reason to use ubasic is cameras with very little memory. Once your scripting optional stuff is done, people will have the option of ubasic only, and might still want ptp.
But this argumentation is only valid if OPT_LUA_CALL_NATIVE is not made a requirement for OPT_PTP.

The way things are now, the "supported" bit will be (1<< (executescript number)).
What is "executescript number"?
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / December / 2010, 00:49:45
One reason to use ubasic is cameras with very little memory. Once your scripting optional stuff is done, people will have the option of ubasic only, and might still want ptp.
But this argumentation is only valid if OPT_LUA_CALL_NATIVE is not made a requirement for OPT_PTP.
There is no reason CALL_NATIVE should be required for OPT_PTP. At most you'd need to disable PTP_CHDK_CallFunction (although I'm not sure that's really needed)

Or we could retire PTP_CHDK_CallFunction completely, since you can do it from lua anyway.
Quote
The way things are now, the "supported" bit will be (1<< (executescript number)).
What is "executescript number"?
PTP_CHDK_SL_LUA
PTP_CHDK_SL_UBASIC

Param2 of PTP_CHDK_ExecuteScript
Title: Re: CHDK PTP interface
Post by: Bernd R on 22 / December / 2010, 08:16:02
Is there a wiki or a text explain how ptpcam work ?
I want transfer the chdk files to camera so i need not put SD-Card in Card reader always.

I search in google and see the option --get-all-files for testusage of ptpcam

seem my camera work with ptp.

when i type this in, LCD display get dark, and the LED blink for about 1 sec.
then come the output.

I can redo this command and work always same.

C:\Users\pc>E:\chdk\ptpcam.exe --get-all-files
Camera: Canon IXUS 1000HS

C:\Users\pc>

but some new files are not in c:\users\pc written

I dont like using the shell special windows shell, and i always forget how can in windows change the drive, maybe there is also a GUI for newest ptpcam, that allow the transfer of camera binary zip files to Camera easy ?
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / December / 2010, 23:20:31
Is there a wiki or a text explain how ptpcam work ?
I want transfer the chdk files to camera so i need not put SD-Card in Card reader always.

I search in google and see the option --get-all-files for testusage of ptpcam

seem my camera work with ptp.

when i type this in, LCD display get dark, and the LED blink for about 1 sec.
then come the output.

I can redo this command and work always same.

C:\Users\pc>E:\chdk\ptpcam.exe --get-all-files
Camera: Canon IXUS 1000HS

C:\Users\pc>

but some new files are not in c:\users\pc written

I dont like using the shell special windows shell, and i always forget how can in windows change the drive, maybe there is also a GUI for newest ptpcam, that allow the transfer of camera binary zip files to Camera easy ?
I have not had much luck with non-chdk commands in ptpcam. To upload/download files, use
ptp --chdk
this will give you an interactive prompt where you can use CHDK ptp commands, like
download A/DISKBOOT.BIN DISKBOOT.BIN
or
upload DISKBOOT.BIN A/DISKBOOT.BIn

The A/ is important when specifying filenames on the camera, it will probably crash if you leave it out.
Title: Re: CHDK PTP interface
Post by: Bernd R on 23 / December / 2010, 05:28:40
I try several things out and here is the shell log of that.
upload a file test.txt(which have content of changelog.txt) give

unexpected return code 0x2ff
upload failed!

what are this error numbers ?
I test also without chdk start, there come same numbers, so it look as on IXus 1000 some functions are miss in chdk

I have use the 1004 trunk build, without your script patches.or is this wrong ?


I see too, that after i install usb dll for my Ixus 1000 for use with ptpcam, i can not use the IE explorer to read files from Camera.

before when i plug in the USB cable display get dark.when i start ptpcam with --chdk display get not dark.
when i start with --get-all-files display get dark and stay dark.


C:\Users\pc>e:\chdk\ptpcam.exe --chdk
error: camera has unsupported camera version 0.1; some functionality may be miss
ing or cause unintented consequences
<conn> download a/diskboot.bin diskboot.bin
unexpected return code 0x2fe
download failed!
<conn> download a/diskboot.bin diskboot.bin
unexpected return code 0x2fe
download failed!
<conn> upload diskbot.bin a/diskboot.bin
could not open file 'diskbot.bin'
upload failed!
<conn> upload test.txt a/test.txt
unexpected return code 0x2ff
upload failed!
<conn> upload test.txt a/test.txt
unexpected return code 0x2ff
upload failed!
<conn>

if you tell me what i should test on my Camera or add testcode in source i can do that.
Title: Re: CHDK PTP interface
Post by: rudi on 23 / December / 2010, 07:52:16
<conn> upload test.txt a/test.txt

Write the camera driveletter uppercase e.g. upload test.txt A/test.txt
Title: Re: CHDK PTP interface
Post by: rudi on 23 / December / 2010, 08:09:16
I don't understand why native call is required, you can use without levent native call.
That's right. For mode-switching we don't need OPT_LUA_CALL_NATIVE. Thanks for your hint.

It looks like the code you are using is identical to lua set_record, which doesn't work on (most ?) dryos cameras when USB is connected. I know I tried a bunch of things on D10 and couldn't get it to switch using levent.
Yes, it was my idea. It's a pity. It would be so easy to switch mode on DryOS cameras. Now, I will find the entrypoints for DryOS reference BINs.

rudi
Title: Re: CHDK PTP interface
Post by: Bernd R on 23 / December / 2010, 10:05:42
<conn> upload test.txt a/test.txt

Write the camera driveletter uppercase e.g. upload test.txt A/test.txt

I try that but not work.
I also see, when remove USB cable error is same.so seem ptpcam do just nothing in --chdk

<conn> upload test.txt A/TEST.TXT
unexpected return code 0x2ff
upload failed!
<conn> upload test.txt A/TEST.TXT
unexpected return code 0x2ff
upload failed!
<conn> upload test.txt A/TEST.TXT
unexpected return code 0x2ff
upload failed!
<conn>

when i try this and have USB cable not connect i get this message.


C:\Users\pc>e:\chdk\ptpcam.exe --get-all-files
could not find any device matching given bus/dev numbers

C:\Users\pc>

I test when chdk not run, i get same message as when chdk run

C:\Users\pc>e:\chdk\ptpcam.exe --get-all-files
Camera: Canon IXUS 1000HS

C:\Users\pc>
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / December / 2010, 16:05:14
I try that but not work.
I also see, when remove USB cable error is same.so seem ptpcam do just nothing in --chdk

<conn> upload test.txt A/TEST.TXT
unexpected return code 0x2ff
upload failed!
My guess either you have not correctly implemented and enabled CHDK PTP, or your libusb driver is not set up correctly. There is some discussion of the latter in this thread.

Quote
C:\Users\pc>e:\chdk\ptpcam.exe --get-all-files
Camera: Canon IXUS 1000HS
C:\Users\pc>
CHDK only uses ptpcam as a convenient place to put some code.  As I said earlier, I wasn't able to get many of the non-chdk ptpcam functions to work. It appears to me that ptpcam development was abandoned a long time ago.
Title: Re: CHDK PTP interface
Post by: Bernd R on 24 / December / 2010, 07:53:13
>CHDK only uses ptpcam as a convenient place to put some code.  As I said earlier, I wasn't able to get >many of the non-chdk ptpcam functions to work. It appears to me that ptpcam development was >abandoned a long time ago.

I dont know, ptpcam is not know in the wiki, there is only chdkcam which you tell not work on newer trunk.
what have change here, and what trunk begin not work on chdkcam ?
and what need change in chdkcam to get it working ?

there is for Ixus 1000 trunk 958 trunk 969 and trunk 1004 working

I can revert to an old trunk,

Do you get not such a message on ptpcam --chdk ?

"""""
error: camera has unsupported camera version 0.1; some functionality may be miss
ing or cause unintented consequences
""""""

I read some posts, but find no source of ptpcam

merry christmas too all
Title: Re: CHDK PTP interface
Post by: msl on 24 / December / 2010, 10:15:33
I read some posts, but find no source of ptpcam

Here is the original source code by mweerden: https://github.com/mweerden/CHDK/tree/ptp (https://github.com/mweerden/CHDK/tree/ptp) (in tools/ptpcam)

And here you can find the code with reyalp's modifications: http://my-trac.assembla.com/chdkde/browser/trunk/tools/ptpcam (http://my-trac.assembla.com/chdkde/browser/trunk/tools/ptpcam)

The last source also contains the necessary things (libUSB components) to compile ptpcam in CHDK-Shell: CHDK-Shell -> console -> make -C tools/ptpcam -f makefile.chdkshell



I wish also merry christmas all
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / December / 2010, 15:25:17
and what need change in chdkcam to get it working ?
Two things.
- you need to build it, which requires borland c builder
- the current minimal CHDK protocol doesn't support all the features of chdkcam, so they would need to be implemented again, or taken out of CHDK cam. In the long term we want to have something like this, but it will take time to implement it in a way that we can support all cameras, and have a tool we can all work on.
Quote
there is for Ixus 1000 trunk 958 trunk 969 and trunk 1004 working

I can revert to an old trunk,

Do you get not such a message on ptpcam --chdk ?

"""""
error: camera has unsupported camera version 0.1; some functionality may be miss
ing or cause unintented consequences
""""""

Camera protocol version should be 0.2 if using current trunk code, but using 0.2 ptpcam with 0.1 chdk is fine, only the new script-support and script-status commands will fail.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / December / 2010, 19:14:39
Updated ptpcam

This has the cli and auto-reconnect stuff from fudgeys post http://chdk.setepontos.com/index.php?topic=4338.msg54414#msg54414 (http://chdk.setepontos.com/index.php?topic=4338.msg54414#msg54414)

the cli stuff could use some cleanup, but should be useful as is.

corrected sleep() for win32. as it was before, it would have used seconds on linux and milliseconds on win32.

I didn't add the luaw stuff

code in http://tools.assembla.com/chdkde/changeset/515 (http://tools.assembla.com/chdkde/changeset/515)
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2010, 04:07:06
Here's an idea I've been thinking about for a while for a better (?) PTP <> script interface. Finally got around to working on it  :xmas
The code is functional but basically at the proof of concept stage.

The basic idea is to let PTP talk to a running script, instead of just running snippets of lua.

Here's how it works:
The CHDK ptp code has two queues of "messages", one for PC->camera (input queue) and one for camera->PC (output queue)

A message is a sequence of bytes, size limited by available memory. From lua it is a string but lua strings are binary safe so it can be anything. The queues just store pointers to the messages.

No task synchronization is needed between the script task and the PTP task, because Lua only reads from the input queue and writes to the output queue, while PTP only does the reverse.

This is implemented with two new PTP commands WriteScriptMsg and ReadScriptMsg and two new lua functions write_usb_msg and read_usb_msg

PC sends WriteScriptMsg to add a message to the input queue. read_usb_msg fetches the message in lua
write_usb_msg adds a message to the output queue. ReadScriptMsg fetches the message on the PC

read*/write* return indications if the queue is empty or full, respectively.

Now a lua script can call read_usb_msg in a loop, and do something based on the content of the messages. This could be commands, or could be lua code. It can send output back with write_usb_msg

Plan is to make the lua functions optionally block with a timeout (like wait_click) but this isn't implemented yet.

Some benefits
- No need to stall PTP waiting for lua results. Long executing lua calls work be fine, as long as they sleep just like other lua scripts. The PC side can just poll until the response message(s) appear.
- you can return arbitrary data.
- You can maintain state between commands on the camera, unlike the current lua command which start from scratch every time.
- The need to expand the core protocol is reduced, because you can implement arbitrary protocols in lua

Other thoughts
- Taking full advantage of this will require a more flexible client than the current ptpcam. Something we need anyway.
- right now there is only one message channel. You can always send messages, even if there is nothing listening, and any script that starts later will see them if it reads. It would be possible to add some listen/connect/close semantics and have multiple channels, but I'm not sure if this is needed.
- it would be useful to be able to send data without going through a lua string, e.g. directly from a pointer

Attached files
chdk-ptpmsg-1.patch - patch against chdk code trunk
ptpcam-chdkde-ptpmsg-1.patch - patch against chdkde ptpcam
ptpmsg.lua - example script

example
Code: [Select]
ptpcam --chdk
upload ptpmsg.lua A/ptpmsg.lua
lua loadfile('A/ptpmsg.lua')()
putm ls A/
getm
exec return 1+1
getm
Title: Re: CHDK PTP interface
Post by: Bernd R on 25 / December / 2010, 11:48:47
@reyalp
>- you need to build it, which requires borland c builder

hope this is not too complicate and use special borland libs, i can try when i have time to compile with wxdevcpp.it use then wxwidgets(work on win /Linux/Mac OS/ Unix too).

http://wxdsgn.sourceforge.net/ (http://wxdsgn.sourceforge.net/)

its free and its easy too use (at least i understand a little how it work).i use this also for crosscompile, so to make some day a linux version for chdkcam (if that not use specific win) functions is possible.there need only a gui switrch change to set the target platform.

every target have a dialogbox that contain dir, path to compiler ,C++, assembler, linker.i know eclipse can do more, but i dont understand how make a compiler set.

what do you think about that ?
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2010, 13:36:36
@reyalp
>- you need to build it, which requires borland c builder

hope this is not too complicate and use special borland libs, i can try when i have time to compile with wxdevcpp.it use then wxwidgets(work on win /Linux/Mac OS/ Unix too).
It's a C++ builder app, so it needs the corresponding c++ builder libs. Definitely not portable. I don't know whether the free Borland command line tools (linked earlier in this thread) are sufficient to build it, and I'm not really interested in spending the time to find out.
Title: Re: CHDK PTP interface
Post by: Bernd R on 25 / December / 2010, 14:01:44
I use now the newest chdk files, no

"""""
error: camera has unsupported camera version 0.1; some functionality may be miss
ing or cause unintented consequences
""""""

error come and i can now upload files.
only i see that ptpcam do no full init after a conn command.

for example when i do this lines

C:\Users\pc>e:chdk\ptpcam.exe --chdk
<conn> upload ps.fi2 A/ps.fi2
<conn> upload ps.fi2 A/ps.fi2

work 2 times

now i remove the USB cable on camera and then i put it in again

then i get that output

<conn> upload ps.fi2 A/ps.fi2
unexpected return code 0x2ff
upload failed!
<conn>

so there seem on every conn command no full usb init as --chdk do.

Is that possible to change ?
also a good idea is to have a command to transfer a chdk zip to Camera
 then you need only do

ptpcam --chdkupd ......zip

then the SD Card change is not need.

I see only little Problem in Ixus  1000 that when the USB cable is plug in, the firmware keys do not work.So when i switch camera on in play mode, i can not press menu to do firmware update.

I need remove the USB cable
is this on other camera same ?
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2010, 14:13:13
error come and i can now upload files.
only i see that ptpcam do no full init after a conn command.

for example when i do this lines

C:\Users\pc>e:chdk\ptpcam.exe --chdk
<conn> upload ps.fi2 A/ps.fi2
<conn> upload ps.fi2 A/ps.fi2

now i remove the USB cable on camera and then i put it in again

then i get that output

<conn> upload ps.fi2 A/ps.fi2
unexpected return code 0x2ff
upload failed!
<conn>
This seems normal to me. If you unplug the camera, then you need to do reset command to reconnect.
The newest ptpcam will try to reconnect if you reboot.
Quote
ptpcam --chdkupd ......zip
The fugeys cli stuff that I added in the latest ptpcam also lets you do
ptpcam --chdk="upload diskboot.bin A/diskboot.bin"

You should also be able to write a "batch file" of chdk ptpcommands and then redirect input, e.g.
ptpcam --chdk < mycommands.txt
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2010, 21:42:47
I see only little Problem in Ixus  1000 that when the USB cable is plug in, the firmware keys do not work.So when i switch camera on in play mode, i can not press menu to do firmware update.

I need remove the USB cable
is this on other camera same ?
Yes, cannon keys are disabled. Alt mode should still work.

To load your new FI2, use the reboot command. If the appropriate bits of CHDK are implemented, you can do lua reboot("A/PS.FI2") and it will do the right thing. See the code and comments in lib/armutil/reboot.c

edit:
a plain reboot() should work on almost any camera, but if you are using a multipartition card, you won't be able to upload a diskboot to the non-active partition.
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2010, 22:04:06
Updated usb script message code. Timeouts now implemented for read_usb_msg and write_usb_msg

ptpmsg.lua updated to use this. the lsa command shows blocking writes. The low timeouts are just for testing.

ptpcam code is unchanged

note that you don't have to use the message loop, you can use write_usb_msg() to return a value, e.g.

Code: [Select]
<conn> lua write_usb_msg(tostring(1 + 1))
<conn> getm
message 1 size=1
2
<conn>
Title: Re: CHDK PTP interface
Post by: Bernd R on 26 / December / 2010, 08:36:20
@reyalp
>To load your new FI2, use the reboot command. If the appropriate bits of CHDK are implemented, you can >do lua reboot("A/PS.FI2") and it will do the right thing. See the code and comments in lib/armutil/reboot.c

thanks, this work great.chdk is new start after upload.

I do

C:\Users\pc>e:\chdk\ptpcam.exe --chdk < chdkupd.txt
<conn> <conn> <conn>

C:\Users\pc>

with that chdkupd.txt file content

upload ps.fi2 A/PS.FI2
lua reboot("A/PS.FI2")

there is only a very little problem in ptpcam.when start it without Camera is on, there come after some checks a crash of ptpcam r515 StackHash_0a9e error code c0000005 on my win 7 64 bit.

here is output, but in front is german text

"""""
 Problemereignisname:   APPCRASH
  Anwendungsname:   ptpcam.exe
  Anwendungsversion:   0.0.0.0
  Anwendungszeitstempel:   4d15364c
  Fehlermodulname:   StackHash_0a9e
  Fehlermodulversion:   0.0.0.0
  Fehlermodulzeitstempel:   00000000
  Ausnahmecode:   c0000005
  Ausnahmeoffset:   00000000
.....
""""""



"""""
C:\Users\pc>e:\chdk\ptpcam.exe --chdk < chdkupd.txt
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
Could not find any device matching given bus/dev numbers, retrying in 1 s...
could not find any device matching given bus/dev numbers
<    >
C:\Users\pc>
"""""

maybe it can add too in the chdkshell buildscript, when a new version is compile, file is upload to camera and reboot is done automatic.but for automatic, i think its better when the automatic poll if camera is on, can be disable or is only do for 10 sec.
Title: Re: CHDK PTP interface
Post by: philmoz on 01 / January / 2011, 02:46:02

example
Code: [Select]
ptpcam --chdk
upload ptpmsg.lua A/ptpmsg.lua
lua loadfile('A/ptpmsg.lua')()
putm ls A/
getm
exec return 1+1
getm


Not sure what I'm doing wrong here; but 'putm' and 'getm' give 'unknown command' error message.
Using ptpcam from 'Ptpcam-chdkde-r515.zip' and I've applied the CHDK patches from 'ptpmsg-work-2.zip' and rebuilt (camera is SX30).

Regards,
Phil.

Title: Re: CHDK PTP interface
Post by: reyalp on 01 / January / 2011, 16:09:11

example
Code: [Select]
ptpcam --chdk
upload ptpmsg.lua A/ptpmsg.lua
lua loadfile('A/ptpmsg.lua')()
putm ls A/
getm
exec return 1+1
getm


Not sure what I'm doing wrong here; but 'putm' and 'getm' give 'unknown command' error message.
Using ptpcam from 'Ptpcam-chdkde-r515.zip' and I've applied the CHDK patches from 'ptpmsg-work-2.zip' and rebuilt (camera is SX30).
You need to build a patched PTPcam too. Patch is against the source in chdkde
http://tools.assembla.com/chdkde/browser/trunk/tools/ptpcam (http://tools.assembla.com/chdkde/browser/trunk/tools/ptpcam)

This is really an experiment, not intended as something for end users yet. But it is pretty functional.

I think the of approach of queuing messages is definitely the way to handle getting data back, but it needs quite different PTP client, because the client needs to be able to poll in the background. It also needs to be flexible enough to handle different scripts on the camera end. I'm still not sure exactly the best way to structure this, but I have some ideas...

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Flh5.ggpht.com%2F_UDetsZvPfqQ%2FTRodou98rAI%2FAAAAAAAAA0U%2F1Lh3vDWyF8g%2Fwhee.JPG&hash=e71dcc40645161c1481dbc3db9eaf3f2)

Goals:
- easy enough for other developers to work on.
- portable, built with all free tools/libraries
- optional GUI
- PC side scripting/extending
- CHDKcam style live view

Current work uses
- ptpcam code for low level stuff, with everything that isn't CHDK related ripped out
- IUP 3.3 http://www.tecgraf.puc-rio.br/iup/ (http://www.tecgraf.puc-rio.br/iup/) for gui
- Lua for both GUI (using IUP) and interface to CHDK PTP commands
- all builds with out of the box mingw gcc4.5 binary

I hope to get it in a usable enough state to put it in a public repository this weekend. Once that happens, chdk, chdkde and other interested developers will be welcome to contribute.

Title: Re: CHDK PTP interface
Post by: reyalp on 02 / January / 2011, 18:45:25
I've shamelessly stolen most of chdkde changeset 530 (http://tools.assembla.com/chdkde/changeset/530), trunk changeset 1018 (http://tools.assembla.com/chdk/changeset/1018)

This adds the necessary functions for mode changing on most dryos cameras. I haven't turned it on in camera.h, but this should give us what we need to support PTP out of the box on almost all cameras.

I see they are also working on a PTP GUI http://forum.chdk-treff.de/viewtopic.php?f=7&t=2122&start=75#p20351 (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2122&start=75#p20351)
Title: Re: CHDK PTP interface
Post by: rudi on 03 / January / 2011, 06:14:11
I've shamelessly stolen most of chdkde changeset 530 (http://tools.assembla.com/chdkde/changeset/530), trunk changeset 1018 (http://tools.assembla.com/chdk/changeset/1018)
Such a thing! But you must it do another one, because the G12_100c is also ready.

The "switch_mode_usb"-routine for all cams are in "/generic/lib.c", see changeset 465 (http://my-trac.assembla.com/chdkde/changeset/465) and 470 (http://my-trac.assembla.com/chdkde/changeset/470).

rudi
Title: Re: CHDK PTP interface
Post by: msl on 03 / January / 2011, 06:48:58
I've shamelessly stolen ...
This is not shameless, that's great. So we have more opportunities to locate any errors.

I see they are also working on a PTP GUI ...
The GUI design is a small attempt to help people who have problems with a console. So we get more feedback  (maybe). Wim will probably laugh at this Autoit attempt. ;)

Your proposal (IUP) is certainly the better way for a GUI because it is platform independent. The idea of using read/write_ptp_msg is also very interesting.

edit: You can find the GUI now here: http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207 (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207)
Title: Re: CHDK PTP interface
Post by: hwntw on 03 / January / 2011, 10:38:21
Tested ptpGUI on Ixus95/SD1200 and WinXP, using CHDKDE build 531. All seems to work.
Colin
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / January / 2011, 02:32:16
The "switch_mode_usb"-routine for all cams are in "/generic/lib.c", see changeset 465 (http://my-trac.assembla.com/chdkde/changeset/465) and 470 (http://my-trac.assembla.com/chdkde/changeset/470).
Thanks. Equivalent changes are in trunk 1022-1023. I did it a little differently so I wouldn't have to touch every lib.c

I didn't get as much as I wanted done on the PTP tool this weekend. Got distracted by patches and exmem, but still made a lot of progress.

I'll try to get it in a public repository next weekend. Not sure where it should go, I'm thinking of making a new project for it on assembla, or maybe github ?
Title: Re: CHDK PTP interface
Post by: hwntw on 04 / January / 2011, 13:04:26
Hello,
Exciting times for CHDK-PTP is progressing, scripting support could soon be optional and result in smaller builds, more camera memory availability looks on the cards. My question to developers is: if I opt out of scripting support, will this render PTP usage inoperable?

Colin
Title: Re: CHDK PTP interface
Post by: c10ud on 04 / January / 2011, 13:30:56
unless you hardcode some actions in the ptp code, the possibilities without scripts are very tiny (upload, download, mode change?)
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / January / 2011, 15:34:24
unless you hardcode some actions in the ptp code, the possibilities without scripts are very tiny (upload, download, mode change?)
We could expose the "action stack" commands and PostLogicalEvent with very little overhead.

But really I think scripting is the way way to go. If we hard code it in PTP, then we take memory away from every user, even if they don't use PTP at all

You could always use a different binary for PTP and regular shooting, since we now have reboot("filename"), although that currently uses script as well...

Title: Re: CHDK PTP interface
Post by: hwntw on 04 / January / 2011, 16:44:51
Deleted by a craven coward
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / January / 2011, 21:30:35
No, no, no, bad conclusion: if we are going to end up with more memory from this exmem thingy, then use it for compiled PTP (and better zebra for Ixus 95).  CHDK is for photographers, scripting is for programmers
I disagree completely with this, but it's off topic to this thread. Feel free to start a new one in general discussion about CHDK development directions.

If I have any say in the matter, scripting will remain a core part of CHDK, and PTP will be enabled by default as soon as it can be cleanly supported across cameras.
Title: Re: CHDK PTP interface
Post by: ultimA on 05 / January / 2011, 00:05:10
In my oppinion PTP is just as much a power-user feature as scripting, not much point in arguing which is more for photographers.

But to stay on the topic, I do agree to keep PTP-functionality minimal. However, I would add just two more commands: 1) shooting a picture and 2) transferring a single frame from the live buffer. Note that I'm NOT proposing webcam-like streaming or anything that would require real-time transfer rates. Merely a request to send over a single frame from the current live buffer. I'd propose these in addition to what is already there to be available without scripting, rest to be scripted. Reason is that then the PTP feature set would be enough and adaquate for basic computer controlled camera without the overhead of scripts.
Title: Re: CHDK PTP interface
Post by: fudgey on 06 / January / 2011, 04:40:05
But to stay on the topic, I do agree to keep PTP-functionality minimal. However, I would add just two more commands: 1) shooting a picture and 2) transferring a single frame from the live buffer. Note that I'm NOT proposing webcam-like streaming or anything that would require real-time transfer rates. Merely a request to send over a single frame from the current live buffer. I'd propose these in addition to what is already there to be available without scripting, rest to be scripted. Reason is that then the PTP feature set would be enough and adaquate for basic computer controlled camera without the overhead of scripts.

If PTP must be kept somehow useful without scripting, then instead of a shooting command I'd go with access to half+full shutter press/release (or even better, to the entire keyboard). But my vote would go against that.

IMO there's no point in making PTP that doesn't require scripting, because UBASIC is small (11.6 KiB according to http://chdk.setepontos.com/index.php?topic=5793.msg56643#msg56643, (http://chdk.setepontos.com/index.php?topic=5793.msg56643#msg56643,) probably hasn't changed immensely after the recent patches). AFAIK, CHDK PTP doesn't currently support UBASIC, but that's not the only thing that's not quite there yet -- Lua is just so much more powerful that it hasn't made any sense to use anything but it so far.

My understanding is that most users who do not want scripting at all don't want it because it complicates camera usage, mainly because of the alt+shutter shortcut which is sort of a trap for beginners and those that don't know CHDK is running on the camera someone gave them. For those users, disabling the script start and menu shortcuts (and optionally menu entries) suffices. This is something that should be easy for a developer to disable for a custom build, but in the long run is solved by user settable shortcut key mapping.

So basically my vote would go for using scripting for all PTP commands that make sense to be implemented as scripts. In a PC side application, use UBASIC commands internally whenever possible since Lua may not be available. Users will not know they are running tiny scripts all over when clicking buttons on a PC GUI and shouldn't care either as long as the camera zooms and shoots as commanded. And if it happens that we really do get some RAM for CHDK on all cameras using that new EXMEM stuff and can use it to solve memory issues, then my vote changes to requiring Lua for PTP.


As for live view, ewavr already implemented it in real time (more or less, depending on USB speed). If my memory serves, the main obstacle for adding that to the trunk CHDK PTP is that it needs some work to make it more generic across cameras with different sorts of live view buffers, resolutions and colors -- something that probably doesn't become much easier even if it's not in real time.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / January / 2011, 12:52:26
If PTP must be kept somehow useful without scripting, then instead of a shooting command I'd go with access to half+full shutter press/release (or even better, to the entire keyboard). But my vote would go against that.
As I said, it would be quite easy (almost trivial) to add "action stack" and/or levent support. I'm pretty tempted to do this, just because it would be a tiny amount of code, and would allow basic camera control natively.

One useful part that is missing, and would also be non-trivial to do in ubasic is directory listing. With directory listing, we can make a nice gui for file transfer, which will really help people getting DNG off of multi-paritition cards and similar scenarios. Directory listing can be done in lua, but if we are going to offer non-lua functionality, it seems like this should be included.
Quote
AFAIK, CHDK PTP doesn't currently support UBASIC, but that's not the only thing that's not quite there yet -- Lua is just so much more powerful that it hasn't made any sense to use anything but it so far.
Agreed.
Quote
My understanding is that most users who do not want scripting at all don't want it because it complicates camera usage, mainly because of the alt+shutter shortcut which is sort of a trap for beginners and those that don't know CHDK is running on the camera someone gave them.

The other issue is memory. Excluding lua could allow some cameras that experience memory related shutdowns to operate normally (although at least some of these have turned out to be coding errors and there's more fat that can be trimmed without losing lua). Ubasic is small enough that it doesn't really matter, IMO.
Quote
As for live view, ewavr already implemented it in real time (more or less, depending on USB speed). If my memory serves, the main obstacle for adding that to the trunk CHDK PTP is that it needs some work to make it more generic across cameras with different sorts of live view buffers, resolutions and colors -- something that probably doesn't become much easier even if it's not in real time.
It has always been my intention to add this back. This is one of the main reasons I've started a new gui tool.
Title: Re: CHDK PTP interface
Post by: sironitomas on 07 / January / 2011, 18:59:08
@asm1989 The bracketing features still don't work if you shoot with the "Custom Timer" option.

Strange, because they work if you shoot with the "Drive Mode" set in continuous, but that is not wanted in some cases because you must have your finger in the shutter.
Title: Re: CHDK PTP interface
Post by: waterwingz on 08 / January / 2011, 11:34:10
This adds the necessary functions for mode changing on most dryos cameras. I haven't turned it on in camera.h, but this should give us what we need to support PTP out of the box on almost all cameras.

@reyalp So at this point do I simply need to use the latest trunk release,  add  #define  CAM_CHDK_PTP in the appropriate spot in camera.h,  enable the OPT_PTP box in the CHDK-Shell compile options, rebuild and start testing ? 
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / January / 2011, 15:47:15
This adds the necessary functions for mode changing on most dryos cameras. I haven't turned it on in camera.h, but this should give us what we need to support PTP out of the box on almost all cameras.

@reyalp So at this point do I simply need to use the latest trunk release,  add  #define  CAM_CHDK_PTP in the appropriate spot in camera.h,  enable the OPT_PTP box in the CHDK-Shell compile options, rebuild and start testing ?
Probably. The entry points for the various functions may not have been identified correctly on your camera, but most should be OK.

Edit:
If people can report which cameras have been tested successfull (including mode switching through PTP) that would be helpful.

A540 and D10 work correctly. Most vxworks cameras should be fine, since they don't need extra functions to switch.
Title: Re: CHDK PTP interface
Post by: msl on 08 / January / 2011, 19:07:32
If people can report which cameras have been tested successfull (including mode switching through PTP) that would be helpful

Successfully tested on A495, A590, A610 (VxWorks), A650, A720, Ixus95, Ixus 100 (not clearly), Ixus970, S5, SX200.
Title: Re: CHDK PTP interface
Post by: waterwingz on 08 / January / 2011, 21:10:44
If people can report which cameras have been tested successfull (including mode switching through PTP) that would be helpful.
No luck for the SD940 with just enabling CAM_CHDK_PTP.  Camera is detected by PC but crashes as you try to open folders.

ROMLOG.TXT attached if that helps any.

EDIT :  Hmmmm ... CreateTask_init_chdk_ptp() exists in some copies of boot.c.  Time to see what that's all about.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / January / 2011, 21:23:52
EDIT :  Hmmmm ... CreateTask_init_chdk_ptp() exists in some copies of boot.c.  Time to see what that's all about.
It should be removed from any boot.c it exists in, started from spytask now.


Title: Re: CHDK PTP interface
Post by: waterwingz on 08 / January / 2011, 21:53:23
It should be removed from any boot.c it exists in, started from spytask now.
Thanks.  One less thing to worry about.  Its commented out in the g12 and sx30 of the current trunk.
Title: Re: CHDK PTP interface
Post by: jrkblo on 09 / January / 2011, 06:45:03
Hi all
I'm trying to use PTPCAM whit a A495 and 'm getting the following error

c:\Ptpcam-chdk-1005>ptpcam --chdk
unexpected return code 0x2005
error: cannot get camera CHDK PTP version; either it has an unsupported version
or no CHDK PTP support at all
<conn>

Does anyone know what can be that?
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / January / 2011, 14:46:15
Hi all
I'm trying to use PTPCAM whit a A495 and 'm getting the following error

c:\Ptpcam-chdk-1005>ptpcam --chdk
unexpected return code 0x2005
error: cannot get camera CHDK PTP version; either it has an unsupported version
or no CHDK PTP support at all
<conn>

Does anyone know what can be that?
What ptpcam binary are you using ? What a495 build are you using ?

I think this one is in CHDKDE, so you might want to use their build.
Title: Re: CHDK PTP interface
Post by: Bernd R on 14 / January / 2011, 10:04:21
>Edit:
>If people can report which cameras have been tested successfull (including mode switching through PTP) >that would be helpful.

I test Ixus 1000 HS

C:\Users\pc>e:\chdk\ptpcam --chdk="mode 1"

The command move out the lens and Camera switch off with lens out.no image see, seem crash.later commands with ptpcam give same error message as no camera is connect

I use trunk 1023.maybe this is too old ?

upload and download files and lua reboot work over ptpcam
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / January / 2011, 12:14:39
The command move out the lens and Camera switch off with lens out.no image see, seem crash.later commands with ptpcam give same error message as no camera is connect

I use trunk 1023.maybe this is too old ?
More likely some entry points (pb2rec, rec2pb, set_control_event) are wrong.
Title: Re: CHDK PTP interface
Post by: Bernd R on 14 / January / 2011, 12:54:28
The address of PB2REC is find in that function that stand this text

AC:PB2REC

I verify that and seem ok.

I add shutdown after _PB2Rec

 _PB2Rec();
shutdown();

Now lens do not move out and camera display get dark earlier.

seem the function return immidiate.

So i add a msleep(2000); (see below)

then lens move out and camera shutdown without move in the lens.

Do you know if shutdown() command move in the lens if it is out ?

if yes then camera is crash in function  _Rec2PB();

_set_control_event

// Best match: 93%
NSTUB(set_control_event, 0xff89bfe4)

seem a good find.do you know if this work all on S95 ?
If so i can compare the asm source with that, maybe there is something really wrong.


int __attribute__((weak)) switch_mode_usb(int mode)
{
#ifdef CAM_CHDK_PTP
    if ( mode == 0 ) {
        _Rec2PB();
        _set_control_event(0x80000902); // 0x10A5 ConnectUSBCable
    } else if ( mode == 1 ) {
        _set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        _PB2Rec();
         msleep(2000);
         shutdown();
    } else return 0;
    return 1;
#else
  return 0;
#endif // CAM_CHDK_PTP

Title: Re: CHDK PTP interface
Post by: Bernd R on 16 / January / 2011, 06:55:58
I have  now remove

//_set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        _PB2Rec();
msleep(4000)

and camera crash too as soon the optic is out of camera correct.

what happen on other cam when _set_control_event is not execute ?
maybe the value is wrong for new camera.

or maybe you can tell me a test, to see if  _set_control_event work ok.
Title: Re: CHDK PTP interface
Post by: rudi on 16 / January / 2011, 09:35:20
More likely some entry points (pb2rec, rec2pb, set_control_event) are wrong.

I confirm manual PB2REC and REC2PB for each cam in trunk. For SET_CONTROL_EVENT I make some spot tests, because the code is equal (finsig works fine for that).

@Bernd R
I would use for IXUS1000_100d this addresses:
PB2REC: 0xFF89F73C
REC2PB: 0xFF89DFE4
set_control_even: 0xFF89BFE4

rudi
Title: Re: CHDK PTP interface
Post by: Bernd R on 16 / January / 2011, 11:46:14
>PB2REC: 0xFF89F73C
>REC2PB: 0xFF89DFE4
>set_control_even: 0xFF89BFE4

yes, this addresses the IX1000 D Port use

stubs_entry_2.s

NHSTUB(PB2Rec,                          0xFF89F73C)  // search "AC:PB2Rec"
NHSTUB(Rec2PB,                          0xFF89DFE4)  //"AC:Rec2PB"

and in stubs_entry.s file

 // Best match: 93%
NSTUB(set_control_event, 0xff89bfe4)

but it not work.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / January / 2011, 13:56:17
Related to a problem discussed over in chdkde:
http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220 (http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220)

I don't like luar, the code on the camera is too complicated. If we remove it, maybe the problem goes away.

I think luar should work like this

on PC:
exec_lua("... return some value")
while(script_status() == LUA_IS_RUNNING)
  sleep()
get_lua_result()

On camera
when script ends, luascript code stores the value somewhere when script ends, instead of PTP task sleeping and playing with lua states
Could be a function or global instead of using lua return, example
ptp_result = "hello world"

Then code can set anywhere and not worry about having return in the right place. With a global, C code doesn't need to worry storing/freeing the value until the very end.

Need to clear the value if another script is started before result is fetched. Would also be good to clear if PTP is disconnected.

My script message experiment was similar, but I think for "run some code and return a result" should be simpler. Message queue may be useful later.

This will break compatibility with previous protocol, but might be a better use of time than debugging this.
Title: Re: CHDK PTP interface
Post by: Bernd R on 16 / January / 2011, 14:12:31
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / January / 2011, 14:19:21
I don't think this is related to your problem on the ixus1000, I think it only affects luar
Title: Re: CHDK PTP interface
Post by: fudgey on 16 / January / 2011, 14:48:26
This will break compatibility with previous protocol, but might be a better use of time than debugging this.

I don't see a reason to maintain compatibility -- ptp has been announced as experimental and subject to change for the better, and the particular flavour now in trunk probably doesn't even have many users yet (at least not the kind that gets confused by change) given the state and age of the PC side tools.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / January / 2011, 17:35:31
This will break compatibility with previous protocol, but might be a better use of time than debugging this.

I don't see a reason to maintain compatibility -- ptp has been announced as experimental and subject to change for the better, and the particular flavour now in trunk probably doesn't even have many users yet (at least not the kind that gets confused by change) given the state and age of the PC side tools.
Agreed. I'm working on this now (instead of my new ptp tool  :-[ )
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / January / 2011, 22:16:27
Work in progress patch. There are still some issues, lots of mess and unfinished bits. Enclosed ptpcam will only work with this code.

Basic idea
set_usb_result() in lua sets the value to be returned. Accepts string, number boolean or nil. nil is the same as not setting a result. There is currently no way to tell the difference.  Setting more than once is fine, it just replaces the previous value. Tables are not allowed, but a lua function to serialize simple tables can be made standard somewhere. I already planned this for my lua based client.

Result is only available to ptp once the script has finished.

Result is saved for every script run, whether you use lua or luar. Old result is thrown away next time a script is run. This means a big result could be stored and never freed if you don't run any more scripts. I plan to add script execution status and error message to the result, so it will make sense even if script doesn't set result.

If you want the result from the previous lua (not luar) command, you can use getr [timeout]

Currently, if there is an error, the 'press a key to close' appears, and the result isn't available until this is done. I think we don't need this for ptp scripts, especially if they return flag and error message.

If you start another script while a script is running, the old scripts is killed and any result is thrown away. But I'm not sure this cleans up properly in other areas, needs to be looked into.

Currently getr and luar just polls script-status every 250ms. I may add additional bits for error or result available, but I'm not sure they are needed yet.

If there is no result (already received or not set) GetResult returns TYPE_NOTHING. This is a change of meaning, might indicate it in a different way later.


If anyone has feedback on how it should work, now is your time to speak.
Title: Re: CHDK PTP interface
Post by: msl on 17 / January / 2011, 05:57:57
@reyalp
Thank you for your tireless work.

I think the last patch missing ptp_script.h / ptp_script.c. The compiler generates an error message.

I'm not a programmer, I am a CHDK user. ;)
If I understand this patch correctly, it is the right way. We need a good solution, with which  we can send e.g. mod maps or directories from the camera to the computer. In addition, there should be only one command for script functions, lua and not another luar.

Then we have all the options to build a GUI. A GUI is the most important condition to explain to a CHDK users, why should he use a different USB driver. Most people can not do much with a console.

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / January / 2011, 12:06:06
@reyalp
Thank you for your tireless work.

I think the last patch missing ptp_script.h / ptp_script.c. The compiler generates an error message.
You are right, missing ptp_script.h. It's only prototypes for some functions which are in ptp.c. Attached.

Unfortunately, I won't have much time to work on this until the next weekend.
Quote
If I understand this patch correctly, it is the right way. We need a good solution, with which  we can send e.g. mod maps or directories from the camera to the computer. In addition, there should be only one command for script functions, lua and not another luar.
Agreed.  New client I'm working on is mostly lua, so you can send lua table from camera as string, make back into table and use very easily.

Quote
Then we have all the options to build a GUI.
Lua client is nice. Real example:
Code: [Select]
button_shoot=iup.button{
title="shoot",
action=function(self)
chdk.execlua('shoot()')
end,
}
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / January / 2011, 15:54:01
It looks like rudi has found the cause of the immediate problem with luar http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220&start=15#p20567 (http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220&start=15#p20567)
Title: Re: CHDK PTP interface
Post by: Bernd R on 18 / January / 2011, 04:06:44
>It looks like rudi has found the cause of the immediate problem with luar http://forum.chdk-treff.de (http://forum.chdk-treff.de)>/viewtopic.php?f=3&t=2220&start=15#p20567

i test it and the ptpluartest work now ok on Ixus 1000 HS.
But it help not on the switch to record mode crash.

I dont know, whats diffrent, but it work, when i start a script in play mode, Camera switch to record mode, as soon a shoot command come and shoot a image.

but there seem no pb2rec use for this.

very strange wy pb2rec not work on my camera and on other it work.

I see the function  core_get_free_memory do not disable other tasks to work.I think its better when do a task lock so other tasks can not try to alloc memory during the memeaten and maybe fail due too few memory or memory get more fragment




int core_get_free_memory() {
    int size, l_size, d;
    char* ptr;

    size = 16;
    while (1) {
        ptr= malloc(size);
        if (ptr) {
            free(ptr);
            size <<= 1;
        } else
            break;
    }

    l_size = size;
    size >>= 1;
    d=1024;
    while (d) {
        ptr = malloc(size);
        if (ptr) {
            free(ptr);
            d = l_size-size;
            if (d<0) d=-d;
            l_size = size;
            size += d>>1;
        } else {
            d = size-l_size;
            if (d<0) d=-d;
            l_size = size;
            size -= d>>1;
        }
        
    }
    return size-1;
}
Title: Re: CHDK PTP interface - what is luar ?
Post by: waterwingz on 18 / January / 2011, 07:16:30
So what is luar ? And how is it different than lua ?

I tried searching this forum and the CHDK wiki without finding anything that introduced this new concept. I'm guessing its something from the German forum but that's just a guess.

Title: Re: CHDK PTP interface - what is luar ?
Post by: mweerden on 18 / January / 2011, 09:48:16
So what is luar ? And how is it different than lua ?
They are commands from the ptpcam tool. One just runs a script, the other also waits for a return value. It was discussed in this thread a while ago. The reasons why they both exist (in ptpcam, mind you) were also discussed.

From what I've seen/read I really like reyalp's message-queue patch and would suggest it above his getr approach (if that's still on the table after rudi's fix). It doesn't really seem more complex and probably provides all the flexibility you'll "ever" need.

But it help not on the switch to record mode crash.

I dont know, whats diffrent, but it work, when i start a script in play mode, Camera switch to record mode, as soon a shoot command come and shoot a image.

but there seem no pb2rec use for this.
I seem to remember it being mentioned here before that some cameras work with the "normal" mode switch (i.e. without doing PB2Rec or something) in Lua.
Title: Re: CHDK PTP interface
Post by: Bernd R on 18 / January / 2011, 11:05:03
>I seem to remember it being mentioned here before that some cameras work with the "normal" mode >switch

I think the IX1000 can work too with normal mode switch, i test with USB cable in, it work ok.
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / January / 2011, 12:18:51
From what I've seen/read I really like reyalp's message-queue patch and would suggest it above his getr approach (if that's still on the table after rudi's fix). It doesn't really seem more complex and probably provides all the flexibility you'll "ever" need.
Yes, i thought getr was going to be simpler, but it didn't really turn out that way. My problem with the message stuff was it was too generic: For most cases, you probably just want to run a script and return a value, and it doesn't really distinguish those form user defined messages. Having a status available for each script invocation is also important.

Definitely going to remove the current luar method one way or the other.

Quote
I think the IX1000 can work too with normal mode switch, i test with USB cable in, it work ok.
So set_record(1) works ? This is very surprising, it doesn't work on any other recent dryos cameras
Title: Re: CHDK PTP interface
Post by: mweerden on 18 / January / 2011, 13:22:49
Yes, i thought getr was going to be simpler, but it didn't really turn out that way. My problem with the message stuff was it was too generic: For most cases, you probably just want to run a script and return a value, and it doesn't really distinguish those form user defined messages. Having a status available for each script invocation is also important.

Definitely going to remove the current luar method one way or the other.
Why all this hate towards luar? ;)

Seriously though, considering the possible usage, in a world with a message queue, I doubt there is a real need to deal with the return value in CHDK itself. People who know what they're doing will know to use write_usb_msg and "normal" users will use some GUI tool that can take care of the return value by wrapping all code in a write_usb_msg. At least, I don't expect the latter case requires something more than submitting code, possibly providing text input and having the output (messages and return value) printed in some text box.

Alternatively, you could tag messages with a type ('user', 'return value') or something. Possibly even by using some bits of the size variable. (I mean, 4GB messages seem unlikely and, if not, what about messages of size MAX_INT+1.)
Title: Re: CHDK PTP interface
Post by: Bernd R on 18 / January / 2011, 13:43:47
>So set_record(1) works ?

I dont understand what ypu mean.do you mean in C source or as lua command use set_record(1) ?

I have USB cable plug in camera and press when camera is in play mode and alt mode the shoot button full.this script switch then to record mode and shoot the images without problems.please read below too

rem Author - Keoeeit
rem Written for S-Series
rem Should be okay on others
rem Use Endless mode with caution
rem See documentation for important info
rem first version
@title Ultra Intervalometer
@param a Delay 1st Shot (Mins)
@default a 0
@param b Delay 1st Shot (Secs)
@default b 0
@param c Number of Shots
@default c 5
@param d Interval (Minutes)
@default d 0
@param e Interval (Seconds)
@default e 0
@param f Interval (10th Seconds)
@default f 5
@param g Endless? No=0 Yes=1
@default g 0
p=a*60000+b*1000
t=d*60000+e*1000+f*100
if c<1 then let c=5
if t<100 then let t=100
if g<0 then let g=0
if g>1 then let g=1
if p<0 then let p=0
z=t*c
y=p+z
print "1 Cycle Time:", y/60000; "min", y%60000/1000; "sec"
goto "interval"
:interval
  if p>0 then gosub "pause"
  print "Shot 1 of", c
  shoot      
  if c=1 then end
  for n=2 to c
  sleep t
  print "Shot", n, "of", c
  shoot
  next n

.......


so maybe can call what this script do too with C functions ?

I add

 set_record(1);

in C source, but give error

wrappers.c:(.text+0x1254): undefined reference to `set_record'

#ifdef CAM_CHDK_PTP
    if ( mode == 0 ) {
        _Rec2PB();
        _set_control_event(0x80000902); // 0x10A5 ConnectUSBCable
    } else if ( mode == 1 ) {
        //_set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        //_PB2Rec();
          set_record(1);
    } else return 0;
    return 1;
#else
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / January / 2011, 15:44:47
>So set_record(1) works ?

I dont understand what ypu mean.do you mean in C source or as lua command use set_record(1) ?
This is the lua function that switches between record and play normally, when PTP isn't involved. This also works in PTP for most vxworks cameras.

I'm pretty sure this is what mweerden was referring to.
Quote
I have USB cable plug in camera and press when camera is in play mode and alt mode the shoot button full.this script switch then to record mode and shoot the images without problems.please read below too
If I understand correctly, this would also be very unusual. Normally when the camera is connected by USB, it doesn't respond to any canon buttons. CHDK alt buttons are expected to work.
Title: Re: CHDK PTP interface
Post by: mweerden on 18 / January / 2011, 16:27:57
I'm pretty sure this is what mweerden was referring to.
Me too.

so maybe can call what this script do too with C functions ?

I add

 set_record(1);

in C source, but give error
Try levent_set_record() (and levent_set_play() for set_record(0)).
Title: Re: CHDK PTP interface
Post by: Bernd R on 19 / January / 2011, 09:22:33
I try now with ptpcam(with the lua fix) this line

C:\Users\pc>e:\chdk\ptpcam --chdk="lua set_record(1)"

Camera do nothing.
I also try now this C Code and Camera do nothing

        //_set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        //_PB2Rec();
       levent_set_record();

when i try out this C code and set_control_event is execute, camera crash in same way as with _pb2rec.
it move out lens and then crash.

  _set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        //_PB2Rec();
       levent_set_record();

maybe Camera have diffrent values for diconnect USB cable ?

But what does levent_ mean ?

is this the code lua execute.

What C code do the basic script execute ?
It seems diffrent because the basic script switch when call shoot from play mode to record mode and shoot correct when USB cable is plug in.LUA do this not.

C:\Users\pc>e:\chdk\ptpcam --chdk="lua shoot()"

do nothing

I find out, when i have chdk run and USB cable is in, after 2-3 minutes do no action Camera switch off complete.
Is this ok, or is maybe a function call to display off wrong ?

I have now do a lua script, but this bring eof expected near end on last line.but demo scripts in chdk scripts folder work. but maybe is something wrong with the Camera port, i have upload the script here

http://www.zshare.net/download/854432334e4ec216/ (http://www.zshare.net/download/854432334e4ec216/)

source is this, i want test if lua switch with USB cable plug in with that script same as basic script in record mode.
I ghave do this script on windowseditor which add 0xd and 0xa
 


--[[

@title interval

]]
set_record(1)
repeat    
   press("shoot_full")
   release("shoot_full")
   sleep(5000)
        press("shoot_full")
   release("shoot_full")
   sleep(5000)
until false
end
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / January / 2011, 12:10:00
I try now with ptpcam(with the lua fix) this line

C:\Users\pc>e:\chdk\ptpcam --chdk="lua set_record(1)"
As I told you before, this method only works on old cameras, it would be very surprising if it worked on yours.

Quote
       levent_set_record();
Pointless, this is the same thing is the lua call would do. If the lua version doesn't work, then this also will not work.
Quote
  _set_control_event(0x902); // 0x10A6 DisconnectUSBCable
        //_PB2Rec();
       levent_set_record();

maybe Camera have diffrent values for diconnect USB cable ?
Random mixing and matching code is unlikely to help. It's possible the value for set control event is wrong.

Quote
But what does levent_ mean ?
"logical event"  from the camera functions PostLogicialEvent
Quote
is this the code lua execute.

What C code do the basic script execute ?
Why don't you look and find out for yourself ?
Quote
It seems diffrent because the basic script switch when call shoot from play mode to record mode and shoot correct when USB cable is plug in.LUA do this not.
It's not different, shoot uses exactly the same code. Shoot does not switch any other camera to record mode with USB connected that I know of.
Title: Re: CHDK PTP interface
Post by: Bernd R on 19 / January / 2011, 14:21:42
>It's not different, shoot uses exactly the same code. Shoot does not switch any other camera to record >mode with USB connected that I know of.

I find now wy shoot can work on my Camera.its because key mask2 for pysw_status[2] is wrong.

when in alt mode the USB flag bit is clear.So USB does not work in alt mode(i get could not find any device messages then) , but shoot can switch to record mode.

only when leave alt mode USB work.but then shoot full always switch to record mode due to canon firmware

so a solution to deactivate USB temporary seem also set the pysw_status flag switch to record mode, and set it back.
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / January / 2011, 15:26:38
I find now wy shoot can work on my Camera.its because key mask2 for pysw_status[2] is wrong.

If you mask the USB power bit (for example, by enabling USB remote), then your cameras isn't in PTP mode, so you can switch and shoot without any special tricks, it's just like unplugging the cable.

I actually considered as an alternative to mode switching: write a script that masks USB, does whatever it needs to, then turns USB back interact with PTP. But this is far more limited than having USB running while shooting.
Title: Re: CHDK PTP interface
Post by: Bernd R on 20 / January / 2011, 04:49:25
>I actually considered as an alternative to mode switching: write a script that masks USB, does whatever it >needs to, then turns USB back interact with PTP. But this is far more limited than having USB running while >shooting.

maybe the value of

_set_control_event(0x902);

is wrong for the Camera.How is this value get ?

maybe a G12 or SX30 user can tell if this is really work in ptp code, to switch to rec mode during play(when alt mode is not active to avoid mask set problems)

this is the command for this i use.

C:\Users\pc>e:\chdk\ptpcam --chdk="mode 1"

I dont understand  wy G12 SX30 can work, because IX1000 is very simular to this.
Title: Re: CHDK PTP interface
Post by: jrkblo on 26 / January / 2011, 16:22:17
Do somebody know if there are a version of ewavr's application that works with A495 or A480? When I try to use that crashes camera, currently I'm using the CHDK 1053 trunk

tks
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / January / 2011, 16:25:52
Do somebody know if there are a version of ewavr's application that works with A495 or A480? When I try to use that crashes camera, currently I'm using the CHDK 1053 trunk
No there is not. As I've explained before, getting any of this working requires hacking.
Title: Re: CHDK PTP interface
Post by: waterwingz on 27 / January / 2011, 00:18:29
Stupid question time - again.  

Trying to run ptpCamGui.exe with my CHDK PTP enable camera (SD940 beta6).  It finds my camera okay  ( init() successful ).  But when I click on any of the buttons in the GUI, the camera appears to try to run a script (script type menu box on camera LCD briefly scrolls past) but not much happens.   If I click the "Camera Off" button it shuts down the camera so something is working.

I'm guessing that I need a LUA script of some sort loaded on the camera when I do this ?  Is that what luar is ?  I really get lost understanding the term luar - posted about that previously but did not understand the answer.

EDIT: seems to  hang with status window on ptpCamGui.exe scrolling  >> luar get_mode() << false (Length: 6)
Title: Re: CHDK PTP interface
Post by: whim on 27 / January / 2011, 03:20:07
Hi waterwingz,

try this:
Hook up cam and start in Play mode, then start ptpCamGui.
After init() completes, press Record, and then Play. After that, most options work
on my old ixus70_sd1000. You don't need to install any script, or anything, ptpCamGui
just needs a recent ptpcam.exe, and (on the cam) a plain vanilla CHDK-DE trunk to run.

wim
Title: Re: CHDK PTP interface
Post by: waterwingz on 28 / January / 2011, 00:51:56
ptpCamGui just needs a recent ptpcam.exe, and (on the cam) a plain vanilla CHDK-DE trunk to run.
Hmmm... trying to get PTP working with the current trunk version of CHDK.  I'm not too interested in exploring the German versions of CHDK - I'm just working on a beta for the SD940 in the current trunk. 

I can talk to my camera with ptpcam and seem to get ptpcam --chdk to interact with me.

Simple things like
        ptpcam --chdk="lua print('test'); sleep(1000);"
or
        ptpcam --chdk="lua a=10; b=20; c=a+b; print('answer=',c); sleep(1000); return c;"
print a value on the display and then exit so things seem to be working.

Does ptpCamGui need CHDK PTP to support commands not in the current (not-DE) trunk ? And if so, then can the CHDK_GUI be modified to not require the DE version of CHDK ?

Title: Re: CHDK PTP interface
Post by: whim on 28 / January / 2011, 05:16:28
Quote
Does ptpCamGui need CHDK PTP to support commands not in the current (not-DE) trunk ? And if so, then can the CHDK_GUI be modified to not require the DE version of CHDK ?
Good questions, but wrong person to address them to  :D
All I can tell you is what's happening in CHDK-Shell, it


wim
Title: Re: CHDK PTP interface
Post by: msl on 28 / January / 2011, 06:10:54
Does ptpCamGui need CHDK PTP to support commands not in the current (not-DE) trunk ? And if so, then can the CHDK_GUI be modified to not require the DE version of CHDK ?

I've tested the current trunk (rev1053) and the GUI work fine for the a720.

You need a CHDK version with activeted PTP support (camera.h) and ptpCamGui & ptpcam.exe in the same directory. Of course, the ptp-addresses must be available for the used camera.

Execute ptpCamGui. Upon successful connection between the camera and the GUI, you can see the following message in the output window: [** init() successful]

The GUI send to the camera only ptpcam.exe commands (incl. lua & luar).

[luar get_mode() << false] means PLAY mode
[luar get_mode() << true] means RECORD mode

In PTP mode the camera keys are locked. You must switch PLAY->RECORD->PLAY. This unlocked the keys in PLAY mode.

All GUI-buttons send lua commands, e.g. [MENU] lua click('menu')

By activating MD the SHOOT-button send not shoot, but lua md_detect_motion(). This is a simple motion detection test.

In the GUI file menu you can find the item "Copy to Camera". Select a CHDK relevant file. *.bas and *.lua files are copied to A/CHDK/SCRIPTS. *.bin and *.fi2/*.fir are copied to A/. Here is the ptpcam.exe command 'upload' used.

Every command can be also entered directly into the input line. Use (') and not (") for strings.

msl
Title: Re: CHDK PTP interface
Post by: whim on 28 / January / 2011, 06:27:03
Quote
I've tested the current trunk (rev1053) and the GUI work fine

Thanks msl !
 
I'll modify my error message to reflect this, because it now says:
Quote
A CHDK-DE build trunk560 or newer
is required both in CHDK-Shell and
on your camera

Glad to see that the CHDK community is in 'healthy competition' rather than 'tribal warfare' mode  ;)
 
wim
Title: Re: CHDK PTP interface
Post by: waterwingz on 29 / January / 2011, 12:11:11
My camera will not go into shooting mode when the USB cable is attached. 

As reported earlier,  I have PTP working somewhat.  I can issue commands via ptpcam and send LUA scripts that execute.  However, once a USB cable is plugged in, the camera buttons stop working and if the camera was in shooting mode it switches to playback mode.

Where do I start looking ?  Do I need to enable remote mode - I thought that might interfere with PTP ?

Title: Re: CHDK PTP interface
Post by: reyalp on 29 / January / 2011, 17:14:29
I can issue commands via ptpcam and send LUA scripts that execute.  However, once a USB cable is plugged in, the camera buttons stop working and if the camera was in shooting mode it switches to playback mode.
This is completely normal.
Quote
Where do I start looking ?
Use switch_mode_usb. If it doesn't work, implement it correctly for your camera.
Quote
  Do I need to enable remote mode
Absolutely note.
Quote
- I thought that might interfere with PTP ?
Correct, enabling the remote will completely disable all USB protocol functionality. "USB" remote is not a USB protocol connection, it's just detecting whether there is power on the USB port. To make this useful, it hides the signal from the canon formware (which in turn hides it from CHDK PTP).
Title: Re: CHDK PTP interface
Post by: Bernd R on 30 / January / 2011, 04:18:03
@reyalp
>Correct, enabling the remote will completely disable all USB protocol functionality. "USB" remote is not a >USB protocol connection, it's just detecting whether there is power on the USB port. To make this useful, it >hides the signal from the canon formware (which in turn hides it from CHDK PTP).

does this mean, i must activate remote on in chdk menu, to get ptpcam correct working ?
All test i do i have done with default chdk setting(no remote on)

when i enable "remote on" then when i plug in the USB cable, camera switch to record mode and do a shoot half.It do not crash.

But then USB do not work.I guess this is ok, because code in keyboard clear always USB flag when remote is on.

see here the original code

   if (conf.remote_enable) {
        physw_status[2] = physw_status[2] & ~(SD_READONLY_FLAG | USB_MASK);   // override USB and SD-Card Readonly Bits
    }


the romlog of the crash when remote on is disable and switch from ptpcam in play mode to record mode is this

Edit: i shorten romlog.


ASSERT!! KerQueue.c Line 86
Occured Time  2011:01:30 10:01:55
Task ID: 16711713
Task name: CtrlSrv
..
Title: Re: CHDK PTP interface
Post by: fudgey on 30 / January / 2011, 04:30:09
does this mean, i must activate remote on in chdk menu, to get ptpcam correct working ?

No, just the opposite.
Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 30 / January / 2011, 14:22:55
Since i've discovered UART for SD4000 i've start documenting and playing with Event Procedure (http://chdk.wikia.com/wiki/Event_Procedure)...

On SD4000 this works for switching Playback / Record mode:

1. register required functions with UI.Create

2. switch mode:
UIFS_Capture  - Switch to Record Mode or start Capture if we are already in Record Mode
ModeDialToMovie  - Switch to Movie Record Mode
UIFS_SetDialPlay  - Switch to Playback Mode

3. switch to different Still Image Capture modes:
ModeDialToAuto
ModeDialToPortrait
ModeDialToKidsAndPets
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / January / 2011, 14:43:41
@reyalp
does this mean, i must activate remote on in chdk menu, to get ptpcam correct working ?
No, it means completely the opposite. How can I make this more clear ? CHDK "USB REMOTE" PREVENTS THE CAMERA FROM SEEING A USB CONNECTION AT ALL. If you look at the code, this should be quite obvious. If you test it, this should be obvious. If you read the wiki pages on how to build and use the remote, it should be obvious.

...

Also, you really don't need to post a romlog for every crash in your broken port. It's up to *you* to fix it.


edit:
This post was unnecessarily flamey. Sorry. I know you've spent a lot of time and effort on CHDK. It would be nice if you'd use an attachment for the ROMLOGs.
Title: Re: CHDK PTP interface
Post by: waterwingz on 30 / January / 2011, 15:27:31
Also, you really don't need to post a romlog for every crash in your broken port. It's up to *you* to fix it.

It would be a little easier to read these forums if romlogs were either submitted as attachments or inserted in a code scroll box.

Title: Re: CHDK PTP interface
Post by: reyalp on 30 / January / 2011, 18:16:24
Since i've discovered UART for SD4000 i've start documenting and playing with Event Procedure (http://chdk.wikia.com/wiki/Event_Procedure)...

On SD4000 this works for switching Playback / Record mode:

1. register required functions with UI.Create

2. switch mode:
UIFS_Capture  - Switch to Record Mode or start Capture if we are already in Record Mode
ModeDialToMovie  - Switch to Movie Record Mode
UIFS_SetDialPlay  - Switch to Playback Mode

3. switch to different Still Image Capture modes:
ModeDialToAuto
ModeDialToPortrait
ModeDialToKidsAndPets
This works with PTP connected ? Very interesting. If it works on other cameras, this might be a good alternative to the PB2Rec/REC2PB/set_control_event stuff.
Title: Re: CHDK PTP interface
Post by: waterwingz on 30 / January / 2011, 19:09:56
Use switch_mode_usb. If it doesn't work, implement it correctly for your camera.

@reyalp : Looks like the three stubs called by switch_mode_usb() are okay (PB2Rec, Rec2PB, set_control_event).  What's the best reference port to check them against ?

Also, are the values used in set_control_event the same for every camera ? 
Title: Re: CHDK PTP interface
Post by: Bernd R on 31 / January / 2011, 05:21:56
@reyalp
>If you test it, this should be obvious. If you read the wiki pages on how to build and use the remote, it >should be obvious.

sorry for the question, fudgey have answered ok, so you need not again.
The reason i ask, was because ptpcam is new implement, and as can see in chdk wiki pdpcam entry, its outdate.
So i ask, maybe i have miss something, and remote on have now other features too.

the thing pixeldoc2000 find i think sounds good to test.and when he can tell me how i should test on IX1000 Port, i do that.
Title: Re: CHDK PTP interface
Post by: waterwingz on 06 / February / 2011, 13:07:17
On SD4000 this works for switching Playback / Record mode:

@pixeldoc2000 :  Any chance you can share a code snippet using this to implement switch_mode_usb() ?

TIA

Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 11 / February / 2011, 12:04:45
@pixeldoc2000 :  Any chance you can share a code snippet using this to implement switch_mode_usb() ?
I only did some quick test using UART console on SD4000. Probably the easiest way would hack a little Canon Basic script. If script does work on other cameras we can implement an alternate switch_mode_usb() for particular cameras.

I'll try to create a Canon Basic test script.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / February / 2011, 00:23:18
@pixeldoc2000 :  Any chance you can share a code snippet using this to implement switch_mode_usb() ?
I only did some quick test using UART console on SD4000. Probably the easiest way would hack a little Canon Basic script. If script does work on other cameras we can implement an alternate switch_mode_usb() for particular cameras.

I'll try to create a Canon Basic test script.
You should be able to do this using eventprocs from lua ? You can even replace the existing switch_mode_usb function if you want...
Title: Re: CHDK PTP interface
Post by: achillies on 12 / February / 2011, 18:19:33
I hope I don't get on anyones nerves asking for the wine before it's time, but I'm using an SX130IS, with a new and not yet beta CHDK built by Quid.  I have loaded CHDK-Shell, and when I tried to run ptpcamgui, I got a "line 934 _GUICtrlEdit_BeginUpdate function not found" error.  I remarked that line and the rest of the lines in the debugWrite function and could get ptpcamgui to start, but not connect to the camera.  Once I connect the USB cable the camera will not switch out of playback mode.  Any ideas?  (and "just wait" is not necessarily a bad idea)
Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 13 / February / 2011, 00:32:40
@waterwingz
After a long night of tinkering around with switch_mode_usb() i figured out my set_control_event() address was wrong. Signature Finder (stubs_entry.S) address is correct.
Since reverting to sigfinder address "ptpcam --chdk" --> mode command does work.

Check your set_control_event() address. Compare your firmware to SD990 or SD4000 to verify your set_control_event() address.

SD4000:
Code: [Select]
ROM:FF895504 set_control_event             ; CODE XREF: sub_FF89570C
ROM:FF895504                                         ; sub_FF89576C:loc_FF8957C0
ROM:FF895504                 AND     R1, R0, #0xFF00 ; Sigfinder OK
ROM:FF895508                 AND     R12, R0, #0x40000000
ROM:FF89550C                 CMN     R0, #1
ROM:FF895510                 MOV     R12, R12,LSR#30
ROM:FF895514                 MOV     R1, R1,LSR#8
ROM:FF895518                 AND     R2, R0, #0xFF
ROM:FF89551C                 MOV     R3, R0,LSR#31
ROM:FF895520                 BXEQ    LR
ROM:FF895524                 CMP     R12, #0
ROM:FF895528                 LDR     R0, =0x3D460
ROM:FF89552C                 BNE     loc_FF89554C
ROM:FF895530                 MOV     R12, #1
ROM:FF895534                 CMP     R3, #0
ROM:FF895538                 LDR     R3, [R0,R1,LSL#2]
ROM:FF89553C                 MOV     R2, R12,LSL R2
ROM:FF895540                 MVNEQ   R2, R2
ROM:FF895544                 ANDEQ   R2, R3, R2
ROM:FF895548                 ORRNE   R2, R3, R2
ROM:FF89554C
ROM:FF89554C loc_FF89554C                            ; CODE XREF: set_control_event_sigfinder
ROM:FF89554C                 STR     R2, [R0,R1,LSL#2]
ROM:FF895550                 BX      LR
ROM:FF895550 ; End of function set_control_event
Title: Re: CHDK PTP interface
Post by: msl on 13 / February / 2011, 03:45:20
I got a "line 934 _GUICtrlEdit_BeginUpdate function not found" error... 
Use a current version of the CHDK Shell (3.04).

PTP support need some entry points, set_control_event, PB2Rec and Rec2PB (see also trunk rev. 1018). I don't know if they are available for the SX130.

msl
Title: Re: CHDK PTP interface
Post by: fudgey on 13 / February / 2011, 03:58:16
I enabled PTP for a570 in CHDK trunk 1055. I tested it with ptpcam from chdkde trunk 572 tools/ptpcam.

Btw, is there currently a way to do what my old luaw command did, i.e. run a script with more than one command and get its result? I know there's been discussion and tests but is any of it in trunk and supported by ptpcam yet? I suppose not?

I do understand the use of your version, but I'd probably either use (my) luar (function () body end)() (not tested) or make another command for
I tested this a bit outside the camera (Ubuntu's Lua) but couldn't cook up a syntax Lua would accept (for defining and running a function inside the return command).
Title: Re: CHDK PTP interface
Post by: rudi on 13 / February / 2011, 05:39:32
Hi achillies,

I got a "line 934 _GUICtrlEdit_BeginUpdate function not found" error
Try this:
- close CHDK-Shell
- open "...\CHDK-Shell\guest\ptpCamGui\work\guirevision.txt"
- edit revisionsnumber to a lower value and save it
- start CHDK-Shell again

rudi
Title: Re: CHDK PTP interface
Post by: waterwingz on 13 / February / 2011, 10:13:37
@waterwingz
After a long night of tinkering around with switch_mode_usb() i figured out my set_control_event() address was wrong. Signature Finder (stubs_entry.S) address is correct.
Since reverting to sigfinder address "ptpcam --chdk" --> mode command does work.

Wow - the SD940 works now.  Was able to use ptpCamGui.exe to switch into shooting mode and take a picture !  I guess we get complacent expecting all stubs to be bracketed by the STMFD /  LDMFD calling convention.

However, using ptpcam.exe --chhd with the mode 1 command puts the camera into shooting mode but the mode 0 command does not put it back into playback mode.  Is this normal ?
Title: Re: CHDK PTP interface
Post by: fudgey on 13 / February / 2011, 10:42:21
However, using ptpcam.exe --chhd with the mode 1 command puts the camera into shooting mode but the mode 0 command does not put it back into playback mode.  Is this normal ?
I don't know, really, but this is how I switch between play and rec with ptp:

ptpcam --chdk="lua set_record(true)"
ptpcam --chdk="lua set_record(false)"
Title: Re: CHDK PTP interface
Post by: waterwingz on 13 / February / 2011, 11:50:04
ptpcam --chdk="lua set_record(true)"
ptpcam --chdk="lua set_record(false)"

Two steps forward - one step back.  Those doesn't do anything although this puts the camera into shoot mode :

ptpcam --chdk="mode 1"

Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 13 / February / 2011, 14:50:50
@waterwings

Did you check PB2Rec and Rec2PB address too?

SD4000:

Code: [Select]
ROM:FF898B40 AC_PB2Rec                               ; CODE XREF: AC_PB2PC:loc_FF897B44
ROM:FF898B40                                         ; AC_EnryPB+D0 ...
ROM:FF898B40                 STMFD   SP!, {R4,LR}    ; PB2Rec
ROM:FF898B44                 LDR     R0, =0x10A5
ROM:FF898B48                 BL      eventproc_export_IsControlEventActive
ROM:FF898B4C                 CMP     R0, #0
ROM:FF898B50                 LDMNEFD SP!, {R4,PC}
ROM:FF898B54                 MOV     R0, #0x60
ROM:FF898B58                 ADR     R1, aAcPb2rec   ; "AC:PB2Rec"
ROM:FF898B5C                 BL      LogPrintf       ; LOCATION: CameraLog.c:237
ROM:FF898B60                 MOV     R0, #0xD
ROM:FF898B64                 BL      _sub_FF896F60__CameraConState.c__215 ; LOCATION: CameraConState.c:215
ROM:FF898B68                 BL      DispSwCon_MuteOnPhysicalScreen
ROM:FF898B6C                 MOV     R0, #1
ROM:FF898B70                 BL      AC_ExitPB
ROM:FF898B74                 LDMFD   SP!, {R4,LR}
ROM:FF898B78                 MOV     R0, #0
ROM:FF898B7C                 B       sub_FF83C1D8
ROM:FF898B7C ; End of function AC_PB2Rec

Code: [Select]
ROM:FF897590 AC_Rec2PB                               ; CODE XREF: EnrySRec:loc_FF8978EC
ROM:FF897590                 STMFD   SP!, {R4,LR}    ; Rec2PB
ROM:FF897594                 ADR     R1, aAcRec2pb   ; "AC:Rec2PB"
ROM:FF897598                 MOV     R0, #0x60
ROM:FF89759C                 BL      LogPrintf       ; LOCATION: CameraLog.c:237
ROM:FF8975A0                 LDR     R1, =0x3580
ROM:FF8975A4                 MOV     R0, #0
ROM:FF8975A8                 STR     R0, [R1,#0x80]
ROM:FF8975AC                 BL      sub_FF89BBFC
ROM:FF8975B0                 MOV     R0, #1
ROM:FF8975B4                 BL      sub_FF83C1D8
ROM:FF8975B8                 BL      sub_FF97A664
ROM:FF8975BC                 CMP     R0, #0
ROM:FF8975C0                 BEQ     loc_FF8975D0
ROM:FF8975C4                 BL      sub_FF89073C
ROM:FF8975C8                 CMP     R0, #0
ROM:FF8975CC                 BLNE    DispSwCon_MuteOnPhysicalScreen
ROM:FF8975D0
ROM:FF8975D0 loc_FF8975D0                            ; CODE XREF: AC_Rec2PB+30
ROM:FF8975D0                 BL      ShutdownRecMode
ROM:FF8975D4                 LDMFD   SP!, {R4,LR}
ROM:FF8975D8                 MOV     R0, #0x10
ROM:FF8975DC                 B       _sub_FF896F60__CameraConState.c__215 ; LOCATION: CameraConState.c:215
ROM:FF8975DC ; End of function AC_Rec2PB

Else maybe overwrite switch_mode_usb() with different control event id may help?
Title: Re: CHDK PTP interface
Post by: pixeldoc2000 on 13 / February / 2011, 14:53:37
I don't know, really, but this is how I switch between play and rec with ptp:

ptpcam --chdk="lua set_record(true)"
ptpcam --chdk="lua set_record(false)"
So does mode command work for you too or only lua command?
Title: Re: CHDK PTP interface
Post by: waterwingz on 13 / February / 2011, 15:18:27
@waterwingz
Did you check PB2Rec and Rec2PB address too?

Yup - 100% match between what you posted and my source dissassembly (except for addresses of course).

Else maybe overwrite switch_mode_usb() with different control event id may help?

Wow - where do I even start with that?
Title: Re: CHDK PTP interface
Post by: waterwingz on 13 / February / 2011, 15:36:54
A little more testing. 

ptpcam --chdk="mode 1"   - extends the lens and enters shooting mode
ptpcam --chdk="mode 0"   - leaves the lens extended and enters playback mode

I guess that is working correctly after all if one doesn't expect the lens to retract in playback mode.

Still no luck with lua set_record(true) though.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / February / 2011, 15:54:59
Still no luck with lua set_record(true) though.
This is expected on dryos cameras. That's why switch_mode_usb exists.

It would really be better to just have one function that does the appropriate thing if USB is connected, but for historical reasons, this isn't the case.
Title: Re: CHDK PTP interface
Post by: fudgey on 13 / February / 2011, 16:48:16
So does mode command work for you too or only lua command?

All 3 ways work for me:
ptpcam --chdk="mode 1"
ptpcam --chdk="mode 0"
ptpcam --chdk="lua switch_mode_usb(1)"
ptpcam --chdk="lua switch_mode_usb(0)"
ptpcam --chdk="lua set_record(true)"
ptpcam --chdk="lua set_record(false)"

waterwingz: the camera shouldn't be expected to retract the lens because it doesn't do that when you switch to play during normal use either...until a configurable delay.
Title: Re: CHDK PTP interface
Post by: whim on 13 / February / 2011, 16:58:51
Quote
waterwingz: the camera shouldn't be expected to retract the lens because it doesn't do that when you switch to play during normal use either...until a configurable delay.

This delay can be set to 0 seconds though (at least on my cams)

cheers,

wim
Title: Re: CHDK PTP interface
Post by: achillies on 14 / February / 2011, 18:05:55
Thank you msl and rudi, I can successfully load the ptpcamgui interface.  I will do more homework before asking too many more questions!
Title: Re: CHDK PTP interface
Post by: mirriro on 18 / February / 2011, 16:15:34
Hi all, sorry for the interruption. I am very new to PTP extension and I am trying to get my computer to control the camera A710IS. Right now I have the lastest build from CHDKDE and loaded onto my SD card, but when I try to issue the command "ptpcam.exe --chdk" in windows console, it says "Could not find any device matching given bus/dev numbers, retrying in 1 s...". It seems that somehow the connection is not setup between my computer and the camera. Can someone tell me which part I did it wrong?
Thanks
JL

I just posted a new thread about the questions I have, so please ignore above. Thanks
JL
Title: Re: CHDK PTP interface
Post by: Bernd R on 21 / February / 2011, 12:02:17
I test newest ptpcamgui with image download button, Ixus 1000 seem crash when write ptpgui.txt. File is then 0 byte in size.
This happen only when exmem is enable.
I do a test to limit buffer, in ptp.c

buf_size= 4096; //core_get_free_memory()>>1;

but this does not help.
have somebody test with exmem enable.does it work or not ?

when exmem is not enable, then i get transfer rate in raw around 2  megabyte.
The card can read 12 megabyte.

Is there no way that transfer can be faster ?
what other camera get for transfer rate.

EDIT:

Problem solved, i have in wrappers.c static char de[50];
because i want try smaller.

this was too small.i use 100 again and it work stable

void* readdir(void *d) {
# if !CAM_DRYOS
    return _readdir(d);
#else
// for DRYOS cameras  A650, A720  do something with this!  - sizeof(de[]) must be >= sizeof(struct dirent): 'static char de[40];'
  static char de[100];
  _ReadFastDir(d, &de);
  return de[0]? &de : (void*)0;
#endif
}
Title: Re: CHDK PTP interface
Post by: Bernd R on 26 / February / 2011, 05:01:08
I do now some more test with the non working switch to record mode on my Ixus 1000 HS.

I add in wrapper.c when should switch to record mode a keyb_stopusb = 1 in a global variable that is access from keyboard task too.
This tell the keyboard task  my_kbd_read_keys() function that it should do action.

This code work, without crash and switch to record mode, but when the time is over to clear the USB bit, then the Camera move in Lens and go to playback mode.

  if ((keyb_stopusb >= 1) && (keyb_stopusb <= 399)){physw_status[2] = physw_status[2] & ~(SD_READONLY_FLAG | USB_MASK);

when i remove this line

  if ((keyb_stopusb >= 1) && (keyb_stopusb <= 399)){physw_status[2] = physw_status[2] & ~(SD_READONLY_FLAG | USB_MASK);

complete, then crash happen, same as original Code.

if(keyb_stopusb == 50).....

is need because the USB bit need clear earlier or mode switch do nothing.

Code: [Select]

void my_kbd_read_keys() {

......

if(keyb_stopusb == 400){keyb_stopusb = 0;}
    if (keyb_stopusb == 1){
        sprintf(osd_buf, "want switch");
        draw_txt_string(28, 14,osd_buf, conf.osd_color);
        physw_status[2] = physw_status[2] & ~(SD_READONLY_FLAG | USB_MASK);
    }
    if (keyb_stopusb == 50){ _set_control_event(0x902);_PB2Rec();
     sprintf(osd_buf, "call _PB2Rec");
        draw_txt_string(28, 14,osd_buf, conf.osd_color);}
    if ((keyb_stopusb >= 1) && (keyb_stopusb <= 399)){physw_status[2] = physw_status[2] & ~(SD_READONLY_FLAG | USB_MASK);

    }
    if(keyb_stopusb)keyb_stopusb++;

really strange wy this Camera crash in fsionotify, look as a task race condition.same errors IX1000 get on boot without msleep fix , or when call mkdir on second RAW shoot.

 
i get only in mind maybe something with this code is wrong, but how is it possible to see if the values are correct ?

 *(int*)0x1938=(int)taskHook;   //was 1934 in sx200 if 1938 hangs
   *(int*)0x193C=(int)taskHook;

Can somebody please explain more what this should do, and how i can verify if ox1938 0x193c is really the correct value ?
Title: Re: CHDK PTP interface
Post by: achillies on 03 / March / 2011, 22:27:54
I am trying to modify PTPCamGUI (simply changing ptpcamgui.au3) to allow for deleting of files after transfer.  I have added a checkbox which when checked deletes the files you are transferring to your computer.  I have tested it with all of the download options (all, new, number of pics), and because it works from the same file list as downloading, shouldn't interfere with anything.. BUT it does reboot the camera to accurately reflect the current number of pictures.  If checked you will also get the "Download and Delete these files now" confirmation/cancel dialog.  

Also, I was having trouble with the timelapse "STOP" button not really stopping anything but ptpcamgui.  I changed some lines and fixed that too. (at least for myself!)  I'm using an SX130IS, and everything works like a charm!

As of build #82, the line numbers in this text file were accurate to make changes in the ptpcamgui.au3 and ptpcamgui_obfuscated.au3 files, but the notation is written so that I understand it.  If you try to use this file, I hope you can figure it out.  
 EDIT Attachment removed to avoid confusion
Title: Re: CHDK PTP interface
Post by: rudi on 04 / March / 2011, 14:55:55
Hi

I noticed what I think is a typing error around line 1260
'  if fd~=nli and #fd>0 then' & @LF & _
I think should be '  if fd~=nil and #fd>0 then' & @LF & _
Yes, that's true. I've change in ptpcamGUI rev.#80. Thanks achillies!

Usually, I write the routine for new feature at first and chage then the GUI. Sorry, but delete files on cam is not the topmost feature for implement in moment.

an other theme: "table results with ptpcam.exe"
I provide a solution for return results from simple lua-tables with ptpcam. The most tables have one or two dimensions. My code convert tables to a formatted string for retrieve.

Code: [Select]
format: key 1st dimension \t value or values 2nd dimension sparated by \t and \n

values for 1st dimension: BOOL, INT, STRING (NIL is not enumerated)
values for 2nd dimension: NIL, BOOL, INT, STRING

same examples:
Code: [Select]
<conn> luar get_buildinfo()
platformid      12662
platform        a590
version CHDK
platsub 101b
build_number    0.9.9-1077
os      dryos
build_date      Mar  4 2011
build_time      19:08:04

<conn> luar {1,2,3,4}
1       1
2       2
3       3
4       4

<conn> luar {X=44,G=2}
G       2
X       44

<conn> luar {"Monday","Tuesday","Wednesday","Thursday","Friday"}
1       Monday
2       Tuesday
3       Wednesday
4       Thursday
5       Friday

<conn> luar {{3,8,55},G=2}
1       3       8       55
G       2

<conn> luar {{3,8,55}, D={"S","M","D"},G=2,"value",678}
1       3       8       55
2       value
3       678
G       2
D       S       M       D

<conn> luar {U={3,8,55}, D={"S","M","D"},G=2}
U       3       8       55
D       S       M       D
G       2

<conn> luar {}

<conn> luar {{},{}}

<conn> luar {A={},{}}

<conn> luar {A={},B={}}

<conn> luar {A={1},B={33}}
A       1
B       33

<conn> luar {A={1,2},B={33}}
A       1       2
B       33

<conn> luar {A={1,2},B={33,{},44}}
A       1       2
B       33              44

<conn> luar {A={1,2,"true",false},B={33,{},44}}
A       1       2       true    false
B       33              44

<conn> luar {A={1,2,true,"false"},B={33,{},44}}
A       1       2       true    false
B       33              44

<conn> luar {3,4,nil,5,6,true,7}
1       3
2       4
4       5
5       6
6       true
7       7

<conn> luar {{3,4,nil,5,6,true,7}}
1       3       4       nil     5       6       true    7

<conn> luar require("capmode")
mode_to_name    AUTO    P       TV      AV      M       PORTRAIT        NIGHT_SC
ENE     LANDSCAPE       VIDEO_STD       VIDEO_SPEED     VIDEO_COMPACT   VIDEO_MY
_COLORS VIDEO_COLOR_ACCENT      VIDEO_COLOR_SWAP        STITCH  MY_COLORS
SCN_UNDERWATER  SCN_NIGHT_SNAPSHOT      LONG_SHUTTER    SCN_LANDSCAPE   COLOR_SW
AP      SCN_SNOW        SCN_BEACH       SCN_FIREWORK    SCN_COLOR_ACCENT
SCN_COLOR_SWAP  VIDEO_HIRES     SCN_AQUARIUM    COLOR_ACCENT    SCN_NIGHT_SCENE
SCN_ISO_3200    SCN_SPORT       SCN_KIDS_PETS   INDOOR  KIDS_PETS       NIGHT_SN
APSHOT  DIGITAL_MACRO   SCN_FOLIAGE     VIDEO_TIME_LAPSE        SCN_INDOOR
SCN_PORTRAIT    SUPER_MACRO     VIDEO_PORTRAIT  VIDEO_NIGHT     VIDEO_INDOOR
VIDEO_FOLIAGE   VIDEO_SNOW      VIDEO_BEACH     VIDEO_AQUARIUM  VIDEO_SUPER_MACR
O       VIDEO_STITCH    VIDEO_MANUAL    SPORTS  QUICK   SCN_SUNSET      SCN_CREA
TIVE_EFFECT     EASY    SCN_DIGITAL_MACRO       SCN_STITCH      SCN_LONG_SHUTTER
        LOWLIGHT        SCN_NOSTALGIC   SCN_SMART_SHUTTER       SCN_LOWLIGHT
SCN_SUPER_VIVID SCN_POSTER_EFFECT       SCN_FISHEYE     SCN_MINIATURE   SCN_HDR

I think we can this also use in future get_lua_result implementations. If we can use tables with ptpcam, then we can update ptpcamGUI with more effective code.

rudi
Title: Re: CHDK PTP interface
Post by: fudgey on 05 / March / 2011, 09:48:10
This thing: http://www.akond.net/index.php?issue_id=292 (http://www.akond.net/index.php?issue_id=292) came up in another thread... (http://chdk.setepontos.com/index.php?topic=6180.0 (http://chdk.setepontos.com/index.php?topic=6180.0)).

From some clues (A480 needs to be a specific fw version, SD card needs to be dealt with some wizard) I'm temped to guess that they didn't get any help from Canon, but are instead selling modified or rewritten CHDK and CHDK PTP.

"inPhoto ID PS works only with Canon A480, Canon A495, Canon SX200 IS and Canon SX210 IS cameras. Next camera will be Canon SX130 IS."

http://www.akond.net/?issue_id=262 (http://www.akond.net/?issue_id=262)
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / March / 2011, 22:48:03
an other theme: "table results with ptpcam.exe"
I provide a solution for return results from simple lua-tables with ptpcam. The most tables have one or two dimensions. My code convert tables to a formatted string for retrieve.
Good. This is important.

Some thoughts:
C code seems complex, could be better to do this in lua. We can have lua code in a C string if we want hardcoded in CHDK.

Would be good to have a standard library of lua functions to use with PTP somehow. Not sure the best way to do this, loading from SD card every time would be slow, sending over PTP every time not so nice either.

Format is OK to display values, but it's ambiguous in some cases and quite limited. Doesn't support non-numeric keys in second level table, e.g. {t={a='a',b='b'}}, showing nil in one and not the other is a bit odd.

OK for now, but I think we'll want to revisit, real work crunch is over for a while.

My plan was to format table returns as a string of lua code, using lua (but only simple types as you have, and no cyclic references etc.) When the PC side has lua this is very convenient. It's also quite readable on it's own, but maybe not easy to parse in autoit.

I'll have a little more time to work on CHDK now.

lua version of table format code. Could be simpler, but I was trying to match output of rudi's code as closely as possible. There are probably some minor differences still
Code: [Select]
function t_to_s(t)
local v2s=function(v)
local t=type(v)
if t=='string' then
return v
end
if t=='number' or t=='boolean' or t=='nil' then
return tostring(v)
end
return ""
end
local r=""
for k,v in pairs(t) do
local s,vs=""
if type(v)=='table' then
for i=1,table.maxn(v) do
s=s..'\t'..v2s(v[i])
end
else
vs=v2s(v)
if #vs then
s=s..'\t'..vs
end
end
vs=v2s(k)
if #vs>0 and #s>0 then
r=r..vs..s..'\n'
end
end
return r
end
test (! is pc side lua in my client)
Code: [Select]
___> !print(t_to_s({1,2,3,4}))
1       1
2       2
3       3
4       4

___> !print(t_to_s({X=44,G=2}))
G       2
X       44

___> !print(t_to_s({"Monday","Tuesday","Wednesday","Thursday","Friday"}))
1       Monday
2       Tuesday
3       Wednesday
4       Thursday
5       Friday

___> !print(t_to_s({{3,8,55},G=2}))
1       3       8       55
G       2

___> !print(t_to_s({{3,8,55}, D={"S","M","D"},G=2,"value",678}))
1       3       8       55
2       value
3       678
G       2
D       S       M       D

___> !print(t_to_s({U={3,8,55}, D={"S","M","D"},G=2}))
U       3       8       55
D       S       M       D
G       2

___> !print(t_to_s({}))

___> !print(t_to_s({{},{}}))

___> !print(t_to_s({A={},{}}))

___> !print(t_to_s({A={},B={}}))

___> !print(t_to_s({A={1},B={33}}))
A       1
B       33

___> !print(t_to_s({A={1,2},B={33}}))
A       1       2
B       33

___> !print(t_to_s({A={1,2},B={33,{},44}}))
A       1       2
B       33              44

___> !print(t_to_s({A={1,2,"true",false},B={33,{},44}}))
A       1       2       true    false
B       33              44

___> !print(t_to_s({A={1,2,true,"false"},B={33,{},44}}))
A       1       2       true    false
B       33              44

___> !print(t_to_s({3,4,nil,5,6,true,7}))
1       3
2       4
4       5
5       6
6       true
7       7

___> !print(t_to_s({{3,4,nil,5,6,true,7}}))
1       3       4       nil     5       6       true    7
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / March / 2011, 01:01:42
Patch implementing the above. One possible danger, we probably don't want to trigger the call hook sleep from ptp task.

This danger will go away when I get the alternative luar code done. More on that soon.
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / March / 2011, 00:48:14
I've created a temporary branch for PTP improvements, because it's a bit complicated to keep track of without version control.
http://tools.assembla.com/chdk/browser/branches/reyalp-ptp (http://tools.assembla.com/chdk/browser/branches/reyalp-ptp)

I intend this branch to a short lived. If no one says this is a horrible idea, it will go into the trunk after a few things are cleaned up. I want to give everyone (especially chdkde / ptpcamgui developers) a chance to comment first.

This basically merges my earlier ptp script message and result code.

Highlights:
- all lua script return values are returned as messages (the way luar adds return(...) doesn't support multiple return so e.g. luar get_mode() will only return the first value, and luar 1,2 fails.)
- messages from script->pc now have lua types, like old result code. Tables are returned as string, in rudi's format using lua as described in previous post.
- lua compile and runtime error messages are returned as messages. Return values, script generated messages, and error message are all identified, so the pc software can ignore whatever it isn't interested in.
- protocol is changed, but ptpcam commands/output are almost 100% compatible.
- scripts now have a 'process id', returned when you start the script. This allows camera and pc side to discard messages that were from/to a previous script invocation.

Other stuff
- ptpcam doesn't take advantage of all the new features, new client will use them.
- error messages can be lost if queue is full.
- would probably be better to flush all messages when a new script starts.

attached patch against chdkde ptpcam source implements pc side.
attached ptpmsg script demonstrates sending/recieving messages within script.

some examples
Code: [Select]
<conn> lua return get_mode()
<conn> getm
false
false
513 (201)
<conn> lua foo()
<conn> getm
runtime error: :1: attempt to call global 'foo' (a nil value)
<conn> lua 'blah
syntax error: :1: unfinished string near '<eof>'
execution failed!
<conn> luar get_mode
unsupported data type: function

Title: Re: CHDK PTP interface
Post by: rudi on 09 / March / 2011, 13:20:23
Hi reyalp,
very good work and implementation!
Now I had some time for tests only with modified ptpcam.exe and reyalp-brunch/modified CHDK-DE (identical results) - my result: great! more informations about states and errors, more result values. On this time 'ptpmsg.lua' untested.

some comments:
TEST 'function usb_msg_table_to_string(arg)':
The function fails is arg not a table.
Code: [Select]
<conn> lua return usb_msg_table_to_string(os.stat('A/ptpmsg.lua'))
<conn> getm
dev     2
attrib  32
ctime   1299672574
atime   1299628800
blksize 512
blocks  6
mtime   1299585998
is_file true
mode    33279
is_dir  false
size    2683

<conn> lua return usb_msg_table_to_string(os.stat('A/ptpmsgB.lua'))
<conn> getm
runtime error: :1: bad argument #1 to 'pairs' (table expected, got nil)
a small change for all types -> attachment
Code: [Select]
<conn> lua return usb_msg_table_to_string(os.stat('A/ptpmsgB.lua'))
<conn> getm
nil
A/ptpmsgB.lua: error
0 (0)

TEST script id and results:
Very good idea, but how much results are from current id and how much from script-id 24?
For example we can use a text 'message' to separate old id from current id?
Code: [Select]
<conn> lua return '1'
<conn> lua return '1\n2'
<conn> lua return '1\n2\n3'
<conn> lua return '1\n2\n3\n4'
<conn> getm
message from unexpected script id 22
1
message from unexpected script id 23
1
2
message from unexpected script id 24
1
2
3
1
2
3
4

TEST 'lua return'-commands after CHDK-start/reboot
It looks like the luar-problem from CHDK-rev.1032 to 1033. My fast solution at that time 'return(...)' in ptpcam.exe. But I know that is not the real cause. Is it back again? Lua initialisation fails?
Code: [Select]
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua return usb_msg_table_to_string(get_buildinfo())
<conn> getm
runtime error: :1: attempt to call global 'usb_msg_table_to_string' (a nil value
)
<conn> lua return usb_msg_table_to_string(get_buildinfo())
<conn> getm
platformid      12662
platform        a590
version CHDK
platsub 101b
build_number    0.9.9-1083
os      dryos
build_date      Mar  9 2011
build_time      12:56:47

<conn> shutdown
<    > r
<conn> lua return usb_msg_table_to_string(get_buildinfo())
<conn> getm
runtime error: :1: attempt to call global 'usb_msg_table_to_string' (a nil value
)
<conn> lua return usb_msg_table_to_string(get_buildinfo())
<conn> getm
platformid      12662
platform        a590
version CHDK
platsub 101b
build_number    0.9.9-1083
os      dryos
build_date      Mar  9 2011
build_time      12:56:47
a solution with a dummy-command (type 'lua'+space)
Code: [Select]
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua return 1
syntax error: :1: malformed number near '1 '
execution failed!
<conn> getm
<conn> lua return 1
syntax error: :1: malformed number near '1 '
execution failed!
<conn> getm
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua return (1)
<conn> getm
1 (1)
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua
<conn> lua return 1
<conn> getm
1 (1)

To witch time is ptp-handler destroyed. I'm looking for a solution to switch the powersavemode for ptp-duration to 'always'.

rudi
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / March / 2011, 22:47:20
some comments:
TEST 'function usb_msg_table_to_string(arg)':
The function fails is arg not a table.
In my code, this function is called automatically, and only if the argument is a table. See luascript.c lua_create_usb_msg

Users shouldn't need to call it.

Quote
TEST script id and results:
Very good idea, but how much results are from current id and how much from script-id 24?
For example we can use a text 'message' to separate old id from current id?
Code: [Select]
<conn> lua return '1'
<conn> lua return '1\n2'
<conn> lua return '1\n2\n3'
<conn> lua return '1\n2\n3\n4'
<conn> getm
message from unexpected script id 22
1
...
This is one of the features that's mostly intended for the new client, I only put enough in ptpcam to test.

I tried to not change the output to much so I wouldn't break ptpcamgui. If you want to change the output, that's fine with me.

It would be easy to make this more friendly to parse, I suggest:
- output script id when script starts
- output script id and and message type for each message
example (fake ;))
Code: [Select]
<conn> lua return '1'
script:22
<conn> lua return '1\n2'
script:23
<conn> lua write_usb_msg('hi')
script:24
<conn> lua return 2
script:25
<conn> getm

22 return string:"1"
23 return string:"1
2"
24 message string:"hi"
25 return number:1
Of course you should format it whatever way is easiest for you.
Quote
TEST 'lua return'-commands after CHDK-start/reboot
It looks like the luar-problem from CHDK-rev.1032 to 1033. My fast solution at that time 'return(...)' in ptpcam.exe. But I know that is not the real cause. Is it back again? Lua initialisation fails?
Code: [Select]
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua return usb_msg_table_to_string(get_buildinfo())
<conn> getm
runtime error: :1: attempt to call global 'usb_msg_table_to_string' (a nil value)
Strange, I don't see this on d10 in my build.
Quote
To witch time is ptp-handler destroyed. I'm looking for a solution to switch the powersavemode for ptp-duration to 'always'.
If you mean stop the camera from going to sleep when PTP is connected, I want this too :)
Title: Re: CHDK PTP interface
Post by: achillies on 10 / March / 2011, 02:34:26
I know you guys are working on MUCH larger things, so I will try to keep this short.

I don't know how other cameras function, but on the SX130is, if I use os.remove to delete the picture/file that is displayed on the Camera LCD screen, the display does not change even though the file was deleted.

How can I refresh the LCD so that it doesn't still show the deleted picture (which no longer exists)?  Rebooting works, but it seems like there is a better way.
Title: Re: CHDK PTP interface
Post by: msl on 10 / March / 2011, 05:54:26
@achillies

Reboot is the only way to refresh the display. The Canon OS does not notice, if you have deleted a picture file with CHDK. But you can program a keyboard sequence to delete a picture.

msl
Title: Re: CHDK PTP interface
Post by: rudi on 10 / March / 2011, 07:04:30
In my code, this function is called automatically, and only if the argument is a table. See luascript.c lua_create_usb_msg

Users shouldn't need to call it.
Yes, I see. That's my fault. On first time use I get this error message. On this time I don't know, that the reason is on a other part and not the table.
Code: [Select]
<conn> reboot
Could not find any device matching given bus/dev numbers, retrying in 1 s...
<conn> lua return get_buildinfo()
<conn> getm
attempt to call a nil value
<conn> lua return get_buildinfo()
<conn> getm
platformid      12662
platform        a590
version CHDK
platsub 101b
build_number    0.9.9-1083
os      dryos
build_date      Mar  9 2011
build_time      12:56:47

I tried to not change the output to much so I wouldn't break ptpcamgui. If you want to change the output, that's fine with me.
The ptpcamGUI command routines need to rewrite for version 1.0 in any cases. It would be better to make all necessary changes for simply parse the messages.

Quote
TEST 'lua return'-commands after CHDK-start/reboot
Strange, I don't see this on d10 in my build.
We had here (http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220) a test for this problem, but not a final solution. I know, you written "an older gcc3 is a way", but all build-server use gcc4.

rudi
Title: Re: CHDK PTP interface
Post by: achillies on 10 / March / 2011, 09:31:29
@msl - Once again, Thank you.  It saves alot of time not trying to do things I can't do!

deleted.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / March / 2011, 22:24:52
We had here (http://forum.chdk-treff.de/viewtopic.php?f=3&t=2220) a test for this problem, but not a final solution. I know, you written "an older gcc3 is a way", but all build-server use gcc4.
Oh, I thought the cause of this problem was found and fully fixed. I think I understand a little better now, fix stopped syntax error from crashing, but syntax error happens when it shouldn't.

Older gcc is not a real solution either :(
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / March / 2011, 01:48:11
I added modified ptpcam in reyalp-ptp branch. Output easier to parse. Running a script prints script id, message/return/error always starts with script id.

String values are quoted with ''

Note that it would be easy to make lua strings that look like other return values.
Code: [Select]
<conn> lua return 1
script:1
<conn> lua return 'hi'
script:2
<conn> lua write_usb_msg('a message');  return true
script:3
<conn> lua return 'one',2,{a='a',b='b'},nil,false
script:4
<conn> getm
1:ret:1 (1)
2:ret:'hi'
3:msg:'a message'
3:ret:true
4:ret:'one'
4:ret:2 (2)
4:ret:'a        a
b       b
'
4:ret:nil
4:ret:false
<conn> lua 'a bad script
script:5
5:syntax error: :1: unfinished string near '<eof>'
execution failed!
<conn> lua bad()
script:6
<conn> getm
6:runtime error: :1: attempt to call global 'bad' (a nil value)
<conn>
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / March / 2011, 00:37:12
return strangeness:
gcc3
Code: [Select]
<conn> lua return 1
script:1
<conn> getm
1:ret:1 (1)
gcc4
Code: [Select]
<conn> lua return 1
script:1
1:syntax error: :1: malformed number near '1 '
execution failed!
<conn>
If I put a space after the 1, it works. (note error message above shows space, but there isn't one in my command!)

The malformed number error does come from some code that was hacked up to make lua work in chdk (lib/lua/llex.c trydecpoint)

but
Code: [Select]
<conn> lua n=1; return n
script:2
2:syntax error: :1: '<eof>' expected
execution failed!
<conn> lua n=1; return n
script:3
<conn>
Again, works with space after n, works on gcc3

on gcc 4, usb_msg_table_to_string doesn't seem to get defined.

 :-[

edit:
usb_msg_table_to_string problem is related, adding a \n at the end fixes. This is not needed in gcc3 build....
Title: Re: CHDK PTP interface
Post by: achillies on 14 / March / 2011, 01:28:28
Was anyone else having a problem with stopping the timelapse in ptpcamgui?  If I clicked on the stop button whle using ptpcamgui's timelapse, it caused the ptpcamgui interface to stop responding, and then I couldn't exit without killing it.

I changed some lines and now that doesn't happen.  And Again.. the stuff for deleting after download is in here too (because I use it all the time).  Based on build 82.  (obfuscated?  I dunno, but here they are *NEW CHANGES IN FOLLOWING POST*).  Two weeks ago I had never heard of AutoIt.. and you all probably wish I still hadn't!   ;)

Attachments removed to avoid confusion.
Title: Re: CHDK PTP interface
Post by: msl on 14 / March / 2011, 06:19:42
@achillies

Timelapse was fix in rev. 83, thank you for correction.

The delete function is a other thing. We have currently enough other options to delete files with CHDK. Later with an improved ptp interface it may be safe enough to delete image files.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 14 / March / 2011, 07:51:57
We have currently enough other options to delete files with CHDK.

Hmm.. I certainly won't argue with you.  I can understand why you are so hesitant to put in a potentially destructive feature (delete files=destructive).  For me, the other methods aren't "easy" enough, and so I keep sticking this code in for myself.  It's not a problem though.

I also understand that the things I am working on are not really important to the rest of the world, but to me they are and so I keep doing them!  It is good to learn, and I'm enjoying playing with CHDK, Lua code, UBasic, and AutoIt. 

Last night I made an external help file for the gui, and I'm trying to pull together a good enough PTPCamGUI help file that explains how to use each feature.  I'm also trying to get the timelapse section to have start delays, etc.. more like the intervalometer scripts.  Why?  Because I don't have a job, and it keeps me busy!  ::)
Title: Re: CHDK PTP interface
Post by: rudi on 15 / March / 2011, 11:54:06
return strangeness:
Sorry reyalp, I have not enough time in this moment, so only a short comment.
I tested many options for two month ago (rev.1032 to 1033) to find the reason for return-fail. An easy way for gcc4 was to put $(OPT_OBJS) in core/Makefile to begin of line.

rudi
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2011, 15:50:05
Sorry reyalp, I have not enough time in this moment, so only a short comment.
I tested many options for two month ago (rev.1032 to 1033) to find the reason for return-fail. An easy way for gcc4 was to put $(OPT_OBJS) in core/Makefile to begin of line.

rudi
Thanks, this is very a good clue. I also don't have much time during the week, but this gives me something work on.
Title: Re: CHDK PTP interface
Post by: msl on 16 / March / 2011, 06:59:55
ptpCamGui (use with CHDK Shell or stand alone from here (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207)):

I changed some lines and now that doesn't happen.  And Again.. the stuff for deleting after download is in here too (because I use it all the time).  Based on build 82.

Because it generally is desired, I have added also the changes for deleting image files after download - thx achillies. I've  slightly adjusted the code for a better integration in the GUI. Settings will be saved in ini file.

Use this function at your own risk! Perhaps pictures can be lost.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 16 / March / 2011, 18:00:14
 8)  No, Thank you!  (All of you!)  In a previous post I mentioned other GUI things I was working on such as Timelapse start delay and an external help file. I have those things finished, but I don't really know how you like to see the changes (one change at a time, or all of the changes at once). 

If someone like me makes changes, how would you all prefer to see them?
Title: Re: CHDK PTP interface
Post by: msl on 17 / March / 2011, 12:16:34
If someone like me makes changes, how would you all prefer to see them?
The best way would be to generate a patch/diff file. But this is not necessary. We can also compare the current version with other versions and merge, e.g. with KDiff3 (http://kdiff3.sourceforge.net/).

Post the changed Autoit file. We need only the ptpCamGui.au3 file. ptpCamGui_Obfuscated.au3 is generated automatically.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 18 / March / 2011, 01:33:25
Attached are the Timelapse/Delay Changes. I don't know if anyone will use the "days" delay for anything, but it might be useful. I only included the ptpcamgui.au3 file this time. I am trying to understand focus and DOF bracketing, and that is where I will go next.  I have also been trying to figure out how to get the zoom level (0-127) to accurately show my cameras zoom or equivalent (5.0-60mm or 28-336mm).  I really do need to get a job and leave you guys alone for a while! :D

I don't know how I lost so many lines, but this last simple change to ptpcamgui.au3 completes my Timedelay changes.
1089 - CHANGED GUICtrlSetData($LTLCurPic, "")
TO 1089 - GUICtrlSetData($PTLDTime, 0)
Title: Re: CHDK PTP interface
Post by: msl on 18 / March / 2011, 06:01:27
Attached are the Timelapse/Delay Changes.
Sorry, there are no changes for time lapse in the attached file. The changes relate to the already built-in delete function.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 18 / March / 2011, 08:21:48
@msl - It looks like it's all there to me!  I also attached the text file with differences this time.  I will try to learn how to generate a better diff file.

EDIT - It was "mostly" there.  I missed a variable or two related to switching languages, and I'm sure since many of you are german, you hit it right away.  It has been fixed, and reposted in the message above. I apologize for not testing more carefully.  Attached to this message is the obfuscated version.  

Also, when I try to use CHDK-DE builds (sx130is compiled) with PTPCamGUI I can not take pictures. it seems to go into  a loop with ">> luar get_mode() << false (Length: 5)" repeating.  When I use the international builds (eg. 1089 patched with quids sx130is patch) everything works fine.  What might be the cause?  The CHDK-DE build seems to work well with this camera if I don't try to use PTPCamGUI (fresh version.. none of my new changes).
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / March / 2011, 00:03:46
Sorry reyalp, I have not enough time in this moment, so only a short comment.
I tested many options for two month ago (rev.1032 to 1033) to find the reason for return-fail. An easy way for gcc4 was to put $(OPT_OBJS) in core/Makefile to begin of line.

rudi
Thanks, this is very a good clue. I also don't have much time during the week, but this gives me something work on.
A little more on this: Just moving $(OPT_OBJS) to not be the last item is sufficient. Trying the order of things within $(OPT_OBJS) seems like the next step, to narrow it down to the smallest change.

I still don't see why this is happening. It seems too consistent to be just something like value of uninitialized memory being different.

gcc4 is more sensitive to link order than gcc3. It seems possible that the linker could be picking up a different function for something depending on order. My first guess was the ctype functions (isspace/iscntrl etc) seem like they might be related, based on the problem with numeric return and newline, but if this is the case I don't see where.

I thought the fact that iscntrl was always false might be related, but fixing that doesn't change anything. I'll fix that in the trunk anyway, since lua patterns use it.

Core makefile uses
 --start-group $^  $(LDLIBS) --end-group

I wasn't able to find good documentation for --start-group and --end-group, but it seem to force the linker to repeatedly scan all the libs to resolve cyclic dependencies. $(LDLIBS) is only -lgcc which doesn't seem like it should have anything relevant.

edit:
good
 ... script.o console.o
bad
 ... console.o script.o

edit:
this seems specific to the order of script.o and console.o, putting other .o files later doesn't seem to change whether it works or not.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / March / 2011, 03:16:22
Solved:

The dryos ctype functions have a bug

Code: [Select]
unsigned char _ctype[] = {
...
int isdigit(int c) {
    return _ctype[c]&_D;
}
note that c is an integer. If the value falls outside of the _ctype array, a random value in memory will be used.

It is legal to pass EOF (generally int -1) to ctype functions, and lua does this.
Title: Re: CHDK PTP interface
Post by: philmoz on 20 / March / 2011, 03:43:24
Solved:

The dryos ctype functions have a bug

Code: [Select]
unsigned char _ctype[] = {
...
int isdigit(int c) {
    return _ctype[c]&_D;
}
note that c is an integer. If the value falls outside of the _ctype array, a random value in memory will be used.

It is legal to pass EOF (generally int -1) to ctype functions, and lua does this.


Brilliant :D

FYI - this also fixes the problem where scripts crash with an 'unexpected symbol' error if the last line of the script does not have a 'newline' character at the end (on versions of CHDK built under GCC4 / Windows).

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / March / 2011, 04:08:27
FYI - this also fixes the problem where scripts crash with an 'unexpected symbol' error if the last line of the script does not have a 'newline' character at the end (on versions of CHDK built under GCC4 / Windows).
Yes, turns out this wasn't really a PTP problem. Fixed in changeset 1092 (http://tools.assembla.com/chdk/changeset/1092)
Title: Re: CHDK PTP interface
Post by: philmoz on 20 / March / 2011, 04:21:00
FYI - this also fixes the problem where scripts crash with an 'unexpected symbol' error if the last line of the script does not have a 'newline' character at the end (on versions of CHDK built under GCC4 / Windows).
Yes, turns out this wasn't really a PTP problem. Fixed in changeset 1092 (http://tools.assembla.com/chdk/changeset/1092)

With the code change in 1092 the second half of the ctypes array is redundant (from 128 - 255), will save 128 bytes by deleting these values.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / March / 2011, 18:10:23
Unless there are objections, I'm planning to merge the new ptp return/message code into the trunk soon, probably today. There are still some rough edges in the code, but it seems to be functional.

This means that existing ptpcamgui and ptpcam builds will no longer work fully with the CHDK trunk. I will provide a ptpcam executable.

If users need a build with the old ptp protocol, they should not update. Alternatively, they can use the CHDKDE autobuild until that is updated.
Title: Re: CHDK PTP interface
Post by: achillies on 20 / March / 2011, 23:57:53
You do very nice work. After updating all components (ptpcam.exe = r601, ptpcam.dll = 85, gui = 85), everything seems to work as expected.  The camera connects immediately using ptpcam.exe, but when using ptpcamgui, disconnects-reconnects several times before finally connecting (but does USUALLY connect).  I'm sure this will become more reliable with time.  So far all basic GUI tests have passed.

I like the (apparent) ability to control/connect to more than one camera, even though I've only got one right now.

Again.. Nice work. Thanks for the possibilities.

Not related: Can one of you Gui-people (or Autoit-people) explain why tooltips don't work for me in the GUI?   I get no tooltips in ptpcamgui, but I do get tooltips in CHDK-Shell.  Point me to a link if necessary, but I have not been including them in my ptpcamgui changes because they don't work for me.
Title: Re: CHDK PTP interface
Post by: achillies on 21 / March / 2011, 01:56:25
I just have to keep doing this.  I hope I'm not getting under anyones skin.

These attachments are changes to the latest ptpcamgui (ver 85).  The TDchange85.txt file contains the changes I make to my timelapse-timedelay, and the HLPDNLDChange85.txt file contains a minor change in the DCIM progress bar as well as changes to the Main Menu Help.  It uses an external help file, which you may not appreciate.  Anyway, here they are.  The previous post contains both the ptpcamgui.au3 and ptpcamgui_obfuscated.au3 files with all of these changes if interested.
Title: Re: CHDK PTP interface
Post by: msl on 21 / March / 2011, 08:27:17
You do very nice work. After updating all components (ptpcam.exe = r601, ptpcam.dll = 85, gui = 85), everything seems to work as expected.
The changes of reyalp do not affect the current trunk version. These are preparations for the future ptp-interface.

These attachments are changes to the latest ptpcamgui (ver 85).  The TDchange85.txt file contains the changes I make to my timelapse-timedelay, and the HLPDNLDChange85.txt file contains a minor change in the DCIM progress bar as well as changes to the Main Menu Help.
I have integrated the minor change for the DCIM progress bar in revision 86 with some small cosmetic changes.

Some general words about the GUI:

- For a help system I prefer gui tooltips + information thread in the forums like this (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207#p20351), maybe also in the CHDK wiki.

- Features like time-lapse, motion detection or exposure bracketing should be only basicly be available. This is a good demonstration for CHDK beginners. Advanced functions, e.g. delay functions in time lapse modul (achillies), should be handled differently for a better overview, maybe with a context menu.

- rudi has now implemented a very nice multi camera feature. You can use more than one camera with the GUI. Every Camera get a unique identification number.

- All necessary additional binaries have been packed into a DLL file, which improves the handling.

- The most important features, upload and download, works quite well. You can download all picture files. The GUI can automatically download the current CHDK or CHDK-DE from the autobuild servers, extracts the files and sends it to the camera

At the moment we should wait with other new developments. reyalp working on an improved ptpcam version. If this version is integrated into the trunk, we have much to do in ptpCamGui code.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 22 / March / 2011, 18:37:41
I understand.  I'll stop messing with it for a while ;)

The reason I started on the help file was because tooltips don't work in my version of ptpcamgui, I'm trying to figure out why.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / March / 2011, 00:47:50
I've checked in the ptp message code in the trunk changeset 1101 (http://tools.assembla.com/chdk/changeset/1101)

This means that ptpcamgui and old ptpcam version will no longer work correctly. Non script functions should be ok.

I've attached a compatible ptpcam, source can be found in the reyalp-ptp branch of the chdk svn. I have not merged this into the trunk because I don't intend to maintain a version of ptpcam in the long run.

Next stop, lua client :)
Title: Re: CHDK PTP interface
Post by: grythumn on 30 / March / 2011, 23:02:51
Quick report:

S3IS, 1.00a, trunk1117, locally compiled with reference firmwares and S3IS firmware for findsig.

ptpcam --chdk works, can send LUA scripts. mode switching doesn't work yet, will dig through this thread again... I remember seeing discussion of different ways to switch modes...

R C
Title: Re: CHDK PTP interface
Post by: msl on 01 / April / 2011, 06:08:34
I've checked in the ptp message code in the trunk changeset 1101 (http://tools.assembla.com/chdk/changeset/1101)

This means that ptpcamgui and old ptpcam version will no longer work correctly. Non script functions should be ok.

ptpcam and ptpCamGui was updated. The GUI is working again properly with CHDK & CHDK-DE. You can test the gui with whim's CHDK shell or as stand alone version (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207).

Another way is reyalp's new project chdkptp (http://chdk.setepontos.com/index.php?topic=6231.0), also a very good thing.

msl
Title: Re: CHDK PTP interface
Post by: blackhole on 02 / April / 2011, 04:58:52

- The most important features, upload and download, works quite well. You can download all picture files. The GUI can automatically download the current CHDK or CHDK-DE from the autobuild servers, extracts the files and sends it to the camera

msl


Whether this option is still existing, or am I missing something as we are constantly repeated message "No internet connection"?

Boris



Title: Re: CHDK PTP interface
Post by: msl on 02 / April / 2011, 13:39:00
Whether this option is still existing, or am I missing something as we are constantly repeated message "No internet connection"?

I've tested once more the recent version of ptpCamGui and it works fore me.

The GUI send google a ping for testing the internet connection. Maybe a firewall block the GUI.

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / April / 2011, 16:43:43
Good observation from msl: http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207&start=150#p21620 (http://forum.chdk-treff.de/viewtopic.php?f=7&t=2207&start=150#p21620)

On dryos cams, when you first start in play mode, buttons are not recognized by the canon firmware. Sending post_levent_to_ui(4484) unlocks them, without the requirement of going to rec and back. The levent number may vary, 4484 worked for me on d10. Unfortunately, this levent does not have a string name.
Title: Re: CHDK PTP interface
Post by: achillies on 03 / April / 2011, 16:38:42
All the basics work here (and then some)! 

Notes: If I do not disable WIA service, my LCD display blanks (everything still works, but I can't see any display).  When I disable the WIA service, my LCD does not blank, and everything works as expected.

Thank you reyalp for observing msl's observation (I would have missed it otherwise! )  :haha
luar post_levent_to_ui(4484)
unlocks my keys just as you said!  That was always a hassle, so I'm glad it's "fixed"

Title: Re: CHDK PTP interface
Post by: msl on 04 / April / 2011, 14:40:05
Also, when I try to use CHDK-DE builds (sx130is compiled) with PTPCamGUI I can not take pictures. it seems to go into  a loop with ">> luar get_mode() << false (Length: 5)" repeating.  When I use the international builds (eg. 1089 patched with quids sx130is patch) everything works fine.  What might be the cause?  The CHDK-DE build seems to work well with this camera if I don't try to use PTPCamGUI (fresh version.. none of my new changes).

The recent revision of CHDK-DE (618) should be solve this problem.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 04 / April / 2011, 16:25:34
@msl, yes, that is absolutly correct.  Thanks. 

I won't be able to play with PTP for a week or so, and it might be my imagination, but it seems like the connection process is more "stable" now, than it was pre 1.0. 
Title: Re: CHDK PTP interface
Post by: msl on 07 / April / 2011, 10:58:12
ptpCamGui:

The command luar post_levent_to_ui(4484) to unlock the keys in play mode is now a start option for all DryOS cameras.  That means, for all DryOS camera the keys are directly after GUI start unlocked.

I hope the value 4484 is really valid for all DryOS cameras.

msl
Title: Re: CHDK PTP interface
Post by: achillies on 07 / April / 2011, 20:33:05
Woudn't it be nice to know rather than guess (retorical question)?  I know everyone and their brother has said this, but CHDK actually sells some cameras for Canon and I (personally) think that Canon should fill you guys in!
Title: Re: CHDK PTP interface
Post by: ioltaworzo on 09 / April / 2011, 18:37:31
Title: Re: CHDK PTP interface
Post by: msl on 09 / April / 2011, 19:09:47
Hello and welcome,

at the moment is it not possible to switch in the CHDK menu over ptpCamGui.

msl
Title: Re: CHDK PTP interface
Post by: philmoz on 15 / April / 2011, 08:38:57
ptpCamGui:

The command luar post_levent_to_ui(4484) to unlock the keys in play mode is now a start option for all DryOS cameras.  That means, for all DryOS camera the keys are directly after GUI start unlocked.

I hope the value 4484 is really valid for all DryOS cameras.

msl

luar post_levent_to_ui(4484) works for G12 and SX30.

I did notice that after using 'Download' with 'Delete files' option checked the camera was rebooted after deleting the files; but it did not do the luar post_levent_to_ui(4484) command so the keys were locked again.

Phil.
Title: Re: CHDK PTP interface
Post by: msl on 15 / April / 2011, 09:17:58
I did notice that after using 'Download' with 'Delete files' option checked the camera was rebooted after deleting the files; but it did not do the luar post_levent_to_ui(4484) command so the keys were locked again.

Thx for the informations. The problem should be solved with the new GUI version (revision 92).

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / April / 2011, 15:29:11
I've tried to bring the wiki up to date to reflect the fact that this is now standard in the trunk and also mention ptpcamgui and chdkptp http://chdk.wikia.com/wiki/PTP_Extension (http://chdk.wikia.com/wiki/PTP_Extension) Further improvements are welcome!

I am considering another change to the PTP protocol:
Currently, tables are returned as PTP_CHDK_TYPE_STRING. I would like to return them as PTP_CHDK_TYPE_TABLE. This will still be string, but it will be easier for the client to know what it is supposed to be. This will be a "major" protocol change since it's incompatible with current code, but supporting it should be easy.

I would also like to change the format that tables are returned with. Currently, in chdkptp, I override usb_msg_table_to_string on every call, which is slightly annoying.

For me, the ideal format would be the output of the serialize function in chdkptp chdku.lua (http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua) but I don't know if this will be too hard to parse in ptpcamgui ? If it is, I can continue overriding usb_msg_table_to_string, this is less of an issue than the type. Or maybe we can add an option for a simplified format in serialize().

It would be nice to be able to set some 'standard libraries' that can be uploaded once and remain available to every ptp lua execution, but don't have to loaded from disk or over ptp every time, and don't have to be in memory when PTP isn't in use.

One way of doing this
add_ram_module("name","lua code")
this stores the lua code in regular malloc memory. require is updated so require("name") runs the code. Lua require already has provisions for various custom loading methods, so this should be easy.
you'd also want remove_ram_module("name") and remove_all_ram_modules(). Names subject to change ;)
Title: Re: CHDK PTP interface
Post by: NormanA on 18 / April / 2011, 15:27:14
I have obviously missed something, but I have tried to follow the instructions as best I could, but I get the same error every time I try to run the PTP interface.  The attached .jpg shows the error, and I think I just need to know where to put the libusb0.dll file, but I don't have a clue.
Title: Re: CHDK PTP interface
Post by: msl on 18 / April / 2011, 16:25:43
You need an alternative USB driver: http://sourceforge.net/projects/libusb-win32/ (http://sourceforge.net/projects/libusb-win32/)

See also here (http://chdk.setepontos.com/index.php?topic=6285.msg64905#msg64905).

msl
Title: Re: CHDK PTP interface
Post by: NormanA on 19 / April / 2011, 15:00:07
I finally got it to recognize the camera, but I now get a continuous loop that I have let run for over 5 minutes before aborting.  The loop goes like this:

** i** init()** init() start ...
>> version << ptpcam: 1.0
camera: 1.0 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil) << script:8
8:ret:false (Length: 21)
>> upload lptpgui.lua A/CHDK/LUALIB/lptpgui.lua
** init() fail
>> reset <<  (Length: 0) [ERROR: Could not close session! (Length: 31)]
** init() start ...
>> version << ptpcam: 1.0
camera: 1.0 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil) << script:9
9:ret:false (Length: 21)
>> upload lptpgui.lua A/CHDK/LUALIB/lptpgui.lua

It will not ever go into the PTP GUI so that I might test it out.  I'm using an SD940 with firmware version 1.03c.
Title: Re: CHDK PTP interface
Post by: mweerden on 19 / April / 2011, 16:58:37
I finally got it to recognize the camera, but I now get a continuous loop that I have let run for over 5 minutes before aborting.
You'll have to make sure the directory A/CHDK/LUALIB is already created. The tool should probably do a "mkdir -p" before trying to upload. (I encountered this my self one or two days ago but didn't get around to posting it yet.)
Title: Re: CHDK PTP interface
Post by: mweerden on 20 / April / 2011, 06:56:51
At the moment I'm working on remote live preview (or whatever it should be called) and I would like to do it in such a way that it can be added to CHDK permanently. So here's is my proposal (and related questions).

There essentially two extensions. One is to retrieve the various details such as image dimensions and buffer addresses. The other is to obtain a live image but also deal with the fact that buffer addresses are typically rotated.

For the latter I propose to add an flags parameter to the PTP_CHDK_GetMemory command. The currently only flag (0x1) will indicate that the first parameter is not a buffer address, but a pointer to function for obtaining the address. So if the flag is set, the camera will essentially first do "addr = ((ftype) addr)();". This seems a nice minimal adjustment to the PTP code.

For the details (such as the function to use above), I propose to introduce a Lua function. This function (I called it "get_video_details()") would either return a string containing a C struct with all the details or perhaps make a nice Lua table for it. The type of result probably depends on how often it will be called, but more on that later.

As for the details themselves, we need the following:


Now one question is how stable is this information and as a consequence how often do we retrieve it? I already assumed we would use a function instead of an address for getting the buffers, but if we get all of this information every time before we get a buffer that seems kind of pointless. The reason I assumed a function is because the other data is relative stable. Only when switching aspect ratio these seem to change. Perhaps it's better to do a less frequent check for such a change?

If details are "unstable" or we just decide to get them every time, perhaps it is a good idea to consider making a function that provides both the details and the buffer(s) together. To keep the PTP code relatively clean we could "export" some functions for sending data that can be used for the big send_details_and_buffers() function. And in this case the proposed change to GetMemory has to be adapted to just call the function instead of using its result to send data. That or adapt CallFunction such that a flag indicates that the address is in Param2 instead of sent as data (to free up the data phase).

Another question is which actual dimensions one should use in displaying images and how the various components are composed in that image. This is not something that appears in CHDK code, but it is important in the use of it. It seems the bitmap image corresponds to the actual dimensions, but I not 100% sure. Do you just stretch the viewport image to those dimensions or should you add black borders to get the maximum viewport dimensions and stretch that?

If I interpret the comments of image_offset and row_offset correctly the image buffer actually already has black borders where needed and we can just always use the maximum viewport dimensions. This does mean some code needs to be added for some platforms to get this maximum. (Although at the moment this is just relevant for G12 en SX30, right?)

With respect to the palette I was thinking of just sending CAM_BITMAP_PALETTE and let tools have the (currently) used palettes hard coded in them. This way you don't have to transfer it, but more importantly it seems that this is the only detail that currently isn't readily available.

Some small things:


Please let me know what you think about all this. And thanks for reading it all. You did read it all, didn't you? ;)



To really conclude some side notes:

Proper serialisation in Lua looks nice, but also complicated/expensive. And it would indeed bump up the PTP version. Perhaps an option is to leave implicit serialisation as it is now and just provide a proper serialise function for Lua programmers to use if they want to communicate more complex things (as is the case in most languages I believe).

I would also like to note that my experience with installing and figuring out how to draw an image with IUP has been quite frustrating. In the end I just piped the data to an external program. It definitely has resulted in my not being a fan of it. Just wanted to get that of my chest. ;)

On a more positive note, I've found a nice project: LibUsbDotNet (http://libusbdotnet.sourceforge.net/) This provides a cross-platform .NET interface to libusb (and something similar(?) called WinUsb). I haven't really tested in on Linux yet, but it seems to work. I'm using C# to make a (CHDK-)PTP layer on top of it.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / April / 2011, 12:53:15
mweerden, nice to see you working on this again.

Some comments below, I'll try to give the other issues a more detailed response when I have a bit more time.

Quote
actual live image dimensions (= bitmap dimensions?)
There is no simple, general relation between bitmap and live dimensions. The CHDK code is currently very ugly in the way it deals with live view dimensions. The best thing to do would be to clean this up before trying to build a PTP interface for it, but this would be a big job.

I wonder if you'd be better off with a new ptp function that's something like "get video frames" which takes flags specifying which items you want (bitmap, viewport, bitmap palette if we can get it) and returns a structured result. The camera side could notice when aspect and possibly palette changed, and automatically send updated information.  edit: batching them all together should be more efficient.

Some discussion of viewport layout is in http://chdk.setepontos.com/index.php?topic=5415.0 (http://chdk.setepontos.com/index.php?topic=5415.0)  and http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers)
Quote
palette (either as a whole or just CAM_BITMAP_PALETTE)
The actual camera palette would be best, but requires find the relevant function for all cameras. Also, it changes at unpredictable times, so it wouldn't be clear when you'd need to update it. Doing it every frame would be wasteful, but as above maybe the camera could notice and only send it when requested or it changes.

Quote
I would also like to note that my experience with installing and figuring out how to draw an image with IUP has been quite frustrating. In the end I just piped the data to an external program. It definitely has resulted in my not being a fan of it. Just wanted to get that of my chest.
IUP documentation isn't great. My understanding is that it doesn't really support drawing directly to a window. To do this you should either use CD http://www.tecgraf.puc-rio.br/cd/ (http://www.tecgraf.puc-rio.br/cd/) or the GL canvas, or roll your own function in C that draws directly the the hwnd or equivalent.

That said, I think the ability to easily receive lua values from the camera and use them directly is very high, and once you get used to it's oddities, it's pretty convenient for general gui stuff.
Quote
In include/platform.h some vid_* functions return long, some int. I don't think there is a reason, but I'd like to be sure
No point, long and int are identical. I would really like to get rid of all the longs from everything except possibly functions that are defined as 'long' in some external standard.
Quote
Proper serialisation in Lua looks nice, but also complicated/expensive. And it would indeed bump up the PTP version. Perhaps an option is to leave implicit serialisation as it is now and just provide a proper serialise function for Lua programmers to use if they want to communicate more complex things (as is the case in most languages I believe).
My current thinking is to add an option to lua exec, which uses serialize for everything (except maybe strings, because escaping them does add quite a bit of overhead for not much value.) The serialize function really isn't very complicated (currently 100 lines in chdku), and the overhead for simple values should be negligible compared to ptp overhead. It doesn't handle cyclic tables or code, but there's not much need for those. Handling cyclic tables wouldn't be that hard if you needed to, and you can just override the serialize function with a smarter one.

Sending the values as lua leaves them quite human readable.
Title: Re: CHDK PTP interface
Post by: mweerden on 21 / April / 2011, 06:25:26
The CHDK code is currently very ugly in the way it deals with live view dimensions. The best thing to do would be to clean this up before trying to build a PTP interface for it, but this would be a big job.
And that's why it's not what we should do. ;)

In my opinion having remote live preview far outweighs it being optimal (or perhaps even working) on each camera. We basically have it ready on a shelf waiting and it's a shame not to use it. I think in the current situation we can make something that works well in almost all cases. If we later find a much better but incompatible method, we'll just have to do a major++ and that's that.

Quote
Quote
actual live image dimensions (= bitmap dimensions?)
There is no simple, general relation between bitmap and live dimensions.
Reading the post you referred to I feel the need to clarify that with "actual live image" I mean the "display area" or the image as it should be shown to the user. Perhaps presentation image/dimensions is a clearer term.

That said, from this statement (and the other post) I get that in general the bitmap dimensions need not be the same as the presentation dimensions. So at this moment there is no way to actually get the latter dimensions.

As far as I can tell, however, it seems that for most cameras we can use the bitmap dimensions. Or perhaps even just default to 360x240. We can add vid_get_presentation_width/height to generic/wrappers.c with either of these choices such that one can easily override it whenever someone figures out it doesn't work for them.

Side question: are there cases where it is not 360x240? And even not 3:2? (As long as it is 3:2 it will just show up a bit smaller or bigger than it should, which isn't the end of the world.)

Quote
I wonder if you'd be better off with a new ptp function that's something like "get video frames" which takes flags specifying which items you want (bitmap, viewport, bitmap palette if we can get it) and returns a structured result. The camera side could notice when aspect and possibly palette changed, and automatically send updated information.  edit: batching them all together should be more efficient.
Yeah, this is pretty much the "big send_details_and_buffers()" function I mentioned. Except I would not make it part of CHDK PTP on account of separation of concerns. (Although that means you'll have to either get the function pointer first or send the data as script result.)

Quote
Some discussion of viewport layout is in http://chdk.setepontos.com/index.php?topic=5415.0 (http://chdk.setepontos.com/index.php?topic=5415.0)  and http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers)
Thanks for that. I searched using the function names and didn't come up with anything like this.

As for the remark about the mismatch of dimensions w.r.t. the S90 and G11: I currently have a DISKBOOT.BIN where viewport_width is 360 and a PS.FI2 where it is 720. No noticeable difference with edge overlay. Very robust code I guess...

Quote
The actual camera palette would be best, but requires find the relevant function for all cameras. Also, it changes at unpredictable times, so it wouldn't be clear when you'd need to update it.
It changes? (Wouldn't expect that at all looking at the code.)

Quote
My current thinking is to add an option to lua exec, which uses serialize for everything (except maybe strings, because escaping them does add quite a bit of overhead for not much value.)
That's even better.
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2011, 12:55:03
It changes? (Wouldn't expect that at all looking at the code.)
The CHDK palette doesn't change. The canon one does (switching between play and rec for example, or opening the menu.) The CHDK palette should be selected such that it is readable in either canon palette, but the exact colors vary, and it doesn't cover anywhere close to the entire canon palette.

Note that ewavrs old live view code did get the canon palette, e.g. from a540:
Code: [Select]
unsigned int *vid_get_palette()
{
    static unsigned pal[16];        
    unsigned int*syspal= (unsigned int*)0x634E0; // GetPaletteFromPhysicalScreen
    int i;
    for (i=0;i<16; i++) {  // big-endian to little-endian
    pal[i] = (syspal[i]>>24) |
             ((syspal[i]<<8) & 0x00FF0000) |
             ((syspal[i]>>8) & 0x0000FF00) |
             (syspal[i]<<24);
    }
    return pal;
}

As for the viewport dimensions:
1) The CHDK code is confusing, because the actual buffer is 4 Y units for each U and V. CHDK splits the difference so "360x240" in lib.c is actually 720 in Y.  360x240 gives square pixels.
2) On some cameras (e.g. SD990, D10, SD1200...) the bitmap pixels aren't square either. All of these have 720x240 (non-square pixel) bitmap displays, but the lib.c code still says 360x240, and correction is done elsewhere. Not all of them are a simple 2x, see the CAM_ASPECT_CORRECTION nonsense in */platform_camera.h but beware the comments have been copy pasted!
3) On some cameras, the height of the live view varies slightly between record and play mode (e.g. a570)
4) some cameras have buffers that are bigger than the display area. Can also apply to bitmap buffer (e.g. tx1)
5) some cameras are switchable between 16:9 and 4:3. The display on the SD4000 is actually 16:9, while some others (e.g. G12) are 4:3.

The great difficulty with all this is that without the particular camera, it's quite hard to know what it's actually doing.

edit to add:
In spite of all the above, all the necessary information should be available, since CHDK can display and do edge overlay correctly. It's just a matter of gathering all the information in a way that doesn't drive you insane...

Quote
As for the remark about the mismatch of dimensions w.r.t. the S90 and G11: I currently have a DISKBOOT.BIN where viewport_width is 360 and a PS.FI2 where it is 720. No noticeable difference with edge overlay. Very robust code I guess...
Do histogram, zebra and edge overlay work correctly on both ?
Oops, you say edge overlay works. I'm guessing they are just using a different value there, but like I said, it's a mess.

Title: Re: CHDK PTP interface
Post by: mweerden on 21 / April / 2011, 17:26:05
Hmm... It seems that, just as in life, the more you know, the more it sucks.

... so "360x240" in lib.c is actually 720 in Y.  360x240 gives square pixels.
Just to make sure I absolutely understand correctly: the value vid_get_viewport_width() returns is not the actual width of the image in the buffer (or the number of Y's, if you want)?


I think it is key to first figure out what information we precisely need, without looking at what is available (in CHDK). For every thing we don't have (or just not reliable or easy enough) we should just introduce new functions (e.g. vid_get_viewport_width_proper()) with some default implementation. Getting the palette? Just return a palette with completely transparent colours. But, of course, preferably default implementations that works for most cameras.


One thing I keep wondering about is what happens with these changing viewport dimensions. The bitmap dimensions seem to be constant, right? So that seems to suggest that the presentation(/display area) dimensions are constant as well. If so, and if the unused pixels in the viewport buffer are set to black by the camera (which I'm hoping), doesn't that mean that we don't have to concern ourselves with the whole changing dimensions and aspect ratio business? Can't we just use the buffer as if the viewport dimensions are maximal?

Of course, there might be interest in having the live image without overlay with the border stripped. However, it does become optional.
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / April / 2011, 00:42:39
Hmm... It seems that, just as in life, the more you know, the more it sucks.

... so "360x240" in lib.c is actually 720 in Y.  360x240 gives square pixels.
Just to make sure I absolutely understand correctly: the value vid_get_viewport_width() returns is not the actual width of the image in the buffer (or the number of Y's, if you want)?
Right, on the classic cameras where the viewport is "360x240" there are actually 720 y values. Histogram, zebra, MD etc, just ignore half of them. This made things easy on these cameras, because the bitmap was actually 360x240.

Quote
One thing I keep wondering about is what happens with these changing viewport dimensions. The bitmap dimensions seem to be constant, right?
I'm nut sure what the bitmap does on cameras with widescreen modes... I don't own one ;)

Quote
I think it is key to first figure out what information we precisely need, without looking at what is available (in CHDK).
Agreed. Looking at ewars CHDKCAM and corresponding CHDK patches may also be useful. He addressed a lot of these issues (by adding new functions) but the cameras permutations have also become more complicated.

I would say
bitmap dismensions and aspect ratio (cameras like D10 do not have square pixels).
palette - you'll want to get it from the cameras eventually, but you can just use a default one when it's not available. You could use CAM_BITMAP_PALETTE (probably pulled out of the source code, not returned by the camera) to populate some of it.

For the viewport, I'm less sure because I'm not sure I understand how all permutations actually work. But you can start with whatever camera you have, and make the owners of the funny ones implement their own ;)
Quote
So that seems to suggest that the presentation(/display area) dimensions are constant as well. If so, and if the unused pixels in the viewport buffer are set to black by the camera (which I'm hoping),
Worth experimenting, but I wouldn't count on it. My guess is the canon video hardware is doing the overlay stuff much later.
Title: Re: CHDK PTP interface
Post by: mweerden on 22 / April / 2011, 06:12:02
Looking at ewars CHDKCAM and corresponding CHDK patches may also be useful. He addressed a lot of these issues (by adding new functions) ...
Yeah, but until our discussion I had no idea what these "_for_ptp()" functions were about. Looking at it now it has become a lot clearer.

Thanks very much for your detailed information, reyalp. I'm pretty confident that I can now make a nice patch.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / April / 2011, 17:35:53
protocol update: http://chdk.setepontos.com/index.php?topic=2509.msg65421#msg65421 (http://chdk.setepontos.com/index.php?topic=2509.msg65421#msg65421)

I've decided to hold off changing the format of returned tables, since overriding it in lua is quite convenient for development anyway (if you have code to send additional lua with every call, like chdkptp does).
Title: Re: CHDK PTP interface
Post by: Bernd R on 28 / April / 2011, 15:07:17
I have test Ix 1000 HS with 1154 build and chdkptp.

I guess when i click on files tab and i call refresh, the directory should show.But camera show only in log short some "finished ***" messages and nothing happen

console output is this.i test several times

"""""
tree right click: fullpath A/
old state COLLAPSED
populate branch 0 A/
tree right click: fullpath A/
old state COLLAPSED
populate branch 0 A/
tree right click: fullpath A/
old state COLLAPSED
populate branch 0 A/
""""""

reboot button work, but it do not start chdk when sd card is not write protect.

shutdown button do not shutdown.there is only "finished ***" on cam log show.when i remove USB cable, i am not able to switch off camera.i need remove battery.

same happen when i do after a connect and upload file or press play.camera is not dead, show finish on every action, but it can not switch off with the buttons.when remove USB cable canon keys work all,but i am not able to switch to record mode, even if no USB cable is in.
 
do a disconnect before remove of USB cable too not help to switch camera off.

more tests i do:

when i click on files tab upload of file work.

the switch to record mode crash this camera as before.lens move out and after that, camera crash.seem this camera is not able to switch to record mode
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / April / 2011, 15:59:32
Thanks for testing CHDKPTP.

This belongs in the chdkptp thread: http://chdk.setepontos.com/index.php?topic=6231.0 (http://chdk.setepontos.com/index.php?topic=6231.0) if any mods want to move it.
I have test Ix 1000 HS with 1154 build and chdkptp.

I guess when i click on files tab and i call refresh, the directory should show.But camera show only in log short some "finished ***" messages and nothing happen
You need to double click to expand the tree. This automatically re-freshes. When I said the file browser was very alpha, I wasn't joking ;)
Quote
reboot button work, but it do not start chdk when sd card is not write protect.
What exactly did you expect to happen ?

With script you can boot to a specific file (PS.FI2 or *unencoded* disboot.bin) but I'm not sure how you'd expect that to be done automatically. Reboot without a file just reboots the camera, which obviously goes through the normal canon boot process. Adding a file selection option (boot to...) is a good idea, I'll add it to the planner.

Quote
shutdown button do not shutdown.there is only "finished ***" on cam log show.when i remove USB cable, i am not able to switch off camera.i need remove battery.
Sounds like shutdown script function is broken in your port.
Quote
same happen when i do after a connect and upload file or press play.camera is not dead, show finish on every action, but it can not switch off with the buttons.when remove USB cable canon keys work all,but i am not able to switch to record mode, even if no USB cable is in.
 
do a disconnect before remove of USB cable too not help to switch camera off.
Sounds like: http://chdk.setepontos.com/index.php?topic=4338.msg64324#msg64324 (http://chdk.setepontos.com/index.php?topic=4338.msg64324#msg64324)

I have not yet implemented this workaround in CHDKPTP. I think it should be a function e.g. "unlock_keys_for_usb()" with the default implementation sending that message, not hardcoded in PTP client.

Quote
the switch to record mode crash this camera as before.lens move out and after that, camera crash.seem this camera is not able to switch to record mode
Sounds like your ports implementation of mode switching is broken.
Title: Re: CHDK PTP interface
Post by: mweerden on 04 / May / 2011, 12:19:32
At GitHub (https://github.com/mweerden/CHDKPTPRemote/tree/remote-preview) you can now find my patch for remote live preview as well as a CHDK PTP .NET library (+test app). (Direct link to the patch: chdk.patch (https://github.com/mweerden/CHDKPTPRemote/blob/remote-preview/chdk.patch))

For the .NET library you'll need the LibUsbDotNet DLL. With VS2010 you can just put in the "root" (i.e. where the .sln file is). Currently the library is for .NET 4.0, but it is pretty easy to make it work with 3.5. The library consist of a three layers: PTP, CHDK PTP and CHDKPTPRemote. The latter provides an easy interface with the basic functionality. Note that I haven't implemented all CHDK PTP functionality (and definitely not all PTP functionality).

As for the patch: I've adapted the CallFunction command such that you can call functions that return data via PTP and added a function that can send a combination of the buffers and additional dynamic info. The address of the function together with static information can be obtained with Lua using the get_video_details() function.

Regarding the viewport buffer and different aspect ratios: I'm told that on the G12 the buffer simply contains black borders. On my IXUS870IS I can select a "wide" format, but that doesn't affect the viewport buffer. The black borders are added by drawing them in the bitmap.

Edit: I've made a separate branch for the remote live preview stuff. The master branch (https://github.com/mweerden/CHDKPTPRemote/) should be compatible with the current CHDK trunk (i.e. CHDK PTP v2.0).
Title: Re: CHDK PTP interface
Post by: E^3 on 06 / May / 2011, 05:44:03
Hello To All,

Actually , I am an avid fan of this forum.

But now ,I want to join some discussion and hopefully am able to contribute into the development.

My waiting interest, is for a Canon G11 to have these following features:

USB/PTP
1) Remote Capture
-capture image and download
-capture-video
2) Remote Zoom

Can anyone point out there some tips:
1)Thread where there is the development of G11 USB/PTP aside form "G11 porting"?
2) Entry point in G11 (Start dumping -> loading USB/PTP scripts into CHDK

Hope I am saying it right

Thank you very much

E^3
Philippines
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / May / 2011, 09:15:42
1)Thread where there is the development of G11 USB/PTP aside form "G11 porting"?
I don't think there is one. All I can find is that ERR99 gave it a shot (http://chdk.setepontos.com/index.php?topic=4647.msg50425#msg50425), but had problems with his setup.

Quote
2) Entry point in G11 (Start dumping -> loading USB/PTP scripts into CHDK
It seems that the required functions are already found* for the G11. Defining CAM_CHDK_PTP in platform/g11/platform_camera.h could be all that is needed to get CHDK PTP to work on the G11. At least for the basic functionality. Try that and see how it goes.

* Some function's addresses (set_control_event, PB2Rec in platform/g11/sub/100?/stubs_entry.S are slightly uncertain. Perhaps you want to make sure these are alright.
Title: Re: CHDK PTP interface
Post by: whim on 06 / May / 2011, 09:44:47
@mweerden

Quote
It seems that the required functions are already found* for the G11. Defining CAM_CHDK_PTP in platform/g11/platform_camera.h could be all that is needed to get CHDK PTP to work on the G11. At least for the basic functionality. Try that and see how it goes.

Note that CAM_CHDK_PTP is already defined by default for all cams (in  /include/camera.h) since r1116

wim
Title: Re: CHDK PTP interface
Post by: msl on 06 / May / 2011, 09:53:25
USB/PTP
1) Remote Capture
-capture image and download
-capture-video
2) Remote Zoom

The G11 should work with the ptp interface.

You can try this (http://chdk.setepontos.com/index.php?topic=6285.msg64905#msg64905) or this (http://chdk.setepontos.com/index.php?topic=6231.0) ptp interface project. Do not forget to install the alternative USB driver.

msl
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / May / 2011, 10:25:15
Note that CAM_CHDK_PTP is already defined by default for all cams (in  /include/camera.h) since r1116
Ah, right. Thanks. I guess I still have to get used to the new situation. ;)
Title: Re: CHDK PTP interface
Post by: dmcdonnell on 06 / May / 2011, 21:11:11
At GitHub (https://github.com/mweerden/CHDKPTPRemote/tree/remote-preview) you can now find my patch for remote live preview as well as a CHDK PTP .NET library (+test app)....

....I've made a separate branch for the remote live preview stuff. The master branch (https://github.com/mweerden/CHDKPTPRemote/) should be compatible with the current CHDK trunk (i.e. CHDK PTP v2.0).

Hi, I'd like to try the remote live preview under linux (ubuntu) using my G9. gphoto2/libgphoto2 are developing nicely and now include some chdk functions, I believe. It appears your code is made for Windoze. How do I get it going under linux? I downloaded the latest G9 chdk build but I guess from your post that I need to compile a special G9 build to enable remote live preview. Thank you and well done!
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / May / 2011, 23:06:05
gphoto2/libgphoto2 are developing nicely and now include some chdk functions, I believe.
Hmm.. interesting. They seem to have added something, but it is based on ewavr's patch. So I'm not sure it works with the current trunk.

Quote
It appears your code is made for Windoze. How do I get it going under linux? I downloaded the latest G9 chdk build but I guess from your post that I need to compile a special G9 build to enable remote live preview. Thank you and well done!
Yeah, you'll need to apply the chdk.patch to the CHDK trunk and build your own binaries. You might need to (re)implement some of the new functions to return the correct sizes for your camera. If you want to get the overlay bitmap you'll certainly have to implement the vid_get_bitmap_active_palette() function.

The code is not made for Windows. It does, however, use a few minor things that seem to require .NET 4.0 (enum's HasFlag is one I can recall at the moment). With a few adjustments it should be ok for .NET 3.5 and usable with Mono on Linux. At a very early stage I did this and was able to run the executable on Linux. I haven't looked at it after that, though. I also don't really know how one goes about compiling the code with Mono, but I don't see why that shouldn't be possible (all relevant stuff seems to be in .cs files). If you try it out, let me know how it goes.
Title: Re: CHDK PTP interface
Post by: E^3 on 09 / May / 2011, 01:08:01

Hi Sir msi,

Good Day..

USB/PTP
1) Remote Capture
-capture image and download
-capture-video
2) Remote Zoom

The G11 should work with the ptp interface.

You can try this (http://chdk.setepontos.com/index.php?topic=6285.msg64905#msg64905) or this (http://chdk.setepontos.com/index.php?topic=6231.0) ptp interface project. Do not forget to install the alternative USB driver.

msl
USB/PTP
1) Remote Capture
-capture image and download
-capture-video
2) Remote Zoom



The G11 should work with the ptp interface.

You can try this (http://chdk.setepontos.com/index.php?topic=6285.msg64905#msg64905) or this (http://chdk.setepontos.com/index.php?topic=6231.0) ptp interface project. Do not forget to install the alternative USB driver.

msl


Actually I learned a lot from your tips(CHDK inside,yet I could find hard times decoding German languages.

Here is what I've done and is not.

my Camera side:
->Camera G11
->Firmware:G11 version100L
->Download CHDK
Where to  download script for USB/PTP compatible with 100L?

My PC side:
Windows:
->Download & Install libusb
->easy to follow
Linux:
1) apt-get install:
subversion
 gcc
 libusb-1.0
 libusb-dev (may be called something like libusb-1.0-dev)
 liblua-5.1
 liblua-5.1-dev

2)copy config-sample-linux.mk to config.mk

3)build it with
$ make

4) LUA path settings

Remarks:
So, I think its more on the Camera side that I will have a hard time.
If ever I've done it successfully then I will blog the steps 123 for all the users/newbie out there.
But now, am just in my learning curve
http://cobecoballes-embedded.blogspot.com/2011/04/canon-g11-remote-capture-chdk.html (http://cobecoballes-embedded.blogspot.com/2011/04/canon-g11-remote-capture-chdk.html)

Thanks to every body

E^3
Title: Re: CHDK PTP interface
Post by: jimb on 03 / June / 2011, 13:03:58
Hoping someone can point in the right direction...

Camera: A560
Firmware: 1.0a

I have installed both the latest CHDK (0.9.9-1196) and the latest CHDK-DE (1.1.0-677). I have installed libusb-win32-1.2.4, ptpCamGui 2.0.99 with its bundled ptpcam, and ptpchdk-r57-win32. The latest version of all of these tools. And, as expected, camera behavior is identical.

However, there are problems. I can Shutdown and Reboot without problem. However, I am unable to use any button on the camera or in the interface. Although I am not sure this should work since the A560 is a VxWorks rather than a DryOS based camera, once I execute the command:

luar post_levent_to_ui(4484)

Then the buttons are usable. But, other commands (such as switching modes, zooming, or timelapse) loop forever performing the command:

luar get_mode()

Title: Re: CHDK PTP interface
Post by: reyalp on 03 / June / 2011, 21:02:52
On some vxworks cameras, switching to record using set_record(1) unlocks the keys. After that you can switch back to play and they are still unlocked. This works for me on a540, so there's a fair chance it will also work on a560.
Title: Re: CHDK PTP interface
Post by: jimb on 04 / June / 2011, 17:11:46
Using set_record(1) did not help to enable the buttons. But luar post_levent_to_ui(4484) does, it is just that I didn't think that it should. But still cannot get the other functions (such as timelapse and change mode) to do anything except loop forever on the luar get_mode() command.
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / June / 2011, 23:59:08
Using set_record(1) did not help to enable the buttons. But luar post_levent_to_ui(4484) does, it is just that I didn't think that it should. But still cannot get the other functions (such as timelapse and change mode) to do anything except loop forever on the luar get_mode() command.
Does set_record(1) switch it into record mode ?

If it does, what does
=return get_mode()
do in chdkptp after calling set_record(1)

In vxworks, switch_mode_usb and set_record do the same thing (switch mode with levent) but maybe this camera needs the dryos style switch_mode since it's right on the transition...
Title: Re: CHDK PTP interface
Post by: jimb on 05 / June / 2011, 00:46:52
Using set_record(1) did not help to enable the buttons. But luar post_levent_to_ui(4484) does, it is just that I didn't think that it should. But still cannot get the other functions (such as timelapse and change mode) to do anything except loop forever on the luar get_mode() command.
Does set_record(1) switch it into record mode ?

If it does, what does
=return get_mode()
do in chdkptp after calling set_record(1)

In vxworks, switch_mode_usb and set_record do the same thing (switch mode with levent) but maybe this camera needs the dryos style switch_mode since it's right on the transition...

Unfortunately, I do not know how to tell if it has switched to record mode. None of the buttons work and nothing in the display changes, so I presume it does not. Following is the output, immediately after initialization of the camera, of the sequence:

set_record(1); get_mode(); click('menu'); post_levent_to_ui(4484); get_mode(); click('menu');

The menu will not come up until after the post_levent_to_ui(4484):

** init() successful
>> luar set_record(1) << script:6
6:ret:nil (Length: 19)
>> luar get_mode() << script:7
7:ret:false (Length: 21)
>> lua click('menu') << script:8 (Length: 8)
>> script-status << script-status:0x0 run=no msg=no (Length: 31)
>> luar post_levent_to_ui(4484) << script:9
9:ret:nil (Length: 19)
>> luar get_mode() << script:10
10:ret:false (Length: 23)
>> lua click('menu') << script:11 (Length: 9)
>> script-status << script-status:0x0 run=no msg=no (Length: 31)

After dozes of times running the get_mode() in various conditions and after many commands, I have never seen it return anything except a false.

In chdkptp the return from get_mode() is always:

> = return get_mode()
9:return:false
9:return:false
9:return:513
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / June / 2011, 01:14:30
Unfortunately, I do not know how to tell if it has switched to record mode.
The lens will extend and the display will switch to live view.
Quote
> = return get_mode()
9:return:false
9:return:false
9:return:513
Looks like it's not switching.
Title: Re: CHDK PTP interface
Post by: jimb on 05 / June / 2011, 08:32:42
Unfortunately, I do not know how to tell if it has switched to record mode.
The lens will extend and the display will switch to live view.
Never does.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / June / 2011, 17:45:56
Unfortunately, I do not know how to tell if it has switched to record mode.
The lens will extend and the display will switch to live view.
Never does.
OK, so mode switch does not work on this camera. Thanks for tracking that down. I would guess it need PB2Rec and REC2Pb like dryos cameras.
Title: Re: CHDK PTP interface
Post by: jimb on 10 / June / 2011, 15:27:38
OK, so mode switch does not work on this camera. Thanks for tracking that down. I would guess it need PB2Rec and REC2Pb like dryos cameras.

I have tried calling the PB2Rec and Rec2PB routines, both using call_func_ptr from lua and calling them from switch_mode_usb. Neither routine seems to do anything and get_mode() still always returns false.

So I made the assumption that the a560 might need something like the DryOS requirement to "disconnect" the USB port. After having tried several options that I thought sounded useful, and combing this thread for other options and trying them (such as DisableNotificationPTP), I have succeeded in some spectacular crashes, but, alas, am no closer to getting mode switching in PTP to work.

Anyone have any other ideas?
Title: Re: CHDK PTP interface
Post by: ntstatic on 11 / June / 2011, 01:55:02
checked the SX120 with PtpCam, PtpCamGui, and CHDKPtp (http://subversion.assembla.com/svn/chdkptp/ (http://subversion.assembla.com/svn/chdkptp/))

one thing is to be noted, which i think someone must have already mentioned in the forums, is that the camera tends to hang or shutdown very frequently if the camera is set to continous autofocus. as soon as i turned off the continous focus all the function become very smooth and stable.

i would think continous focussing must take quite a bit of computing power which would leave the connection and running the scripts prone to errors

next on my list would be to test mweerden's live preview, but i am a little wary about patching and compiling myself - never tried that before, am on a windows machine- but i should thnk it should not be a problem due to the excellent work of everyone involved with CHDK.

any advice or link where i can download an already patched verson for SX 120 ? one can hope, cant one :)
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / June / 2011, 01:27:48
Some notes getting this set up on a fresh win7/64 (no canon or other PTP software installed)

- installed the filter driver (libusb-win32-devel-filter-1.2.4.0.exe  from http://sourceforge.net/apps/trac/libusb-win32/wiki (http://sourceforge.net/apps/trac/libusb-win32/wiki) )
- connected cameras and setup filters in using the "filter wizard"

both cameras show up in chdkptp list, so the filter is installed correctly.

d10
screen goes black afters connecting the camera (or powering on while connected)
can connect and execute lua but cannot switch to record mode or enable the display.
disabling the WIA (Windows Image Acquisition) service *sometimes* prevents this. If an explorer window is open and looking at "my computer" it still goes black. If it's looking at a folder, it seems to be OK.

a540
screen only goes black if I browse into the camera folder, but cannot connect.
disabling WIA does not fix inability to connect.

edit:
Removing the filters and using the inf wizard instead, the both cameras are fully functional. The cameras no longer appear in the windows explorer.
Title: Re: CHDK PTP interface
Post by: melli182 on 13 / June / 2011, 10:54:21
Hello... anyone knows if this is compatible with the canon sx130 or some continous compact model???
Title: Re: CHDK PTP interface
Post by: ntstatic on 13 / June / 2011, 11:03:04
hello mweerden, can you pls help me a little - i am trying to patch CHDK for the live preview
I am using the Compiler Shell V 3.26

it has downloaded the Trunk 1204 and CHDK DE trunk 685

i am facing two problems -
1. the int Trunk 1204 does not list my SX120
however if i go to Source Tools an Apply Patch it basically ends with the following

|Index: core/ptp.h
|===================================================================
|--- core/ptp.h (revision 1174)
|+++ core/ptp.h (working copy)
-- ------------------------
Patching file core/ptp.h using Plan A...
Hunk #1 FAILED at 1.
Hunk #2 FAILED at 30.
2 out of 2 hunks FAILED -- saving rejects to file core/ptp.h.rej
Hmm...  The next patch looks like a unified diff to me...
The text leading up to this was:
--------------------------
|Index: core/luascript.c
|===================================================================
|--- core/luascript.c   (revision 1174)
|+++ core/luascript.c   (working copy)
--------------------------
Patching file core/luascript.c using Plan A...
Reversed (or previously applied) patch detected!  Assume -R? [n] y
Hunk #1 succeeded at 1389 (offset 6 lines).
Hunk #2 FAILED at 1745.
1 out of 2 hunks FAILED -- saving rejects to file core/luascript.c.rej
done


2. if i use CHDK which does indeed list SX120 the patch fails at multiple locations

i am a newbie to this compiling can you point me where the patch may be going wrong

thank you
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / June / 2011, 13:13:17
@nstatic
It's up to you to understand the use off diff/patch. This is not a CHDK problem or a problem with mweerdens patch.

You can look at the .rej files to see what failed. You can probably find some tutorials on working with patches on the internet somewhere. You may also find some gui tools that let you interactively resolve the problems, but understanding the code will still be required to do this successfully. If the original patch was generated with svn, tortoisesvn apply patch is very good, assuming the patch came from the same svn tree.

Note that you should almost certainly not answer yes to the "reversed" question.

The patch should apply cleanly if you start with whatever revision it was made against, but assuming that was from the CHDK tree rather than the CHDKDE tree, you won't have the sx120 so that won't solve your problem.

As you may have realized by now, this is not something you should expect to get working without some hacking...
Title: Re: CHDK PTP interface
Post by: ntstatic on 14 / June / 2011, 10:18:24
@nstatic
It's up to you to understand the use off diff/patch. This is not a CHDK problem or a problem with mweerdens patch.

You can look at the .rej files to see what failed. You can probably find some tutorials on working with patches on the internet somewhere. You may also find some gui tools that let you interactively resolve the problems, but understanding the code will still be required to do this successfully. If the original patch was generated with svn, tortoisesvn apply patch is very good, assuming the patch came from the same svn tree.

Note that you should almost certainly not answer yes to the "reversed" question.

The patch should apply cleanly if you start with whatever revision it was made against, but assuming that was from the CHDK tree rather than the CHDKDE tree, you won't have the sx120 so that won't solve your problem.

As you may have realized by now, this is not something you should expect to get working without some hacking...

oh, i am not implying something is wrong either with the patch or mweerdens code. Very Sorry if that was the impression my previous post gave, it only ment to imply that i am ignorant about what to do :)

it is the first time that i am compiling it for myself

i was just asking if the version(branch?) of the trunk i am using is ok and if the patch should work against it

or if it should work with the CHDK DE current version.

i am not against putting in some ( or considerable ) effort to make it work  :)

i will do as you say and see what failed
Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / June / 2011, 06:41:17
......
i am not against putting in some ( or considerable ) effort to make it work  :)

i will do as you say and see what failed


i managed to pach the files manually (i skipped the G12 and IXUS 870 files) to the CHDK DE trunk 685 and compiled for SX120. it compiled ok  (apart from a warning about a skewed time stamp). i loaded it into the camera and it loaded properly. ptpcam worked ok. 'luar get_video_details()' in ptpcam returns a few funny characters where it used to fail in the non patched version.

i need a little help from the gurus - mweerden, reyalp
where do i go from here - how do i try getting a preview. i have your .net test project compiled but it doesnt give me a preview (it works excellently otherwise !), and also the get overlay and get image buttons are disabled. ill look in to the c# code next but a little help on the way would be welcome
thanks

oh by the way while patching i numbered the ptp to version 2.1 instead of 0x10002.0 - hope that is not the problem.


Title: Re: CHDK PTP interface
Post by: mweerden on 16 / June / 2011, 08:24:30
where do i go from here - how do i try getting a preview. i have your .net test project compiled but it doesnt give me a preview (it works excellently otherwise !), and also the get overlay and get image buttons are disabled. ill look in to the c# code next but a little help on the way would be welcome
thanks

oh by the way while patching i numbered the ptp to version 2.1 instead of 0x10002.0 - hope that is not the problem.
Sounds to me like you are using the master branch instead of the remote-preview one. In the first the buttons are indeed disabled (as that one is intended for unpatched CHDK) and in the other they are always enabled. The latter also needs the version to be 0x10002 (unless you change it as well in CHDKPTPUtil.cs).


Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / June / 2011, 08:35:47
where do i go from here - how do i try getting a preview. i have your .net test project compiled but it doesnt give me a preview (it works excellently otherwise !), and also the get overlay and get image buttons are disabled. ill look in to the c# code next but a little help on the way would be welcome
thanks

oh by the way while patching i numbered the ptp to version 2.1 instead of 0x10002.0 - hope that is not the problem.
Sounds to me like you are using the master branch instead of the remote-preview one. In the first the buttons are indeed disabled (as that one is intended for unpatched CHDK) and in the other they are always enabled. The latter also needs the version to be 0x10002 (unless you change it as well in CHDKPTPUtil.cs).




wow !! that was a lightning reply,  thank you
let me check it out -
i will recompile with 0x10002 and get it working with your settings .
it is indeed possible that i may have downloaded from the master branch. ill download a fresh copy and recompile and get back

thank you again
Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / June / 2011, 09:06:32
Got It mweerden !!

it just proves that even a muggle (http://en.wikipedia.org/wiki/Muggle) can perform tricks (not magic) if a wizard shows how !!!

thank you
it was indeed the master branch and so the two buttons were disabled. also i compiled the trunk with 0x10002.0 in ptp.h (will try updating to 2.1 at ptp.h and the cs file later)
pressing the 'Get Image' gives me an image from the preview.

however 'Get Overlay' does nothing. should i be getting a live moving preview ??
Title: Re: CHDK PTP interface
Post by: mweerden on 16 / June / 2011, 09:46:29
Quote
however 'Get Overlay' does nothing. should i be getting a live moving preview ??
My test program only gets one image when you press the button. If you want something more dynamic you'll have to write the code to repeatedly get the image. Or just press the button rapidly. ;)

As for the overlay, it does get it, but per default it uses an "empty" palette (i.e. every colour is fully transparent). To change that you'll have to patch the CHDK code to send the correct palette for your camera. For the ixus870 you can see how it is done in the patch. This does mean figuring out the right address from the firmware, though. Or you can hack the code to use some made up palette.
Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / June / 2011, 09:56:57
Quote
however 'Get Overlay' does nothing. should i be getting a live moving preview ??
My test program only gets one image when you press the button. If you want something more dynamic you'll have to write the code to repeatedly get the image. Or just press the button rapidly. ;)

ok then ill probably put it on a timer - do you think it will be able to give me around 7-10 fps (rapidly pressing the button gives me a feeling it may be possible)

Quote
As for the overlay, it does get it, but per default it uses an "empty" palette (i.e. every colour is fully transparent). To change that you'll have to patch the CHDK code to send the correct palette for your camera. For the ixus870 you can see how it is done in the patch. This does mean figuring out the right address from the firmware, though. Or you can hack the code to use some made up palette.

ok, will try to do that, thank you

the thing is i need to compile it on a remote machine as mine doesnt have VS 2010. anyways thanks once again i will keep this thread posted on whatever small progress i make
Title: Re: CHDK PTP interface
Post by: mweerden on 16 / June / 2011, 14:53:37
ok then ill probably put it on a timer - do you think it will be able to give me around 7-10 fps (rapidly pressing the button gives me a feeling it may be possible)
When I started working on this I tried it out by just dumping the data to files. This got me about 100 images in 5 to 6 seconds, if I recall correctly. The code on the camera is a bit different now, but I don't think it should matter much.

Also, the C# code I wrote to convert the image to an RGB .NET Image might not be the fastest method to get it on the screen. So I would guess 10 fps should definitely be possible (assuming your camera isn't much slower than mine for some reason).
Title: Re: CHDK PTP interface
Post by: ntstatic on 17 / June / 2011, 01:58:47
ok then ill probably put it on a timer - do you think it will be able to give me around 7-10 fps (rapidly pressing the button gives me a feeling it may be possible)
When I started working on this I tried it out by just dumping the data to files. This got me about 100 images in 5 to 6 seconds, if I recall correctly. The code on the camera is a bit different now, but I don't think it should matter much.

Also, the C# code I wrote to convert the image to an RGB .NET Image might not be the fastest method to get it on the screen. So I would guess 10 fps should definitely be possible (assuming your camera isn't much slower than mine for some reason).


hi mweerden,
just putting a timer and calling the getimagebutton_click() gave me about ( 4 fps ). im just doing a little dirty testing for the moment.

would using overlaybutton_Click() be much different and much faster ? (ill be paching for the pallete for SX 120 next)
i think a little bit of tinkering with the code will juice out around 7-10 fps which should be enough for me for the moment. id like to have more of course if possible. :)

i will post an update on what happens
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / June / 2011, 07:11:13
just putting a timer and calling the getimagebutton_click() gave me about ( 4 fps ). im just doing a little dirty testing for the moment.
That's very low. Perhaps you compiled the program for debugging? If found that setting it to "release" and running it outside of VS made quite a difference.

Quote
would using overlaybutton_Click() be much different and much faster ? (ill be paching for the pallete for SX 120 next)
The overlay is smaller (by a factor 3 in my camera). Processing it should also easier/faster. There might be room for improvement by getting and/or processing the palette less often, but this might have a minimal effect.
Title: Re: CHDK PTP interface
Post by: ntstatic on 17 / June / 2011, 09:58:08
just putting a timer and calling the getimagebutton_click() gave me about ( 4 fps ). im just doing a little dirty testing for the moment.
That's very low. Perhaps you compiled the program for debugging? If found that setting it to "release" and running it outside of VS made quite a difference.
i have indeed compiled for debugging - will try and compile it for release and see. although the gut feeling says the bottleneck is on the camera side. i am almost cretainly wrong as you have recorderded close to 17fps. whatever may be the case, that will be my next step ...

by that time i am converting it to VB.Net (vs2008) so that i can work on my local computer (and think in my local language -basic ;)) and debug it more efficiently. ive almost finished converting it - i am getting the list of ptp devices but not able to connect - i will upload the vb sln if someone is intrested once it is finished.


Quote
Quote
would using overlaybutton_Click() be much different and much faster ? (ill be paching for the pallete for SX 120 next)
The overlay is smaller (by a factor 3 in my camera). Processing it should also easier/faster. There might be room for improvement by getting and/or processing the palette less often, but this might have a minimal effect.
once i convert it to VB and can start thinking i may be able to optimize it a little and use the overlay image if necessary

keep you posted !
Title: Re: CHDK PTP interface
Post by: mweerden on 17 / June / 2011, 12:22:11
i have indeed compiled for debugging - will try and compile it for release and see. although the gut feeling says the bottleneck is on the camera side.
You can try disabling the image processing (and drawing) code. That is, make it just receive the image data from the camera but no do anything with it. This won't necessarily give you the maximum output of the camera, but it might be a lot closer.

Perhaps it could also be you are not using a USB 2.0 port?
Title: Re: CHDK PTP interface
Post by: ntstatic on 18 / June / 2011, 02:23:22
i have indeed compiled for debugging - will try and compile it for release and see. although the gut feeling says the bottleneck is on the camera side.
You can try disabling the image processing (and drawing) code. That is, make it just receive the image data from the camera but no do anything with it. This won't necessarily give you the maximum output of the camera, but it might be a lot closer.

i will do that once the VB Port is complete, i am in a little fix ive got everything on VB but the code fails at
get_video_details() while doing a connect
Sendrequest() - returns ok
ReceiveData() - returns ok
ReceiveResponse() - fails with a timeout at _device.reader.read()

though the problem may be at sendrequest() as i may have messed something and may be sending the command wrong. ill modify your original code to include sent and received response to the log and see what i am doing wrong.

Quote

Perhaps it could also be you are not using a USB 2.0 port?
i always verify that the USB and the Cable is V 2.0 compliant. this was very much the issue while using the camera (older versions SX 110, SX 100, S5, S3 etc) with the CANON SDK which was very picky about V2.0.
however i feel that the connection with CHDK-PTP is much more stable and forgiving.  ;)

just a thought - can a loop be incorporated in to the CHDK itself which will post the image at regular intervals which the receiving program collects - maybe on another thread ? so instead of requesting one instance of the image the command from the computer turns on the feed which the camera posts and another command which can turn it off - maybe suspending the loop while other commands are received if necessary

Title: Re: CHDK PTP interface
Post by: mweerden on 18 / June / 2011, 06:08:42
just a thought - can a loop be incorporated in to the CHDK itself which will post the image at regular intervals which the receiving program collects - maybe on another thread ? so instead of requesting one instance of the image the command from the computer turns on the feed which the camera posts and another command which can turn it off - maybe suspending the loop while other commands are received if necessary
It's possible, I'm pretty sure. Not so sure about why, though. It seems to me that it is much easier and much more flexible to pull from the camera when needed.
Title: Re: CHDK PTP interface
Post by: ntstatic on 18 / June / 2011, 10:49:25
just a thought - can a loop be incorporated in to the CHDK itself which will post the image at regular intervals which the receiving program collects - maybe on another thread ? so instead of requesting one instance of the image the command from the computer turns on the feed which the camera posts and another command which can turn it off - maybe suspending the loop while other commands are received if necessary
It's possible, I'm pretty sure. Not so sure about why, though. It seems to me that it is much easier and much more flexible to pull from the camera when needed.
i would still like to try it once this porting thing s complete. well the problem was the difference in how bit shifting works in c# and vb i think. 
byte a=10; a<<8; would give 2560 in c# i assume, while vb returns 10

well finally i am able to connect to the camera and run the commands. the picture code particularly the conversion to rgb remains to be checked for the same issue (doesnt work) i think i should be able to finish it in a day or two
Title: Re: CHDK PTP interface
Post by: ntstatic on 20 / June / 2011, 02:10:14
ok so now i am getting the image too, and i think the port is complete...
seems a (sbyte)x works differently than csbyte(x) in vb. if x is a byte and exceeds 127 vb throws an exception while c# quitely converts it to a signed byte.

so here is the source (before i mess it up ;))
http://www.megaupload.com/?d=XUTRK44S (http://www.megaupload.com/?d=XUTRK44S)

pls note that i have done nothing other than translate mweerdens' excellent code, so he is to be thanked if anyone uses the code. Also note that any bugs which may have crept in during translation are entirely mine :)

Title: Re: CHDK PTP interface
Post by: ntstatic on 22 / June / 2011, 08:52:31
@mweerden
is it possible by any chance to get a bigger preview image. i am getting a 360x240. any possibility, it can be around something like 640x480 or so  :)

if not any other way in which i can achieve a 5fps at a higher resolution maybe continous shooting - i would be needing 5fps for a minute totalling to 300images.
Title: Re: CHDK PTP interface
Post by: mweerden on 22 / June / 2011, 09:50:09
@mweerden
is it possible by any chance to get a bigger preview image. i am getting a 360x240. any possibility, it can be around something like 640x480 or so  :)
Depends on what your camera provides and how much work you are willing to do.

For my ixus870 the actual size of the live image is 720x240 (so it is stretched) and I know the G12 has one that is 720x480. In my test app I just always scale the image (and overlay) to 360x240.

I'm pretty sure this format is fixed (i.e. per camera). The only way I see to get more is to somehow access the real raw data provided by the sensor. I have no idea about the possibilities of this. I do know that it means transferring more data and thus likely a (much) lower fps. Only solution to that would be compression before transfer, but that would mean figuring out how to use the camera's dedicated hardware for this or somehow letting the camera just take pictures/movies like normal and directly stream it to your PC. As far as I know the knowledge for these kinds of things is currently not available.
Title: Re: CHDK PTP interface
Post by: ntstatic on 23 / June / 2011, 01:31:30
@mweerden
is it possible by any chance to get a bigger preview image. i am getting a 360x240. any possibility, it can be around something like 640x480 or so  :)
Depends on what your camera provides and how much work you are willing to do.

For my ixus870 the actual size of the live image is 720x240 (so it is stretched) and I know the G12 has one that is 720x480. In my test app I just always scale the image (and overlay) to 360x240.

I'm pretty sure this format is fixed (i.e. per camera). The only way I see to get more is to somehow access the real raw data provided by the sensor. I have no idea about the possibilities of this. I do know that it means transferring more data and thus likely a (much) lower fps. Only solution to that would be compression before transfer, but that would mean figuring out how to use the camera's dedicated hardware for this or somehow letting the camera just take pictures/movies like normal and directly stream it to your PC. As far as I know the knowledge for these kinds of things is currently not available.
how do i go about knowing what my camera can provide. its a SX120 and in future i am planning to be working on a SX 130 ( it may be possible to get the SX 200 series ). 720x480 is still a 4 fold improvement and i can live with it for the moment :) if it is possible on the SX 120 or the 200 series.
Quote
Depends on what your camera provides and how much work you are willing to do.
there no problem with me putting in the effort. only problem is my limited exposure to this kind of source. still can you guide me what may be needed to do so that i can evaluate if it is in realm of my current capabilities ;).
Title: Re: CHDK PTP interface
Post by: philmoz on 23 / June / 2011, 01:42:38
... and I know the G12 has one that is 720x480.

Are you sure?
The G12 has the same resolution live view buffer as all the other recent cameras - 720x240.

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 23 / June / 2011, 09:15:45
i would like to try and patch CHDK to provide two function in the tune of

enable_video_transfer()
disable_video_transfer()

the enable video transfer would provide a preview image or overlay at regular intervals.

can the gurus (mweerden, philmoz, reyalp ...)  guide me and point me if there is a background timer function or a system function which goes on in the background and which i can hook into to provide this.

i dont think this should be run as a lua script - pls correct me if i am wrong or if the whole idea is ridiculous

Title: Re: CHDK PTP interface
Post by: mweerden on 23 / June / 2011, 09:38:25
... and I know the G12 has one that is 720x480.

Are you sure?
The G12 has the same resolution live view buffer as all the other recent cameras - 720x240.
Reasonably sure, but I admit I haven't checked it myself. My remote-preview code has been tested by someone with a G12. The code uses its own functions for widths and heights that default to 720x240 for the viewport. This gave only the upper half of the viewport. Changing the height to 480 gave everything. So unless I'm missing something crucial, the viewport should be 720x480 on the G12.
Title: Re: CHDK PTP interface
Post by: funnel on 23 / June / 2011, 09:57:25
Quote
Are you sure?
The G12 has the same resolution live view buffer as all the other recent cameras - 720x240.

Phil.

 In sx220 the livefb buffer size is 960x720. I found the buffer size here
Code: [Select]
FF371D70 loc_FF371D70                            ; CODE XREF: sub_FF371C18+13Cj
FF371D70                 CMP     R2, R0
FF371D74                 BHI     loc_FF371D58
FF371D78                 STR     R5, [R8,#0xC]
FF371D7C                 MOV     R2, R6
FF371D80                 MOV     R1, R5
FF371D84                 ADR     R0, aMaxyLdMinyLd ; "MaxY %ld MinY %ld\r"
FF371D88                 STR     R6, [R8,#0x10]
FF371D8C                 BL      sub_FF15334C
FF371D90                 LDR     R0, [R8,#8]
FF371D94                 STR     R0, [R10]
FF371D98                 LDR     R0, [R8,#4]
FF371D9C                 LDR     R1, [R8]
FF371DA0                 MOV     R2, R0,LSL#2
FF371DA4                 LDR     R0, [R9]
FF371DA8                 BL      sub_FF060874
FF371DAC                 LDR     R2, =0xA8C00                //960x720
FF371DB0                 LDR     R1, =0x405D7980
FF371DB4                 LDR     R0, [R9,#4]
FF371DB8                 BL      sub_FF060874
FF371DBC                 MOV     R0, R4
FF371DC0                 BL      j_free
FF371DC4                 LDR     R0, [R8]
FF371DC8                 LDMFD   SP!, {R4-R12,PC}
Title: Re: CHDK PTP interface
Post by: mweerden on 23 / June / 2011, 10:07:18
how do i go about knowing what my camera can provide.
Looking it up online, in the CHDK code or in the firmware. And by experimentation.

Regarding the resolution of the viewport buffer, if you didn't change the patch related to this and you're getting the full image, then it's 720x240. And, as said before, this is almost certainly fixed.

Quote
there no problem with me putting in the effort. only problem is my limited exposure to this kind of source. still can you guide me what may be needed to do so that i can evaluate if it is in realm of my current capabilities ;).
One thing you probably need is functions to send commands to the host instead of the other way around. This means disassembling the firmware and trying to find such functions (or functions that allow you to build it yourself). Unless you have quite some experience reverse engineering like this, I don't expect it is something that you can pick up easily.

As for timing, I guess you could start a separate task and just call msleep. It probably isn't very accurate or reliable though. I'm sure there are some other timing facilities elsewhere; I expect the firmware to need it as well.

pls correct me if i am wrong or if the whole idea is ridiculous
I wouldn't go as far as calling it ridiculous, but I really don't see the point. It's much easier to regularly pull from the PC and I can't see any advantage in pushing from the camera.
Title: Re: CHDK PTP interface
Post by: ntstatic on 24 / June / 2011, 03:52:30
how do i go about knowing what my camera can provide.
Looking it up online, in the CHDK code or in the firmware. And by experimentation.

Regarding the resolution of the viewport buffer, if you didn't change the patch related to this and you're getting the full image, then it's 720x240. And, as said before, this is almost certainly fixed.

Quote
there no problem with me putting in the effort. only problem is my limited exposure to this kind of source. still can you guide me what may be needed to do so that i can evaluate if it is in realm of my current capabilities ;).
One thing you probably need is functions to send commands to the host instead of the other way around. This means disassembling the firmware and trying to find such functions (or functions that allow you to build it yourself). Unless you have quite some experience reverse engineering like this, I don't expect it is something that you can pick up easily.

As for timing, I guess you could start a separate task and just call msleep. It probably isn't very accurate or reliable though. I'm sure there are some other timing facilities elsewhere; I expect the firmware to need it as well.

pls correct me if i am wrong or if the whole idea is ridiculous
I wouldn't go as far as calling it ridiculous, but I really don't see the point. It's much easier to regularly pull from the PC and I can't see any advantage in pushing from the camera.

ok thank you for the detailed explanation. i think for the moment i would try to optimize the routine pulling the image from the pc side, like you suggested. also my absolute requirement is only 5 fps and anything more is only for cosmetic purposes. :)

it is only that i was using the previous version - SX 110 and previous - with the canon sdk and it provided a fluent preview. i had SX110 worth a year's stocked but alas they are over. CHDK team and particularly you mweerden have been a lifesaver for me. thank you once again. previously i was thinking about using a video grabber and combining the cables for usb and video ( i used to do that in olympus a couple of years back when they were supported by their SDK ) but for the sx120, the problem is that the video out is not clean and there is at least an overlay of the focus rectangle and a +0 of the ev value. i need a clean video intermittently. i could do that by going to the Video Rec mode and keeping the shoot button half pressed for the duration i wanted to grab the low quality frames. getting a live preview with your patch is 100 times better

and, yes i am getting the whole image in the image preview so it is pretty much settled for the moment 720(360) x 240.

so i would try getting the overlay instead of the bitmap which should be around 3x smaller (like you mentioned). any pointers as to how i should locate the location for the palette in my camera SX120 ?

Title: Re: CHDK PTP interface
Post by: mweerden on 24 / June / 2011, 10:58:26
it is only that i was using the previous version - SX 110 and previous - with the canon sdk and it provided a fluent preview.
Which also suggest the camera shouldn't be the bottleneck (although the firmware might have used compression; which might be interesting to look into). In any case, reversing the roles should have no (significant) effect on the speed.

Quote
so i would try getting the overlay instead of the bitmap which should be around 3x smaller (like you mentioned). any pointers as to how i should locate the location for the palette in my camera SX120 ?
The overlay is the bitmap and note that it does not contain the live image. I found the palette for my camera in the firmware by comparing it with where ewavr found it for other cameras, if I remember correctly. So you'll need two firmware disassemblies, one where you know where it is and the other of your own camera.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / June / 2011, 16:01:38
it is only that i was using the previous version - SX 110 and previous - with the canon sdk and it provided a fluent preview.
Which also suggest the camera shouldn't be the bottleneck (although the firmware might have used compression; which might be interesting to look into)
I would bet that the canon firmware jpeg'd the live view before sending it, using something similar to whatever does the mjpeg for video.

In fact, there are references to this in canon (non-chdk) code in ptpcam (ptp.c)
Code: [Select]
* ptp_canon_getviewfinderimage:
 * This operation can be used to read the image which is currently
 * in the camera's viewfinder. The image size is 320x240, format is JPEG.
 * Of course, prior to calling this operation, one must turn the viewfinder
 * on with the CANON_ViewfinderOn command.
 * Invoking this operation many times, one can get live video from the camera!
It's not clear what generation of Canon camera this refers to.

This also shows that the Canon SDK probably used polling just mweerdens code. This isn't a surprise, AFAIK USB up to 2.0 doesn't really have device initiated communications, at the lowest level everything is initiated by the host, even though the software stack might expose it as an event. I could be wrong here, my understanding of USB is fairly limited...
Title: Re: CHDK PTP interface
Post by: ntstatic on 25 / June / 2011, 07:07:13
it is only that i was using the previous version - SX 110 and previous - with the canon sdk and it provided a fluent preview.
Which also suggest the camera shouldn't be the bottleneck (although the firmware might have used compression; which might be interesting to look into)
I would bet that the canon firmware jpeg'd the live view before sending it, using something similar to whatever does the mjpeg for video.

In fact, there are references to this in canon (non-chdk) code in ptpcam (ptp.c)
Code: [Select]
* ptp_canon_getviewfinderimage:
 * This operation can be used to read the image which is currently
 * in the camera's viewfinder. The image size is 320x240, format is JPEG.
 * Of course, prior to calling this operation, one must turn the viewfinder
 * on with the CANON_ViewfinderOn command.
 * Invoking this operation many times, one can get live video from the camera!
It's not clear what generation of Canon camera this refers to.

This also shows that the Canon SDK probably used polling just mweerdens code. This isn't a surprise, AFAIK USB up to 2.0 doesn't really have device initiated communications, at the lowest level everything is initiated by the host, even though the software stack might expose it as an event. I could be wrong here, my understanding of USB is fairly limited...

Canon most certainly compresses (used to compress - for thepowershots) the live feed as there were heavy compression artifacts in the image. and both your and mweerden's explanation makes me realize that it is indeed true that camera with a USB 2.0 should not be a bottleneck.

i think i must download the source for libptp and study it !. thank you for pointing it reyalp!

Quote
The overlay is the bitmap and note that it does not contain the live image. I found the palette for my camera in the firmware by comparing it with where ewavr found it for other cameras, if I remember correctly. So you'll need two firmware disassemblies, one where you know where it is and the other of your own camera.
i dont think i totally understand mweerden - "does not contain the live image" part. what does it contain. i was under the impression that get_bitmap and bet_overlay were .....

ok so the overlay returns what ever is overlaied on the live image ? please be patient if i am being soooo stupid ... ( a stupid student always taxes the wise teacher  ;) )

so the get image gets the live feed and the overlay the matter overlaied on the image on the lcd ??
Title: Re: CHDK PTP interface
Post by: mweerden on 25 / June / 2011, 11:43:46
i dont think i totally understand mweerden - "does not contain the live image" part.
You already know what the live image (a.k.a. viewport) is: the image produced by the camera sensor (or at least a derivative of it).

The overlay (a.k.a. bitmap) is the rest. ;) The focus rectangle, the mode information etc. Also the menus are drawn on the overlay. The parts of the overlay that are transparent allow you to see the live image. It is superimposed (or overlaid ;)) on the live image.
Title: Re: CHDK PTP interface
Post by: mweerden on 25 / June / 2011, 12:07:30
B.t.w., as said a while back, you can also just manually fill in (part of) the palette to see what is in the overlay.
Title: Re: CHDK PTP interface
Post by: vino on 27 / June / 2011, 12:09:39
I have been using CHDK for a year or so and I am now experimenting with ptpCamGui.

So far I have failed to get ptpCamGui to connect to a camera.  I have tried two computers, three different cameras (A590is 1.00E, A590 101B, SX110 1.00B).  In all cases, ptpCamGui waits for the camera and then resets, over and over.  No error messages are generated.

libusb-win32 is installed and seems to be working for each camera.  When a camera is attached to a USB port, Windows device manager lists the camera in the Imaging devices category with a warning that Windows "cannot load the device driver".  This appears to be as intended.

Perhaps the camera is not in the correct state or I have not followed the necessary start up sequence.  Can you suggest how I should proceed?

 ???


Title: Re: CHDK PTP interface
Post by: whim on 27 / June / 2011, 13:32:13
@vino

This (http://chdk.setepontos.com/index.php?topic=6285.msg64905#msg64905) might help.

Also, it seems a service installed by the Canon tools (ZoomBrowser etc.) conflicts with libusb ...
I'm told it's called something like "CAlib8" - you might want to look into temporarily disabling this service,
if you have the Canon USB tools installed.

hope that helps,

wim
Title: Re: CHDK PTP interface
Post by: achillies on 01 / August / 2011, 11:30:17
I was under the impression that a person could use either the internal ptpcam (ptpcam.dll), or an external one (ptpcam.exe).

Is this possible, and if so how?
Title: Re: CHDK PTP interface
Post by: rudi on 01 / August / 2011, 17:22:28
Hi achillies,

ptpcam.dll is a adaptor between windows applications and ptpcam.exe. The dll need ptpcam.exe. If ptpcam.exe not found on directory, only then extract ptpcam.dll an internal version of ptpcam.exe. The dll only clean up an internal ptpcam.exe on exit.

rudi
Title: Re: CHDK PTP interface
Post by: Microfunguy on 02 / August / 2011, 07:21:12
I have written a ColorTab-Viewer (http://chdk.bplaced.net/extra/ColorTab.zip).

can you upload this somewhere else ?

Thanks.

David
Title: Re: CHDK PTP interface
Post by: msl on 02 / August / 2011, 08:35:21
can you upload this somewhere else ?

Ok, the file is back online, same link. But this is not my work, rudi has this programmed!

msl
Title: Re: CHDK PTP interface
Post by: Microfunguy on 02 / August / 2011, 09:30:19
Thanks.

It seems that Rudi does some good work, too bad I cannot read German.

Did anyone ever manage to compile or adapt EWAVR's CHDKCAM code ?

Reyalp made a comment (somewhere) that certain of that code had been removed (from where ?) and he hoped to replace it one day.

I am assuming at a required framerate of 10 fps the camera does not have the memory or computing power to reduce framesize to 160x120 and compress before transmission ?

Presumably at the camera end you only need to implement PTP_CHDK_GetVideoSettings for each supported camera ?

I have no idea how you would display it at the PC end.

EWAVR seems to have made use of a DirectShow filter VCamFilter.ax supplied with "e2eCam, A WDM capture driver that requires no hardware."

Somehow, CHDKCAM must repeatedly requests frames from the camera using ptp_chdk_get_memory() and copy them to livebuf,crop the active area (if necessary) and convert to RGB.

I guess the location of that buffer is then used by e2ecam.

GDI+ is used for something, have not studied it and don't know if I can compile it with the Borland C++ 5.5 that I have downloaded.


David
Title: Re: CHDK PTP interface
Post by: mweerden on 02 / August / 2011, 11:46:41
Did anyone ever manage to compile or adapt EWAVR's CHDKCAM code ?
Does this (http://chdk.setepontos.com/index.php?topic=4338.msg66042#msg66042) qualify?
Title: Re: CHDK PTP interface
Post by: Microfunguy on 02 / August / 2011, 12:06:10
Thanks Muck !
Some serious study required and I will inevitably have to message you with detailed questions.

There is so much information on the forum now that  it is difficult to find the topic of interest unless you were somehow associated with it.


David
Title: Re: CHDK PTP interface
Post by: Microfunguy on 06 / August / 2011, 08:38:12
No one said this would be easy but it is so tedious ....

CHDKCAM performs most functions by sending Lua commands to camera.
I send uBasic commands.

Problem is, the script data is being 'corrupted' at the camera end in a rather bizarre way .

I have found that the same thing happens when using the upload function of the original ptpcam modified for CHDK.

So, I have loaded the CHDKDE code on the camera and ptpcamGui.
In the console this works :-

download A/diskboot.bin  D/test.bin

Good, so I can test this :-

upload D/test.bin A/test.bin

That does not work, no file from any directory can be uploaded because ptpCamGui console cannot open it.

EDIT
Unlike ptpcam that I normally use, ptpCamGui does not like capitals in filename
It also does not like the current directory letter being included in the pathname.

What version of ptpcam.exe is being used and is the source online ?

With my script data, two 0xFF are being inserted at the end and the rest of the data pushed to the left but not beyond character 36.

(The 'end' was added at the camera end.)

See attached file below :-

Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / August / 2011, 07:46:32
Deleted.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 15 / August / 2011, 06:53:28
- rudi has now implemented a very nice multi camera feature. You can use more than one camera with the GUI. Every Camera get a unique identification number.

Is that discussed in the German forum ?


David
Title: Re: CHDK PTP interface
Post by: msl on 15 / August / 2011, 09:16:04
Is that discussed in the German forum ?

Yes, a little bit.

http://forum.chdk-treff.de/viewtopic.php?p=21155#p21155 (http://forum.chdk-treff.de/viewtopic.php?p=21155#p21155)
http://forum.chdk-treff.de/viewtopic.php?p=21173#p21173 (http://forum.chdk-treff.de/viewtopic.php?p=21173#p21173)
http://forum.chdk-treff.de/viewtopic.php?p=21493#p21493 (http://forum.chdk-treff.de/viewtopic.php?p=21493#p21493)

But this feature was not really useable. Not every camera sends a unique id (older Vxworks cams). The system was instable. Therefore this feature was removed again in the ptpCamGui.

msl
Title: Re: CHDK PTP interface
Post by: Microfunguy on 15 / August / 2011, 09:35:15


Yes, a little bit.


Thanks.

Let us hope Google translate does a decent job.

I guess further research will also be needed.
Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / August / 2011, 10:35:23
as i posted previously ive got almost everything working with mweerden's code with live preview on the SX 120.
I ported the patch for the SX 130 ver101f and everything seems to be ok. however i have noticed something strange.
at around 1/8 th of the total zoom ( and even at higher zooms) if i take a snap using the ptp interface there is significant pincushion distortion which is absent if i take the snap by pressing the button physically.

is it possible that the lua shoot() function is skipping some correction routine which is called after the normal button press ??
has this been observed in other models ??
any help is greatly appreciated.
Title: Re: CHDK PTP interface
Post by: ntstatic on 18 / August / 2011, 02:17:18
in followup to the above post philimoz was lightning fast in providing an update for the SX 130 and the pincushion distortion was solved

i am glad to note that mweerden's live preview works like a charm on his so graciously provided .net source on the SX 130 and the patched binary can be downloaded from the SX 130 thread or this post http://chdk.setepontos.com/index.php?topic=5691.msg71903#msg71903 (http://chdk.setepontos.com/index.php?topic=5691.msg71903#msg71903)
Title: Re: CHDK PTP interface
Post by: philmoz on 20 / August / 2011, 01:47:17
Played with mweerden's code on the G12/SX30/IXUS310.

Managed to figure out the OSD bitmap palette for these newer cameras, so I can get both the live view and OSD overlay.

Attached is a screen shot of IXUS310 using a modified version of mweerden's test PTP program & library.

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 02 / September / 2011, 08:28:48
hi phil,
any progress on your changes to the live preview or adding it to the trunk. ?

not that everything is not working as it should, just as it is, just hoping to get a little more juice out of it. at the moment im getting around 7fps. i know it is the code at my client side which is to be blamed but was hoping to optimize it only after the thing got incorporated in the trunk so that i do not have to worry about patching every time the trunk changes, :)
Title: Re: CHDK PTP interface
Post by: philmoz on 02 / September / 2011, 08:48:31
hi phil,
any progress on your changes to the live preview or adding it to the trunk. ?

not that everything is not working as it should, just as it is, just hoping to get a little more juice out of it. at the moment im getting around 7fps. i know it is the code at my client side which is to be blamed but was hoping to optimize it only after the thing got incorporated in the trunk so that i do not have to worry about patching every time the trunk changes, :)

Had a busy week last week, then went whale watching over the weekend - actually took some photos for a change :)

I sent the the latest code to mweerden for review a couple of days ago - so I should have something to put into the core code soon.

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 02 / September / 2011, 09:44:14
Quote

Had a busy week last week, then went whale watching over the weekend - actually took some photos for a change :)


hope u had a good time :)
Title: Re: CHDK PTP interface
Post by: philmoz on 02 / September / 2011, 20:02:51
Quote

Had a busy week last week, then went whale watching over the weekend - actually took some photos for a change :)


hope u had a good time :)

Yes, saw lots of whales and they were very curious and came right up to the boat.
Didn't get any shots of them breaching unfortunately; but got a few that I'm happy with (http://www.pbase.com/phil_a_mitchell/whalewatching (http://www.pbase.com/phil_a_mitchell/whalewatching))

Attached are two files.
The first is the PTP code patch for CHDK & SX130. If it works then this is what will be put into SVN for live view.
The second is my current test .Net code (based on mweerden's original).

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 03 / September / 2011, 09:53:29
hi phil,
managed to patch the DE version that i had and it compiled ok after a bit of tweaking

however could not compile your .net app as it is in a newer version (vs 2008) i could try adding the files manually and tweaking the few incompatible function but if you could just post the binary for the moment i could verify that the thing works ok
your old binary posted on the 130 forum does not recognize the cam - probably due to the PTP vers 2.1-

by the way....
excellent pics !!
Title: Re: CHDK PTP interface
Post by: mweerden on 03 / September / 2011, 10:03:28
your old binary posted on the 130 forum does not recognize the cam - probably due to the PTP vers 2.1-
You can also change the CHDK code (see core/ptp.h) to match the version, but that won't help here as the code is incompatible, I'm sure.
Title: Re: CHDK PTP interface
Post by: ntstatic on 03 / September / 2011, 10:09:16
yes mweerden i thought about that - i just mentioned it because i did try it !
Title: Re: CHDK PTP interface
Post by: ntstatic on 03 / September / 2011, 10:18:07
though i dont think much has changed - which is the feeling i got while copying the changes from the patch file.

by the way is there a better way to patch - i am using the DE version with CHDK Shell and the patch always fails
ive since stopped trying to apply the patch and just make the changes in an editor
Title: Re: CHDK PTP interface
Post by: mweerden on 03 / September / 2011, 10:50:06
by the way is there a better way to patch - i am using the DE version with CHDK Shell and the patch always fails
ive since stopped trying to apply the patch and just make the changes in an editor
This depends on the problem. If CHDK-DE doesn't differ too much in the changed files, patching shouldn't be much of a problem. There might be an issue with line endings, though, which seem to be able to confuse the patch tool.
Title: Re: CHDK PTP interface
Post by: philmoz on 03 / September / 2011, 18:29:50
hi phil,
managed to patch the DE version that i had and it compiled ok after a bit of tweaking

however could not compile your .net app as it is in a newer version (vs 2008) i could try adding the files manually and tweaking the few incompatible function but if you could just post the binary for the moment i could verify that the thing works ok
your old binary posted on the 130 forum does not recognize the cam - probably due to the PTP vers 2.1-

by the way....
excellent pics !!

Compiled version attached.
One note, there is a checkbox to 'autoupdate' the live view (also calculates the frame rate).
If you have this checked it will crash if you try and send other commands to the camera (it needs to stop the autoupdate before sending the command; but I haven't coded this yet).

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 05 / September / 2011, 01:30:42
runs ok gives me around 5.5fps
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / September / 2011, 18:35:22
I see philmoz added live view support in trunk changeset 1316 (http://tools.assembla.com/chdk/changeset/1316/trunk)

This is useful, commonly requested functionality. It has sat on the back burner for far to long, and that's mostly my fault. I appreciate the effort both mweerden and philmoz have put into it.

That said, the implementation leaves me shaking my head.

Why is there PTP code in luascript.c (so lua can return a pointer to a static I guess but ...) ?
Why are we overloading PTP_CHDK_CallFunction with new magic behavior ?
Why are we passing a single hard coded address of a function from Lua (in a struct stuffed into a binary string), to the PTP client just so the PTP client can just pass it back for CHDK to call it ? How is this preferable than just making another CHDK PTP opcode that calls the function ? We have 2^32 available...
Why are we involving Lua at all when we are just passing back a hard-coded binary blob ? Sure, some of these values might be useful for other things, but this is not a very usable format. If that blob ever changes, it will be an incompatible protocol revision.
Why are there magic numbers all over the place ?

Guess this is what I get for not looking at it sooner...  :(

I understand the desire to get something working, but we've already reached the point where CHDK is nearly unmaintainable due to people piling on half baked hacks. We really need a development branch or something where we can refine larger features like this without worrying too much about compatibility in the intermediate revisions.
Title: Re: CHDK PTP interface
Post by: philmoz on 05 / September / 2011, 20:33:11
I see philmoz added live view support in trunk changeset 1316 (http://tools.assembla.com/chdk/changeset/1316/trunk)

This is useful, commonly requested functionality. It has sat on the back burner for far to long, and that's mostly my fault. I appreciate the effort both mweerden and philmoz have put into it.

That said, the implementation leaves me shaking my head.

Why is there PTP code in luascript.c (so lua can return a pointer to a static I guess but ...) ?
Why are we overloading PTP_CHDK_CallFunction with new magic behavior ?
Why are we passing a single hard coded address of a function from Lua (in a struct stuffed into a binary string), to the PTP client just so the PTP client can just pass it back for CHDK to call it ? How is this preferable than just making another CHDK PTP opcode that calls the function ? We have 2^32 available...
Why are we involving Lua at all when we are just passing back a hard-coded binary blob ? Sure, some of these values might be useful for other things, but this is not a very usable format. If that blob ever changes, it will be an incompatible protocol revision.
Why are there magic numbers all over the place ?

Guess this is what I get for not looking at it sooner...  :(

I understand the desire to get something working, but we've already reached the point where CHDK is nearly unmaintainable due to people piling on half baked hacks. We really need a development branch or something where we can refine larger features like this without worrying too much about compatibility in the intermediate revisions.

Hi reyalp,

Thanks for the feedback, here's a summary of some of the discussion I had with mweerden.

I can't comment on the PTP_CHDK_CallFunction, that was there when I started looking at it (I assumed this was something already worked out).

Putting the live view code in Lua makes sense to me (mweerden convinced me of this).
Almost everything else done in regards to controlling the camera via PTP is done via Lua code - it made sense to do this the same way rather than put the live view as a special PTP function.

The current structure is pretty localised in terms of changes to CHDK, and minimises the number of calls between the client and camera to get the live view info (I played around with different options; but this was the fastest in terms of achievable frame rate). I'm not sure how else you could do something like this without passing data structures around - there's a reasonable amount of information required and some of it can change between calls.

I agree changes to the data structures could cause problems if not done carefully; but, short of using XML, I don't know how else you could do this.

I tried sending back the viewport/bitmap/palette buffer addresses and then using the PTP 'get memory' call to retrieve the data - but it was a lot slower for some reason. Plus there's more chance the buffer address will change between the time the client gets it and the time it uses it to get the data.

Not sure what magic numbers you are referring to; but these can always be changed to constants if it makes the code more readable?

None of this is set in stone, there are no real clients using it - the goal was to get something that was being used and tested to a point where active development on clients could proceed without having to constantly patch the source. A lot of testing was done by nstatic on the SX130 as well as my testing on the G12/SX30/IXUS310. This could have been in a different branch; but then you have to deal with the metadata mess in SVN every time you want to merge.

There's still plenty of scope for improving the way this is done.

I'd actually consider this to be a reasonably small change, it's localised and (apart from the PTP change) doesn't affect anything else. The amount of extra code is also pretty small.

Phil.

Title: Re: CHDK PTP interface
Post by: mweerden on 05 / September / 2011, 21:37:45
My two cents:

It seems your main point is about adding functionality to Lua vs. adding it to CHDK PTP. At least, most of the big things you question seem to be a consequence of this choice.

I think the rationale has been given in the past, but it comes down to me having preferred a minimal CHDK PTP. And a large argument for that is that adding more to it makes incompatible protocol revisions more likely. The new functionality is not a part of CHDK PTP, just something that is used through it.

Below some more detailed answers to the specific questions.

Why is there PTP code in luascript.c (so lua can return a pointer to a static I guess but ...) ?
As said, I don't see it as PTP code. However, there is little consequence (if any) if you wish to move it to a different location.

Quote
Why are we overloading PTP_CHDK_CallFunction with new magic behavior ?
Why is it magic? I believe it's properly defined and on purpose in a way that is non-specific to the remote live view functionality.

Quote
Why are we passing a single hard coded address of a function from Lua (in a struct stuffed into a binary string), to the PTP client just so the PTP client can just pass it back for CHDK to call it ? How is this preferable than just making another CHDK PTP opcode that calls the function ? We have 2^32 available...
The core question, as discussed above.

Quote
Why are we involving Lua at all when we are just passing back a hard-coded binary blob ? Sure, some of these values might be useful for other things, but this is not a very usable format. If that blob ever changes, it will be an incompatible protocol revision.
Apart from what I've said so far, because Lua is (at this moment) the only way we can call a named function.

The format is not very usable from within Lua itself, but the alternatives I saw when I started this were a function that returns a Lua structure with the information or separate functions for each of the values. Both I found less practical in their actual use and the second also meant adding a lot more clutter to Lua. Besides, I'm not sure that use of this information within Lua is ever going to be of any significance.

Changes to "the blob" that will lead to incompatibility with previous revisions will have the same effect in pretty much any other way remote live view can be implemented, I'd think. Unless the actual meaning of certain values has to be adjusted, I believe the code is pretty robust against possible future extensions.

Quote
Why are there magic numbers all over the place ?
I believe "all over the place" isn't entirely fair. In any case, it's not so much criticism on the new features as something that I'm sure can be easily taken care of if asked.

Quote
I understand the desire to get something working, but we've already reached the point where CHDK is nearly unmaintainable due to people piling on half baked hacks. We really need a development branch or something where we can refine larger features like this without worrying too much about compatibility in the intermediate revisions.
And, as happens often, we come to the bigger discussion. I believe I've spoken my mind about it before, so I'll try to restrain myself. Fact is that things are the way they are and they don't seem likely to change significantly any time soon. "Don't forget what the H stands for." comes to mind.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / September / 2011, 22:25:54
I can't comment on the PTP_CHDK_CallFunction, that was there when I started looking at it (I assumed this was something already worked out).
Fair enough. This feels like the wrong way to do it to me. I can sort of see the argument that you might want other functions that produce a similar stream of data, but passing them around seems suspect to me. Since these functions would have to be defined in CHDK code anyway, it's not as if clients are going to make these up on the fly.

Also, if you did end up with multiple functions like this, you'd want to combine all the data together rather than polling them independently.
Quote
Putting the live view code in Lua makes sense to me (mweerden convinced me of this).
Almost everything else done in regards to controlling the camera via PTP is done via Lua code - it made sense to do this the same way rather than put the live view as a special PTP function.
I'm not convinced of this. It doesn't make sense to handle the live view data (framebuffer/palette etc) in Lua, so passing this one chunk a different way seems needless complexity. You already need a non-lua part on both ends to handle the data, and you are already sending *some* of the information about framebuffer layout with that. If you could sanely do the whole thing in Lua, I'd be all for that.
Quote
I agree changes to the data structures could cause problems if not done carefully; but, short of using XML, I don't know how else you could do this.
If you are going to use Lua, put it in a Lua table. That gives you a nice key/value representation, without the overhead of XML.
Quote
I tried sending back the viewport/bitmap/palette buffer addresses and then using the PTP 'get memory' call to retrieve the data - but it was a lot slower for some reason. Plus there's more chance the buffer address will change between the time the client gets it and the time it uses it to get the data.
This all makes sense. I agree with packing them together like this. In fact, I would like to take this one step further, which I'll get to in another post.
Quote
None of this is set in stone, there are no real clients using it - the goal was to get something that was being used and tested to a point where active development on clients could proceed without having to constantly patch the source.
The problem is the trunk is the build used by end users, so the "not-set-in-stone" bit has the potential to come back and bite you. But I agree, we need something to work from without constantly shuffling patches. My gut reaction aside, it needed to be done :)
Quote
This could have been in a different branch; but then you have to deal with the metadata mess in SVN every time you want to merge.
I've removed the spurious mergeinfos (generally you aren't supposed to mess with it but these were introduced by mistakes in the first place...)
Quote
I'd actually consider this to be a reasonably small change, it's localised and (apart from the PTP change) doesn't affect anything else. The amount of extra code is also pretty small.
Agree this doesn't directly impact anything else. My reaction is to the (IMHO) ugliness of the code.
Quote
Not sure what magic numbers you are referring to
The numbers for the different outputs of handle_video_transfer etc. Understand this is work in progress. Not a big deal, but they should appear as constants in ptp.h along with comments. I'm trying to keep that as the canonical definition of our protocol.


On the up side, I managed to build the dot net app and connect to my d10 without any additional changes :)
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / September / 2011, 23:19:54
First, thanks for doing this work, and responding to my initial, flamey reaction.
It seems your main point is about adding functionality to Lua vs. adding it to CHDK PTP. At least, most of the big things you question seem to be a consequence of this choice.
Agreed.
Quote
I think the rationale has been given in the past, but it comes down to me having preferred a minimal CHDK PTP. And a large argument for that is that adding more to it makes incompatible protocol revisions more likely. The new functionality is not a part of CHDK PTP, just something that is used through it.
That seems like a marginal distinction. It is effectively part of the CHDK PTP protocol. To actually get the live view data, any client has to accept a data phase from PTP_CHDK_CallFunction, and then understand the results. Realistically, this is one of the main features people will want PTP for, so it makes sense to have the method of doing that be a first class part of the protocol.

As I said in my earlier post, if this could sanely be done entirely in lua, I'd be all for that, but it can't. So I'd rather extend the main protocol in a clear, well defined way instead of throwing stuff in lua and existing functions just to say we didn't change the protocol. If we use new PTP functions, this will still be backward compatible, old clients won't call them.

Here's my thought on an (IMHO) cleaner way to deal with this.

One new PTP command, PTP_CHDK_GetStreamingData (name subject to change... suggestions ?)
- replaces handle_video_transfer
- input parameters are bit flags defining what should be returned, like handle_video_transfer.  The available input params should be enough for pretty much anything we'd want to do, but if you needed more you could have an additional command to select what data is returned by each poll.
- Isn't specific to live view data, that's just one set of things that can be polled. Should also include flags for script status and script messages so a client can just repeatedly poll this one PTP command and get everything it needs in one send. These don't have to be added in the initial implementation though.
- returns all the requested fields with a structure describing their locations. The structure can be very similar to the offset/size handle_video_transfer does now, but rather than implying the meaning of the size/offset fields by their location, they should be matched to the flags that select output.
- The static framebuffer data (from luaCB_get_video_details) just becomes another field that can be selected. Since you no longer need get the function address of handle_video_transfer, you don't need separate function to get this before you start getting video data. You just request this with the first frame, and leave it out later. Not really clear if it really makes sense to separate these values out of the more dynamic ones that have to be sent every frame.
- Compatibility of the returned structures isn't really any different from current implementation, except if we make them chunks that are included in the index structure, we could expand them in a backward compatible way if needed, or define new flags to select different data.

This is more complicated, more code, but IMO would result in a protocol and code we'd be a lot happier living with down the road .

I will try to come up with an implementation of this (edit: if no one else does or convinces me it's a dumb idea) to see if it actually works out like i think, but I'll have to get my head around the C# code or hack live view into chdkptp first.
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / September / 2011, 04:35:26
Apart from the change to PTP_CHDK_CallFunction I'm not sure I really see much difference between the two approaches. One puts the code in Lua although this could be refined (see below), the other puts it in PTP - does the distinction really make a difference?

I can understand the concern over overloading the PTP_CHDK_CallFunction function parameters / return so let me propose a slight variation.

- Change the 'luaCB_get_video_details' function to just return the address of 'handle_video_transfer' (as an int). I would also rename the function to something like 'luaCB_get_liveview_handler'.
- Move all the live view data to be transferred into the 'handle_video_transfer' function (using the bit mask to control what info to return). Again I'd probably rename this function.
- Move the 'handle_video_transfer' function to a separate liveview.c / liveview.h file.
- Add a major / minor version number to the live view data structure.

This means:
- no change to the PTP protocol.
- localised protocol for live view.
- can be extended to other data by adding more 'luaCB_get_???_handler' functions and associated handler functions. This keeps functionality separate and also avoids having a monolithic PTP function that all the data transfer blobs get added into. Alternatively, instead of multiple 'luaB_get_???_handler' functions a parameter to a generic function could be used to determine which handler address to return (a return value of 0 means the handler is not implemented).

Phil.

Edit:
Patch for CHDK (1317) attached to illustrate what I'm proposing, plus updated Session.cs from the sample .Net code.
Note the function I've implemented as luaCB_get_data_handler which returns the address of a handler function could be done as a new PTP function instead - I'm not fussed either way. But I think separating out the handler/transfer code from the Lua / PTP code makes sense.

Title: Re: CHDK PTP interface
Post by: mweerden on 06 / September / 2011, 11:31:23
Quote
I think the rationale has been given in the past, but it comes down to me having preferred a minimal CHDK PTP. And a large argument for that is that adding more to it makes incompatible protocol revisions more likely. The new functionality is not a part of CHDK PTP, just something that is used through it.
That seems like a marginal distinction. It is effectively part of the CHDK PTP protocol.
To me that is (almost) like saying HTTP is part of TCP.

But in any case, my point was more related to preventing non-backwards-compatible protocol updates. And that's also why I wouldn't be a fan of your monolithic PTP_CHDK_GetStreamingData. It only takes one of the flags to change in meaning to destroy backwards compatibility.

I can understand the concern over overloading the PTP_CHDK_CallFunction function parameters / return so let me propose a slight variation.
Perhaps I'm missing your point, but I believe your variation still needs the extended PTP_CHDK_CallFunction. I also don't really see what the concern regarding this extension is.

Quote
- Add a major / minor version number to the live view data structure.
Adding a version is probably a good idea. Instead of adding it to structure you could also make it part of the function name. This allows multiple versions to coexist. Or perhaps a combination where backwards-compatible versions are in the structure, and other revisions use a new function. Not yet sure how much sense this makes, though. ;)
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / September / 2011, 16:12:12
I can understand the concern over overloading the PTP_CHDK_CallFunction function parameters / return so let me propose a slight variation.
Perhaps I'm missing your point, but I believe your variation still needs the extended PTP_CHDK_CallFunction.

No, it can use the original version (see the patch I posted) - because the return is a single 'int' value.
Ignore previous comment - I misunderstood how the PTP / live view client interaction was working.
Back to the drawing board.

Quote
Quote
- Add a major / minor version number to the live view data structure.
Adding a version is probably a good idea. Instead of adding it to structure you could also make it part of the function name. This allows multiple versions to coexist. Or perhaps a combination where backwards-compatible versions are in the structure, and other revisions use a new function. Not yet sure how much sense this makes, though. ;)

Not sure how manageable that would be. For example if an updated client connects to an older version of CHDK then it first has to check if the function name exists for the latest version. If it doesn't then it has to check the the next oldest one, and so on until it finds a function (or give up and fail). Would make it hard to to support older versions of CHDK in the client code.

Similar problem going the other way, if an old client connects to a newer version of CHDK the function won't exist (unless you keep all the function names in CHDK which could get messy) - so how would the client tell if it's a newer version or just not there at all.

Phil.
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / September / 2011, 17:09:25
Not sure how manageable that would be. For example if an updated client connects to an older version of CHDK then it first has to check if the function name exists for the latest version. If it doesn't then it has to check the the next oldest one, and so on until it finds a function (or give up and fail). Would make it hard to to support older versions of CHDK in the client code.
That's quite inevitable (but optional) when supporting multiple versions, I think. So the question is whether or not such support is desirable at all or whether it is all too hypothetical anyway.

Quote
Similar problem going the other way, if an old client connects to a newer version of CHDK the function won't exist (unless you keep all the function names in CHDK which could get messy) - so how would the client tell if it's a newer version or just not there at all.
Is such a distinction relevant? It's not like knowing there is a newer version somehow allows it to do more (except perhaps tell the user).
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / September / 2011, 18:40:19
Not sure how manageable that would be. For example if an updated client connects to an older version of CHDK then it first has to check if the function name exists for the latest version. If it doesn't then it has to check the the next oldest one, and so on until it finds a function (or give up and fail). Would make it hard to to support older versions of CHDK in the client code.
That's quite inevitable (but optional) when supporting multiple versions, I think. So the question is whether or not such support is desirable at all or whether it is all too hypothetical anyway.

But making it harder to support older versions won't help encourage people to do it :)

Quote
Quote
Similar problem going the other way, if an old client connects to a newer version of CHDK the function won't exist (unless you keep all the function names in CHDK which could get messy) - so how would the client tell if it's a newer version or just not there at all.
Is such a distinction relevant? It's not like knowing there is a newer version somehow allows it to do more (except perhaps tell the user).

Giving the end user accurate information is important - a generic 'somethings wrong' message is not good. Being able to tell the user that 'you don't have the live view extensions in CHDK', or 'you have and older/newer version you need to update your CHDK/client program' is preferable.

It's also about style.
To me, changing the function name implies that something has changed about the function itself (new signature, different return value etc).
Changing the version in the data tells me that the protocol has changed - which is probably the more likely scenario.

Phil.
Title: Re: CHDK PTP interface
Post by: mweerden on 06 / September / 2011, 19:36:49
But making it harder to support older versions won't help encourage people to do it :)
Not sure I see how it's harder than other obvious options.

Quote
Giving the end user accurate information is important - a generic 'somethings wrong' message is not good. Being able to tell the user that 'you don't have the live view extensions in CHDK', or 'you have and older/newer version you need to update your CHDK/client program' is preferable.
In principle I agree. However, I think "no or incompatible support" is about as accurate and useful as you can get. The extra distinction doesn't seem 100% reliable to me and still means that the user has to go out and find compatible versions of CHDK and "client".

Quote
It's also about style.
To me, changing the function name implies that something has changed about the function itself (new signature, different return value etc).
The function does change. Only looking at its signature or something is rather arbitrary. :P
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / September / 2011, 22:31:42
Apart from the change to PTP_CHDK_CallFunction I'm not sure I really see much difference between the two approaches. One puts the code in Lua although this could be refined (see below), the other puts it in PTP - does the distinction really make a difference?
The distinction is the Lua part is completely artificial. There is no use for it in Lua, it is, as mweerden said, just a way of calling a function by name, so you can pretend that the protocol hasn't changed. This is not helpful, because anything that actually *uses* it will be affected by changes just the same as a protocol change. It just makes the whole thing more opaque and complicated.

The compatibility problems are the same, you are just making them less centrally documented. Imagine a third party wants to implement live view (gphoto actually picked up ewavrs old code, so this isn't just theoretical. Hopefully once we've got this stabilized we can get them to support the trunk version instead) If it's in the protocol, then they only have to update when the protocol changes, which is visible, centralized and has a well defined way to check protocol compatibility. If it's defined elsewhere, then (as you discuss with mweerden in the following posts) you have to add versioning to that elsewhere, which makes things more complicated.

That's why I'm arguing for putting it in the protocol. Once you get the protocol right it shouldn't need to change too often.
To me that is (almost) like saying HTTP is part of TCP.
Right, if you want to define another protocol for live view, that runs on top of CHDK PTP, but IMO that's not warranted.
Quote
that's also why I wouldn't be a fan of your monolithic PTP_CHDK_GetStreamingData. It only takes one of the flags to change in meaning to destroy backwards compatibility.
Then don't change the flags unless you really need to, deprecate them, add new ones, and only drop them when you are forced to make a protocol change for other reasons. If you use up all 128 bits of params to PTP_CHDK_GetStreamingData, you can always add PTP_CHDK_GetStreamingDataEx if you really want to ;)

The same thing happens if change the flags in your system, it just less clearly defined.

Centralizing other things that a client would also want to poll also has real value. If getting the palette and frame buffer separately hurts frame rate, then polling script status and live view will do the same.

There are other ways you could set it up rather than using flags, but honestly I don't see us using more than a couple ints worth.
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / September / 2011, 23:01:15
To me that is (almost) like saying HTTP is part of TCP.
Right, if you want to define another protocol for live view, that runs on top of CHDK PTP, but IMO that's not warranted.

I think it makes sense to define the live view data transfer as a seperate protocol on top of PTP.
It's a complex transfer including metadata, isolating it away from the core PTP keeps things cleaner.
PTP becomes a means to initiate the live view transfer (and the conduit over which the data travels), other than that it shouldn't care what's going on.
The model is extensible to other data transfers (no idea what this might be) without changing the PTP protocol again.

Tonight I'll try a PTP only version of the previous patch for comparison.
I have a feeling that reyalp's right and the resulting code will be cleaner and easier to understand.

Phil.
Title: Re: CHDK PTP interface
Post by: philmoz on 07 / September / 2011, 06:04:17
PTP based version for comparison / review.

Phil.
Title: Re: CHDK PTP interface
Post by: mweerden on 07 / September / 2011, 10:57:49
I think it makes sense to define the live view data transfer as a seperate protocol on top of PTP.
It's a complex transfer including metadata, isolating it away from the core PTP keeps things cleaner.
PTP becomes a means to initiate the live view transfer (and the conduit over which the data travels), other than that it shouldn't care what's going on.
The model is extensible to other data transfers (no idea what this might be) without changing the PTP protocol again.
Exactly. And because of this tools that do not user remove live view should never feel any consequences of changes to it.

In my eyes it is this approach that is actually less complicated and I really don't see how it makes things  less clearly defined. Except perhaps that at this moment remote live view isn't really defined other than in code. ;)

Centralizing other things that a client would also want to poll also has real value. If getting the palette and frame buffer separately hurts frame rate, then polling script status and live view will do the same.
Now this is an actual argument for centralization. However, as I understand it the PC dealing with the image data is the main bottleneck at the moment. As mentioned a while back, I got a significantly higher fps by just dumping the image data in a file. I remember Phil having a similar result. So I wouldn't want to jump too quickly to this option.
Title: Re: CHDK PTP interface
Post by: philmoz on 07 / September / 2011, 16:15:44
Centralizing other things that a client would also want to poll also has real value. If getting the palette and frame buffer separately hurts frame rate, then polling script status and live view will do the same.
Now this is an actual argument for centralization. However, as I understand it the PC dealing with the image data is the main bottleneck at the moment. As mentioned a while back, I got a significantly higher fps by just dumping the image data in a file. I remember Phil having a similar result. So I wouldn't want to jump too quickly to this option.

There's no polling required for live view - whatever data is required is sent in each call (unless I'm mis-understanding what you mean by polling here).
Although the client sample code doesn't currently use it, the CHDK code is set up so that it can return any or all of the viewport, bitmap & palette buffers in one call to the handler.

On the G12 I can transfer the viewport data 100 times in 6.4 seconds if I don't display it. When I was using PTP_CHDK_GetMemory I had to make two calls for each frame (one to get the current buffer address and then another to get the data).
This took 7.2 seconds to get 100 viewport images - so even just one extra PTP round trip makes a difference.

The sample .Net code can display the viewport at ~6fps so the conversion from YUV to RGB and subsequent display is a bottleneck.

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 09 / September / 2011, 04:35:14
just my 2 cents... (not that they are worth too much ... at least in terms of CHDK as i have very shallow experience )

the function to provide the live preview should be a proper function and a part of PTP. it may not be realised immediately but live preview is an important part of PTP and that in itself would warrant its role in PTP. it may or may not be overloaded to provide other functions.

the polling ('per se') is not a problem and repeated calls to the PTP to get the live view are perfectly ok. the bottleneck at the client end - the conversion to RGB and the subsequent display - can be optimized by the end user any way.

having said that ... i have had a very stable connection with mweerdens' code and have kept the live view running while doing other operations - zoom, capture, changing properties etc - without any problems (SX 120 and SX 130). although not part of lua the function is the quickest workaround to getting the live view with minimum patching. and as long as it was not a proper part of the trunk, it is imho a most efficient implementation !!
Title: Re: CHDK PTP interface
Post by: newmedia42 on 30 / September / 2011, 19:31:44
I have a quick question - I'm currently using the PTP interface, and apart from having a heck of a time figuring out what LUA side of things, the PTP side has been pretty painless.

One thing that is problematic for me is that the USB connection resets (or at least disconnects/reconnects) when you erase an image (ptp_deleteobject).  I seem to recall that this was needed in order to refresh the directory or something to that effect.  What I would like to know is if there is another way I could delete the file without causing this reset (maybe via os.remove)?  Is there anything that might be an issue with doing this?  Thanks, and great job on PTP - finally makes my cameras worth playing with!
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / September / 2011, 23:20:13
What I would like to know is if there is another way I could delete the file without causing this reset (maybe via os.remove)?
os.remove from lua should be fine. Note that some parts of the camera OS may not notice that it has been deleted, so for example if you are browsing images in playback mode or over a regular ptp file browser, you might see the names of images that aren't really there. This is the same as if you delete from the CHDK file browser.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 01 / October / 2011, 06:51:16
the USB connection resets (or at least disconnects/reconnects) when you erase an image (ptp_deleteobject).

Strange, that works fine for me with A620 and SX130is.


David
Title: Re: CHDK PTP interface
Post by: msl on 02 / October / 2011, 03:44:43
For your information: With changeset 1316 ptpCamGui will only work with CHDK-DE because the minor version number of the the ptp modul is not compatible.

See also here: http://chdk.setepontos.com/index.php?topic=6285.msg73674#msg73674 (http://chdk.setepontos.com/index.php?topic=6285.msg73674#msg73674)

msl
Title: Re: CHDK PTP interface
Post by: newmedia42 on 08 / October / 2011, 06:35:27
I'm running into a problem with overlapped commands - I know that if you run a second command before the first has completed, that PTP crashes.  The problem I'm having is trying to detect when an action has completed.  Currently I call ptp_chdk_exec_lua(), then I poll ptp_chdk_get_script_status() until Status doesn't have PTP_CHDK_SCRIPT_STATUS_RUN set (sleeping 50ms each loop).  This seems to work in most cases, but in a couple it doesn't - the most obvious example is trying to use the lua "set_aflock(0);"  In my script I toggle it, so that it sets the focus, then disables autofocus. 

Now, it returns almost immediately from "set_aflock(0);", so when I issue "set_aflock(1);", the camera crashes.  I could combine the two, like "set_aflock(0);set_aflock(1);", but then it crashes on the next command.  Right now my terrible terrible workaround is to do this:

set_aflock(0);press(\"shoot_half\"); repeat sleep(50); until get_shooting() == true; release(\"shoot_half\"); repeat sleep(50); until get_shooting() == false;

which works, but does a ton of other stuff that's irrelevant to what I'm trying to do.

My question is, is this the expected behavior with set_aflock(), and if so, how can I wait until it's completed?
Title: Re: CHDK PTP interface
Post by: markanini on 08 / October / 2011, 22:34:15
Compiled version attached.
One note, there is a checkbox to 'autoupdate' the live view (also calculates the frame rate).
If you have this checked it will crash if you try and send other commands to the camera (it needs to stop the autoupdate before sending the command; but I haven't coded this yet).

Phil.


Works here on A650IS, I get 9.9fps. Overlay checkbox make it crash. Cant wait to see whats in store for this feature!
Title: Re: CHDK PTP interface
Post by: zeno on 09 / October / 2011, 12:49:07
I'm currently trying to get ptpcam working on my Ubuntu linux system. I've installed libusb (see below) and managed to get the ptpcamcode to compile and run, but every time I run it I get the message:
  ERROR: Could not open session!
  Try to reset the camera.
It does detect the camera, but won't open a session. I'm not really familiar with linux internals and none of the things I've read about the problem seem to apply to my ubuntu system (e.g. the information here http://libptp.sourceforge.net/README (http://libptp.sourceforge.net/README) doesn't help because I don't have a /proc/bus/usb folder).

The libusb I've installed is "libusb-compat-0.1.3" because this seems to correspond to the windows libusb-win32-bin-1.2.2.0 that works fine for me. The other linux libusb versions don't fit (e.g. they have a libusb.h file rather than a usb.h file).

I suspect I've bitten off more than I can chew, but after lengthy struggles to get ptpcam to compile, I now seem quite close to getting it to run.

Postscript: I didn't realise that 'Try to reset the camera' meant try the command 'ptpcam -r'. That did the trick - ptpcam now talks to the camera as it should!

Title: Re: CHDK PTP interface
Post by: sgtrum on 11 / October / 2011, 12:47:32
I'm also experiencing a camera shutdown when sending the lua shoot() command.  I'm using the sample .net app (live view works).  I have also tried with ptpcamgui with the same results. 

I've tried both a Canon SX130 and SX110 using changeset 1359 from the autobuild server.

I have made sure to set the camera in record mode before sending the shoot() command.  Anyone have any ideas for me?

Sgtrum
Title: Re: CHDK PTP interface
Post by: enuro12 on 11 / October / 2011, 14:01:58
Back on page 10 there was a patch to make this work on an A540. Those links are broken now. Is there anyway to get this on my A540's?

Chuck
Title: Re: CHDK PTP interface
Post by: msl on 12 / October / 2011, 03:23:13
Back on page 10 there was a patch to make this work on an A540. Those links are broken now. Is there anyway to get this on my A540's?

You can try this version: http://chdk.bplaced.net/content/download/view.download/7/23.html (http://chdk.bplaced.net/content/download/view.download/7/23.html)

with this M$ interface: http://chdk.bplaced.net/content/download/view.download/6/11.html (http://chdk.bplaced.net/content/download/view.download/6/11.html)

But this is a very old CHDK version based on ewavr's PTP interface. You need also the alternate USB driver.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / October / 2011, 01:05:15
Regarding the live view stuff.

I clearly won't have time to work on this for a while, so I don't want to hold things up. IMO the implementation in phils branch is preferable to the original one.

I still reservations but we can always do protocol 3.0 down the road if needed. IMO, a combined "select what data I'm interested in and fetch it all in one call" is the right thing to do in the long run, and should not be terribly hard to implement in a reasonably flexible way.

Title: Re: CHDK PTP interface
Post by: AndrewS on 02 / November / 2011, 13:36:58
I have tried S95 with ptpCamGui 2.0.112 and got message "CHDK isn't started on camera!". There is a message in console "** init() start ...
>> version << error: cannot get camera CHDK PTP version; either it has an unsupported version or no CHDK PTP support at all
ptpcam: 2.0 (Length: 122) [unexpected return code 0x2005
unexpected return code 0x2005 (Length: 60)]
"
CHDK 0.9.9 firmware 100h. Usb-driver libusb-win32-bin-1.2.4.0.
Could You please tell me what I do wrong?
Title: Re: CHDK PTP interface
Post by: rudi on 02 / November / 2011, 15:33:10
got message "CHDK isn't started on camera
Make sure CHDK is loaded in play mode before you start ptpCamGui.
Title: Re: CHDK PTP interface
Post by: AndrewS on 03 / November / 2011, 03:16:48
Make sure CHDK is loaded in play mode before you start ptpCamGui.
CHDK is loaded automatically after power on. The yellow label with CHDK version is appeared on camera screen.  But camera starts in play mode with retracted lens.
Title: Re: CHDK PTP interface
Post by: rudi on 05 / November / 2011, 09:21:31
>> version << error: cannot get camera CHDK PTP version; either it has an unsupported version or no CHDK PTP support at all
ptpcam: 2.0 (Length: 122) [unexpected return code 0x2005
unexpected return code 0x2005 (Length: 60)]
This message means "CHDK ptp-task not run".

Why? e.g. ptp is not enabled in your build, but I think it is enabled by default for S95.
A good answer looks like
Code: [Select]
>> version << ptpcam: 2.0
camera: 2.0 (Length: 24)

No hint found on S95 porting thread about wrong ptp and ptpcamGUI works fine.

Try this:
- use the newest CHDK build (http://mighty-hoernsche.de/)
- test CHDK-DE build (http://forum.chdk-treff.de/download.php)
- post a question to S95 thread (http://chdk.setepontos.com/index.php?topic=5641.0)

rudi
Title: Re: CHDK PTP interface
Post by: Mikjely on 11 / November / 2011, 14:28:04
Hello everyone,

I have only browsed thus far through the thread. (alot of information! =D )

But I had a few questions, that I was hoping someone could answer for me here in relation to the functions provided by what mweerden & ewavr have done here.

1) By switching a compatible camera to rec mode from playback, is it still possible to transfer photos through the USB connection to a computer while setting up a script to continuously capture photos. In other words, is photo capture possible with simultaneous data transfer?

2) What has been the average image transfer rate over a USB2 connection? I read some values of 6Hz, but is this relative to what I am talking about?

Thanks again guys! :xmas
Title: Re: CHDK PTP interface
Post by: AndrewS on 12 / November / 2011, 08:20:50
rudi, thanks for advice! I tried the newest CHDK and got remoute control! Works good. Are there any software for Linux with functionality of PtpCamGui?
Title: Re: CHDK PTP interface
Post by: Mikjely on 12 / November / 2011, 22:42:07
Ok so I have done quite a bit of reading since my last post and seems that to better understand everything I will need to actually purchase a compatible camera and test it out. I have seen alot of testing with the SX120, G12, and others. My only dilemma is I don't want to go out and buy something that won't actually help me. From what I understand, which is not much... it is possible (I think?) to do what was stated above. Another question I have is if this is possible to run continuously? Kind of like setting up a camera to take a certain amount of images over a given time AND transfer the data without me having to interfere inbetween? I am sorry again for the noobie questions... and thank you for any replies.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 13 / November / 2011, 09:48:12
Well, you either have to  upload the image to the PC between shots (let us say no faster than every four or five seconds) or you have to spend longer uploading a batch at certain longer intervals.

You can do both  .. your choice.

You cannot capture images faster than one every four seconds and upload them at the same time.


David
Title: Re: CHDK PTP interface
Post by: waterwingz on 13 / November / 2011, 10:31:24
Another question I have is if this is possible to run continuously? Kind of like setting up a camera to take a certain amount of images over a given time AND transfer the data without me having to interfere inbetween? I am sorry again for the noobie questions... and thank you for any replies.
You could buy or make an A/C adapter to replace the camera battery.  Then use an Eye-Fi (http://www.eye.fi/) card to tranfer your pictures over wifi
Title: Re: CHDK PTP interface
Post by: Mikjely on 13 / November / 2011, 14:04:37
I really appreciate the replies. Thank you. So I had already previously researched using eye fi but found it to be too slow for what I wanted to accomplish, therefore I began looking into other options. I found eyefi to have an image transfer rate of about 2-3 seconds and that was holding the camera right next to the router.

When you say no faster than one every four second, is that including the process of uploading the image to a computer? In other words it would take 4 seconds to take a photo and then transfer it before restarting the process all over.. Is that what you are saying?

I would assume the time intervals would be the same for a longer batch.. Maybe. For instance, have the camera take 10 photos every 10 seconds, then stop to upload them. It would still take 40 seconds, correct?
 
Title: Re: CHDK PTP interface
Post by: Mikjely on 13 / November / 2011, 14:28:45
Another thought... using a USB interface, uploading images from the camera to the computer is independent of the SD card, right? Or does reading occur directly from the SD card? Again, thank you for the replies.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / November / 2011, 15:34:32
Or does reading occur directly from the SD card?
As far as I know, yes. The writing of the .jpg can't be prevented yet.
Some older PowerShots do have official remote capture capability, but Canon decided to remove this from all recent models. Some info: http://www.gphoto.org/doc/remote/ (http://www.gphoto.org/doc/remote/)
Title: Re: CHDK PTP interface
Post by: Mikjely on 14 / November / 2011, 14:52:06
Sorry for the thousand questions, but has anyone tested the speed of this process? (Taking a shot, transferring the image then taking a photo again) I really hoped this method would have been faster than using an eye-fi card, but looks like I may be back to the drawing board. Thanks again guys!
Title: Re: CHDK PTP interface
Post by: Microfunguy on 14 / November / 2011, 16:20:38
has anyone tested the speed of this process?

just over three seconds for a DNG or JPG on an A620.

On higher resolution cameras it may well be slower.

Your other question about downloading (to PC) a batch, ten of the above images download in 15 seconds.

Title: Re: CHDK PTP interface
Post by: achillies on 14 / November / 2011, 18:50:54
With a 12.1 MP sensor, it takes around 4 secs to shoot and download DNG or JPG.  With a slightly different process, I can shoot 10 images at 2 secs per image, and then download all images in a batch in about 5 secs, so that's 25 secs to shoot and download 10 images.
Title: Re: CHDK PTP interface
Post by: Mikjely on 14 / November / 2011, 22:41:46
Thank you very much for the numbers, they really help. So, in theory it would be ideal to upload in batches rather than in single uploads. I suppose that if we were to take a bigger batch, the time should decrease even more, correct? Are there any more numbers out there for other cameras?

Another question, could the receiving end of the image be nothing more than a minipc, where the whole loop wouldn't require a human to operate it? Of course, initial programming would be done, but is this feasible? For example, program the whole procedure to take 20 images, upload to the minipc, repeat, without any human interference inbetween. (1000 images total we would say)

Seriously, thanks again for all the replies.
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / November / 2011, 23:19:38
So, in theory it would be ideal to upload in batches rather than in single uploads. I suppose that if we were to take a bigger batch, the time should decrease even more, correct?
I'd expect you will hit diminishing returns quite quickly.
Quote
Another question, could the receiving end of the image be nothing more than a minipc, where the whole loop wouldn't require a human to operate it? Of course, initial programming would be done, but is this feasible? For example, program the whole procedure to take 20 images, upload to the minipc, repeat, without any human interference inbetween. (1000 images total we would say)
Yes, with the caveat that CHDK as a whole is a hack, and the PTP stuff even more so. You should not assume that it will be 100% reliable and stable. It might work fine, or you might run into mysterious crashes, hangs or other difficulties. If it turns out to be unstable in your situation, you should not assume that someone here will be able to magically fix it for you. If further hacking is required to make it work for your project, that will be up to you.
Title: Re: CHDK PTP interface
Post by: Mikjely on 17 / November / 2011, 17:02:29
So, in theory it would be ideal to upload in batches rather than in single uploads. I suppose that if we were to take a bigger batch, the time should decrease even more, correct?
I'd expect you will hit diminishing returns quite quickly.
Quote
Another question, could the receiving end of the image be nothing more than a minipc, where the whole loop wouldn't require a human to operate it? Of course, initial programming would be done, but is this feasible? For example, program the whole procedure to take 20 images, upload to the minipc, repeat, without any human interference inbetween. (1000 images total we would say)
Yes, with the caveat that CHDK as a whole is a hack, and the PTP stuff even more so. You should not assume that it will be 100% reliable and stable. It might work fine, or you might run into mysterious crashes, hangs or other difficulties. If it turns out to be unstable in your situation, you should not assume that someone here will be able to magically fix it for you. If further hacking is required to make it work for your project, that will be up to you.

I apologize if I have came off as wrong to anyone. I was not looking for any free hand-outs. Simply questions for what is already in existence. I apologize again if I came across any differently. Looks like I will be purchasing a camera fairly soon to play with things. Thanks again everyone for your replies.
Title: Re: CHDK PTP interface
Post by: Canonero on 20 / November / 2011, 10:11:53
Please allow for little intrusion here, recently there was an ongoing discussion on the SX130 thread (page 62), about the possibly "ready made" solutions, how to include webcam driver functionality into the "live view" feature inside the CHDK universe. In addition to various freeware/shareware addons, which can in effect capture the preview frames generated by PTP GUI and transport it via webcam driver - finally, an open source webcam driver (named SCFH-DSF) working under winxp has been identified and briefly tested, anyone interested in the possibility making this an integral part of future PTP GUI versions is very welcome to join the musings. I guess this thread is more suitable to continue in this talk..

Original thread with more details and links here: http://chdk.setepontos.com/index.php?topic=5691.msg75779#msg75779 (http://chdk.setepontos.com/index.php?topic=5691.msg75779#msg75779)
Title: Re: CHDK PTP interface
Post by: ntstatic on 29 / November / 2011, 06:48:18
Or does reading occur directly from the SD card?
As far as I know, yes. The writing of the .jpg can't be prevented yet.
Some older PowerShots do have official remote capture capability, but Canon decided to remove this from all recent models. Some info: http://www.gphoto.org/doc/remote/ (http://www.gphoto.org/doc/remote/)

Just a thought as this topic is at hand - can the gurus of CHDK indicate if it is at all possible to take a picture and directly transfer it to the PC, without saving it to the card - in theory at least :) - meaning is it at least worth putting on the wishlist.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / November / 2011, 13:05:17
is at all possible to take a picture and directly transfer it to the PC, without saving it to the card

Yes, with DNG.
I do it now.
For jpg and movies I simply delete the images from the card after download to the PC.

David
Title: Re: CHDK PTP interface
Post by: ntstatic on 01 / December / 2011, 05:44:28
is at all possible to take a picture and directly transfer it to the PC, without saving it to the card

Yes, with DNG.
I do it now.
For jpg and movies I simply delete the images from the card after download to the PC.

David

can you please explain in a little bit more detail how i can capture and transfer a DNG directly to the PC
ive been capturing in JPG - transferring - Deleting at the moment, and the whole process takes around 7 seconds. i know that getting the DNG directly is not likely to reduce the time, in fact increase the post processing on the PC.
but would definitely like to actually find out if it is any quicker.


Title: Re: CHDK PTP interface
Post by: Microfunguy on 01 / December / 2011, 06:17:59
I am using SDM which behaves rather differently to CHDK.

After the shutter has been pressed the raw data and a header file are immediately sent to the PC without saving on the camera.

That process is quite fast depending on file size and card speed.

The memory card should have been low-level formatted in the camera beforehand, as recommended by Canon.

On the PC, they are converted to a DNG file.

The JPG left on the camera is tiny, only about 10k (!) and is instantly deleted.

I do not know how the other PTP clients deal with this.


David
Title: Re: CHDK PTP interface
Post by: andyroo on 19 / December / 2011, 16:59:19
I have a question about getting the Lua console to run on ptpcamgui. I have tried on two computers (Win7x32 and Win7x64) with two cameras (SX220HS and SX30) to run the lua console, and it freezes ptpcamgui. I resorted to using CHDKPTP to communicate in lua with the cameras and it works fine, but I would like to have the functionality in ptpcamgui since it's so useful for everything else.

After the freeze (spinny wheel, prog not responding) if I close ptpcamgui then ptpcam is still working in task manager. I am wondering if I missed something as far as how it works. Here's my info from the PTPCAM console:

Code: [Select]
** init() start ...
>> version << ptpcam: 2.0
camera: 2.1 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil) << script:15
15:ret:true (Length: 22)
>> luar require("lptpgui").version << script:16
16:ret:113 (71) (Length: 26)
>> luar get_buildinfo() << script:17
17:ret:'platformid 12816
platform sx30
version CHDK
platsub 100p
build_number 0.9.9-1487
os dryos
build_date Dec 15 2011
build_time 10:13:08
' (Length: 161)
is DryOS=True
CHDK-DE=False
>> luar get_config_value(67) << script:18
18:ret:1 (1) (Length: 23)
current powersave mode: 1
>> luar get_raw() << script:19
19:ret:0 (0) (Length: 23)
>> help << q quit                         quit program
h help                         list commands
r reset                        reconnect to camera
  version                      get CHDK PTP version (ptpcam and camera)
  shutdown                     shutdown camera (soft)
  reboot                       reboot camera
  reboot <filename>            reboot camera using specified firmware update
  reboot-fi2                   reboot camera using default firmware update
m memory <address>             get byte at address
m memory <address>-<address>   get bytes at given range
m memory <address> <num>       get num bytes at given address
  set <address> <long>         set long value at address
c call <address> <arg1> ...    call function at address with given arguments
  upload <local> <remote>      upload local file to camera
  download <remote> <local>    download file from camera
  mode <val>                   set mode (0=playback,1=record)
  lua <code>                   execute lua code
  luar <code>                  execute "return <code>" and retreive result
  script-support               show supported script interfaces
  script-status                show script execution and message status
  getm                         get messages / return values from script
  putm <message>               send <message> to running script (Length: 1359)
* enable keys for GUI control: >> lua post_levent_to_ui(4484) << script:20 (Length: 9)
>> script-status << script-status:0x0 run=no msg=no (Length: 31)
** init() successful
Title: Re: CHDK PTP interface
Post by: msl on 11 / January / 2012, 07:08:02
Btw,

is there any reason why we not activate the PTP support for all cameras in camera.h?

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / January / 2012, 02:00:13
Btw,

is there any reason why we not activate the PTP support for all cameras in camera.h?
It is in CHDK.
Title: Re: CHDK PTP interface
Post by: msl on 14 / January / 2012, 04:02:58
It is in CHDK.

Thx.

You're right. Sorry, I haven't seen the entry. So we can delete all entries in the platform_camera.h files for a better overview.

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / January / 2012, 15:14:18
You're right. Sorry, I haven't seen the entry. So we can delete all entries in the platform_camera.h files for a better overview.
Yes :)
Title: Re: CHDK PTP interface
Post by: asmodyne on 09 / February / 2012, 18:48:40
Hello lads !

Knowing we've just hit trunk1654, may I ask if the ptp handlers & usb descriptors are implemented generically, or does each platform (already ported) needs its own implementation of the CHDK ptp extension to enable live preview with mweerden's .Net app ? 

I'm trying to establish some communication between mweerden's CHDKPTPRemote and an A430 (which is currently-ish being ported), but since the app seems to be designed for overlaid previews, it asks for a 512-bytes-capable PTP-class endpoint, which clearly isn't implemented in the current A430 port [1] ...hence my previous question. :-[

Since I'm a newbie of the most blueish kind, I guess the implementations I'm talking about may be a CHDK-DE "exclusivity"... aren't they ?  ???

Thanks, and best regards.  :)


[1] I haven't seen anything like it when enumerating the A430's PTP interface descriptors.  ;)
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / February / 2012, 00:35:20
Hello lads !

Knowing we've just hit trunk1654, may I ask if the ptp handlers & usb descriptors are implemented generically, or does each platform (already ported) needs its own implementation of the CHDK ptp extension to enable live preview with mweerden's .Net app ? 
This question doesn't really make sense to me.

CHDK PTP protocol has certain commands. These are supported generically in CHDK code. A build for any camera should be compatible with with any CHDK PTP client implementing the matching protocol version. You don't need to worry about handlers and descriptors... although I suppose it's possible that the a430 is old enough that it's weird in some way. If you can upload/download with chdkptp or ptpcamgui, then CHDK PTP is implemented and working properly. Neither one will give you live view however.

The live view stuff is completely disabled in in the CHDK release branch, to avoid having an under development protocol "released". There is some of this code in the trunk, I don't know if it is compatible with whatever version of CHDKPTPRemote you are trying to use.

Properly supporting live view is on the list for the next release, but is not finished. The protocol will likely change from whats in the trunk. I keep meaning to do some work on this Real Soon Now. Maybe this weekend...
Title: Re: CHDK PTP interface
Post by: waterwingz on 11 / February / 2012, 10:13:35
Properly supporting live view is on the list for the next release ...
List ?  There's a list ?
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / February / 2012, 16:09:45
Properly supporting live view is on the list for the next release ...
List ?  There's a list ?
http://chdk.wikia.com/wiki/Release_Strategy#Roadmap (http://chdk.wikia.com/wiki/Release_Strategy#Roadmap)
Title: Re: CHDK PTP interface
Post by: waterwingz on 11 / February / 2012, 16:41:33
http://chdk.wikia.com/wiki/Release_Strategy#Roadmap (http://chdk.wikia.com/wiki/Release_Strategy#Roadmap)
This would be less embarrassing if my nick was not there in the revision history ...
Title: Re: CHDK PTP interface
Post by: asmodyne on 11 / February / 2012, 18:03:01

The live view stuff is completely disabled in in the CHDK release branch, to avoid having an under development protocol "released". There is some of this code in the trunk, I don't know if it is compatible with whatever version of CHDKPTPRemote you are trying to use.


Thank you reyalp !

Okay, so if I understand it right, the device's code matching the expectations of CHDKPTPRemote is in the developper edition of CHDK, and should appear in the trunk once the two of them are merged, as it has recently been meant in this topic : http://chdk.setepontos.com/index.php?topic=7601.0 (http://chdk.setepontos.com/index.php?topic=7601.0)

Excellent ! I'll wait a bit then, no need to reinvent the wheel.   :P
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / February / 2012, 18:55:48
Okay, so if I understand it right, the device's code matching the expectations of CHDKPTPRemote is in the developper edition of CHDK,
I'm not sure, there was some back and forth. In any case, existing builds will probably not be compatible with the final live view protocol.
Quote
and should appear in the trunk once the two of them are merged, as it has recently been meant in this topic : http://chdk.setepontos.com/index.php?topic=7601.0 (http://chdk.setepontos.com/index.php?topic=7601.0)
That thread is discussing merging CHDKDE and the CHDK trunk. It looks like that stuff never made it into CHDK, but I'm not sure. Unless someone continues development of CHDKPTPRemote, then it will probably not be compatible with any future version of CHDK. If you want, you can try building the trunk build with chdkshell and see if it works.

It is my intention to support live view in chdkptp. Actually, that's the first step for me to be able to get back to working on the CHDK side. The need to create and maintain a client is one of the things that has slowed down the development of this feature (another thing: my stubbornness and lack of time. Sorry :().

The bottom line is this feature isn't done. There is no "supported" build with live view and a matching client. If you are willing and able to do some hacking and digging through old threads, you may be able to get something working for your specific camera and desired use. Or not...
Title: Re: CHDK PTP interface
Post by: asmodyne on 11 / February / 2012, 23:26:39
I'll build and transfer trunk1662 to the A430 I own right now then.

This camera answers quite well to ptpCam & chdkptp, and executes remote Lua flawlessly.
So far, I've used mweerden's C# code to do a step-by-step debug of the LibUsbDotNet calls : his "ptpUtils" class filters the devices by enumerating its ptp-class interface endpoints, and flags the device as "ptp-able" if and only if one of its usb endpoints presents a 512-bytes capacity.
Since the last trunk I tested (1652) didn't have such an endpoint, I came to the conclusion it lacked the specific "live view" handling CHDKPTPRemote was expecting.  ;)

So far, I've used an USB sniffing app to record some USB activity between CHDKPTP (which operates faster than ptpCam) and the A430.  I've done some device-side USB programming some years ago, and it shouldn't be long before I unravel the requests opcode & contents. (I just have to gather the courage to read through all theses journals I've recorded).

Maybe if the "live view" becomes a trunk's asset, I'll look into implementing a unified DLL (.Net and Mono) for everyone to control them easily via C# or VB code. I need it for automation vision anyway  :P, so me making it "generic" would be a good idea. I'd love to feed a GPU's pixel shader with a kick-arse bitmap freshly grabbed from a Canon camera.
Digital camera are way much more adequate for vision purposes than crappy 768p webcams and their recurring pixel noise  :(, always requiring their lenses seriously hacked in the "aperture" department  :haha.

Title: Re: CHDK PTP interface
Post by: reyalp on 12 / February / 2012, 00:14:20
So far, I've used mweerden's C# code to do a step-by-step debug of the LibUsbDotNet calls : his "ptpUtils" class filters the devices by enumerating its ptp-class interface endpoints, and flags the device as "ptp-able" if and only if one of its usb endpoints presents a 512-bytes capacity.
This sounds to me like it's unrelated to CHDK protocol issues. It may be that mweerden just assumed all cameras would support that. CHDK doesn't see or change that kind of stuff on the camera, it just responds to certain a specific PTP commands. Setting up the endpoints would all be done by the Canon firmware. I'd suggest just changing his code to skip that check...

Quote
Maybe if the "live view" becomes a trunk's asset, I'll look into implementing a unified DLL (.Net and Mono) for everyone to control them easily via C# or VB code. I need it for automation vision anyway  :P, so me making it "generic" would be a good idea. I'd love to feed a GPU's pixel shader with a kick-arse bitmap freshly grabbed from a Canon camera.
If you can come up with shaders that efficiently transform the live view YUV format and paletted bitmap into something suitable to display, that could be very useful.
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 09:50:30

This sounds to me like it's unrelated to CHDK protocol issues. It may be that mweerden just assumed all cameras would support that. CHDK doesn't see or change that kind of stuff on the camera, it just responds to certain a specific PTP commands. Setting up the endpoints would all be done by the Canon firmware. I'd suggest just changing his code to skip that check...


Obviously, I didn't start from the right angle with mweerden's code.
So I'lll stick to chdkptp's implementation (even though it's a mix of C and Lua, which confuses me a lot  :-X ).
I should to rethink my approach an start from a PTP standard implementation, just as you did whith ChdkPtp.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 11:37:01
I've used an USB sniffing app to record some USB activity

Can you give more details of that, I need it to solve a problem ?

Quote
Digital camera are way much more adequate for vision purposes than crappy 768p webcams

Well, LiveView is 320x240.

Quote
I'd love to feed a GPU's pixel shader with a kick-arse bitmap freshly grabbed from a Canon camera.

You cannot grab a bitmap, just the low-resolution YUV viewfinder image or a raw image (at far slower frame-rate) that needs converting to bitmap.
The raw image (especially at wide angle) has very large lens distortions, not exactly suitable for machine vision unless individually calibrated.

I convert the viewfinder YUV image to bitmap for capture and display.






Title: Re: CHDK PTP interface
Post by: srsa_4c on 12 / February / 2012, 14:41:52
For clarification.
Digital camera are way much more adequate for vision purposes than crappy 768p webcams

Well, LiveView is 320x240.
No. :) 360x240 is the resolution CHDK works with (at least this was the case a few months ago).
Liveview's real resolution depends on many factors. The real resolution you usually get is 720x240. If you plug something into the TV-out socket, it will be reduced to 704x240.
At least a few DIGIC II cameras supply much greater vertical resolution when in VGA movie mode (the A430 for example provides 720x568 at a framerate of 10fps). The S80 is the only DIGIC II model with greater-than-SD movie resolution, don't know what happens there (but that port is lost anyway). I also have no idea what happens in new models where a HDMI connection is available. When not in record mode, the YUV buffers usually provide greater vertical resolution (at least when TV-out is used).

http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers)
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 15:12:16

Quote
Digital camera are way much more adequate for vision purposes than crappy 768p webcams

Well, LiveView is 320x240.

My point is : 240p 5/4r is perfect for live feed vision processing BUT you can snap a shot anytime in a much, much higher resolution, then pass it to a more advanced processing stage, when you vision app needs it.


Quote
I'd love to feed a GPU's pixel shader with a kick-arse bitmap freshly grabbed from a Canon camera.

You cannot grab a bitmap, just the low-resolution YUV viewfinder image or a raw image (at far slower framerate) that needs converting to bitmap.
The raw image (especially at wide angle) has very large lens distortions, not exactly suitable for machine vision unless individually calibrated.

I convert the viewfinder YUV image to bitmap for capture and display.

Yes, that's exactly the point of using a pixel shader here : process a large amount of raw data (YUV), apply some color matrix transformation using the GPU, and, if the lens's artifacts requires it, use a geometric matrix transformation to obtain a corrected picture.

As regards the framerate : the point is to have a high-resolution RAW or DNG snapshot on-demand, without using jpeg files (and more artifacts), but nothing like some live 30fps Utra-HD feed that would melt our GPU down. By the way, I doubt any baseline GPU could process a 10MP picture without us having to split it into smaller parts beforehand, and reassemble the output once processed.
My hopes, initially, were to achieve a 1fps or 2fps framerate. Let's face it : doing so with an off-the-shelf deprecated camera and an open-source hack would be a feat in itself.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 15:14:27
The real resolution you usually get is 720x240.
that has been the case from the earliest days, GrAnd even posted an image showing it was expanded 2x in width.
It was suggested this might be to give better results when interpolated to 360x240.
It is not really 'resolution'.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 15:17:19
process a large amount of raw data (YUV)

The raw data is not YUV, that is just the viewfinder image.
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 15:19:43

Can you give more details of that, I need it to solve a problem ?


Sorry, I almost forgot : I used the 15-days USBTrace trial.

Here : http://bit.ly/wTfIKf (http://bit.ly/wTfIKf)

Raw data, YUV, YCrBr, CMYN, whatever.... color matrix lad, co.lor.  maaa.trix .   :D
Here's what I'm talking about : http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c (http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c)
Do it with YUV, you also apply the same modus operandi once you know how to transform from one color space to another. Implement it in HSLS, the shader will do the rest.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 15:32:28
So, what matrix will you use to convert raw data to a colour space, see line 219 here http://trac.assembla.com/chdk/browser/trunk/core/raw.c. (http://trac.assembla.com/chdk/browser/trunk/core/raw.c.)

It is raw sensor data.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / February / 2012, 15:49:28
The real resolution you usually get is 720x240.
that has been the case from the earliest days, GrAnd even posted an image showing it was expanded 2x in width.
It was suggested this might be to give better results when interpolated to 360x240.
It is not really 'resolution'.
Luminance resolution is 720. U/V is 160!

Raw data, YUV, YCrBr, CMYN, whatever.... color matrix lad, co.lor.  maaa.trix .   :D
Raw data = bayer 10 or 12 bit RGB. Different animal. But you can't get that at any reasonable speed. Downloading a 18mb raw file from my D10
Code: [Select]
con 1> !cli.showtime=true
time 0.0000
con 1> d -nolua DCIM/100CANON/CRW_0714.CRW
time 4.4093
Taking the SD card out of the equation would help a bit, but not enough, I think...
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 16:19:16
So, what matrix will you use to convert raw data to a colour space, see line 219 here http://trac.assembla.com/chdk/browser/trunk/core/raw.c. (http://trac.assembla.com/chdk/browser/trunk/core/raw.c.)

It is raw sensor data.

I get a "Trac Error , No node /trunk/core/raw.c. at revision 1665".
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 16:29:36

Raw data = Bayer 10 or 12 bit RGB. Different animal. But you can't get that at any reasonable speed. Downloading a 18mb raw file from my D10
Code: [Select]
con 1> !cli.showtime=true
time 0.0000
con 1> d -nolua DCIM/100CANON/CRW_0714.CRW
time 4.4093
Taking the SD card out of the equation would help a bit, but not enough, I think...

Fact is, I'm not planning to retrieve RAW data, it was Microfunguy who brought it in the conversation.  :-X As long as I manage to get picture data, whatever the encoding is (being intertwined bayer or not) without relying on an extraneous jpg compression and file exchange, I'm good. The only interest we all find in Ptp is powerful chdk remote control, and high definition stills. 8)
 Real view is just gravy, don't you agree ? Although it's always interesting to have a realtime viewfinder somewhere in the client app's corner.  :P
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / February / 2012, 16:48:04
Fact is, I'm not planning to retrieve RAW data, it was Microfunguy who brought it in the conversation.  :-X As long as I manage to get picture data, whatever the encoding is (being intertwined bayer or not) without relying on an extraneous jpg compression and file exchange, I'm good.
The only other data you can get easily is the live view, which as discussed is quite low resolution. Of course if you want to take an actual exposure, you can get a nice high res jpeg after a small delay ;)

srsa_4c has also done some work with the video buffers, and retrieving the jpeg before it's written to disk.

I highly recommend chdk.wikia.com/wiki/Frame_buffers
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 17:00:28

Now that you've mentioned it... Having a Bayer components layout would give us a fantastic amount of information for grayscale processing, over RGB .  :-* I love it !
You may know that most edge detection filters (Sobel, Canny) uses grayscale inputs when implemented in the simplest and easyest fashion. And since the BT709 grayscale algorithm I like to use take 71% of its luminance output from the GREEN channel, a Bayer input would be great !

I have to make my generic .Net ptp client DLL work, based on the trunk.

Getting the fresh jpeg out the memory would be great too. But as you said, the file exchange would not make a big difference in the capture duration. We all know the bottleneck is the data exchange here. I wonder how long it takes for the firmware's JPEG codec to compress the raw pic into .jpg .
That's a conundrum :
I'll be in touch.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / February / 2012, 18:02:23
Should we grab the frame buffer once the camera has processed its sensor data, if it ever exist sometime in its RAM (the jpeg encoder may process the Bayer data directly, I dunno, that your expertise domain.  :P
I'm pretty sure this is the case, I don't think there is a de-bayered version of the image outside of jpeg, with the probable exception of the half res high ISO/fast modes and video.

What exactly the high ISO modes do is unknown (to me at least...) but they don't seem to have a normal bayered raw in the first place. This makes sense, because the reason they are fast is presumably some kind of binning going on early in the pipeline but I don't know what (if any) intermediate format they go into before jpeg.

You could potentially return a sub-sampled version of the raw buffer (e.g. every Nth element) but the CPU is quite slow and you have to do some bit fiddling to extract specific pixels, so depending how much of the buffer you wanted, that might not end up much better than just returning the whole thing.

I get a "Trac Error , No node /trunk/core/raw.c. at revision 1665".
Try without the period on the end:
http://trac.assembla.com/chdk/browser/trunk/core/raw.c (http://trac.assembla.com/chdk/browser/trunk/core/raw.c)
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 18:30:10
I'm not planning to retrieve RAW data, it was Microfunguy who brought it in the conversation.  :-X

I rather think you are, unless you prefer the distortion-corrected,nicely colour-rendered JPG's.
Only drawback is white-balance has already been applied.

Before you get too carried away with this can I ask for technical details of the proposed application ?

Based on what existing PTP clients can do (including my own) I cannot see that you need anything special, bearing in mind the constraints mentioned.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 12 / February / 2012, 18:32:29
I don't think there is a de-bayered version of the image outside of jpeg
On (at least) DIGIC II, when reduced image size is requested, the first phase of the picture creation process is a resampled YUV (UYVY) image. This does not happen when the target image is full size or cropped 16:9. Wrong: there's "recreview", a YUV image has to be available for instant review. Don't remember exactly where I saw this (would have to look into my notes).
Now I do: I checked out memory dumps of the A420 (RAM snapshot was created manually after the shot), and noticed the resized YUV version(s) of the recently shot picture.
Quote
, with the probable exception of the half res high ISO/fast modes
As I wrote in another thread a few days ago, modern CCDs (I read some Sony CCD product briefs) have a special readout mode which combines pixels (therefore the Bayer matrix arrangement probably gets lost), and is fast.
Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 21:37:24

I rather think you are, unless you prefer the distortion-corrected,nicely colour-rendered JPG's.
Only drawback is white-balance has already been applied.


Eeeyup... Now I am.  :P
I'm not really enjoying the fact that jpeg compression would add even the tinyest artifacts to the original sample. I doubt Canon uses JPEG-LS or JPEG2000, so I'll continue to assume there is artifacts. But I'm not adamant to the point I'd transfer a complete sensor output dump each time. As reyalp mentioned (or was is you), returning the buffered jpeg would be the best compromise, both in access time and data weight.


Before you get too carried away with this can I ask for technical details of the proposed application ?


Yes, you can....  ::)
More seriously, I plan to achieve "static" vision, many leagues away from the "motion detection" or "mach-speed assembly line QC" people usually associate automation vision with.
Static vision is mostly used in punctual but thourough checks, such as machine tool inspections (what is the actual tap or drill bit dimensions, did the operator made a mistake), items counting (imagine a bed of Swarovski beads your machine has to pick and sort, or SMD components to be rotated precisely), perceptive tint aspect checks (does the hull a robot just painted has speckles or embedded dust ) .
Etc.
This can only be achieved with high-resolution devices. Canon camera over PTP are a great trade-off to handymen (as yours truly) when you consider the price of some secondhand ones on eB... an such trade site.


Based on what existing PTP clients can do (including my own) I cannot see that you need anything special, bearing in mind the constraints mentioned.


Fact is, I don't need anything complicated from the client app. I'd just like a DLL to offer me remote control options reacting as quick as CHDKPTP does, and direct snapshot downloading without messing with the flash card (this last part, however, may not be included in the PTP standard, so I may put it aside).
Ideally, all this would have to be acheivable on any platform ported to CHDK, trunk release.
Since C# would allow me to distribute this dll for free for both Windows (LibUSbDotNet) and Linux (MonoLibUsb) architectures, I though it was worth a try as an open-source project.
Moreover, C# makes pixel shaders easy to access on both platforms ( with DirectX or OpenGL), isn't prone to memory leaks, and a great non-commercial image manipulation Managed library exist, that some of you may already know : Aforge.Net  (http://www.aforgenet.com/ (http://www.aforgenet.com/)).
Title: Re: CHDK PTP interface
Post by: Microfunguy on 12 / February / 2012, 21:53:16
machine tool inspections (what is the actual tap or drill bit dimensions
This can only be achieved with high-resolution devices.

Well, if you are serious about such applications you need optics that are telecentric in object space, normally available in 'C' mount for machine vision cameras.

Quote
direct snapshot downloading without messing with the flash card

Yes, that is OK.

I was doing it yesterday with a stop-motion test.


Title: Re: CHDK PTP interface
Post by: asmodyne on 12 / February / 2012, 22:15:44

Well, if you are serious about such applications you need optics that are telecentric in object space, normally available in 'C' mount for machine vision cameras.


Hehe...  the "seriousness" of my hardware is inversely proportional to my wallet's contents. Don't forget what the 'H' in CHDK stands for.  :P

Wait... isn't that reyalp signature ?  :-[
Title: Re: CHDK PTP interface
Post by: ntstatic on 13 / February / 2012, 00:38:05
Hello lads !

Knowing we've just hit trunk1654, may I ask if the ptp handlers & usb descriptors are implemented generically, or does each platform (already ported) needs its own implementation of the CHDK ptp extension to enable live preview with mweerden's .Net app ? 
This question doesn't really make sense to me.

CHDK PTP protocol has certain commands. These are supported generically in CHDK code. A build for any camera should be compatible with with any CHDK PTP client implementing the matching protocol version. You don't need to worry about handlers and descriptors... although I suppose it's possible that the a430 is old enough that it's weird in some way. If you can upload/download with chdkptp or ptpcamgui, then CHDK PTP is implemented and working properly. Neither one will give you live view however.

The live view stuff is completely disabled in in the CHDK release branch, to avoid having an under development protocol "released". There is some of this code in the trunk, I don't know if it is compatible with whatever version of CHDKPTPRemote you are trying to use.

Properly supporting live view is on the list for the next release, but is not finished. The protocol will likely change from whats in the trunk. I keep meaning to do some work on this Real Soon Now. Maybe this weekend...


Thank you Reyalp, been meaning to hear that for quite a long time, as you probably know i have been keeping an eye on this thread and a "trunk" implementation of the live view for quite some time. for the time being mweerden's code and some of the patches provided by phil and you and other gurus work for me. i have frozen my version of ckdk to a few sub versions back, just for that purpose.

Title: Re: CHDK PTP interface
Post by: ntstatic on 13 / February / 2012, 01:00:46
Quote
Yes, that is OK.
I was doing it yesterday with a stop-motion test.

hello microfunguy, you did provide an explanation about it a few pages back, thank you, but i never got to doing that. at the moment i cannot switch to SDM (too dependent on other features of CHDK) - i think you mentioned that SDM is required.

can you tell me if direct capture to PC without the card is possible with CHDK ??
Title: Re: CHDK PTP interface
Post by: Microfunguy on 13 / February / 2012, 06:16:07
at the moment i cannot switch to SDM

It is not available in the 'official' 1.85 version.
Spring is almost here in the Northern hemisphere so it is about time that I got this released.


Quote
too dependent on other features of CHDK

As a matter of interest, which features ?

Quote
can you tell me if direct capture to PC without the card is possible with CHDK ??

I do not know specifically about CHDK and it depends what you mean by 'without the card'.
With SDM, the best you can do is save a tiny jpg (which is later deleted) and download the raw data and instantly convert to DNG on the PC.

Title: Re: CHDK PTP interface
Post by: asmodyne on 13 / February / 2012, 18:05:55
Okay, so a bit of news.

I "noticed" the PTP is an INTERFACE class lads, not a device class.  ;)
Since a composite device MAY have several configurations, it MAY offer several PTP interfaces (which, in USB jargon is know as a function).

I've just implemented this case in the open-source DLL strain , since we don't know what tomorrow holds. (I'll avoid to call it "trunk" for obvious reasons) :-X
Maybe Canon will release 3D cameras, appearing as composite USB devices.  ???

More seriously, this should offer users the ability to choose a specific configuration amongst many on a single device in their client app.
Title: Re: CHDK PTP interface
Post by: ntstatic on 14 / February / 2012, 09:13:45
at the moment i cannot switch to SDM

It is not available in the 'official' 1.85 version.
Spring is almost here in the Northern hemisphere so it is about time that I got this released.


Quote
too dependent on other features of CHDK

As a matter of interest, which features ?
i am using mweerden's live preview code along with regular remote control, my application is actually simple the camera is inaccessible in a container(i open up the camera and solder the power connector, so applying power to the camera turns it on) and i need to control it via the pc - however  i need a preview,  i might use a A/V cable but live preview works ok.

in regular mode i just need high resolutions snaps, in the other mode i require a 5fps feed for an interval of 1-1.5 mins. at the moment i am  using the live view feed but the quality of the feed requires much to be desired.

i am contemplating doing this offline. capturing a video, downloading it and then saving every 6th frame would give a list of images at 5 fps and the quality of the video is sufficient for most of my purposes. ( the feed does not need to be live, i can just barely live with a downloaded video file )

Quote

Quote
can you tell me if direct capture to PC without the card is possible with CHDK ??

I do not know specifically about CHDK and it depends what you mean by 'without the card'.
With SDM, the best you can do is save a tiny jpg (which is later deleted) and download the raw data and instantly convert to DNG on the PC.
i do not know how much of a lag downloading and converting from DNG will introduce. but i dont think it will save me much time. at the moment capturing a picture and saving takes around 6-8 seconds with the preview constantly on (pauses during download). in your opinion is it worth the effort - i mean will direct capture to pc and its subsequent conversion to jpg (with the distortion correction) halve the process time, can i expect to download process to complete in aroud 3-4 seconds. that may justify my changing the application interface.

thank you, i always appreciate the opinions and help of everyone on this forum. pls let me know when the direct download capability is available in the official release of your SDM maker (hope i got the name right :) ). i would definitely like to play with it and see if i can implement it


Title: Re: CHDK PTP interface
Post by: Microfunguy on 14 / February / 2012, 09:48:24
i am contemplating doing this offline. capturing a video

It is the only way you will get 5 fps.

as a matter of interest, I used 640x480 movie frames from a SINGLE rotating camera to create the top stereo panorama here :  http://www.stereomaker.net/panorama/panoramae.htm (http://www.stereomaker.net/panorama/panoramae.htm)

Here are some technical details http://stereo.jpn.org/eng/stphmkr/help/file_27.htm (http://stereo.jpn.org/eng/stphmkr/help/file_27.htm)


Quote
can i expect to download process to complete in aroud 3-4 seconds. that may justify my changing the application interface.

I have just tried on my old 6MP A620.
JPG and DNG both took three seconds, a certain amount of time for the JPG being the saving to the card.

Either you need 5 fps or you do not.

The only in-between is to run in burst-shooting mode at whatever resolution you wish.

So, you can have 5 fps, 0.3 fps or something in-between.

The accumulated images can be batch-downloaded at intervals via PTP.

Bear in mind that my A620 uses MJPEG encoding for the movies, every frame is a JPG.

With the more recent MOV files, most frames are interpolated.
I would use VirtualDub to change the framerate to 5 fps, save as an image sequence and then inspect them to determine the quality loss.
Title: Re: CHDK PTP interface
Post by: ntstatic on 15 / February / 2012, 09:38:34

It is the only way you will get 5 fps.

as a matter of interest, I used 640x480 movie frames from a SINGLE rotating camera to create the top stereo panorama here :  http://www.stereomaker.net/panorama/panoramae.htm (http://www.stereomaker.net/panorama/panoramae.htm)

Here are some technical details http://stereo.jpn.org/eng/stphmkr/help/file_27.htm (http://stereo.jpn.org/eng/stphmkr/help/file_27.htm)

i did indeed go thru your site keenly a few months back the results are quite impressive from my point of view

Quote
...
Either you need 5 fps or you do not.
The only in-between is to run in burst-shooting mode at whatever resolution you wish.
So, you can have 5 fps, 0.3 fps or something in-between.
The accumulated images can be batch-downloaded at intervals via PTP.
Bear in mind that my A620 uses MJPEG encoding for the movies, every frame is a JPG.
With the more recent MOV files, most frames are interpolated.
I would use VirtualDub to change the framerate to 5 fps, save as an image sequence and then inspect them to determine the quality loss.

i dont intend changing the frame rate in virtualdub as in any case i would be finally saving the frames. i would be saving every 6th frame that would give me the 5fps (assuming 30fps i think that the camera uses) that i want.

thankyou for your feedback - after discussing with you i think it is the way to go. also as i am using SX 130 i would be getting 1280 x 720 (or thereabouts i think) and i have done some test runs the video quality is excellent for my requirement.


Title: Re: CHDK PTP interface
Post by: Microfunguy on 15 / February / 2012, 09:54:06

i dont intend changing the frame rate in virtualdub

Maybe you misunderstand, that in effect temporarily throws away most frames and allows you to save the remainder as an image sequence.

Quote
i think it is the way to go. also as i am using SX 130 i would be getting 1280 x 720 (or thereabouts i think) and i have done some test runs the video quality is excellent for my requirement.

I am also interested in using a 1280x720 camera for the stereo panoramas, orientated vertically to give almost 3x the height of my 640x480 images.

Is it possible to post a full-size extracted frame somewhere ?

There may be an earlier Canon camera that supports movie size greater than 640x480 AND still uses MJPEG encoding.

If so, maybe the compression is higher.
The unknown factor is whether the quality of the extracted frame would be better than the interpolated higher-resolution one.


David
Title: Re: CHDK PTP interface
Post by: ntstatic on 16 / February / 2012, 00:38:00
of course i can post a full fram capture -
if you want i can also upload a small clip so that you may experiment with it.

give me a few hrs and i will post the clip and the frame

from what little i have had time to check the movie mode- the quality really blew me away. it was more than anything i had expected ( :) i had low expectation from the movie mode anyways )
Title: Re: CHDK PTP interface
Post by: ntstatic on 17 / February / 2012, 05:49:32
sorry about the delay ....
here are the snaps from the clip

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fthumbnails55.imagebam.com%2F17526%2Fb4caed175257229.jpg&hash=726440fa1168cd3c3de820be05c5a4c8) (http://www.imagebam.com/image/b4caed175257229) (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fthumbnails28.imagebam.com%2F17526%2Ffc6468175257244.jpg&hash=528c4afd42ac95b001a89e00c6d7593c) (http://www.imagebam.com/image/fc6468175257244) (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fthumbnails38.imagebam.com%2F17526%2F0dd99e175257243.jpg&hash=7da24c8cd48ef0f7041e7fa0ce8fc723) (http://www.imagebam.com/image/0dd99e175257243) (https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fthumbnails25.imagebam.com%2F17526%2Fa9863e175257227.jpg&hash=0e987d94294ca0c73134ea28d5f73de6) (http://www.imagebam.com/image/a9863e175257227)

download the clip from here..
MVI_0006.MOV (http://www.4shared.com/video/UBThHSr3/MVI_0006.html)

Title: Re: CHDK PTP interface
Post by: Microfunguy on 17 / February / 2012, 16:58:24
Many thanks for that.

Yes, they are not bad at all, especially when you consider the fairly low light level.
I set framerate in VirtualDub to 3 which therefore selected 26 frames.
It would not detect that value for export as image sequence so i saved as uncompressed AVI, reloaded and saved as image sequence.

What software are you using ?


Can you lock the exposure in movie mode ?

This camera, and others, would capture 180 frames in six seconds .. sufficient for most 360 degree stereo panoramas.

Just need a 10 rpm rotator.

Something like a cordless screwdriver could rotate the camera.
Title: Re: CHDK PTP interface
Post by: asmodyne on 17 / February / 2012, 20:32:01
sorry about the delay ....
here are the snaps from the clip


Wa wa wa wa wa wait...  :o
What's the nature of this clip again ? Is it a PTP capture, or a movie-mode shoot, downloaded as a file from the device ?  ???
Title: Re: CHDK PTP interface
Post by: ntstatic on 18 / February / 2012, 01:16:42
Many thanks for that.

Yes, they are not bad at all, especially when you consider the fairly low light level.
i hope it is sufficient for your purposes. if you require i could get the thing outdoors and get you a clip. lazy is that i am, i just took the clip sitting at my table :). yes that mess is actually my office table.

Quote
I set framerate in VirtualDub to 3 which therefore selected 26 frames.
It would not detect that value for export as image sequence so i saved as uncompressed AVI, reloaded and saved as image sequence.

What software are you using ?
for movie i use VirtualDub. for extracting the frames from the .mov files i am going to write a utility in vb6. (hoping it would not be more effort than what i am anticipating). if you are intrested i will upload it once it is done.

Quote

Can you lock the exposure in movie mode ?
i do not think movie mode allows any setting other than White balance, Movie Quality and resolution etc. i am not sure about CHDK. dont have it at hand, will revert back.

Quote
This camera, and others, would capture 180 frames in six seconds .. sufficient for most 360 degree stereo panoramas.

Just need a 10 rpm rotator.

Something like a cordless screwdriver could rotate the camera.

i would use a 10 rpm synchronous AC motor if left to a choice - in case AC is a problem outdoors, DC synchronous geared motors are available. here in india 10rpm A/c synchro would cost around inr 100. (around us$ 2) and dc synchronous would be approx inr 150 - 200 (us$ 3 -4)

Quote
Wa wa wa wa wa wait...  :o
What's the nature of this clip again ? Is it a PTP capture, or a movie-mode shoot, downloaded as a file from the device ?  ???
it is not a PTP capture, just a regular capture from the camera. but PTP is perfectly capable of capturing in movie mode and downloading the clip.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / February / 2012, 06:17:04
i am going to write a utility in vb6. (hoping it would not be more effort than what i am anticipating). if you are intrested i will upload it once it is done.

Yes, thanks.
If you were really clever you could write a VDub plugin but ther last time I looked at the code it was very complicated.

Quote
in case AC is a problem outdoors

I will probably use DC motor but you have reminded me that I have a 12V DC/240C AC converter that I have not used.


You can lock the exposure on your SX130is in movie mode, see page 103 of the manual.

David
Title: Re: CHDK PTP interface
Post by: ntstatic on 18 / February / 2012, 08:58:02
i am going to write a utility in vb6. (hoping it would not be more effort than what i am anticipating). if you are intrested i will upload it once it is done.

Yes, thanks.
If you were really clever you could write a VDub plugin but ther last time I looked at the code it was very complicated.
yes a plugin in VDub would be one way of doing it, but i need the end user to feel that the whole damn thing is a proper solution without patchwork. i could probably call VirtualDub in the background but still i would like to have control and know when exactly the process is completed. also i always think of a solution in VB so probably i can do it faster that way.

Quote
Quote
in case AC is a problem outdoors

I will probably use DC motor but you have reminded me that I have a 12V DC/240C AC converter that I have not used.


You can lock the exposure on your SX130is in movie mode, see page 103 of the manual.
David
thanks will check
Title: Re: CHDK PTP interface
Post by: Microfunguy on 18 / February / 2012, 10:15:48
i always think of a solution in VB so probably i can do it faster that way.

Are you saying a VB application can extract the frames without requiring the VDub MOV plugin and without having QuickTime installed on your PC ?
Title: Re: CHDK PTP interface
Post by: ntstatic on 19 / February / 2012, 02:57:20
i always think of a solution in VB so probably i can do it faster that way.

Are you saying a VB application can extract the frames without requiring the VDub MOV plugin and without having QuickTime installed on your PC ?
QuickTime or Quicktime alternative (i think that is what it is called) is still required, but it wont be requiring VirtualDub. i already have the utility for extracting frames from avi's ready and working. mov should not be very different. however i will not be available in the next week so will be able to see how it turns up only after that.

contrary to belief, you can do quite a lot in vb. eg. my HID dongle (software lock) is totally accessed by vb6(totally no dlls etc), the hardware i use -stepper motor controller, etc is controlled by vb6 via usb apart from the database access etc which my regular softwares use. it is relatively faster to code in vb6, generally(compared to c or c++ for eg) which leaves more time for better features. and for a small (tiny) enterprise like mine (around 10 people) it is the way to go.
Title: Re: CHDK PTP interface
Post by: waterwingz on 19 / February / 2012, 08:46:41
contrary to belief, you can do quite a lot in vb. eg. my HID dongle (software lock) is totally accessed by vb6(totally no dlls etc), the hardware i use -stepper motor controller, etc is controlled by vb6 via usb apart from the database access etc which my regular softwares use. it is relatively faster to code in vb6, generally(compared to c or c++ for eg) which leaves more time for better features. and for a small (tiny) enterprise like mine (around 10 people) it is the way to go.
Slightly off topic now, but Microsoft no longer supports vb6.  Obviousy, its still usable but you never know when the next OS version or other package will no longer be compatible.
Title: Re: CHDK PTP interface
Post by: webguy on 19 / February / 2012, 14:46:05
I'm trying to get PTPcamGui working with my A560. Downloaded the latest build, and PTPCamGUI hangs on get_mode() when trying to switch to capture mode. There was a post about half a year ago, but couldn't really find a followup. Assuming this is the same issue, but wondering where to start to tackle this...
Title: Re: CHDK PTP interface
Post by: ntstatic on 20 / February / 2012, 00:54:56
contrary to belief, you can do quite a lot in vb. eg. my HID dongle (software lock) is totally accessed by vb6(totally no dlls etc), the hardware i use -stepper motor controller, etc is controlled by vb6 via usb apart from the database access etc which my regular softwares use. it is relatively faster to code in vb6, generally(compared to c or c++ for eg) which leaves more time for better features. and for a small (tiny) enterprise like mine (around 10 people) it is the way to go.
Slightly off topic now, but Microsoft no longer supports vb6.  Obviousy, its still usable but you never know when the next OS version or other package will no longer be compatible.

sorry to keep off topic - you are perfectly right waterwingz - but remember in most of these kind of utilities we are using the api anyways and if the next os breaks compatibility, unless it breaks the vb runtime specifically, i dont see y it would not break the same utility written in C or C++ too. anyways i am taking my risk - no doubt my new projects are in .net. but i hardly see the logic in writing a small utility in .net and then expecting for someone to download and install the framework (you would not believe how great of a percentage of my clients still use XP)
Title: Re: CHDK PTP interface
Post by: ntstatic on 20 / February / 2012, 01:01:01
I'm trying to get PTPcamGui working with my A560. Downloaded the latest build, and PTPCamGUI hangs on get_mode() when trying to switch to capture mode. There was a post about half a year ago, but couldn't really find a followup. Assuming this is the same issue, but wondering where to start to tackle this...

hello webguy,
can you verify the ptpcamgui version is latest
try using the CHDK DE version and see if it solves the problem
try PTPcam command line and verify that it actually fails on get_mode()
check if other commands work

Title: Re: CHDK PTP interface
Post by: Microfunguy on 20 / February / 2012, 05:25:02
i hardly see the logic in writing a small utility in .net and then expecting for someone to download and install the framework

I really hate this lazy reliance on the .Net framework.
It makes it easier for the developer but inconvenient for many users.
I prefer to do development on an old PC because it is connected to a large-screen TV and is easier to view than my modern system.
There are a number of applications I will not run because of the bloat the .Net framework would add.

Quote
(you would not believe how great of a percentage of my clients still use XP)

I believe it, I do.
I see no reason to change, it does not cause me any problems, just the opposite.
Title: Re: CHDK PTP interface
Post by: webguy on 21 / February / 2012, 14:40:03
hello webguy,
can you verify the ptpcamgui version is latest
try using the CHDK DE version and see if it solves the problem
try PTPcam command line and verify that it actually fails on get_mode()
check if other commands work
- Using latest PTPcamgui, version 2.0.113
- Tried using CHDK DE
- Other commands seem to work, but get mode() or set_record() don't seem to work. PTPCamGui ends in a loop like this:
Code: [Select]
>> luar get_mode() << script:10
10:ret:false (Length: 23)
>> luar get_mode() << script:11
11:ret:false (Length: 23)
>> luar get_mode() << script:12
12:ret:false (Length: 23)
>> luar get_mode() << script:13
13:ret:false (Length: 23)
>> luar get_mode() << script:14
14:ret:false (Length: 23)
>> luar get_mode() << script:15
15:ret:false (Length: 23)
>> luar get_mode() << script:16
16:ret:false (Length: 23)
>> luar get_mode() << script:17
17:ret:false (Length: 23)
Other commands on the command line seem to work, even when using the ptpcam command tool.

What's happening also is that in USB/PTP mode, none of the buttons work. The issue is essentially the same as here: http://chdk.setepontos.com/index.php?topic=4338.msg67930#msg67930 (http://chdk.setepontos.com/index.php?topic=4338.msg67930#msg67930) (in this same thread). That user however doesn't seem to have a resolution.

Any more ideas?
Title: Re: CHDK PTP interface
Post by: webguy on 21 / February / 2012, 14:43:47
Oh, did just test running "luar post_levent_to_ui(4484)" and that unlocks all the buttons except for the mode switch...
Title: Re: CHDK PTP interface
Post by: rudi on 21 / February / 2012, 15:42:52
- Other commands seem to work, but get mode() or set_record() don't seem to work.
All my tests showed, that we should not use set_record() on lua code over ptp. The better way is ptp command "mode".

rudi
Title: Re: CHDK PTP interface
Post by: webguy on 21 / February / 2012, 16:20:28
Just tried that, doesn't do anything either.
Title: Re: CHDK PTP interface
Post by: asmodyne on 22 / February / 2012, 17:53:47

 unless it breaks the vb runtime specifically, i don't see y it would not break the same utility written in C or C++ too.


Okay, that one's easy : because C++ runtimes are still maintained on x64 platform by MS, whereas VB runtime aren't.  :blink:
As to know why... well... VB7 is .Net, and .Net is obviously still maintained.

i hardly see the logic in writing a small utility in .net and then expecting for someone to download and install the framework (you would not believe how great of a percentage of my clients still use XP)

There's no more logic in installing the .Net Framework than installing MinGW, Cygwin, or even AutoIT. And as regards coders laziness, I think I've listed in increasing order.  :haha


I really hate this lazy reliance on the .Net framework.


Lazy reliance ? It's not laziness, it's pragmatism.

It makes it easier for the developer but inconvenient for many users.

Not as much as Cygwin did when I had to install it on a CE platform !!!!  :blink:

I prefer to do development on an old PC because it is connected to a large-screen TV and is easier to view than my modern system.

Seriously ? Each an every PC I use in my workshop are old junks picked from the scrapyard and refurbished by yours truly, and they still run on XP. What is this PC of yours ? a 386 ?

There are a number of applications I will not run because of the bloat the .Net framework would add.

  ??? seriously ???
A bloat ?

Quote
Quote

 (you would not believe how great of a percentage of my clients still use XP)


I believe it, I do.


I believe it, and see it everyday too. I even repaired a PC running on 98SE last month...  :D
No kidding, I did ! It's a remote area here, many people still use Win98.

And, I think their main reason is the same as Microfunguy's, who said :


I see no reason to change, it does not cause me any problems, just the opposite.


Well, that's a point of view, not a unalienable truth. Thing is, you can't rely on a old TECHNOLOGY because the new one is more TECHNOLOGIC. Doesn't make sense.
VB7 over VB6 is an improvement.
iPhone over PockedPC is a commercial scam.
Win7 over WinXP is a "$hIt, my 10 yo trident graphic card's burnt, are those nVidia things compatible with ISA bus" ? ... see what I mean ?  ::)



Fact is, I don't encounter much .Net apps when it comes to applications targeting wide audiences (except for most of the XBox Live indies).
But I do when it's "by coders for coders" stuffs, and proprietary industrial automation. Again, pragmatism : MS platform now have the .Net framework embedded into it.


Title: Re: CHDK PTP interface
Post by: reyalp on 22 / February / 2012, 23:04:42
Please take this discussion of VB, XP etc somewhere else. This thread is for discussion of the PTP extension.

Getting back on topic:
I've finally got live view working enough in chdkptp that I can work on the protocol. The CHDK side of this is in a branch http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live) but will probably move it back to the trunk once I've got a few things sorted out. This is based on philmoz work from http://chdk.setepontos.com/index.php?topic=4338.570 (http://chdk.setepontos.com/index.php?topic=4338.570)

If you want to play with it, you can build chdkptp with CD_SUPPORT=1 and LIVEVIEW_SUPPORT=1 defined in config.mk (and the CD libraries in place). I'll put up a binary build of this soon. This is still very rough, it should generally display something, bit it will probably break on screen layouts different form my cameras. It currently only supports the style of bitmap palette used on a540.

Some initial thoughts:
- I think GetHandler is redundant. We need a well known number to identify the handler, and all the handler is to the client is an opaque number. So just use the well known number to start with.
- There seems little value in differentiating the "fixed" data (LV_TFR_CORE_DETAILS) vs the per frame data. If you are fetching 200kb framebuffer, having a few extra ints in there isn't going to make much difference. Forcing clients to be prepared for anything to vary frame-to-frame will help us if any of the stuff that we thought was fixed turns out to be variable on some camera. 
- The frame buffer parameters need some work. More on this in another post, I'm still trying to get my head around it...
Title: Re: CHDK PTP interface
Post by: Pier on 23 / February / 2012, 06:22:20
@reyalp,
I don't understood whether above link and all the files there are related to CHDKPTP in
this tread http://chdk.setepontos.com/index.php?topic=6231.0 (http://chdk.setepontos.com/index.php?topic=6231.0) or not.
Can't find in the ziped files/folders/files  CD_SUPPORT=   and LIVEVIEW_SUPPORT=   to try with my SX130.
Maybe this is only for developers.I can't get along build with CHDK-SHELL if there in core folder are Modules.Diskboot.bin is not complete..I think..?? Pls excuse me - nooby in programming..
I made short test- CHDKPTP with Gui and cli r160 and it's doing well on this stage.
Title: Re: CHDK PTP interface
Post by: asmodyne on 23 / February / 2012, 16:12:27

I've finally got live view working enough in chdkptp that I can work on the protocol.

 
Sweet !  :)


The CHDK side of this is in a branch http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live) but will probably move it back to the trunk once I've got a few things sorted out.


Does this mean your code only concern the A540 platform ?  ;)

I can't wait to see a new set of Chdk PTP subcommand to request a live PTP feed (even if it will be rough to achieve it without an isochronous endpoint.) The trunk would need to implement something bigger than the tiny 64 bytes bulk endpoints I see on the A430  :haha). But anything different from bulk would make us step out of the PTP domain, right ?

[addendum]

So far, the open-source library stem I'm implementing has its "ChdkDevice" objects implementing two separate interfaces, namely : IPtpDevice, which sticks to the PIMA 15740 USB variation by offering the basic PIMA15470 opcodes set, and IChdkDevice which offers CHDK-specific methods, such as "SwitchMode()", "ExecuteLuaScript()" or "InstantSnap()", etc...
So I'm eager to read about your future work.



Title: Re: CHDK PTP interface
Post by: asmodyne on 23 / February / 2012, 16:22:24

I should post a class hierarchy graph from my current work progress in the next few weeks... if anyone is interested ?  :-X
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / February / 2012, 16:29:00
Maybe this is only for developers.
Exactly. CD_SUPPORT and LIVEVIEW_SUPPORT are makefile variables in the chdkptp source, not files anywhere.

As I said before, I'll try to put a binary build of chdkptp soon.

Does this mean your code only concern the A540 platform ?  ;)
Most of it is generic, but there will be platform specific issues, and some code will need to be added to most CHDK ports for full functionality.

Quote
The trunk would need to implement something bigger than the tiny 64 bytes bulk endpoints I see on the A430  :haha). But anything different from bulk would make us step out of the PTP domain, right ?
As I explained before, this is a low level detail outside of the scope of anything CHDK interacts with or modifies. Whatever reason mweerdens code checked it is not directly related to this functionality. If file download works, then we can transfer framebuffer data too, there's no difference as far as the low level USB stuff goes.

It looks like the a430 might be USB 1.x, rather than USB 2.0. That might explain the difference in the endpoint size (IIRC USB 2.0 requires a certain minimum size). If this is the case, then the maximum frame rate will be lower, and CHDK certainly cannot change this.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 23 / February / 2012, 16:33:32
I can't wait to see a new set of Chdk PTP subcommand to request a live PTP feed

As a matter of interest, what application do you have that requires the live feed ?
Title: Re: CHDK PTP interface
Post by: asmodyne on 23 / February / 2012, 18:13:17

As a matter of interest, what application do you have that requires the live feed ?


I have no specific application to use live feed in (I don't even own a Canon device that would handle it). I'm just thinking that adding this functionality to the existing CHDK PTP extension subcodes would be the best way to have uniform live-feed implementation over every platform supporting USB 2.0, rather than distinct implementations and protocols for each platform.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / February / 2012, 23:17:31
I have no specific application to use live feed in (I don't even own a Canon device that would handle it).
Does CHDK file download work on your camera ?

If you actually can't run live view, then I certainly don't see how you'd successfully develop a client library.
Quote
I'm just thinking that adding this functionality to the existing CHDK PTP extension subcodes would be the best way to have uniform live-feed implementation over every platform
This has always been the plan. However, getting the appropriate data for each camera necessarily requires some new code in the ports. There's no way around that, Canon has used different frame buffer layouts etc on different cameras.
Quote
supporting USB 2.0, rather than distinct implementations and protocols for each platform.
USB 2.0 is irrelevant. As I've repeatedly tried to tell you, CHDK PTP code know doesn't or care about anything at that level.
Title: Re: CHDK PTP interface
Post by: asmodyne on 25 / February / 2012, 08:03:33
I have no specific application to use live feed in (I don't even own a Canon device that would handle it).
Does CHDK file download work on your camera ?

Okay, I have 24 pics on the A430, let me test it... ptpCam gets it @390 kB/s and chdkptp...gets them...ish
(it stops randomly depending on what I do to the GUI though).




If you actually can't run live view, then I certainly don't see how you'd successfully develop a client library.


Well I do have an A2000IS at hand, but I got it for 5€ for it has broken lens and misses a focus cogwheel, so I'll have to wait for the replacement optics to be delivered. I have good hope that the A2000IS and its Digic 3 will allow live view,  :'( ... it's still a hope though.  :-X

Quote
I'm just thinking that adding this functionality to the existing CHDK PTP extension subcodes would be the best way to have uniform live-feed implementation over every platform
This has always been the plan. However, getting the appropriate data for each camera necessarily requires some new code in the ports. There's no way around that, Canon has used different frame buffer layouts etc on different cameras.

I'm aware of that. As a matter of fact, I think the CHDK Ptp extension needs a few new subcodes, something like :
You may also consider extending the Ptp events with some Chdk cases, for synchronisation purposes.
Shame is, I didn't had/take the time to dwell into the CHDK code deeply enough to do it myself, but if I did, things like Script execution status or memory exchange controls would be implemented as device's ptp EVENTS, not polled commands. As far as I know, ptpCam doesn't even USE the interrupt endpoint, although can MUST have it implemented on every device, meeting protocol standards.


Quote
supporting USB 2.0, rather than distinct implementations and protocols for each platform.
USB 2.0 is irrelevant. As I've repeatedly tried to tell you, CHDK PTP code know doesn't or care about anything at that level.

So, the endpoints MaxPacketSize(s) are platform-dependant ? Nothing the CHDK can fiddle with ?
Title: Re: CHDK PTP interface
Post by: Microfunguy on 25 / February / 2012, 08:37:46

I think the CHDK Ptp extension needs a few new subcodes
I didn't had/take the time to dwell into the CHDK code deeply enough to do it myself, but if I did

aaahhhh  .... yes ... of course you would.
Title: Re: CHDK PTP interface
Post by: asmodyne on 25 / February / 2012, 12:08:18

I think the CHDK Ptp extension needs a few new subcodes
I didn't had/take the time to dwell into the CHDK code deeply enough to do it myself, but if I did

aaahhhh  .... yes ... of course you would.

Are you Is he always this denigrating and condescending to others ?  :blink:
Title: Re: CHDK PTP interface
Post by: Pier on 25 / February / 2012, 12:56:21
asmodyne,
Do not you think it is time to dwell into the CHDK code deeply enough, as you said.
And then came back and be so kind to tell us what you did.
10x
Title: Re: CHDK PTP interface
Post by: waterwingz on 25 / February / 2012, 13:34:46
Are you Is he always this denigrating and condescending to others ?  :blink:
actually,  you caught him on a good day ::)
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / February / 2012, 15:13:09
I'm aware of that. As a matter of fact, I think the CHDK Ptp extension needs a few new subcodes, something like :
  • GetFrameBufferDesc which would return a frame buffer structure and layout description structure as a ptp data payload.
  • BeginLiveView (or whichever name you give it), which start the VF stream
  • AbortLiveView (note : same as above), which stops the feed.
If you want to contribute to this in a meaningful way, you'll need to familiarize yourself with what is actually being done. FWIW, one of the complications is the that the frame buffer characteristics change at runtime depending what the camera is doing. That's why many of them are included in each frame (and I'm leaning to just sending them all every frame)

Begin and Abort are meaningless, for reasons described below...
Quote
Shame is, I didn't had/take the time to dwell into the CHDK code deeply enough to do it myself
This limits your ability to meaningfully participate in the discussion.
Quote
, but if I did, things like Script execution status or memory exchange controls would be implemented as device's ptp EVENTS, not polled commands. As far as I know, ptpCam doesn't even USE the interrupt endpoint, although can MUST have it implemented on every device, meeting protocol standards.
If you reverse engineer the camera stack enough to do this, we certainly might be interested. At the moment, we don't have this capability, and polling is good enough.

Keep in mind that if your implementation requires new entry points or other addresses in the firmware, they need to be found for >100 camera variants.
Quote
So, the endpoints MaxPacketSize(s) are platform-dependant ? Nothing the CHDK can fiddle with ?
Nothing that CHDK currently fiddles with. We use the cameras PTP stack, we don't talk to the low level USB stuff. It might be doable, but there's no obvious need... if your camera is USB 1.1, changing the packet size isn't going to help your transfer rate that much.
Title: Re: CHDK PTP interface
Post by: asmodyne on 25 / February / 2012, 15:33:32
asmodyne,
Do not you think it is time to dwell into the CHDK code deeply enough, as you said.
And then came back and be so kind to tell us what you did.
10x

I would have though the strength of a community's workforce is the eclecticism of its members area of knowledge (work compartmentalization, anyone ?).
I've seen enough references about selfish uses of CHDK-DE in this forum to know that me, diving into the trunk implementation, won't bring anything more to the CHDK circle.
Beside, I already obtained what it needed from the PTP interface two day ago: quick instant snapshots in an easy-to-read format, the whole thing using LibUsbDotNet and C#.
Since reyalp is working on the live view implementation and is willing as I am to have it working in the trunk, I don't see why I wouldn't offer some time to implement a managed API to access it.

I said I would have made the scripts status report through the interrupt ep. Would.
The CHDK ptp 2.0 is working fair enough as it is, so we move on. For now, I'm following reyalp's workline, and implement a managed library around what's already existing and will appear as a generic feature on the trunk.


One last bit of information, since some lads enjoy poking my pride : I've already worked on ARM7 and ARM9 cores in asm and C.
ARM7 was for the time I developped GameBoy Advance game. ;)
Now, I'm using a mini2440 (ARM920T) in os'less mode as a PLC, since its 1.3MP camera interface was what made me decide to buy it. But experimentations brough me to the conclusion that 1.3MP are too small a resolution, and those nasty pinhole lenses made me wonder for pictures a bit more...sharp and exposed  :'(. Hence my interest in CHDK. See the path I took here ?
So please, do know I'm sorry if I take your advice about "dwelling into the CHDK code" as mere attempt to boast.  :-X

Quote
    Shame is, I didn't had/take the time to dwell into the CHDK code deeply enough to do it myself
This limits your ability to meaningfully participate in the discussion.

I know. But having read the whole PIMA-15740 2000 and its USB implementation in the pass past
2 weeks make me a bit dizzy for now. :blink:
I'll dive in, promise  :P
(where should I start reading if I want to understand you live-view code btw ? The A540 sub in the repository link you gave earlier,  is that it ?)

Quote
So, the endpoints MaxPacketSize(s) are platform-dependant ? Nothing the CHDK can fiddle with ?
Nothing that CHDK currently fiddles with. We use the cameras PTP stack, we don't talk to the low level USB stuff. It might be doable, but there's no obvious need... if your camera is USB 1.1, changing the packet size isn't going to help your transfer rate that much.

Eyup. The bottleneck would be the bitrate itself.
I see. So it solely relies on the mechanism mweerden describes: registering extraneous/extern handlers to ptp commands, right ?
Thus the immuable device's USB config. Makes sense.
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / February / 2012, 15:55:23
where should I start reading if I want to understand you live-view code btw ? The A540 sub in the repository link you gave earlier,  is that it ?)
The chdk side is currently in http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live)

The PC side is in http://trac.assembla.com/chdkptp/browser/trunk (http://trac.assembla.com/chdkptp/browser/trunk)

It is not A540 specific, although obviously I'm working with the cameras I have before worrying too much about others. The basic live view should work on most cameras. Getting things like the UI overlay and exactly the right display and aspect rations etc will require additional work on most cameras.

Quote
I see. So it solely relies on the mechanism mweerden describes: registering extraneous/extern handlers to ptp commands, right ?
Exactly. You need to appreciate that CHDK is hack. It's based on reverse engineering and manipulating the internals of a completely undocumented system. So often the approach taken is not the one you would think is "best" in normal design terms or based on reading specifications. Furthermore, as I mentioned before there is a very large number of platforms, so even if a "better" way is discovered, it may not be pursued if implementing requires a lot of work on each camera.
Title: Re: CHDK PTP interface
Post by: asmodyne on 25 / February / 2012, 16:39:48

It is not A540 specific, although obviously I'm working with the cameras I have before worrying too much about others. The basic live view should work on most cameras. Getting things like the UI overlay and exactly the right display and aspect rations etc will require additional work on most cameras.


Okay then. What made me think your work on live view was relying on A540 was the "reyalp-ptp-live" and "live view ...smtg  :-[" in the "comments/description" column of the repository browser. I (stupidly) assumed you were using platform-dependant hardcoded offsets as where to fetch the frame buffer.
But that was before I fully read mweerden's work on ptp handler's registration.
I'll try to fetch download and compile it as soon as the Assembla's 503 error page's gone (it's maintenance time  ::) ).

Title: Re: CHDK PTP interface
Post by: reyalp on 25 / February / 2012, 16:48:42
Okay then. What made me think your work on live view was relying on A540 was the "reyalp-ptp-live" and "live view ...smtg  :-[" in the "comments/description" column of the repository browser. I (stupidly) assumed you were using platform-dependant hardcoded offsets were to fetch the frame buffer.
Of course I am, the offsets *are* platform dependent, and since they are found by reverse engineering, they are generally hardcoded somewhere, or pulled from variables in the camera which are themselves platform dependent. See platform/<camera>/lib.c, platform/camera_platform.h and platform/<camera>/sub/<version>/lib.c

However, the basic frame buffer addresses and characteristics are already known for all complete ports, since they are required for histogram, zebra, md etc. There are some additional characteristics and special cases required for live view which that are *not* already in the code, and these will have to be added for each camera to enable full functionality. There is no way around this.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / February / 2012, 03:05:18
As I said before, I'll try to put a binary build of chdkptp soon.
This is done, see here http://chdk.setepontos.com/index.php?topic=6231.45 (http://chdk.setepontos.com/index.php?topic=6231.45)

Note that this currently requires a CHDK build from my branch.
Title: Re: CHDK PTP interface
Post by: asmodyne on 26 / February / 2012, 13:02:53

However, the basic frame buffer addresses and characteristics are already known for all complete ports, since they are required for histogram, zebra, md etc. There are some additional characteristics and special cases required for live view which that are *not* already in the code, and these will have to be added for each camera to enable full functionality. There is no way around this.

Tonight will be a long brawl between your trunk's code, Code Compare, and yours truly.  :P
Title: Re: CHDK PTP interface
Post by: asmodyne on 26 / February / 2012, 21:49:01

Uuuh...since I'm not sure... the A540's base ROM address is 0xFFC00000, right ?

Fact is, the last program I used one can call a disassembler was running under MSDOS, and targeted 386 CPUs.  :-[

So, I've done a little cross-check between three "sub/xxxx/lib.c" files, namely :

The main diff I noticed (apart from the platforms offsets, of course), is at the very end of your file :

Code: [Select]

// PTP display stuff
int vid_get_palette_type() { return 1; }
int vid_get_palette_size() { return 16*4; }

void *vid_get_bitmap_active_palette() {
    return (void *)0x634E0; // GetPaletteFromPhysicalScreen
}

void *vid_get_bitmap_active_buffer()
{
    return (void*)(*(int*)0x5ED0); // FFD23420 DisplayPhysicalScreenWithYUVPalette
}


Ask me to do some complicated hardware reverse engineering: fine, I've done it on a regular basis for the last 15 years or so...
Now, I'm so rusty at software reverse engineering I don't even know how to search a runtime ref to a hard-coded string with IDA. :-[
Anyway, that was just to state my current disasm skills... moldy  ;)


Looking at the last two functions in your code, I obviously need to find the bitmap's palette and raster indices map offsets.
To do so, I have to locate any usage references about "GetPaletteFromPhysicalScreen" and "DisplayPhysicalScreenWithYUVPalette"... but DisplayPhysicalScreenWithYUVPalette doesn't even appear in the A540 dump ! I've run it through IDA: nothing ! Where did you find it reyalp ?  :-X



Title: Re: CHDK PTP interface
Post by: reyalp on 26 / February / 2012, 22:53:31
Uuuh...since I'm not sure... the A540's base ROM address is 0xFFC00000, right ?
Yes.
Quote
The main diff I noticed (apart from the platforms offsets, of course), is at the very end of your file :
FWIW, a better way to see what I've changed is http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live) (or check out the source with your favorite svn client and look at the logs and diffs)
Quote

To do so, I have to locate any usage references about "GetPaletteFromPhysicalScreen" and "DisplayPhysicalScreenWithYUVPalette"... but DisplayPhysicalScreenWithYUVPalette doesn't even appear in the A540 dump ! I've run it through IDA: nothing ! Where did you find it reyalp ?  :-X
I don't actually remember  :-[ Someone (probably me, possibly ewarv) found them a long time ago to support ewavrs chdkcam liveview code. That history can probably be found somewhere near the start of this thread...

DisplayPhysicalScreenWithYUVPalette appears to be something identified by the A series flirt sigs. See http://chdk.wikia.com/wiki/Loading_dump_to_IDA (http://chdk.wikia.com/wiki/Loading_dump_to_IDA)

But, since you have the address for one camera (the address in the comment is correct for a540), all you need to do is find some convenient landmark that identifies that code in the known dump, and then find the corresponding landmark in yours.

GetPaletteFromPhysicalScreen is an eventproc, so should be easier to find.
Title: Re: CHDK PTP interface
Post by: asmodyne on 27 / February / 2012, 20:25:36
FWIW, a better way to see what I've changed is http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live)...

Very useful indeed. I'm a noob with assembla. TIL something new about it, thanks reyalp !   :xmas

DisplayPhysicalScreenWithYUVPalette appears to be something identified by the A series flirt sigs. See http://chdk.wikia.com/wiki/Loading_dump_to_IDA (http://chdk.wikia.com/wiki/Loading_dump_to_IDA)

A-series indeed. I've just understood it's part of the VxWorks signatures semantic. Loading those 'old' signatures on both A540 and A430 binaries binary dumps helped me find it in less than an hour !  :P
How could I live this long without using IDA before ?  ::)

GetPaletteFromPhysicalScreen is an eventproc, so should be easier to find.

Yup... found it almost instantly, thanks to the CHDK idc scripts.  :)


Excellent. I now have the offsets I missed in "./sub/lib.c".  8)
As soon as I get my hand on the A430, I'll test it with your brand new ChdkPtp binary. I'm away from home for a week or so, and only brough a copy of my CHDK directory on a laptop.
brb (in a week max, maybe on Friday).
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / February / 2012, 21:59:31
Very useful indeed. I'm a noob with assembla. TIL something new about it, thanks reyalp !   :xmas
If you are going to be working with the source, I strongly suggest getting tortoisesvn (assuming you are on windows) and checking out the code with it.
Quote
Excellent. I now have the offsets I missed in "./sub/lib.c".  8)
FWIW, you don't need any of these bitmap/palette functions for the most basic live view function.
Title: Re: CHDK PTP interface
Post by: waterwingz on 27 / February / 2012, 22:06:34
If you are going to be working with the source, I strongly suggest getting tortoisesvn (assuming you are on windows) and checking out the code with it.
Command line svn commands under Linux turn out to be not too bad.  Still,  the integration of TortoiseSVN into Windows that allows the file and directory icons in change to reflect their svn status is a nice feature I miss a lot.  Yes, you get the same info with   svn st chdk  on the command line but its not the same somehow.

Title: Re: CHDK PTP interface
Post by: fe50 on 28 / February / 2012, 01:29:17
Still,  the integration of TortoiseSVN into Windows that allows the file and directory icons in change to reflect their svn status is a nice feature
You may have a look to RapidSVN (http://rapidsvn.tigris.org/ (http://rapidsvn.tigris.org/) ) for a Linux GUI.
I often use it with Windows, should work on Linux & Mac too.

The deep integration into the windows system is one thing i don't like with TortoiseSVN, with big projects sometimes it slows down a fast PC extremely. If anyway possible, i use all my software portable, without installation; this works with a lot of apps, also with software which isn't designed to run 'portable'.
For SVN, a nice solution for me is portable RapidSVN, running from a RAMdisk (also portable, of course) to speed up things & to hold off thousands of svn files from my hard discs ;)
Title: Re: CHDK PTP interface
Post by: asmodyne on 28 / February / 2012, 14:33:41
over-the-phone test of the modified CHDK, from your live-view trunk, reyalp.
Ain't I a resourceful lad ?  :haha

Anyway, the A430 responded nicely when asking for the UI overlay feed. But as soon as we ask for the viewfinder feed, the beast crashes.

Here is a screenshot of the live streamed UI :

(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fchdk.setepontos.com%2Findex.php%3Faction%3Ddlattach%3Btopic%3D4338.0%3Battach%3D6158&hash=71b8699a7f78da1df0021ac6ffbc1da9)


The operations leading to this were :


Of course, dumping the stream didn't brough any light upon the issue, but ChdpPtp's console textbox gave some (presumably) meaningful info :
[/list]
Code: [Select]
bm_max_width:360
bm_max_height:240
bm_buffer_width:360
lcd_ascpect_ratio:0
update_vidinfo: changed
vp_xoffset:nil->0
vp_yoffset:nil->0
vp_width:nil->720
vp_height:nil->240
vp_buffer_start:nil->0
vp_buffer_size:nil->0
bm_buffer_start:nil->44
bm_buffer_size:nil->86400
palette_type:nil->1
palette_buffer_start:nil->86444
palette_buffer_size:nil->64
palette:
0x00, 0x00, 0x00, 0x00, 0xff, 0xe0, 0x00, 0x00, 0xff, 0x3c, 0xde, 0x4a, 0xff, 0xb9, 0x00, 0x00,
0x7f, 0x00, 0x00, 0x00, 0xff, 0x6e, 0xa1, 0xa2, 0xff, 0xb2, 0x8c, 0x1f, 0xff, 0x5f, 0x00, 0x00,
0xff, 0x9a, 0xa9, 0x50, 0xff, 0x8a, 0x50, 0xb0, 0xff, 0x4b, 0x3d, 0xd4, 0xff, 0x23, 0x1b, 0xe2,
0x7f, 0x00, 0x7b, 0xe2, 0xff, 0x30, 0x00, 0x00, 0xff, 0x69, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00,
recording to chdk_30f8_20120228_132726.lvdump


I suppose all those variable followed by a "nil->xxx" means the value was missing and replaced by default constants, right ?
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / February / 2012, 16:06:53
But as soon as we ask for the viewfinder feed, the beast crashes.
The camera, or the client ?
Quote
I suppose all those variable followed by a "nil->xxx" means the value was missing and replaced by default constants, right ?
Not quite. It only prints this when the information changes (since it would be bad to spam every frame).  The x->y just tells you the old and new value. On the first frame, the "old" values are all nil. The code for this can be seen in lua/gui_live.lua in the chdkptp package.

I'm not clear if the information in the console comes from before crash (in which case, it tells us nothing) or relates to the data that caused the crash.

The camera may crash if the viewport address is incorrect or zero.

The camera may generate a romlog when it crashes, see http://chdk.wikia.com/wiki/Debugging#Camera_crash_logs_.28romlog.29 (http://chdk.wikia.com/wiki/Debugging#Camera_crash_logs_.28romlog.29)

watching the return value of vid_get_viewport_active_buffer may shed light on the situation (see misc debug vals in chdk core/gui.c ).

Note that you can enable "viewfinder" in playback mode, it will show you whatever picture is on the screen. This may fail (return null address, crash) if a video is selected.
Title: Re: CHDK PTP interface
Post by: asmodyne on 28 / February / 2012, 18:46:21
But as soon as we ask for the viewfinder feed, the beast crashes.
The camera, or the client ?

The camera crashes.

I'm not clear if the information in the console comes from before crash (in which case, it tells us nothing) or relates to the data that caused the crash.

The console log here is what's written out before the device crashes. After that, the only thing updated is the console window, saying it received the bad return value 0x2FF, as it does anytime the A430 crashes for any reason whatsoever, while a ptp session's in progress.

The camera may generate a romlog when it crashes, see http://chdk.wikia.com/wiki/Debugging#Camera_crash_logs_.28romlog.29 (http://chdk.wikia.com/wiki/Debugging#Camera_crash_logs_.28romlog.29)

watching the return value of vid_get_viewport_active_buffer may shed light on the situation (see misc debug vals in chdk core/gui.c ).

Nice ! I'll look into it.  8)

Note that you can enable "viewfinder" in playback mode, it will show you whatever picture is on the screen. This may fail (return null address, crash) if a video is selected.

Excellent ! I assumed the record mode was a must for some reason. I'll try that. :)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / February / 2012, 19:01:14
Some observations, also on A430 ( with correct vid_get_bitmap_active_buffer() and vid_get_bitmap_active_buffer() ).
For me, it appears that when I select a target fps that cannot be reached, the chdkptp ui controls seem to freeze (start to lag, text no longer updates). Clicks on gui elements take effect after some (many seconds) delay when this happens. The camera hasn't crashed since I put the additional functions into lib.c (may be a coincidence).
Below values apply for still image (record) or play mode. Client runs on linux.
transferred    max fps    T/P avg kB/s    Xfer last msec    Xfer last kB/s   
viewfinder3 (barely)~755~310~810
ui overlay4 (5 is unstable)~337~159~530
both2~670~415~835

Camera buttons on the gui have no effect until record mode is activated (but once that happens, they also work in play mode). After reconnecting to a running camera with a previously activated record mode the gui cam buttons also work.
Title: Re: CHDK PTP interface
Post by: asmodyne on 28 / February / 2012, 20:12:28
The camera hasn't crashed since I put the additional functions into lib.c (may be a coincidence).

Do you mean you actually got the Viewport stream up and running on A430 ?  :blink:
If that's the case, may I ask you for a copy of your lib.c ? Pretty please ?  :-*

Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / February / 2012, 20:21:41
It's all related to the bitmap overlay:
Code: [Select]
void *vid_get_bitmap_active_buffer()
{
    return (void*)(*(int*)0x5EAC); // sub_ffd0cae8 DisplayPhysicalScreenWithYUVPalette
}

void *vid_get_bitmap_active_palette() {
    return (void *)0x714a8; // found also in sub_ffd0cae8
}

int vid_get_palette_type() { return 1; }
int vid_get_palette_size() { return 16*4; }
Title: Re: CHDK PTP interface
Post by: asmodyne on 28 / February / 2012, 20:29:41
Well, I'll be damned !

here's what I used :
Code: [Select]
// PTP display stuff
int vid_get_palette_type() { return 1; }
int vid_get_palette_size() { return 16*4; }

void *vid_get_bitmap_active_palette() {
    return (void *)0x714A8; // GetPaletteFromPhysicalScreen
}

void *vid_get_bitmap_active_buffer()
{
    return (void*)(*(int*)0x5EAC); // loc_FF90CB50 DisplayPhysicalScreenWithYUVPalette for a430 with ROMSTART = 0xFF800000
}

same offsets...and nothing. No viewport stream without having the camera crashing.

I'll attach my complete inoperative lib.c, for reference's sake. It's a 100b sub, by the way.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / February / 2012, 20:41:21
@asmodyne

Are you using the latest reyalp-ptp-live branch with the latest chdkptp (I mean latest svn)?
If your only change was the code in your post, it should be the same as mine.

But it's not.
You only need those (the ones I and also you posted) additional lines in platform/a430/sub/100b/lib.c
vid_get_viewport_fb_d() also needs to be changed or else (as the comment says) playback mode with a movie selected will cause chdkptp's viewfinder transfer to fail.
Diff against reyalp-ptp-live
Code: [Select]
Index: platform/a430/sub/100b/lib.c
===================================================================
--- platform/a430/sub/100b/lib.c (revision 1701)
+++ platform/a430/sub/100b/lib.c (working copy)
@@ -46,7 +46,8 @@
 
 void *vid_get_viewport_fb_d()
 {
-    return (void*)(*(int*)0x71AB0); // @ffd0f29c
+    int x=(*(int*)0x71AB0); // @ffd0f29c
+    return (void*) (x ? x : vid_get_viewport_fb()) ;
 }
 
 long vid_get_viewport_height()
@@ -59,3 +60,15 @@
 {
     return (char*)0x7C588;
 }
+
+void *vid_get_bitmap_active_buffer()
+{
+    return (void*)(*(int*)0x5EAC); // sub_ffd0cae8 DisplayPhysicalScreenWithYUVPalette
+}
+
+void *vid_get_bitmap_active_palette() {
+    return (void *)0x714a8; // found also in sub_ffd0cae8
+}
+
+int vid_get_palette_type() { return 1; }
+int vid_get_palette_size() { return 16*4; }
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / February / 2012, 22:00:51
For me, it appears that when I select a target fps that cannot be reached, the chdkptp ui controls seem to freeze (start to lag, text no longer updates).
Yes, this is known. chdkptp is currently dumb, it just runs a timer to read usb and update the live view. This seems to behave particularly badly on linux when the code takes >= the timer interval.
Quote
Camera buttons on the gui have no effect until record mode is activated (but once that happens, they also work in play mode). After reconnecting to a running camera with a previously activated record mode the gui cam buttons also work.
This is normal. On newer (dryos ?) cameras you can use the magic post_levent_to_ui(4484) to unlock. For old cams, I believe switching to rec is the only known method.

I should make chdkptp send the unlock event for cams that support it, somehow.

edit:
I think your transfer rates are as expected for a usb 1 device.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 10:45:48
@srsa_4c

from your diff code :
Code: [Select]
long vid_get_viewport_height()
@@ -59,3 +60,15 @@
 {
     return (char*)0x7C588;
 }

What the actual... ??? What ?  :blink:
So, we're truncating the 32bits reference 0x7C588 to a s8 or (s16*) referenece and return it as a s32 ? Is that it ?  :blink:


Would you mean :
Code: [Select]
long vid_get_viewport_height()
@@ -59,3 +60,15 @@
 {
     return (long)0x7C588;
}

Title: Re: CHDK PTP interface
Post by: srsa_4c on 29 / February / 2012, 10:59:36
@asmodyne
That was a unified diff (http://en.wikipedia.org/wiki/Diff). It has since been committed. Get a fresh svn copy, then see that lib.c  :)
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 11:08:50
@asmodyne
That was a unified diff (http://en.wikipedia.org/wiki/Diff). It has since been committed. Get a fresh svn copy, then see that lib.c  :)

eeeeyup. I'll do that.  ;)

PS : I'm SORRY srsa_4c !  :'( My apologies, if I ever lead readers to think this weird code could have been yours.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 12:18:28
Soo, it seems that the live view works without problem. My "sugacube"  :D said the average framerate hit 2.98 fps with ChdkPtp only asking for Viewport feed. I think we hit the A430's maximum usb bandwith here (it was the only device on the host's controller).

@reyalp

Next thing, I'll bring myself to undersand the mechanics of the view stream structure (if I want to decode it).
It's in your ChdkPtp/lua sources,  izznit ?
I'll try to implement a proper way to pass the data container's payload directly to a pixel shader (to get an easy-to-use bitmap output).
Will I use DirectX or OpenGL, I still cannot say. I'm a tadbit inclined to use SharpGL though  (i.e openGL).
Anyway, manipulating the live view frames stream is the GPU's job, IMO.
We'll see this weekend.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / February / 2012, 12:29:34
There are many ways the LiveView frames can be handled.
For the record, are you looking at a solution that works for most users or one that works with your setup ?

They may not be the same.

Another thing, developers are disappointed by low frame-rates.
This is all great coding fun, but realistically why does the framerate matter, what will this feature be used for ?
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 12:46:38
Next thing, I'll bring myself to undersand the mechanics of the view stream structure (if I want to decode it).
It's in your ChdkPtp/lua sources,  izznit ?
The structures defining the live view data are in CHDK core/live_view.h. However... this is going to change because it doesn't adequately describe all the characteristics a client needs to display correctly in every case, so don't get too attached to it. This only describes the layout of the information, not the actual encoding of the framebuffers.

Quote
I'll try to implement a proper way to pass the data container's payload directly to a pixel shader (to get an easy-to-use bitmap output).
For this, you should mostly be worried about the frame buffer formats, described here http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers)

The structure describing them (live_view.h) should be dealt with in normal code, not a GPU.

For live view, you need to take a U Y V Y Y Y and turn it into 2 or 4 RGB pixels. Whether 2 or 4 is preferred is one of the things that isn't adequately described, although with GL, you could just do 4 all the time and scale the resulting output when it comes time to render.

Additionally, the rows in the live view buffer may be wider than the number of valid pixels. E.g on a540, each buffer row is 720 pixels (=1080 bytes) wide, but only the first 704 contain valid data. It's also possible for the data to be offset, e.g. for letterboxed modes.

The data may be offest vertically within the buffer, but I am probably going to change the protocol so any top/bottom padding are not sent. X padding can't easily be handled this way, since it would require a lot of copying on the camera.

The bitmap buffer is 8 bit indexed. There are multiple palette formats, only one of which I've implemented support for so far. In general they will all by AYUV in some form, but the details vary. Note that several of these actually only use 16 palette entries, the 8 bit index is split into nibbles and the two resulting AYUV values are combined.  The frame buffers page has more info.

See chdkptp/yuvutil.c for an adequate (but not necessarily correct) implementation of the format used on a540 and probably most digic II/vxworks cams.
Quote
Will I use DirectX or OpenGL, I still cannot say. I'm a tadbit inclined to use SharpGL though  (i.e openGL).
If you use shaders that can be sent directly to opengl, it should be quite easy to use this in CHDKPTP, which has native support for GL canvases.
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 13:01:11
Another thing, developers are disappointed by low frame-rates.
This is all great coding fun, but realistically why does the framerate matter, what will this feature be used for ?
I think 10fps is perfectly adequate for real time control of the camera.

However, doing the rendering in opengl or similar gives you a lot of flexibility, and performance for free. Opengl is also very portable.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / February / 2012, 13:10:58
doing the rendering in opengl or similar gives you a lot of flexibility, and performance for free. Opengl is also very portable.

That is what I use.

However, I do not have shader support on my old PC that I use, not sure how many people do.

Also, my resizing from 720x240 to 320x240 is very crude  .. though perfectly adequate for what I use it for.

Not sure If I have to create a 1024x256 image if I want OpenGL to do the resizing.

That is a bit messy, slower than a simple copy of a continuous buffer area.

Also, not sure how common the graphics-card support is for the non-power-of-two functions (cannot remember which one offhand).

You never know when hardware or software rendering is being used.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 15:25:59

Not sure If I have to create a 1024x256 image if I want OpenGL to do the resizing.

That is a bit messy, slower than a simple copy of a continuous buffer area.
If it was only for resizing or color shifting or clamping purposes, one wouldn't even think of a pixel shader for such low resolutions.
The point in having an library or an API providing a shader pipeline relies on all the subsequent tortures you can apply to the frames, which can be fairly CPU-expensive.

Also, not sure how common the graphics-card support is for the non-power-of-two functions (cannot remember which one offhand).
By power-of-two, you're speaking about the graphic cards resolutions, right ?  :)
Well, even if you have to deal with non-power-of-two dimensions, you'll do like anyone would do when compressing a video in a codec which doesn't support it : cropping or letterboxing. One given, one taken, we have to make compromises.  ;)


Another thing, developers are disappointed by low frame-rates.
Higher framerate ? To do what ? Some kind of remote video recording ? One just have to buy a bigger SD card, or think about implementing a compatibility extension for SDHC up to 16GB then, cuz' the camera would do it just fine, in higher resolutions than the crappy viewport's 240 lines.
Or would it be to process it for vision ? An old PC's CPU wouldn't handle complex convolution processings without having to give the thread the real-time priority. Thus bye-bye USB synchronicity !

Anyway, its obviousl the old A-series USB peripheral won't handle higher bandwidths. Even with the padding bytes removed from the buffer, I don't think one can achieve more than 5fps anyway...with high hopes.

However, I do not have shader support on my old PC that I use, not sure how many people do.

Well, I bough this crappy mother board two or three years ago : http://www.asrock.com/mb/overview.asp?model=p4vm900-sata2 (http://www.asrock.com/mb/overview.asp?model=p4vm900-sata2), brand new, for less than 50 bucks, shipping included..and guess what : the crappy integrated GPU it bears handles Shaders 2.0. Just have a look at the specs.

So unless one's stingy enough (meaning more than me) to hope manipulating the viewfinder's stream using a computer made of juice boxes and toothpicks (but some expensive glue), he will eventually have to use (hear 'buy') a host machine who can deal with what he expects out of his Canon camera. At 2fps, at least.  :P

However, doing the rendering in opengl or similar gives you a lot of flexibility, and performance for free. Opengl is also very portable.
Gosh, it's so portable I remember making in run on Pocket PCs ! ( <-- re-edit spoiler : IT WAS A TWEAK, don't get your hopes too high !  :P )
I'm just not sure about the way it handles native compilation of HLSL against hardware that actually handles shaders higher than 2.0. I'll have to read more about it, since I fear OpenGL may relies on software shading too often. It's my ignorance talking here. (<-- PS  : Neverming, OpenGL have those new "frame buffer objects" now... all's well)
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 15:38:28
By the way, did you ever heard of Maxim Stepin's hqNx enlarging filters ? It's wonderful !

Just sayin'...  :-*
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / February / 2012, 15:39:53
I was only thinking of shaders for directly rendering the Y411 viewfinder image.
(I have no idea how to do it and cannot test it anyway).

At the moment, I resize from 720x240 to 320x240 in 'C' code.
It is crude nearest neighbour.
I am not sure if interpolating will slow it down too much and with very little gain other than looking nicer.

So, the question is  .. can OpenGL do the resizing (not just cropping but squashing horizontally) and if so does the appropriate function that renders to a quad require a power-of-two source image ?

How would we know if was been hardware accelerated anyway ?
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 15:45:24
Lets not get too deep into graphic APIs here.
By power-of-two, you're speaking about the graphic cards resolutions, right ?  :)
Originally, opengl only supported power of 2 textures. There have been extensions for a long time that support other dimensions, I would guess they are widely supported.
Quote
Higher framerate ? To do what ? Some kind of remote video recording ? One just have to buy a bigger SD card, or think about implementing a compatibility extension for SDHC up to 16GB then, cuz' the camera would do it just fine, in higher resolutions than the crappy viewport's 240 lines.
Not all the cameras are limited to 240 lines. a540 (and presumably most similar vintage digic II) does 528 lines in 640x480 video mode, and some newer cameras like the g12 variety of 480 line modes. So decent resolution video is sometimes available directly over USB.

However, to get nice video you'd also have to somehow synchronize the frame grabs with the camera refresh, or you get tearing.

It would also be very difficult not to have substantial jitter in the frame rate.
Quote
Anyway, its obviousl the old A-series USB peripheral won't handle higher bandwidths. Even with the padding bytes removed from the buffer, I don't think one can achieve more than 5fps anyway...with high hopes.
Only on the very old USB 1.1 cams. The vast majority of CHDK supported cameras are USB 2.0
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 15:49:42
At the moment, I resize from 720x240 to 320x240 in 'C' code.
It is crude nearest neighbour.
I currently do it even cruder (like the CHDK code that reads the viewport): Just skip 2 Y values of every U Y V Y Y Y when doing the initial conversion. If you are going to a 360x240 display anyway, I don't think you are losing much.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 15:54:13
So, the question is  .. can OpenGL do the resizing (not just cropping but squashing horizontally) and if so does the appropriate function that renders to a quad require a power-of-two source image ?

How would we know if was been hardware accelerated anyway ?
I'm not sure using OpenGL to do the resizing would be profitable if you absolutely WANT to write a method to do the interpolation.
Fact is, I'm pretty sure that passing a 320x240 P-buffer to and OpenGL's 640x480 viewport would make your card's OpenGL driver implementation do the interpolation automatically, without underlying code on your side. 

Still, have a look at those hqNx filters... I understand they're dedicated to low-resources platforms, and I wonder what they'd give once applied to a video feed. Hey ! It's all INTEGERS magic ! No floating arithmetic here ! (^w^)

I currently do it even cruder (like the CHDK code that reads the viewport): Just skip 2 Y values of every U Y V Y Y Y when doing the initial conversion. If you are going to a 360x240 display anyway, I don't think you are losing much.

Nice trick indeed !  :P
I know from experience than truncating the LSb.s of a 18bits per channel RGB  frame to get a RGB565 works pretty well, without anyone noticing the difference. In all, I never did interpolate anything.
But don't tell anyone else ...  :-X
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / February / 2012, 16:11:27
I'm pretty sure that passing a 320x240 P-buffer to and OpenGL's 640x480 viewport would make your card's OpenGL driver implementation do the interpolation automatically

The viewport image is 720x240 or 360x240 (3:2 aspect-ratio not the correct 4:3).

Quote
It's all INTEGERS magic ! No floating arithmetic here ! (^w^)

Yes, the thought of software floating point is what has put me off writing interpolation code.

I guess everything could be scaled-up by a 1000x or so.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 16:23:36
The viewport image is 720x240 or 360x240 (3:2 aspect-ratio not the correct 4:3).

Viewport's dimension are irrelevant in this case, since you're working in windowed mode.
You can even use a 551 wide per 777 heigh viewport, FWIW, openGL won't care as long as you'r not in fullscreen mode.
Things made short : powers of two are only required in fullscreen.

Yes, the thought of software floating point is what has put me off writing interpolation code.

I'm with you 100% on that. Whatever the CPU is. Only recent (less than 5 years I guess) GPUs can handle such floating-point workloads.

I guess everything could be scaled-up by a 1000x or so.
Waddayamean ?  :blink:
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 16:26:30
Viewport's dimension are irrelevant in this case, since you're working in windowed mode.
You can even use a 551 wide per 777 heigh viewport, FWIW, openGL won't care as long as you'r not in fullscreen mode.
You aren't following. In CHDK, we call the camera live view (view finder image or display of selected jpeg/avi in playback mode) the "viewport". This has specific fixed dimensions, aspect ratio etc, and is completely unrelated to the opengl concept of a viewport.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 29 / February / 2012, 17:47:10
have a look at those hqNx filters

"The filter was not designed for photographs, but for images with clear sharp edges, like line graphics or cartoon sprites.
 It was also designed to be fast enough to process 256x256 images in real-time."
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 19:19:28
Viewport's dimension are irrelevant in this case, since you're working in windowed mode.
You can even use a 551 wide per 777 heigh viewport, FWIW, openGL won't care as long as you'r not in fullscreen mode.
You aren't following. In CHDK, we call the camera live view (view finder image or display of selected jpeg/avi in playback mode) the "viewport". This has specific fixed dimensions, aspect ratio etc, and is completely unrelated to the opengl concept of a viewport.
Sorry, I realize I wasn't explaining myself correctly.  :-X
My point is : OpenGL or DirectX device frame buffer can be instantiated with a 720x240 resolution, and recklessly be presented on a 333x999 surface (with deformation, that goes without saying). It's up to the graphic card's driver implementation to make it happen, or to OpenGL's software emulation, if your card's driver gives up on this kind of task (which should be quite rare these days).
Need an example : try some old DirectX 9.0c SDK tutorials : you can resize the presenting window without even having DirectX firing an event about frame buffer resizing.
But, if you present a pixel buffer directly to a rendering surface, that's another story : the presentation stage is no more transparent to you, since you affect the rendering surface directly, with your own pixel data.
Fwiw, as I said earlier in a post-scriptum, recent OpenGL developments added those "frame buffer objects", making the implementation of OpenGL client app totally device independent, unlike P-buffers.

"The filter was not designed for photographs, but for images with clear sharp edges, like line graphics or cartoon sprites.
 It was also designed to be fast enough to process 256x256 images in real-time."
Aaaawww... Too bad then. It was a good alternative to nearest-neighbor scaling, without having to use floating-point arithmetic though.
Title: Re: CHDK PTP interface
Post by: asmodyne on 29 / February / 2012, 22:42:04
"The filter was not designed for photographs, but for images with clear sharp edges, like line graphics or cartoon sprites.
 It was also designed to be fast enough to process 256x256 images in real-time."

I tested hq2x against nearest neighbor using nstatic's short videoclip (post 81548 of this very topic).

The result is more than crappy. Luminance gradients gets blocky, while chroma is shifted in unpredictable directions.  :o I almost had the impression to watch early days NTSC.
*sigh*
I had good hope this algorithm would give good result when resizing small frames in real time...
Oh well...There's plenty of other fishes in the sea.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 29 / February / 2012, 23:23:21
However, to get nice video you'd also have to somehow synchronize the frame grabs with the camera refresh, or you get tearing.
You may want to look at sub_ffc95b68 in A540. This function is used by MovieRecordTask to install and remove (frame notification and information) hooks into the liveview code.
LiveImageTool.Pause / LiveImageTool.Resume may also help to fight tearing (don't know what happens when these are called many times per second) when the USB transfer is not fast enough.
Of course LiveView will probably stop in review/play mode.

edit:
Some notes / comments related to the routine(s) I wrote about above, in the A420: http://chdk.setepontos.com/index.php?topic=7067.msg76126#msg76126 (http://chdk.setepontos.com/index.php?topic=7067.msg76126#msg76126)

edit2:
During my experiments with saving uncompressed/compressed images from the live buffers I haven't used any synchronization. By choosing the buffer address vid_get_viewport_live_fb() provided I got tearing in a relatively high % of the pictures. When I chose another buffer address (by subtracting 2 instead of 1 from buff), the tearing disappeared. This was on the A420 in its 10fps video mode, pictures were saved to the SD card.

Models with USB 1.1: Ixus30/SD200, Ixus40/SD300, A410 ... A470 (As USB is handled directly by the DIGIC, this is a configuration issue...)
All other CHDK-supported cameras are hi-speed USB 2.0 .
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / February / 2012, 23:49:15
I had good hope this algorithm would give good result when resizing small frames in real time...
Honestly, I don't think this is anything that we have to worry about for any vaguely recent PC.

Getting back to some more CHDK specific stuff, a couple more observations
- On a540 and d10 digital zoom changes the height of the viewport buffer, more zoom=less lines.
- On a540, the width doesn't change, while on d10, the highest zoom is half width
- I've confirmed with both cameras that recreview mode uses the wrong viewport addresses, as reported by webguy here http://chdk.setepontos.com/index.php?topic=6231.msg81993#msg81993 (http://chdk.setepontos.com/index.php?topic=6231.msg81993#msg81993)
Title: CHDK PTP interface - lightweight frame descriptor
Post by: asmodyne on 11 / March / 2012, 18:51:20
So reyalp...

Do you have any news about the way you transfer frames buffer descriptors in your modified trunk, or are those still included in each frame ?

Title: Re: CHDK PTP interface
Post by: reyalp on 11 / March / 2012, 18:58:34
Do you have any new about the way you transfer frames buffer descriptors in your modified trunk, or are those still included in each frame ?
I have not changed that yet. You can see all changes in that branch here: http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/log/branches/reyalp-ptp-live)

Most information is transferred every frame, because it can (on some cameras at least) change at any time. Future versions will most likely put more (possibly everything) in the per frame information.

I'm at a point where the client is working well enough to get into that, I just need a large block of free time to work on it. I didn't end up having that this weekend, maybe the next one...
Title: Re: CHDK PTP interface
Post by: asmodyne on 13 / March / 2012, 22:20:08

Okay. Perfect then, it will give me time to catch up with your work.
So far, I've implemented every PTP command from the PIMA15740-2000 white papers.
The only things remaining are the events on the interrupt pipe I'll have to encapsulate somehow (I cannot leave tens of those firing raw PTP events to users, it have to be coherent to the "Device" object I implemented).

As soon as this is done, I'll dig into your C code in order to understand the structure of the raw frame's header, and how you use it in you decoding function. Everything is in your sources, so I wouldn't have any problem finding it.
I'll test in with the A430 first, and then switch to the A2000IS (I've replaced the optics, it's working now, yay !  :P) for further "high" fps tests.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / March / 2012, 22:54:49
Okay. Perfect then, it will give me time to catch up with your work.
So far, I've implemented every PTP command from the PIMA15740-2000 white papers.
The only things remaining are the events on the interrupt pipe I'll have to encapsulate somehow (I cannot leave tens of those firing raw PTP events to users, it have to be coherent to the "Device" object I implemented).
Note that for CHDK, you don't need most of this. We don't use events (don't know how to do them on the camera end), and we don't rely on any non-CHDK commands outside of those needed to set up a session. Having the standard PTP could be useful of course, just saying they aren't required.
Quote
As soon as this is done, I'll dig into your C code in order to understand the structure of the raw frame's header, and how you use it in you decoding function. Everything is in your sources, so I wouldn't have any problem finding it.
The header is currently defined in live_view.h in my branch of the chdk source. The decoding stuff is in liveimg.c in chdkptp. Various header fields are also used in several places in the lua code, since it is responsible for figuring out the final dimensions to render.
Title: Re: CHDK PTP interface
Post by: asmodyne on 14 / March / 2012, 10:02:13
The only things remaining are the events on the interrupt pipe I'll have to encapsulate somehow...
Note that for CHDK, you don't need most of this. We don't use events (don't know how to do them on the camera end), and we don't rely on any non-CHDK commands outside of those needed to set up a session. Having the standard PTP could be useful of course, just saying they aren't required.

I know they aren't used by the CHDK extension.
I simply though that having some events like "Object Added" (after you called the "Shoot()" script) , "Canceltransaction" (for committing the cancellation of a large transfer) or "DevicePropchanged" (when modifying the capture size) would be a great asset, even for applications relying on CHDK extensions.
Fact is, those events aren't mandatory in the PTP conformance section of PIMA15740, but It appears Canon implemented them on cameras as "primitive" as the A430.
Thus, I'm implementing their reception.
Title: Re: CHDK PTP interface
Post by: asmodyne on 14 / March / 2012, 10:15:03
Oh, I've just stumbled on this article about Bayer mosaics and pixel shaders.
It's very relevant to what live view requires (and what we're looking for). Here :

http://openendedgroup.com/field/wiki/GigECamerasAndField (http://openendedgroup.com/field/wiki/GigECamerasAndField)

Title: Re: CHDK PTP interface
Post by: philmoz on 14 / March / 2012, 15:42:27
Oh, I've just stumbled on this article about Bayer mosaics and pixel shaders.
It's very relevant to what live view requires (and what we're looking for). Here :

http://openendedgroup.com/field/wiki/GigECamerasAndField (http://openendedgroup.com/field/wiki/GigECamerasAndField)



Live view uses the viewport frame buffer which is generated from the sensor data by the camera, not the raw sensor data itself.
This is much lower resolution (e.g. 720x240) and in a YUV encoded format - so bayer de-mosaicing is not needed. See http://en.wikipedia.org/wiki/YUV. (http://en.wikipedia.org/wiki/YUV.)

Even if you could transfer the the raw sensor data you would be lucky to get 1 frame every 5 seconds over USB.

Phil.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 12:44:23
Even if you could transfer the the raw sensor data you would be lucky to get 1 frame every 5 seconds over USB.
Phil.
Eeeyup, but as I said somewhere in this thread, using shaders here isn't about framerate, it's for quick image data preparation, for futher use : One would appreciate from the client library to provide quick convolution filters on large stills. And GPU shaders are the faster way to achieve it nowadays.
That's why I plan on using GLSL for this: Shaders-processed filters for big stills. Using it to decode Bayer mosaic frames or translate YUV to RGB bitmaps is just gravy. But I love gravy.  :P
By the way, since OpenGL is already usable to present the live view frames in CHDKPTP, having some minds to dig into the GLSL option isn't such a bad idea.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 15 / March / 2012, 12:56:49
One would appreciate from the client library to provide quick convolution filters on large stills. And GPU shaders are the faster way to achieve it nowadays.
That's why I plan on using GLSL for this: Shaders-processed filters for big stills.

So, your PC is connected (probably indoors) to a camera and via PTP and your code you have LiveView.

What then ?

I am just curious, is this an abstract programming excercise or does it have some practical use ?

Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 13:00:17
Most information is transferred every frame, because it can (on some cameras at least) change at any time. Future versions will most likely put more (possibly everything) in the per frame information.

I know this will sound dumb (well, I am !), but I'm wondering... what's actually changing ?  :blink:
Is it the color palette ? Or varying viewport offsets ?
And what is causing this change exactly ?  ???
Title: Re: CHDK PTP interface
Post by: Microfunguy on 15 / March / 2012, 13:17:23
I know this will sound dumb

Not really.

I have been dealing with older cameras and very little changes.
Camera can be in Record or Playback which will affect the palette.
On newer cameras, the bitmap overlay can have various formats and the displayed image can be in various resolutions.

In movie mode, on my A620 at least, the displayed image is just a distorted part of the full image.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 13:39:56
One would appreciate from the client library to provide quick convolution filters on large stills. And GPU shaders are the faster way to achieve it nowadays.
That's why I plan on using GLSL for this: Shaders-processed filters for big stills.

So, your PC is connected (probably indoors) to a camera and via PTP and your code you have LiveView.

What then ?

I am just curious, is this an abstract programming excercise or does it have some practical use ?

Hahaaaaaa ! At last, THE question.  :P  me gusta !
The practical advanced uses of CHDK ptp extensions are, i.m.o. , in the still vision application.
It all relies on two functionalities :

That being said, having these two functionalities reunited in a single device makes CHDKPTP a perfect stepping stone in order to create the poor man's high-end vision solution.

I can envision multiple application to it for myself, such as defect search on a machined workpiece, PCB
analysis, SMD components placement, etc. And that's only my area of expertise.
A biologist could use it for microbial cultures analysis, when population growth rates / environment interactions would require a recent camera's high resolution, but a PC's workload to do the stats.

It's all about enthusiasm, my fair Microfunguy.  :D
And CHDKPTP gives me aplenty !


Camera can be in Record or Playback which will affect the palette.
In Playback, depending on the display option, you may only see a small image top left, you will not see shooting info or histograms.

On newer cameras, the bitmap overlay can have various formats and the displayed image can be in various resolutions.

In movie mode, on my A620 at least, the displayed image is just a distorted part of the full image.

Sooooo... you're saying the frames headers are only changing along with the camera's operating modes, or from one device to another. That's....pretty much expected, isn't it ?
Title: Re: CHDK PTP interface
Post by: philmoz on 15 / March / 2012, 15:04:40
Even if you could transfer the the raw sensor data you would be lucky to get 1 frame every 5 seconds over USB.
Phil.
Eeeyup, but as I said somewhere in this thread, using shaders here isn't about framerate, it's for quick image data preparation, for futher use : One would appreciate from the client library to provide quick convolution filters on large stills. And GPU shaders are the faster way to achieve it nowadays.
That's why I plan on using GLSL for this: Shaders-processed filters for big stills. Using it to decode Bayer mosaic frames or translate YUV to RGB bitmaps is just gravy. But I love gravy.  :P
By the way, since OpenGL is already usable to present the live view frames in CHDKPTP, having some minds to dig into the GLSL option isn't such a bad idea.

Your use of terminology is confusing, specifically 'live view'.

When we talk about live view we are referring to the ability to show the same image that is displayed on the cameras LCD - when the camera is not taking a photo.

AFAIK the sensor raw data is not available at this time. I believe the viewport YUV image is generated using a special read-out mode of the sensor.

The raw sensor data is only available to CHDK immediately after a photo is taken and before the camera saves the JPEG image. The raw data is corrupted during the JPEG image generation.

If I understand correctly, what you're talking about is downloading the saved RAW file from the SD card, after taking a photo, and being able to display it immediately on your PC.
If this is the case why not use the JPEG image - and avoid the demosaicing and all the other processing required to handle a raw image (it will also transfer a lot faster)?

Phil.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 16:11:09
Aaawww, please, don't make me explain everything again.  :'(

I know pretty well what the words "live view" or "liveview" (whatever) refers to, since I've been studying reyalp's DE trunk for about a month now.
My point is, adding GLSL handling in the PTP/CHDK extension .Net library I'm implementing may be useful in any stage/phase/step of the data acquisition since :

Can we move on now ? Please ? :(

Addendum : for my OWN use, which isn't relevant i.m.o, but since you all seem to wonder about it : stored JPEG file are more than sufficient:  they're precompressed, thus quickly transferred, and already corrected against known lenses aberrations. But MY personal usage of isn't relevant in this case.
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2012, 16:14:42
I know this will sound dumb (well, I am !), but I'm wondering... what's actually changing ?  :blink:
The palette changes. Note that this applies to the bitmap (ui overlay) which is separate from the viewfinder live view.

The viewfinder changes size, buffer size and effective pixel aspect ratio on different cameras for various reasons. Some include
1) play / rec mode
2) video recording mode (may be different from still, and different video modes may be different)
3) digital zoom
4) camera aspect ratio setting
5) stitch mode

I'm not aware of any situations where the bitmap changes size at run time, but I wouldn't rule out the possibility yet.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 16:48:58
Yes, I understood that the palette was only applicable to the UI's overlay.

Okay, so, the good news are : device as old as the A430 HAVE (yay !) all the events implemented to declare the status changes than can/may alter the frame properties :

Here, have a look :
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fchdk.setepontos.com%2Findex.php%3Faction%3Ddlattach%3Btopic%3D4338.0%3Battach%3D6218&hash=23e5580f668067cd8a470de3ba2d95c0)
*for DevicePropChanged, that is.

I'll bet my right hand on the fact that Canon had those implemented on every devices they release, at least since the A430.
Thus :

Also, ALL, and I mean ALL of the device props the A430 exposes in its PTP DeviceInfo dataset are Vendor-specific (i.e the property codes MSBs all equals 0xD0.)
Buuut HURRRAAAAAY : the GetDevicePropDesc command is reported as IMPLEMENTED, so we may be able to find out what those proprietary values are.

Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2012, 16:50:54
I know pretty well what the words "live view" or "liveview" (whatever) refers to,
This is not at all apparent from you posts. If you understood our usage of live view, you would know bayer is completely irrelevant to it.

This isn't just pedantry for the sake of it. My reaction to your post was the same as phils, I genuinely have difficulty understanding what you are talking about and how it relates to the stuff I'm working on.
Quote
since I've been studying reyalp's DE trunk for about a month now.
"reyalps DE trunk" ? I honestly don't understand what you are referring to. There are two svns relevant to my live view work:
1) The camera side code is in a branch of the chdk code (not CHDKDE, which is a separate repository): http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live)
2) The client code is in the chdkptp trunk: http://trac.assembla.com/chdkptp/browser/trunk (http://trac.assembla.com/chdkptp/browser/trunk)
Quote
This dll is made to manipulate BITMAP BUFFERS (whatever the color space is, it's up the programmer to know what he have to decode).
In CHDK "bitmap" refers specifically to the paletted UI overlay portion of the camera display.
viewport refers specifically to the UYVYYY display used for "live" images and displaying images stored on the camera.
Raw refers to the bayer, 10 or 12 bpp packed buffer for raw images, which is only available in certain shooting modes and at certain points in the shooting process.

http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers) is the canonical reference.

"Live view" in chdkptp refers the (near) real-time replication of the camera display (the viewport, the bitmap or both) over PTP to a PC.

chdkptp (all one word) refers specifically to the client tool I wrote based on ptpcam. CHDK PTP protocol, PTP Extension refer to the protocol.

If you want to have a coherent discussion with us about these topics, you would be well served by using the same terminology we use. If you have ideas for other functions (for example, transferring raw data over PTP before it is written) then I suggest you use distinct terminology for that.
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2012, 17:07:24
Okay, so, the good news are : device as old as the A430 HAVE (yay !) all the events implemented to declare the status changes than can/may alter the frame properties I'll bet my right hand on the fact that Canon had those implemented on every devices they release, at least since the A430.
Thus :
You appear to be deeply confused. I would strongly suggest making an effort to understand how the existing system works.
Quote
if play/rec mode changes -> DeviceInfoChanged or DevicePropChanged will certainly rise.
Since many of the cameras do not support remote shooting in the canon firmware, there is no reason to expect them to send events when shooting related properties change, and even if they do, I would bet they don't send the information we'd need to correctly interpret the viewport data. We don't need to know the camera changed from play to rec (we already have that information), we need to know how the viewport dimensions changed. Since this behavior varies by camera model, just knowing the mode changed is not useful.
Quote
video recording mode -> this may prove difficult if there is special tricks to it. Sending it over PTP may affect the movie encoding process on device relying on their Digic to do the USB handling.
Again, I was talking *specifically* about the behavior of the viewport when the camera is  in movie mode. Example: on a540, which you switch to 640x480 video mode, the viewport buffer becomes 704x528 (vs the normal 704x240).

This has *nothing* to do with intercepting movie recording. It applies when you are in video mode, regardless of whether you are recording or not.
Quote
Digital zoom -> nasty thing... But I'm pretty confident the zoom value is one the the vendor-specific property, so DevicePropChanged should appear.
Even if it does, this won't tell us how many lines the current viewport buffer has.
Quote
Camera aspect ratio setting -> same as #3.
As above.
Quote
stitch mode ? You mean panoramas ? Aren't those supposed to be handled as associated objects in the PTP specifications ?
Again, all I'm talking about is the behavior of the camera viewport buffer. When the camera is in stitch mode, the viewport buffer becomes smaller. This has absolutely nothing to do with anything in the PTP specification.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 17:30:46
What I meant by "bitmap" is exactly what its stands for : an array of values containing pixel data. I'm not referring to any specific buffer, I was just stating that most of bitmap manipulation handled by the PC's cpu can be implemented in GLSL and passed to the GPU, wherever the data came from.

About the events : of course they're not supposed to give you actual informations about the viewport, since you hacked your way to its buffer, but you can expect actual changes on the viewport buffer when a property change is reported by the device.

I used USBTrace to monitor the A430's activity, a camera which doesn't offer remote shooting. The StorageInfoChanged event is fired every time you make a remote shooting through a Lua script over PTP.

Was I unclear to the point I lead everyone think I assumed the PTP protocol would report device changes that are usually private to the firmware (such as the viewport's wherebouts), and we only can access to using the CHDK and its functionalities ?

Did I mention that english isn't my native language btw ?
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2012, 17:49:23
About the events : of course they're not supposed to give you actual informations about the viewport, since you hacked your way to its buffer, but you can expect actual changes on the viewport buffer when a property change is reported by the device.
What use is this when you have to get and transfer the actual information anyway ? Sending a few extra ints with every 200k+ frame isn't going to be significant, and it makes things very simple. Plus the code to do it this way is pretty mostly already written and working on both the camera and client.
Title: Re: CHDK PTP interface
Post by: asmodyne on 15 / March / 2012, 18:09:52
About the events : of course they're not supposed to give you actual informations about the viewport, since you hacked your way to its buffer, but you can expect actual changes on the viewport buffer when a property change is reported by the device.
What use is this when you have to get and transfer the actual information anyway ? Sending a few extra ints with every 200k+ frame isn't going to be significant, and it makes things very simple. Plus the code to do it this way is pretty mostly already written and working on both the camera and client.

I think I've pinned the source of the confusion about my post : I had two active discussion topics relevant to this thread, the first being live view, which relies on requesting viewport frames from the device as you do in chdkptp, and the second one is including GLSL capabilities to "my" managed dll in order to process bitmaps.

Thus, I sometimes asked you about the nature of the header declared in live_view.h and how it may vary in runtime, and other times answered questions about the purpose of my dll, or pointed interesting links about GLSL usage in still image processing.

Next time, I should use PM to answer questions or ask new ones.  Sorry about that.  :(
Title: Re: CHDK PTP interface
Post by: ntstatic on 09 / April / 2012, 08:19:22
hello everyone,
i have question about live view.
i am using SX 130 (also a few 120) with the live view.
if the camera is in manual mode, the live view does not reflect or resemble the final picture which will be taken. is it possible for the live view to approximate the final picture. eg if exposure is increased the live view becomming brighter (because the final picture will be brighter)

for the moment i am keeping the camera in Program mode - even when my PC software says Manual - only when the PC requires a shot i switch the camera to Manual, set the parameters, take the shot, download pic and switch the camera back to Program mode.

in Manual mode the Live View is often very dark(almost black)

am i doing it right or is there a better way
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / April / 2012, 00:12:35
hello everyone,
i have question about live view.
i am using SX 130 (also a few 120) with the live view.
if the camera is in manual mode, the live view does not reflect or resemble the final picture which will be taken. is it possible for the live view to approximate the final picture. eg if exposure is increased the live view becomming brighter (because the final picture will be brighter)

for the moment i am keeping the camera in Program mode - even when my PC software says Manual - only when the PC requires a shot i switch the camera to Manual, set the parameters, take the shot, download pic and switch the camera back to Program mode.

in Manual mode the Live View is often very dark(almost black)

am i doing it right or is there a better way

Assuming you are talking about CHDK live view over PTP, it should be the same as whatever the LCD display does.  If it's not, then it means Canon is doing something different with the display in different modes, and someone would need to figure out what that was.
Title: Re: CHDK PTP interface
Post by: ntstatic on 11 / April / 2012, 01:33:46
hello everyone,
i have question about live view.
i am using SX 130 (also a few 120) with the live view.
if the camera is in manual mode, the live view does not reflect or resemble the final picture which will be taken. is it possible for the live view to approximate the final picture. eg if exposure is increased the live view becomming brighter (because the final picture will be brighter)

for the moment i am keeping the camera in Program mode - even when my PC software says Manual - only when the PC requires a shot i switch the camera to Manual, set the parameters, take the shot, download pic and switch the camera back to Program mode.

in Manual mode the Live View is often very dark(almost black)

am i doing it right or is there a better way

Assuming you are talking about CHDK live view over PTP, it should be the same as whatever the LCD display does.  If it's not, then it means Canon is doing something different with the display in different modes, and someone would need to figure out what that was.

you are absolutely right reyalp. and the live view does reflect the lcd
what i was doing was that i was setting the TV, AV, ISO etc in the manual mode using the
                        ExecuteScript("set_tv96(" & mTVval & ")")
                        ExecuteScript("set_av96(" & mAVval & ")")
                        ExecuteScript("set_sv96(" & mISOval & ")")
this effectively gave me the intended effect in the final picture however it did not set the on screen setting for these values
i have added
                        ExecuteScript("set_tv96(" & mTVval & ")")
                        ExecuteScript("set_user_tv96(" & mTVval & ") press 'shoot_half'")
...
                        ExecuteScript("set_av96(" & mAVval & ")")
                        ExecuteScript("set_user_av96(" & mAVval & ") press 'shoot_half'")
...
                        ExecuteScript("set_sv96(" & mISOval & ")")
                        ExecuteScript("set_user_sv96(" & mISOval & ") press 'shoot_half'")

and now the LCD as well as the live view resembles the final picture taken (i think - i have not thoroughly tested it - but initial check look ok)

so it turns out it was nothing related to PTP but my (mis)understanding of the method in which the set_tv96 ... etc works.

Title: Re: CHDK PTP interface
Post by: ntstatic on 12 / April / 2012, 01:28:55
on the off note --
i have been using the libUSBWin32 1.2.3.0 and 1.2.5.0 with the live View and PTP code.
recently browsing the libUSB site i came across a libUsb installer called Zadig. Zadig has an option of replacing the stock drivers to libUSB or WinUSB or libUSBK

although i was not able to use libUSBK with the ptp code ( mostly provided by Mweerden on these pages ) the code worked flawlessly without any changes on the WinUSB drivers, so much so that i have a very strong feeling that it is more stable than libUSB. i have removed most of the delays in the VB.net code on the PC side and the thing looks stable enough. the same did not work with libUSB without the delays.

i would like to have any opinions if someone has tried this, or the view of the gurus of CHDK.

i hope this is not off topic for this thread as i feel it is closely related only with the PTP aspect of CHDK.

edit.
just remembered that ptpcam and therefore ptpcamgui does not work with WinUSB.

Title: Re: CHDK PTP interface
Post by: reyalp on 14 / April / 2012, 21:22:29
Some unfinished work in progress on the live view protocol, mostly for discussion on IRC
- gets rid of get_handler
- gets rid of lv_base_info / lv_vid_info distinction
- generic description for frame buffers

This doesn't currently implement the different aspect ratios on newer cams, which would theoretically go into visible_buffer_*offset

The old protocol is still there. The chdkptp patch won't talk correctly to previous builds, and lvdump record/playback isn't implemented


Title: Re: CHDK PTP interface
Post by: philmoz on 14 / April / 2012, 23:20:49
Some unfinished work in progress on the live view protocol, mostly for discussion on IRC
- gets rid of get_handler
- gets rid of lv_base_info / lv_vid_info distinction
- generic description for frame buffers

This doesn't currently implement the different aspect ratios on newer cams, which would theoretically go into visible_buffer_*offset

The old protocol is still there. The chdkptp patch won't talk correctly to previous builds, and lvdump record/playback isn't implemented


To get this to work on the G12 and IXUS310 I had to make the following changes:

chdkptp/trunk/liveimg.c, line 221
   const char *p_row = p_yuv + (height + y_offset - 1) * row_inc + (x_offset*12)/8;

core/live_view.c,
line 143
    lv.vp.buffer_height = vid_get_viewport_max_height();
lines 152-153
    lv.vp.visible_buffer_xoffset = vid_get_viewport_xoffset_proper();
    lv.vp.visible_buffer_yoffset = vid_get_viewport_yoffset_proper();

The viewport display was in the wrong place and using the wrong data without these changes.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / April / 2012, 19:20:08
Thanks Phil.

The liveimg.c one actually applies to the chdkptp trunk as well. Fixed in chdkptp r235.

The offsets are trickier: Currently in a540 and d10, vid_get_viewport_*offset_proper describes an offset of the viewport in what I've "logical" screen, but not the buffer (e.g. stitch, where the image data is in the upper left of the buffer, but is displayed somewhere else on the screen). In your case, the offset is both.

For the Y offset, I'd like to send only the data that is actually valid (calculate viewport buffer + y offset in the chdk code, only send the portion that has valid data), meaning we could drop the buffer offset completely. The offset value would still have to go in the logical offset. The X buffer offset can't get the same treatment though, because extracting the partial lines from the buffer would be slow.

What I've called the "logical" screen is meant to represent the physical screen on the camera (I'm open to better names!) in "buffer dimensions" In other words, the logical height is how tall the buffer would be if it filled the whole screen. In the old implementation, this was essentially vid_get_viewport_max_height and vid_get_viewport_max_width, but they can actually change in various cases.

On cameras like the g12, it looks like the height of a full screen viewport is always 480, but on a540 it can be 528 (640x480 video mode) 240 (playback, most capture modes), or down to ~60 depending on digital zoom. On D10, max digital zoom is also drops to half width.

I'm still struggling to find a way represent this in a way that is convenient and doesn't require a ridiculous number of new lib.c functions.

I think putting everything in one call (no get_handler, no distinction between base_info and vid_info) is the right thing to do, but I'm not really satisfied with the current data structure and the functions that populate it.
Title: Re: CHDK PTP interface
Post by: philmoz on 20 / April / 2012, 18:27:50
What I've called the "logical" screen is meant to represent the physical screen on the camera (I'm open to better names!) in "buffer dimensions" In other words, the logical height is how tall the buffer would be if it filled the whole screen. In the old implementation, this was essentially vid_get_viewport_max_height and vid_get_viewport_max_width, but they can actually change in various cases.

On cameras like the g12, it looks like the height of a full screen viewport is always 480, but on a540 it can be 528 (640x480 video mode) 240 (playback, most capture modes), or down to ~60 depending on digital zoom. On D10, max digital zoom is also drops to half width.

I'm still struggling to find a way represent this in a way that is convenient and doesn't require a ridiculous number of new lib.c functions.

I've been struggling with trying to come up with a good model for this all week - one thing I'm unclear on is how does the logical viewport size relate to the OSD bitmap screen size (and ultimately the live image view) when it gets displayed on the PC?

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2012, 17:49:52
I've been struggling with trying to come up with a good model for this all week - one thing I'm unclear on is how does the logical viewport size relate to the OSD bitmap screen size (and ultimately the live image view) when it gets displayed on the PC?
We discussed this a bit in IRC, but I'll try to elaborate a bit.

The idea of the "logical size" is to tell the client how the valid viewport data (called "visible size" in my test code) relates to the physical screen on the camera. For example, if the viewport data has 120 lines, the client needs to know if this is a 120 line high window inside a 240 line high screen (like stitch), or a whether it is a full screen buffer (like digital zoom, or low res video)

This information was missing from the old information, which effectively assumed vid_get_viewport_max_height was always the full screen height, which is generally true on cameras like the g12, but not true everywhere.

The "logical size" is given in units of buffer pixels, because these are easily available, and convenient for calculation with other offsets etc. The "logical size" that represents a full screen camera display is not fixed. Full screen is indicated by logical size == visible size.

I've been thinking it might be clearer to define the "logical size" in terms of margins, so "logical height" equals top margin + visible height + bottom margin. The top/ left already exist as offsets, and most cases are symmetric.

The offsets are complicated by the fact that there are offsets within the buffer (e.g. 16:9 on G12) and offsets of the buffer data on the screen (e.g stitch, g1x).

The Y offset within the buffer can (and IMO should) go away, so the appropriate offset from the real buffer is calculated on the camera, and only the useful data is sent. But as mentioned earlier, we really can't do this with the X offset.

The final rendering is up to the client. Given the physical aspect ratio of the camera screen, the client can display any size window it wants. The "logical size", "visible size" and offsets tell it how to display the data relative to the window. The current chdkptp code (if correct aspect ratio is selected) fixes width at 1:1 or 1:2 viewport pixels and then scales height for aspect ratio, but this is just because it was convenient to write that way. Clients that want aspect ratio correct display will generally have to do arbitrary non-integer scaling anyway.

Re the bitmap:
As far as we know, the bitmap is always full screen, but the resolution doesn't have a fixed relationship to viewport. (e.g on a540 the visible bitmap data is always 352x240, but the viewport might be 704x240, 704x528, 352x240, 704x60....)

My current test code uses the same lv_framebuffer_desc structure as the viewport, but this is probably overkill.

The "logical sizes" given in the in the viewport and bitmap descriptions are each in their own units (buffer pixels of that buffer), but can be used to display correctly because be the logical size tells you how much of the camera screen each one covers.

Considerations for existing on camera viewport/bitmap code:
Unfortunately, the existing CHDK code isn't aware of a lot of these variations. For example, on cameras where digital zoom varies the size of the buffer, zebra, histogram and md will all be wrong when it is used.

On cameras like a540, the viewport and bitmap are assumed to be 360x240, (using every other Y value in the viewport) but in fact only 352x240 have valid data, which means the histogram will have some junk in it, and md might be spuriously triggered. MD also won't work correctly in video modes on these cameras.

There's is also quite a bit of cruft due to adapting newer cameras with different resolutions to CHDK units.

It would be nice to use the correct dimensions everywhere, but I'd rather leave that as a project for another day. If we get all the values for live view, that will give us a step in the right direction. The downside is we will get more function that return similar but not exactly equivalent values.

Ugh, that was long :(
Title: Re: CHDK PTP interface
Post by: srsa_4c on 21 / April / 2012, 18:22:13
@reyalp
Sorry for this off-topic, but you always seem to mention that the A540's viewport resolution is 704 pixels wide inside the 720px wide buffer. The cameras I've seen change their viewport width from 720px to 704 when they sense that TV-out is in use (this happens on-the-fly). Do you have something plugged into that camera?  :)
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2012, 18:36:49
@reyalp
Sorry for this off-topic, but you always seem to mention that the A540's viewport resolution is 704 pixels wide inside the 720px wide buffer. The cameras I've seen change their viewport width from 720px to 704 when they sense that TV-out is in use (this happens on-the-fly). Do you have something plugged into that camera?  :)
That's useful info, I wondered if TV out would change it. Would also be worth checking modern cameras that have HDMI too. Maybe we don't have to worry about the ones with combined USB/video (can you make a splitter ?)

I don't have anything plugged in. The screen would turn off, so it can't be a stuck switch either.

It turns out that plugging in the TV out does change the height though (probably to 528), and worse, doesn't change the value I've been using to get the actual viewport height.

edit:
Ooops, change in viewport height is in playback mode, which I have hard coded because that value never works in playback. In rec mode, it seems to be normal with TV out connected.
Title: Re: CHDK PTP interface
Post by: philmoz on 21 / April / 2012, 18:49:04
After our chat yesterday I worked on fixing things for the G1X and also stitch mode.

Essentially this adds two new offset values to define the position of the viewport on the LCD/liveview display - the existing offset values now only define the position of the viewport in the memory buffer.

Hopefully this will be general enough to cater for cameras like the A540 and D10 too.

The attached patch is against your live view branch (it includes your previous patch changes as well).
This works with your current client (with the previous patch applied).

I'm thinking that all the viewport_???_proper() functions should be replaced by a single function that populates the live view data structure with the correct values. These are only used in the live view code.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 21 / April / 2012, 19:03:31
Maybe we don't have to worry about the ones with combined USB/video (can you make a splitter ?)
http://chdk.setepontos.com/index.php?topic=5691.msg62525#msg62525 (http://chdk.setepontos.com/index.php?topic=5691.msg62525#msg62525)
Quote
I don't have anything plugged in.
Interesting, I assumed all TV-out models behave the same regarding viewport width.
Quote
It turns out that plugging in the TV out does change the height though (probably to 528), and worse, doesn't change the value I've been using to get the actual viewport height.

edit:
Ooops, change in viewport height is in playback mode, which I have hard coded because that value never works in playback. In rec mode, it seems to be normal with TV out connected.
There's a reason why the buffers follow each other at a distance of >>240 lines.
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2012, 19:06:41
After our chat yesterday I worked on fixing things for the G1X and also stitch mode.

Essentially this adds two new offset values to define the position of the viewport on the LCD/liveview display - the existing offset values now only define the position of the viewport in the memory buffer.
Thanks, I'll take a look.

Quote
I'm thinking that all the viewport_???_proper() functions should be replaced by a single function that populates the live view data structure with the correct values. These are only used in the live view code.
I was thinking about that too, but having a bunch of really simple functions that can be overridden individually may be better. Not sure...
Title: Re: CHDK PTP interface
Post by: philmoz on 21 / April / 2012, 22:34:45
After our chat yesterday I worked on fixing things for the G1X and also stitch mode.

Essentially this adds two new offset values to define the position of the viewport on the LCD/liveview display - the existing offset values now only define the position of the viewport in the memory buffer.
Thanks, I'll take a look.

Attached is an updated patch against your current branch.
This changes all the code that uses viewports (including live view) to use the physical address of the top left visible pixel as the start address of the viewport. The buffer x & y offset functions are then only needed to calculate the correct address. The code using the viewport only needs to know the display offsets for correct screen position.

I left the variables in the live view data structure (set to 0) so I didn't need to change the client.

This also only sends the visible lines of the viewport not the full height.

Title: Re: CHDK PTP interface
Post by: reyalp on 22 / April / 2012, 01:25:56
Thanks phil.

I've checked in a slightly modified version of that on my branch, plus the corresponding chdkptp code. I changed the live_view_get_data to be safe if a null buffer is returned. Also included my fake variable aspect test code.

Note these are quite unfinished and is likely to change in incompatible ways in the next revisions, it's just getting too unwieldy to deal with in patches. Anyone using the previous version might want to just stick with that and the corresponding chdkptp for a while.
Title: Re: CHDK PTP interface
Post by: ntstatic on 02 / May / 2012, 07:06:24
thank you phil, reyalp, (and every one who contributes to chdk)
i am so glad to see progress on the liveview. i have been using the mweerden (manualy) patched version (with sx130) and am therefore wary of upgrading my version of chdk.
liveview in the main trunk will make it possible for me to update my chdk.
thanks once again
Title: Re: CHDK PTP interface
Post by: kpoman on 07 / May / 2012, 20:56:53
Guys, I am trying ptpcam on windows (7 64 bits). It seems to have some sort of communication:
- if I "Enable Remote", I can see "wait for camera" ...  "State: disconnected" on the main screen and """
>> reset
>> reset
>> reset
>> reset"""

on the other one. If I disable remote on the cam, I see this:

>> reset
>> reset
>> reset
>> reset
>> reset
>> reset
>> reset
>> reset <<  (Length: 0)
** init() start ...** init() fail
** init() start ...
>> version << ptpcam: 2.0
camera: 2.0 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil) << script:5
5:ret:false (Length: 21)
>> upload lptpgui.lua A/CHDK/LUALIB/lptpgui.lua << upload failed! (Length: 14) [unexpected return code 0x2002 (Length: 29)]
** init() fail
** init() start ...
>> version << ptpcam: 2.0
camera: 2.0 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil) << script:6
6:ret:false (Length: 21)
>> upload lptpgui.lua A/CHDK/LUALIB/lptpgui.lua << upload failed! (Length: 14) [unexpected return code 0x2002 (Length: 29)]
** init() fail
** init() start ...
>> version << ptpcam: 2.0
camera: 2.0 (Length: 24)
>> script-support << script-support:0x1 lua=yes (Length: 26)
>> luar not(os.stat("A/CHDK/LUALIB/lptpgui.lua")==nil)


etc....

This happens on a SX200IS with firmware full 1.0d. The libusb drivers seem to be correctly installed (as per device manager information). Also when "enable remote" it doesnt show on listing of ptp devices, and when disabling I see it:

C:\tmp\ptpcam>__ptpcam.exe -l

Listing devices...
bus/dev vendorID/prodID device model
bus-0/\\.\libusb0-0001--0x04a9-0x31c0   0x04A9/0x31C0   Canon PowerShot SX200 IS


Is there anything logical about this ? Can someone get me to the correct path please ?
Thank you all !
Title: Re: CHDK PTP interface
Post by: kpoman on 07 / May / 2012, 22:03:05
ok nevermind... I had a LUALIB folder on the 2MB partition, however the camera created the same structure on the other partition too without letting me know, and there, there wasnt a LUALIB dir ! I created and it started executing ! However I cant find how do I see the live preview on the PC ! Hope someone can help !
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / May / 2012, 00:14:29
However I cant find how do I see the live preview on the PC ! Hope someone can help !
The live preview is still not integrated into the main CHDK. Sorry :(

If you look further back in this thread, and in the chdkptp thread http://chdk.setepontos.com/index.php?topic=6231.msg81941#msg81941 (http://chdk.setepontos.com/index.php?topic=6231.msg81941#msg81941) you will find information about using the current work in progress stuff that's in my branch.

Note that ptpcamgui does not support this in any form. You will have to use my chdkptp client. If you want to use the latest pre-built chdkptp binary (r230), then you will have to build a CHDK build from my branch, r1817 or earlier. If you want to use the latest, you will have to build both CHDK and the client.
Title: Re: CHDK PTP interface
Post by: kpoman on 08 / May / 2012, 07:49:41
Reyalp, thanks for your comments. Let me understand: you do patch the camera firmware or the external ptpcam dll ? Is the ptp livepreview a binary compiled thing or some kind of LUA hack to provide realtime buffers ? In the livepreview do we get the viewfinder images or also the menus and everything on the LCD screen ? Also, how do I check out latest version and am I able to compile with mingw ? Finally, I would like to create a python wrapper and make this work both on windows and linux via libusb. I can use some functions to convert from yuv to rgb et.al so if I am able to access the raw buffers it would be nice.
Sorry about asking here, maybe this is pointed out on different forum threads but there are so many different status pages and subprojects that it is quite difficult to see what is trunk and what is fork :)
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / May / 2012, 23:22:30
Let me understand: you do patch the camera firmware or the external ptpcam dll ? Is the ptp livepreview a binary compiled thing or some kind of LUA hack to provide realtime buffers ?
Liveview support requires code in CHDK on the camera. It also requires a client that understands the protocol.
Quote
In the livepreview do we get the viewfinder images or also the menus and everything on the LCD screen ?
The UI (aka bitmap) and viewfinder (aka viewport) are separate framebuffers on the camera. Both are available in the current work-in-progress PTP protocol, although support is not complete for every camera. See http://chdk.wikia.com/wiki/Frame_buffers (http://chdk.wikia.com/wiki/Frame_buffers) for information about the various camera frame buffers.

You can see some screenshots in the chdkptp thread.
Quote
Also, how do I check out latest version and am I able to compile with mingw ?
For the client, see http://www.assembla.com/wiki/show/chdkptp (http://www.assembla.com/wiki/show/chdkptp) - The readme explains the prerequisites. mingw is the preferred toolchain for windows.

For the CHDK side, you need to use this branch http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live)
You can use chdkshell to build on windows. See http://chdk.wikia.com/wiki/For_Developers (http://chdk.wikia.com/wiki/For_Developers) for more information about how to set up a CHDK development environment on various platforms.

Quote
Finally, I would like to create a python wrapper and make this work both on windows and linux via libusb. I can use some functions to convert from yuv to rgb et.al so if I am able to access the raw buffers it would be nice.
That should be possible. If you want to use libusb directly, you will need to make your own implementation of the CHDK PTP protocol. OTOH, chdkptp is cross platform and already has a Lua API (in fact, it's mostly written in Lua, the C code only provides some low level APIs), so you might just want to use lua. It includes code to convert the framebuffers to RGB.
Title: Re: CHDK PTP interface
Post by: carrerag on 28 / May / 2012, 20:49:09
I've been reading this thread all day today hoping I could find someone who experienced the problem I am having.  I can't seem to get chdkptp to connect for me.  I've a SX130IS with firmware 1.01f.  I've downloaded reyalp-ptp-live1871 and successfully built that within CHDK-Shell and installed it on my camera.  I'm using chdkptp r230-win32 as my client.  I've installed libusb as suggested and seem to have no problems at all when running ptpcamgui. After I start chdkptp, I turn on my camera (in play mode) and hit the connect button. I then get an error in the dos console "unexpected return code 0x2fd" and also in the chdkptp console the error "error initializing live streaming: error getting handler: ptp error".  Is there something I missed in my setup?  I read of at least a few users who had this working on an SX130, but I'm not sure what firmware version they were using.  Thanks, Glen
Title: Re: CHDK PTP interface
Post by: waterwingz on 28 / May / 2012, 21:06:20
After I start chdkptp, I turn on my camera (in play mode) and hit the connect button.
reyalp will be better able to help you,  but what happens if you start your camera before you start chdkptp ?
Title: Re: CHDK PTP interface
Post by: carrerag on 28 / May / 2012, 21:53:15
reyalp will be better able to help you,  but what happens if you start your camera before you start chdkptp ?
The same thing really.  I don't see any difference trying it either way. Not sure what else I could try.
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / May / 2012, 01:10:29
I've been reading this thread all day today hoping I could find someone who experienced the problem I am having.  I can't seem to get chdkptp to connect for me.  I've a SX130IS with firmware 1.01f.  I've downloaded reyalp-ptp-live1871 and successfully built that within CHDK-Shell and installed it on my camera.  I'm using chdkptp r230-win32 as my client.
You will need to use the latest chdkptp from svn if you want to use the latest CHDK code from my branch. The reason it's in a private branch is so I don't have to worry about compatibility from version to version.

If you want to use the r230 chdkptp binary build, then you should build chdk 1817. You can download the source for that here http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live?rev=1817 (http://trac.assembla.com/chdk/browser/branches/reyalp-ptp-live?rev=1817)

I'll try to put up a new binary snapshot of chdkptp up soon, I think I'm about though messing with the protocol as of today.

edit:
new chdkptp snapshot is uploaded. I haven't tested the recent very thoroughly.

The protocol should now be able to handle most of the weird variations (like variable aspects, digital zoom, digic 2 640x480 video, even stitch) but many of these will require platform specific code on each camera. It should work reasonably well in normal modes on most cameras.
Title: Re: CHDK PTP interface
Post by: carrerag on 29 / May / 2012, 07:51:14
Wow, thanks!  That made all the difference in the world!  I don't have much time to play with it this morning but most functions I've tried seem to be working.  Livevview doesn't though.  I get this error: "WARNING: camera live view protocol not supported by this client, live view disabled"  I may try building 1817 as you suggested and see how that goes.  Thanks again!
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / May / 2012, 13:11:36
Wow, thanks!  That made all the difference in the world!  I don't have much time to play with it this morning but most functions I've tried seem to be working.  Livevview doesn't though.  I get this error: "WARNING: camera live view protocol not supported by this client, live view disabled"  I may try building 1817 as you suggested and see how that goes.  Thanks again!
If you use the chdkptp r248 snapshot, then you need to use chdk 1873 (not the 1871 you built earlier, sorry) or later from my CHDK branch.
Title: Re: CHDK PTP interface
Post by: carrerag on 29 / May / 2012, 20:09:32
I can't believe I didn't think of that :) I'm in sync now and it seems that everything is working as it should.  I really appreciate your help, and the quick build.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / June / 2012, 20:23:49
Something I noticed with PTP on D10.

If you are connected to PTP and switch to record mode, and then switch to movie mode using lua set_capture_mode(), the func menu is confused. Only white balance and "my colors", are available, not the video size option. If you select video mode using the camera buttons, the func menu is correct. It's also correct if video mode is the default when you switched to rec mode in the first place (meaning it was the last mode selected using the normal Canon UI)

edit:
Same thin happens with a540.

This happens when using script on the camera without PTP so I guess it's a setmode issue not a PTP issue.
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / June / 2012, 20:20:05
Another random observation: On a540 at least, sending data from cached addresses with send_data is much slower than than uncached. I suspect it uses DMA, and has to do an additional copy if address is in cached ranged.

Sending a full viewport (uncached address) normally takes ~30ms. Clearing the uncached bit on the address basically doubled it.
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / June / 2012, 00:53:41
If there are no objections, I'm going to commit the live view stuff in the trunk tomorrow. I did a merge and batch build today, there were a few issues with the merge but I think I got it all sorted out.

There's still lots to be done to get everything working on the individual cameras, but we can do that over time. The basic functionality should work on pretty much every camera, the additional work is just to handle the frame buffer size variations and get the bitmap stuff right.

I'm not completely happy with the protocol but it should do the job, and I need to stop dithering about it.
Title: Re: CHDK PTP interface
Post by: waterwingz on 18 / June / 2012, 01:11:16
If there are no objections, I'm going to commit the live view stuff in the trunk tomorrow.
I'm excited !!!   Are the host clients ready ?
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / June / 2012, 23:33:47
Checked in trunk changeset 1921 (http://trac.assembla.com/chdk/changeset/1921)
Are the host clients ready ?
The most recent snapshot of chdkptp should work.

Some general notes

The following ports should have pretty much full support:
a540, d10 g12, g1x, sx40hs, g10, a590, ixus310_elph500hs

Other are mostly missing some combination of viewport dimensions and offsets, active bitmap and palette.

There are several ways to obtain some of these values. Where possible, I'd like to try to use the same method across ports. Early in the process, I ported over some of the palette and viewport stuff from ewavrs original live view code. The viewport stuff was done by directly accessing variables. I've since added eventprocs to the sigfinder that return these values (GetVRAM*PixelsSize) for all dryos cameras. This should be used in preference to accessing the variables directly. I will add the functions to vxworks as well.

Supporting stitch (done in some of the ports mentioned above) requires some logic in each lib.c. Before putting this in every single platform, I'd like to find a way to make it mostly generic. As mentioned earlier, I don't think having this show up correctly in ptp is very urgent.

Where possible, I'd like to move the stuff that is common to all firmwares of a given camera to the common lib.c rather than the sub lib.c. See g12 for an example.

The sig finder finds bitmap and palette stuff for recent dryos. It would be worthwhile to do the same for the older versions.

Protocol documentation is in ptp.h and live_view.h
Title: Re: CHDK PTP interface
Post by: philmoz on 18 / June / 2012, 23:52:26
Checked in trunk changeset 1921 (http://trac.assembla.com/chdk/changeset/1921)
Huge round of applause - nice job :)

Quote
The following ports should have pretty much full support:
a540, d10 g12, g1x, sx40hs, g10, a590, ixus310_elph500hs
The SX30 works as well.

Quote
The sig finder finds bitmap and palette stuff for recent dryos. It would be worthwhile to do the same for the older versions.
Would be good; but I wasn't able to see any usable patterns for finding this stuff in older DryOS versions.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / June / 2012, 00:04:35
Would be good; but I wasn't able to see any usable patterns for finding this stuff in older DryOS versions.
I think the ones I'm using on d10 shouldn't be too hard (especially the bitmap one), but when I was looking at it, I though I found code equivalent code on newer cameras that gave different addresses from what your method is using (or found code equivalent to the new cameras on d10, I don't remember exactly.) I haven't had a chance to look into it further yet.
Not urgent in any case.

edit:
A few more odds and ends
a540 (and presumably some other cameras from the same era) have bitmap 352 (704) width bitmap and viewport. This is treated as 360/720 in most chdk code, and currently the bitmap size returned for live uses the main CHDK value, so the bitmap doesn't line up perfectly.

In the merge, sx200 ended up with duplicate definitions of vid_get_bitmap_active_palette, I removed one. Someone should check that it's still OK

sx220 and sx230 also ended up with conflicting values in stubs_min.S vs stubs_entry.S. I used the stubs_entry ones.
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / June / 2012, 00:15:30
In trunk changeset 1928 (http://trac.assembla.com/chdk/changeset/1928), I used find_eventproc to add GetVRAM*PixelsSize for all autobuild enabled vxworks cameras except for
a410
a610
ixus40_sd300
ixus50_sd400
ixus700_sd500
ixus750_sd500
ixusizoom_sd30
s2is

I didn't go through and verify all the found values, but they are likely to be OK.
Title: Re: CHDK PTP interface
Post by: msl on 20 / June / 2012, 10:52:17
Checked in trunk changeset 1921 (http://trac.assembla.com/chdk/changeset/1921)

The following ports should have pretty much full support:
a540, d10 g12, g1x, sx40hs, g10, a590, ixus310_elph500hs

Thanks for that great work! This is a big step for CHDK.

a720 & sx220 work well.

There is a little problem with ptpCamGui. The Gui don't know the new PTP version 2.3 and will not start. Not a big thing. We must add one line. But rudi and me are in vacation. When you need ptpCamGui, use the stable CHDK version. In some days we will update the ptpCamGui.

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / June / 2012, 13:10:59
a720 & sx220 work well.
Thanks for the report.
Quote
There is a little problem with ptpCamGui. The Gui don't know the new PTP version 2.3 and will not start. Not a big thing. We must add one line. But rudi and me are in vacation. When you need ptpCamGui, use the stable CHDK version. In some days we will update the ptpCamGui.
Minor versions (like 2.0 to 2.3) are supposed to be backward compatible, so it should be safe for ptpCamGui to start if the minor version is greater than what it knows about.

Title: Re: CHDK PTP interface
Post by: openuas on 25 / June / 2012, 14:03:18
WOW, impressed.  :o One year of no time to be busy with CHDK and now returning to look at changelogdiscovering this improvment is a really pleasant surprise, big thanks to all who work(ed) on this PTP improvement for CHDK  8)
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / June / 2012, 17:14:27
From philmoz
Quote
Here's a weird one for you.

If I use chdkptp to upload files to the camera (in this case the compiled module files), and the module file length is 5592 bytes, and the filename+path is 24 bytes then the PTP upload crashes the PTP code in the camera. The total data size sent is 5592+24+4 = 5620 bytes.

One byte shorter or longer on the filename and it works fine.

The PTP code gets the correct data_size value but gets the wrong value for fn_len (gets 8 instead of 24).

I've tried using umalloc instead of malloc in the PTP code; but the result is the same.

I've tested this on the G12, SX40 and G1X all give the same result.

Any ideas?
I've reproduced this on a540 and d10. As expected, it also happens with ptpcam.

PTP hangs because the file error (due to incorrect length) is generated before the data phase is complete. If we consumed all the rest of the data, it would probably work OK [edit: no, looks like it already does that]. If you fully reset the connection, it's usable again (try to connect once, it will fail, then connect again). I believe this is mostly a deficiency in error handling in the client code.

I don't yet understand why the length is incorrect... chdkptp is definitely putting the right value in the buffer to send.

edit:
This isn't specific to file upload

Code: [Select]
con> !return con:exec('msg_shell:run()',{libs='msg_shell'})
=true
con> putm exec msg_shell.default_cmd=function(msg) write_usb_msg(msg) end
con 1> !con:write_msg('\24\0\0\0'..string.rep('x',5592+24))
... hangs ...
unexpected return code 0x2ff
con 1> !chdk.reset_device({dev="\\\\.\\libusb0-0002--0x04a9-0x311b",bus="bus-0"})
reset_device: dev \\.\libusb0-0002--0x04a9-0x311b       bus bus-0
Device status OK
___> c
con> getm
... returns message, intact ??? ...
con> !con:write_msg('\24\0\0\0'..string.rep('x',5592+25))
... no hang ...
con> getm
... returns message...
con> !con:write_msg('\24\0\0\0'..string.rep('x',5592+23))
... ok ..
con>  !con:write_msg('\24\0\0\0'..string.rep('x',5592+24))
... hangs ...
:blink:

edit:
the 24 isn't needed,
!con:write_msg(string.rep('x',5592+28))
also fails
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / June / 2012, 18:20:39
I have also experienced some weirdness when I tested the PTP liveview stuff on the A410, but I haven't tested it thoroughly. In short: I've been unable to upload the whole (trunk) installation package over CHDK-PTP (using the latest chdkptp GUI, with neither CHDK 1.0 nor CHDK 1.1 on the camera). A particular file which always caused assert was CHDK/LUALIB/drawings.lua . More investigation would be needed, I guess. The romlog shows an assert in BulkTrns.c line 0x5d8, task: tPtpTrsnpV.
Separate (long standing) issue is the extreme slowness of the file upload on USB1.1 cameras (pause of multiple seconds after each file).
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / June / 2012, 18:51:10
I'm not getting an assert with either messages or file upload. The ptp task gets stalled.

However, I wrote a script that sends messages from with every length from 1 to N and that seems to be crashing in a different way.

edit:
Here's the script. Getting several unexplained results, but it looks like D10 gets a similar issue at length=500

Code: [Select]
chdkptp -c -i
!m=require'msgtest'
!m.load()
!m.test(<start lenght>,<optional max length>,<optional increment>)

edit:
Updated, you can now specify increment

edit:
this appears to be related to the bits of the data length ending in 1f4  :o
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / June / 2012, 21:55:20
Filename length may be a red herring.

On my a540, both PTP_CHDK_WriteScriptMsg and PTP_CHDK_UploadFile seem to hang for ~5 sec in recv_ptp_data

Stuffing the filename length into a global displayed with misc debug vals shows the right.

Attached is patch with debug code I'm using to check this.

Another oddity: on D10 0x1f4 is bad, on a540 is not. Subsequent values (3f4, 5f4 etc) are bad on both.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / June / 2012, 22:14:37
However, I wrote a script that sends messages from with every length from 1 to N and that seems to be crashing in a different way.
Just a quick test: problematic lengths on the A410: 0x74, 0xb4, 0xf4, 0x134 (and so on, I guess). The assert (same as above) comes on the next ptp attempt.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / July / 2012, 03:14:17
srsa_4c
Interesting the interval is smaller. IIRC, usb1 uses smaller packets for bulk data ?


Some other random observations:
Examining ptp_data->recv_data, it looks like it returns 0 on success, and various values on error. When this particular problem happens, it returns 1. recv_ptp_data in ptp.c doesn't check the status

On d10
00116180: [PTPState] PTP_Unexpected Type=0 STATE=5 EVENT=16
seems to appear in camera log when this happens. Unfortunately, it's not clear where the function that produces this string is called from.

There are references in the firmware (both a540 and d10) to "A/BulkTrns.Log". On a540 it looks like the eventprocs

PTPRspnd.StartTransportLog
PTPRspnd.StopTransportLog
PTPRspnd.ShowTransportLog
PTPRspnd.ClearTransportLog

should relate to this. However, after registering them with RegComEventProc, I wasn't able to get them to do anything. They don't seem to exist on d10.

Title: Re: CHDK PTP interface
Post by: msl on 01 / July / 2012, 08:44:41
Minor versions (like 2.0 to 2.3) are supposed to be backward compatible, so it should be safe for ptpCamGui to start if the minor version is greater than what it knows about.

Yes, I know. I've made a little update for ptpCamGui. Now the gui will only check the major version.

msl
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / July / 2012, 16:41:01
I had the idea that if the problem is triggered by reading a particular size, we could  detect that size and force multiple calls to data->recv_data, so no single call uses the magic size. Turns out, this doesn't help :(

Another observation: On D10, size 0x1F4 behaves slightly differently from the larger problem values. It appears to hang in data->get_data_size, which then returns 0. For larger values, get_data_size returns the correct value and the hang is in recv_data. I suppose this relates to the fact that ox1F4 is ok on a540...

edit:
The [PTPState] PTP_Unexpected Type=0 STATE=5 EVENT=16  message comes from the get_data_size case, not recv_data
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / July / 2012, 01:44:48
On D10, I narrowed down where the error is returned from in data->recv_data (sub_FF9FA258) to the bne at FF9FA37C. The hang seems to happen in the preceding call to sub_FF869A1C__KerFlag_c (some kind of synchronization object timing out, I think)

Some of the preceding code seems to be related to the unknown parameter to recv_data that we always set to zero. I tried putting in a 1, but that didn't help.

edit:
testing error, setting the unknown param to 1 crashes very promptly when you try to use ptp. No surprise there ;)
Title: Re: CHDK PTP interface
Post by: philmoz on 02 / July / 2012, 04:24:19
On D10, I narrowed down where the error is returned from in data->recv_data (sub_FF9FA258) to the bne at FF9FA37C. The hang seems to happen in the preceding call to sub_FF869A1C__KerFlag_c (some kind of synchronization object timing out, I think)

Some of the preceding code seems to be related to the unknown parameter to recv_data that we always set to zero. I tried putting in a 1, but that didn't help.

edit:
testing error, setting the unknown param to 1 crashes very promptly when you try to use ptp. No surprise there ;)

Out of curiosity, does the problem still happen using the Rasberry PI version you posted about in another thread?
If so that would pretty much make it a firmware problem, as your research seems to indicate. Or at least a problem in the way CHDK is using the firmware.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / July / 2012, 04:33:48
Out of curiosity, does the problem still happen using the Rasberry PI version you posted about in another thread?
If so that would pretty much make it a firmware problem, as your research seems to indicate. Or at least a problem in the way CHDK is using the firmware.
It does the same thing from the pi. Not sure it's really any different than the linux laptop I already tested though...
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / July / 2012, 01:00:34
Another thought: Can we reproduce the problem with ps_uploader mentioned here: http://chdk.setepontos.com/index.php/topic,1632.msg14806.html#msg14806 (http://chdk.setepontos.com/index.php/topic,1632.msg14806.html#msg14806)

File is available in ps_uploader at https://www.box.com/chdk#/chdk/1/55270403 (https://www.box.com/chdk#/chdk/1/55270403)

edit:
We don't know the canon protocol of course, a range of files sizes near one of the magic numbers might be worthwhile.

edit:
I can't seem to get it to recognize my a540 though...
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / July / 2012, 01:45:27
Other ideas
http://biot.com/blog/usb-sniffing-on-linux (http://biot.com/blog/usb-sniffing-on-linux)
http://lxr.linux.no/#linux+v2.6.28.8/Documentation/usb/usbmon.txt (http://lxr.linux.no/#linux+v2.6.28.8/Documentation/usb/usbmon.txt)

edit:
http://wiki.wireshark.org/CaptureSetup/USB (http://wiki.wireshark.org/CaptureSetup/USB)
Title: Re: CHDK PTP interface
Post by: philmoz on 03 / July / 2012, 05:36:52
Other ideas
http://biot.com/blog/usb-sniffing-on-linux (http://biot.com/blog/usb-sniffing-on-linux)
http://lxr.linux.no/#linux+v2.6.28.8/Documentation/usb/usbmon.txt (http://lxr.linux.no/#linux+v2.6.28.8/Documentation/usb/usbmon.txt)

edit:
http://wiki.wireshark.org/CaptureSetup/USB (http://wiki.wireshark.org/CaptureSetup/USB)

Found it :)

While researching how USB PTP transfers work I came across this:
A bulk transfer is considered complete when it has transferred the exact amount of data requested, transferred a packet less than the maximum endpoint size, or transferred a zero-length packet.

When the chdkptp code sends a file/message that is exactly a multiple of the maximum end point size (512) the camera is still waiting for the bulk transfer to be completed. In this case it is necessary to send another 0 length packet to terminate the transfer.

The modified ptp_usb_senddata code below works on my cameras.

Code: [Select]
uint16_t
ptp_usb_senddata (PTPParams* params, PTPContainer* ptp,
unsigned char *data, unsigned int size)
{
static uint16_t ret;
static PTPUSBBulkContainer usbdata;

/* build appropriate USB container */
usbdata.length=htod32(PTP_USB_BULK_HDR_LEN+size);
usbdata.type=htod16(PTP_USB_CONTAINER_DATA);
usbdata.code=htod16(ptp->Code);
usbdata.trans_id=htod32(ptp->Transaction_ID);
memcpy(usbdata.payload.data,data,
(size<PTP_USB_BULK_PAYLOAD_LEN)?size:PTP_USB_BULK_PAYLOAD_LEN);
/* send first part of data */
ret=params->write_func((unsigned char *)&usbdata, PTP_USB_BULK_HDR_LEN+
((size<PTP_USB_BULK_PAYLOAD_LEN)?size:PTP_USB_BULK_PAYLOAD_LEN),
params->data);
if (ret!=PTP_RC_OK) {
ret = PTP_ERROR_IO;
/* ptp_error (params,
"PTP: request code 0x%04x sending data error 0x%04x",
ptp->Code,ret);*/
return ret;
}
    if (size > PTP_USB_BULK_PAYLOAD_LEN)
    {
        /* if everything OK send the rest */
        ret=params->write_func (data+PTP_USB_BULK_PAYLOAD_LEN,
                    size-PTP_USB_BULK_PAYLOAD_LEN, params->data);
        if (ret!=PTP_RC_OK) {
            ret = PTP_ERROR_IO;
    /* ptp_error (params,
            "PTP: request code 0x%04x sending data error 0x%04x",
                ptp->Code,ret); */
        }
    }
    if ((usbdata.length & 0x1FF) == 0)
        params->write_func(data, 0, params->data);
    return ret;
}

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / July / 2012, 09:19:28
Found it :)

While researching how USB PTP transfers work I came across this:
A bulk transfer is considered complete when it has transferred the exact amount of data requested, transferred a packet less than the maximum endpoint size, or transferred a zero-length packet.

When the chdkptp code sends a file/message that is exactly a multiple of the maximum end point size (512) the camera is still waiting for the bulk transfer to be completed. In this case it is necessary to send another 0 length packet to terminate the transfer.

Nice find.  :)

I've tested it with 0x3f as the magic value (still testing with a USB1.1 (or full speed ?) camera), and it really fixes the issue in question. (I now get "unexpected msg type" sporadically while running reyalp's msgtest)

Am I correct that the current implementation assumes "high speed" connection? I've found a define named PTP_USB_BULK_HS_MAX_PACKET_LEN in ptp.h . According to my web search this originates from some libgphoto related code(?). I've also found PTP_USB_BULK_FS_MAX_PACKET_LEN on the web in a project named arducam-osd which assumes full speed instead (which is understandable since it's Arduino-related).

I guess the connection speed could be detected somehow, and that magic value could be based on the connection type. I do not know the libusb code enough to tell how to do that...
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / July / 2012, 13:16:03
Found it :)

While researching how USB PTP transfers work I came across this:
A bulk transfer is considered complete when it has transferred the exact amount of data requested, transferred a packet less than the maximum endpoint size, or transferred a zero-length packet.
Excellent :)

My impression (not knowing much about USB...) is that the ptpcam code is pretty rough if a number of ways.
Title: Re: CHDK PTP interface
Post by: philmoz on 03 / July / 2012, 20:24:18
Found it :)

While researching how USB PTP transfers work I came across this:
A bulk transfer is considered complete when it has transferred the exact amount of data requested, transferred a packet less than the maximum endpoint size, or transferred a zero-length packet.

When the chdkptp code sends a file/message that is exactly a multiple of the maximum end point size (512) the camera is still waiting for the bulk transfer to be completed. In this case it is necessary to send another 0 length packet to terminate the transfer.

Nice find.  :)

I've tested it with 0x3f as the magic value (still testing with a USB1.1 (or full speed ?) camera), and it really fixes the issue in question. (I now get "unexpected msg type" sporadically while running reyalp's msgtest)

Am I correct that the current implementation assumes "high speed" connection? I've found a define named PTP_USB_BULK_HS_MAX_PACKET_LEN in ptp.h . According to my web search this originates from some libgphoto related code(?). I've also found PTP_USB_BULK_FS_MAX_PACKET_LEN on the web in a project named arducam-osd which assumes full speed instead (which is understandable since it's Arduino-related).

I guess the connection speed could be detected somehow, and that magic value could be based on the connection type. I do not know the libusb code enough to tell how to do that...

Attached is a patch to the current chdkptp trunk that attempts to get the maximum endpoint size from the libusb data and use that to determine if the dummy packet needs to be sent.

Can you try this with your camera and see what happens.

I have no idea if this is the right way to do this sort if thing -  I'm still trying to understand the whole USB PTP interface stuff.


Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / July / 2012, 22:07:30
Attached is a patch to the current chdkptp trunk that attempts to get the maximum endpoint size from the libusb data and use that to determine if the dummy packet needs to be sent.

Can you try this with your camera and see what happens.
The recognition of the max packet size works well for the two "full speed" cameras I tried.
After testing them with reyalp's msgtest, the results are:
A410 (DIGIC II, full speed)
Fails at length=0x34 (camera does not become unstable), works with any other length (tried up to 520). Note that as I reported earlier, length=0x34 was not problematic on this camera. (Hmmm, looks like a need for special casing some models...)
A420 (DIGIC II, full speed)
Max packet size recognition correct, msgtest runs correctly with any length.
A470 (DIGIC III, full speed)
Works with any length, but I get random "unexpected msg type" showstoppers while running msgtest. These start to be an issue over length>200. Camera does not become unstable, the test can be restarted. Previously, all lengths of (n*0x40)-0xc were problematic.
Ixus65 (DIGIC II, high speed)
Max packet size recognition correct, msgtest runs correctly with any length.

edit: host controller USB2.0, OS Linux 32bit

A separate note: the test with msgtest runs much slower on DIGIC II cameras, no matter full or high speed.

Quote
I have no idea if this is the right way to do this sort if thing -  I'm still trying to understand the whole USB PTP interface stuff.
Looks good enough to me.
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2012, 01:14:45
Great work.

One thing I noticed, PTP_USB_BULK_PAYLOAD_LEN was based on the old hard coded max_packet_size. I'm not clear if this actually matters anywhere, the first send in send_data might send more than one packet, but I'm not sure there's anything wrong with that.

ptp_usb_getdata looks similar.

I think the "unexpected msg type" error is an unrelated problem. I get it on D10 as well. That is probably the something failing in the msgtest script, which returns an error rather than user message, which msgtest doesn't understand.

edit:
I checked in philmoz patch in chdkptp changeset 258. Leaving the debug print in for now so people can see what size it's detecting. I think getting wMaxPacketSize is correct.

edit:
the "unexpected" message I get is "not enough memory"

edit:
Fixed in trunk 1950 (http://trac.assembla.com/chdk/changeset/1950/trunk)/release 1951 (http://trac.assembla.com/chdk/changeset/1951/branches/release-1_0). This should make anything that relies on sending ptp messages a lot more stable  :-X

edit:
with this change, a540 runs msgtest from 1 to 10000 with no problems
d10 died with a lost ptp connection after over 9000, not clear why
sending 9204 (0x23f4)...unexpected return code 0x2ff
Title: Re: CHDK PTP interface
Post by: cgott4242 on 04 / July / 2012, 15:53:15
I have 2 SD1100IS cameras and have ptpgui working.  It enables me to shoot photos (remote shutter release) and d/l files.
I don't see a live view function
or a way to control multiple cameras

Does the PTPcam do these things?  if not, which software does?

thx
Title: Re: CHDK PTP interface
Post by: msl on 04 / July / 2012, 16:04:46


I don't see a live view function
or a way to control multiple cameras

http://chdk.setepontos.com/index.php?topic=6285.msg87376#msg87376 (http://chdk.setepontos.com/index.php?topic=6285.msg87376#msg87376)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 05 / August / 2012, 15:57:27
@reyalp
I'd like to start implementing remote capture with remote target (i.e. PC). Some months ago I did some research, as you may remember http://chdk.setepontos.com/index.php?topic=7366.0 (http://chdk.setepontos.com/index.php?topic=7366.0) .
I need some help/advice on how this should be done in CHDK and in the reference client (chdkptp).
Remote capture formats could include:
- JPEG (via a hook in FileWriteTask), with or without Exif
- the uncompressed YUV source of the JPEG (which should be available at the same time as the JPEG)
- RAW (via the existing RAW save hook)

What I don't know is the PTP part of all this, and how should scripting be involved. Do you have an idea?
Thanks.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / August / 2012, 16:39:19
I'd like to start implementing remote capture with remote target (i.e. PC). Some months ago I did some research, as you may remember
Question: Is this actually worthwhile compared to letting the camera save to disk and downloading the file ? It could be faster, but what is the use case where saving to disk is too slow, and this isn't ?

I'm not against it, just wondering if you have a specific application in mind.
Quote
What I don't know is the PTP part of all this, and how should scripting be involved. Do you have an idea?
To capture raw (and presumably the other options) you will need to do something like the how the raw hook in capt_seq blocks and waits for spytask. Since PTP transfers can only be initiated by the PC side, I think it will have to go like this (for raw, if you hook some other place the sequence should be similar):

1) Before shot, PC sends a command to tell the camera it wants to transfer the next image over PTP. This just sets a flag for cap_seq_task
2) The raw hook (or spytask raw code) sees the flag, sets another other flag to say raw is available, and waits
3) in the meantime, the PC polls waiting for the raw available flag
4) when the PC sees the raw available, it initiates a command that has a camera->pc data phase to transfer the data
5) when the transfer is complete, it clears the flag that has been blocking the raw hook, and everything continues as normal.

Some additional notes:
1) In my experience, sending uncached data is much faster than cached. So if you send the raw buffer, you should use the uncached address.
2) For the options other than jpeg, it could be useful to be able to request only a sub-image. Practically, the overhead of individual send calls is such that you'd probably send entire lines.
3) Should think about error cases, e.g. if the client requests a remote capture but fails to load the data... so #2 in the preceding list should maybe time out eventually.
4) The "flags" above should probably just be one state variable.

So I see this as at least 3 additional PTP commands (or 1 command with 3 sub commands, but I prefer to separate things that have data phases from ones that don't), something like
RemoteCaptureInit - called before exposure, tells CHDK we want the data over PTP. No data phase, may specify type (e.g. jpeg, raw, yuv) and sub-image.
RemoteCaptureIsReady - Polled after above, no data phase, just tells if data is available.
RemoteCaptureGetData - called after the preceding, has a cam->pc data phase

Re scripting:
We could put the functionality of RemoteCaptureInit and RemoteCaptureIsReady in script, but this just seems like added complexity to me.

Other questions:
Should the transferred data include meta data ? If so, how much in what form ? For raw, it might make sense to send the whole DNG exif ?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 05 / August / 2012, 18:50:08
Thanks for the suggestions!
Question: Is this actually worthwhile compared to letting the camera save to disk and downloading the file ? It could be faster, but what is the use case where saving to disk is too slow, and this isn't ?
For me, the current remote capture solution feels like a workaround (it is a workaround, actually). Canon's "remote control" capability always included (AFAIK) a shooting option where the destination of the capture is the "PC". I would like to restore this functionality. My other concern is: why write to the card (causing wear) when the pictures should end up on the connected host anyway? And yes, it can be a little faster.
Quote
Practically, the overhead of individual send calls is such that you'd probably send entire lines.
I don't quite get what you mean here.
Quote
Should the transferred data include meta data ? If so, how much in what form ? For raw, it might make sense to send the whole DNG exif ?
It could be an option to send metadata or not. For JPEG, exif is available at the same time (it's stored in a separate buffer and is intended to be written first), for raw, probably the DNG exif-generator routine should be reused somehow.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / August / 2012, 19:25:40
Quote
Practically, the overhead of individual send calls is such that you'd probably send entire lines.
I don't quite get what you mean here.
If you want to send the whole buffer, you can do it with one call to data->send_data. Same if your subimage is full width but reduced height: you just adjust the start and total size. Live view does this for modes where the viewport isn't full height (e.g. 16:9 on a 4:5 screen)

If the subimage is narrower than the full image you have to call send_data for each line. I tried this for live view, because some cameras have unused borders (e.g. stitch window) but it was significantly slower than just sending the whole buffer. You could copy it into a new buffer, but that would take time and you wouldn't have enough RAM to do it all at once unless the subimage is very small.
Quote
It could be an option to send metadata or not. For JPEG, exif is available at the same time (it's stored in a separate buffer and is intended to be written first), for raw, probably the DNG exif-generator routine should be reused somehow.
Questions to think about:
Is there some minimum amount of data you need (dimensions, bayer pattern, bit depth) ? Or do you require the user to obtain or know those separately.
If you require them to get it separately, is it available via script ? Currently essential stuff like raw size and bayer are not.
If you need some data, is it really worthwhile to make the rest optional ? With a 20mb raw, or even a 1mb jpeg, adding a few kb of exif isn't going to have a significant impact. It may be better to send it all the time and let the client discard it if they don't care.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 05 / August / 2012, 19:42:22
If the subimage is narrower than the full image you have to call send_data for each line. I tried this for live view, because some cameras have unused borders (e.g. stitch window) but it was significantly slower than just sending the whole buffer.
OK, now I get it. Don't break up data into tiny pieces because the USB DMA doesn't like it.
Quote
If you need some data, is it really worthwhile to make the rest optional ? With a 20mb raw, or even a 1mb jpeg, adding a few kb of exif isn't going to have a significant impact. It may be better to send it all the time and let the client discard it if they don't care.
Good point.
Title: Re: CHDK PTP interface
Post by: c10ud on 06 / August / 2012, 08:17:15
@srsa_4c: I once tried doing this, i found the camera (DryOS, i don't remember the exact model) was keeping a pointer to the last jpg buffer (iirc there also was some offset due to exif data, but it doesn't matter) but i couldn't prevent it from writing data to the SD card, i reached the point where it was writing 0b files, but still ugly, then i gave up (iirc i had to add quite a lot of code...probably now that i think of it there was some simpler solution like overriding the save jump or something like that)

all of this to say, if you simply want to get the job done (if you want to hack it badly then it's another story):
- send lua shoot()
- wait a bit
- download from the SD card with standard ptp commands (or chdk data dl)
- ???
- profit!

A standard SD card will be fast enough when saving and its life will be ~yrs
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / August / 2012, 09:43:12
to get the job done
Job?
Challenge!  :)
BTW, read the link I posted here (http://chdk.setepontos.com/index.php?topic=4338.msg88931#msg88931)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 22 / August / 2012, 21:22:34
Attached to this post are preliminary patches implementing remote shooting with remote target via ptp.
Problems, issues, notes (list is not complete...)
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / August / 2012, 23:41:54
Thanks for working on this srsa_4c. I probably won't get a chance to look at it in detail before the the weekend.

Some initial thoughts.
- Adding a hook to all the cameras is a big job. Since raw doesn't require the while file write hook task, the final version should do raw for all cams, and the ifdef should just apply to the parts that require the filewritetask hook. This implies some way of checking which are available, preferably without trying to take a shot.
- the chdkptp side should expose the individual steps to lua. I can certainly understand doing it the way you are now for testing though, and assuming the CHDK code gets added, I can work on that part.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 23 / August / 2012, 14:32:16
I probably won't get a chance to look at it in detail before the the weekend.
No problem. There is no hurry.
Quote
the final version should do raw for all cams, and the ifdef should just apply to the parts that require the filewritetask hook.
Good idea.
Quote
This implies some way of checking which are available, preferably without trying to take a shot.
Perhaps it could be part of some sort of "capabilities" request.
Quote
- the chdkptp side should expose the individual steps to lua. I can certainly understand doing it the way you are now for testing though, and assuming the CHDK code gets added, I can work on that part.
Well, I had the feeling that the huge ptp_chdk_remoteshoot() in ptp.c is not really appropriate :)

update2: v2 patches, support for RAW retrieval over PTP on cameras without the FileWriteTask hook (cam saves local jpeg, RAW still doesn't contain metadata)
chdkptp side: started to implement those "individual steps", top level lua logic is missing
RemoteCaptureInit now signals success or failure (needed because of cameras with partial support)
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / August / 2012, 16:50:27
From Sticks thread http://chdk.setepontos.com/index.php?topic=8585.msg90041#msg90041 (http://chdk.setepontos.com/index.php?topic=8585.msg90041#msg90041)
but I'm concerned about the chdkptp-side implementation. Especially now that there's a brand new shoot command, I'm not sure how mine should be implemented.
As long as the individual steps are available to lua (which as I said, I can add) and a scripted shoot will honor the remote capture settings, this doesn't seem like it should be much of a problem.

The client will have to know not to use a blocking call for a shoot script if it expects to get remote data.

Would it be useful to be able to set the remote capture parameters in lua, (equivalent to PTP_CHDK_RemoteCaptureInit) or is this redundant ? I'm not sure...

From an efficiency point of view, it would be preferable to add the remote capture data available flag to PTP_CHDK_ScriptStatus rather than giving it a unique command (PTP_CHDK_RemoteCaptureIsReady). That way, the existing wait_status command in chdkptp would be extended to work on that value, without the overhead of polling multiple different commands. This seems like the way to go to me. (Ultimately, there should be a way to combine all the status bits with the live view polling, but that's another project)

How chdkptp side Lua should deal with getting the individual chunks so something of a question, since in some cases you'd want to write directly to disk (for low memory systems, you might want to not even store a whole raw) and in others you might want the data as an lbuf in Lua. I think this shouldn't really influence the protocol though.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / August / 2012, 21:05:30
As long as the individual steps are available to lua (which as I said, I can add)
OK :)
Are these steps similar to what those (unfinished/untested) functions in ptp.c (in the v2 patch) are supposed to do? (ptp_chdk_rcinit, ptp_chdk_rcisready, ptp_chdk_rcgetname, ptp_chdk_rcgetfile)
Quote
and a scripted shoot will honor the remote capture settings, this doesn't seem like it should be much of a problem.

The client will have to know not to use a blocking call for a shoot script if it expects to get remote data.

Would it be useful to be able to set the remote capture parameters in lua, (equivalent to PTP_CHDK_RemoteCaptureInit) or is this redundant ? I'm not sure...
You mean setting file type(s), crop parameters independently of initing / uniniting the remote file target mode?

I've been thinking about a use case where the camera runs a motion detection script, and the client fetches the pictures (continuously) as they become available. In this case the camera would stay in remote file target mode for a while. Maybe this could be considered.
Quote
From an efficiency point of view, it would be preferable to add the remote capture data available flag to PTP_CHDK_ScriptStatus rather than giving it a unique command (PTP_CHDK_RemoteCaptureIsReady). That way, the existing wait_status command in chdkptp would be extended to work on that value, without the overhead of polling multiple different commands.
OK, but the return value of PTP_CHDK_RemoteCaptureIsReady will need to be placed somewhere (param2?)
Quote
This seems like the way to go to me. (Ultimately, there should be a way to combine all the status bits with the live view polling, but that's another project)

How chdkptp side Lua should deal with getting the individual chunks so something of a question, since in some cases you'd want to write directly to disk (for low memory systems, you might want to not even store a whole raw) and in others you might want the data as an lbuf in Lua.
Guess you mean something like you did with ptp_chdk_download(). I'll leave that to you  :D

I'll also need help getting the DNG exif, as that code seems to be mixed into the DNG creation process which my current code avoids (there's no point in stressing the camera with byteswapping).

Also, for cameras with partial (RAW only) support, maybe the SDM method is the way to go (I haven't looked into that code, but I seem to recall that the RAW data is transferred over PTP and the JPEG - which is small - gets erased instantly). I think SDM fills the RAW buffer with some homogeneous value (0?) to achieve a really small JPEG.
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / August / 2012, 21:48:12
Are these steps similar to what those (unfinished/untested) functions in ptp.c (in the v2 patch) are supposed to do? (ptp_chdk_rcinit, ptp_chdk_rcisready, ptp_chdk_rcgetname, ptp_chdk_rcgetfile)
Yes, that's what I had in mind. I still haven't had a chance to really look at it, but next weekend is looking good.
Quote
You mean setting file type(s), crop parameters independently of initing / uniniting the remote file target mode?
Yes.
Quote
I've been thinking about a use case where the camera runs a motion detection script, and the client fetches the pictures (continuously) as they become available. In this case the camera would stay in remote file target mode for a while. Maybe this could be considered.
Yes, it seems like this might be more convenient under script control. Question:
Should we allow both (could lead to odd situation if client uses both, also code complexity) or require that it be done in lua ? I'd be tempted to only do it in lua if we are going to allow lua at all,  so  PTP_CHDK_RemoteCaptureInit would be replaced by a lua function.

Since shooting requires sending lua anyway, it doesn't seem like this would be a big handicap. If anything would make the client simpler.

Thoughts ?

Quote
OK, but the return value of PTP_CHDK_RemoteCaptureIsReady will need to be placed somewhere (param2?)
We have quite a few params and bits free. I also realized after posting that this would make it no longer really "script" status :-[

I wonder if it would make more sense to have this be a flag (remote capture chunk is available), and make PTP_CHDK_RemoteCaptureGetData just return the next chunk along with an ID of what it is ?

Quote
Also, for cameras with partial (RAW only) support, maybe the SDM method is the way to go (I haven't looked into that code, but I seem to recall that the RAW data is transferred over PTP and the JPEG - which is small - gets erased instantly). I think SDM fills the RAW buffer with some homogeneous value (0?) to achieve a really small JPEG.
I haven't looked at SDM, but if we go this way, it seems like it should be something you can set for script, could be useful in other situations beyond remote camera. e.g nuke_next_jpeg()
In some situations, keeping the all black jpeg could be useful, because it would still have the exif

Regarding development:
I understand you didn't want to use the trunk because it's moving too fast. What would you think about having this temporarily go in a branch of the current trunk ? I'd prefer to have it in svn somewhere to play with, and it's not going to go into the stable branch in the end.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / August / 2012, 22:08:05
-
Title: Re: CHDK PTP interface
Post by: srsa_4c on 31 / August / 2012, 16:51:10
Quote
I've been thinking about a use case where the camera runs a motion detection script, and the client fetches the pictures (continuously) as they become available. In this case the camera would stay in remote file target mode for a while. Maybe this could be considered.
Yes, it seems like this might be more convenient under script control. Question:
Should we allow both (could lead to odd situation if client uses both, also code complexity) or require that it be done in lua ? I'd be tempted to only do it in lua if we are going to allow lua at all,  so  PTP_CHDK_RemoteCaptureInit would be replaced by a lua function.

Since shooting requires sending lua anyway, it doesn't seem like this would be a big handicap. If anything would make the client simpler.
I'm sorry, but I don't follow. What does "both" mean here? If it's about the format + cropping settings, I think a single method of setting them would be preferred.

Quote
I wonder if it would make more sense to have this be a flag (remote capture chunk is available), and make PTP_CHDK_RemoteCaptureGetData just return the next chunk along with an ID of what it is ?
I'll think about this. It would require new logic on the client side too.

Quote
Quote
Also, for cameras with partial (RAW only) support, maybe the SDM method is the way to go (I haven't looked into that code, but I seem to recall that the RAW data is transferred over PTP and the JPEG - which is small - gets erased instantly). I think SDM fills the RAW buffer with some homogeneous value (0?) to achieve a really small JPEG.
I haven't looked at SDM, but if we go this way, it seems like it should be something you can set for script, could be useful in other situations beyond remote camera. e.g nuke_next_jpeg()
In some situations, keeping the all black jpeg could be useful, because it would still have the exif
A small step from here is to keep the full jpeg and transfer/erase it on demand :/ This would essentially do what current scripted solutions do. The number of possible options keeps growing...
Quote
Regarding development:
I understand you didn't want to use the trunk because it's moving too fast. What would you think about having this temporarily go in a branch of the current trunk ? I'd prefer to have it in svn somewhere to play with, and it's not going to go into the stable branch in the end.
I'm not against it. Tried my v2 patch, it still applies to current trunk code without change.
Do you plan to take over the chdkptp part?
Title: Re: CHDK PTP interface
Post by: reyalp on 31 / August / 2012, 17:23:04
I'm sorry, but I don't follow. What does "both" mean here? If it's about the format + cropping settings, I think a single method of setting them would be preferred.
Yes, by "both" I meant  the current PTP_CHDK_RemoteCaptureInit + an equivalent script function. And I agree a single method seems better, and the more I think about it, I think script is the better option.
Quote
Quote
I wonder if it would make more sense to have this be a flag (remote capture chunk is available), and make PTP_CHDK_RemoteCaptureGetData just return the next chunk along with an ID of what it is ?
I'll think about this. It would require new logic on the client side too.
This was just thinking out loud, maybe it doesn't make sense don't put a lot of work into it.

Quote
A small step from here is to keep the full jpeg and transfer/erase it on demand :/ This would essentially do what current scripted solutions do. The number of possible options keeps growing...
If they keep the full file, then I don't think there's any need to use remote capture. They can download it as a file and decide what to do. Deleting can be done in script already.

Quote
Quote
Regarding development:...
I'm not against it. Tried my v2 patch, it still applies to current trunk code without change.
OK, I think I'll do this.
Quote
Do you plan to take over the chdkptp part?
I could put it under an ifdef and do some work on it at least.
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / September / 2012, 15:11:28
I've created a branch for the remote capture stuff, with the patch from #829 above applied and the ptp minor version incremented.

As an aside, it would be nice to be able to identify development versions in the version command. We often end up making incompatible changes before the final protocol is nailed down, and it wouldn't make sense to update the major version for this. However from a practical point of view, when developing clients, it's nice to be able to check if you are talking to the corresponding development version.

I'm thinking either
- add a third parameter to PTP_CHDK_Version - 0 (which should be effectively returned by the versions that don't explicitly set it) means it's a release version, other values can be used to uniquely identify test versions.
- declare that a minor version greater than say 10000 is a flag for development.

edit:
I've added the chdkptp patch. It will automatically #ifdef in the remote capture code if you use the ptp.h from the ptp-remote-capture-test branch (set CHDK_SRC_DIR=/path/to/branch in config.mk)

I took out the a410 hack for now, but I would like to make chdkptp do the right thing for these cameras at some point.

edit:
Remote shoot with raw on a540 and d10 work. Transfer for full raw is reasonably quick, the entire rs command took 2 sec on a540, 3.8 sec on d10 (this includes pre-focus, shooting etc in addition to transfer)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 02 / September / 2012, 22:02:34
I took out the a410 hack for now, but I would like to make chdkptp do the right thing for these cameras at some point.
I was too lazy to separate that.

About replacing PTP_CHDK_RemoteCaptureInit with script command(s):
Can this be bulletproof? Currently, PTP_CHDK_RemoteCaptureInit is independent of scripting, so it can be issued any time. I'm asking because of its "uninit" functionality.
If script execution breaks for some reason and the camera keeps reporting "script is already running", can an emergency uninitialization be executed? If not, hooks will continue to be blocked, until they time out (which is not currently implemented).

update:
Quote
Remote shoot with raw on a540 and d10 work. Transfer for full raw is reasonably quick, the entire rs command took 2 sec on a540, 3.8 sec on d10 (this includes pre-focus, shooting etc in addition to transfer)
What do you think about the jpeg? Should it be minimized / blacked out?
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / September / 2012, 01:51:07
I took out the a410 hack for now, but I would like to make chdkptp do the right thing for these cameras at some point.
I was too lazy to separate that.

About replacing PTP_CHDK_RemoteCaptureInit with script command(s):
Can this be bulletproof? Currently, PTP_CHDK_RemoteCaptureInit is independent of scripting, so it can be issued any time. I'm asking because of its "uninit" functionality.
If script execution breaks for some reason and the camera keeps reporting "script is already running", can an emergency uninitialization be executed? If not, hooks will continue to be blocked, until they time out (which is not currently implemented).
This is a good question. I think it's OK to have in script though:
1) Timeout should be implemented before release, so impact will not be so bad.
2) there's already lots of things you can do with script that leave the camera in a bad state, like shoot() in video mode...
3) We should at the capability to cleanly kill a running script. This shouldn't be hard, just need to set a flag for kbd_task that triggers the same code path as pressing shutter.

Quote
What do you think about the jpeg? Should it be minimized / blacked out?
Maybe nice to have, but I don't think it's a high priority.
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / September / 2012, 17:58:24
I added filewritetask hook to a540. Seem to work as expected.

Some thoughts on the code:
Most of the stuff add to generic/capt_seq.c should be in thumb code somewhere.
It might make more sense to do most of the stuff in capt_seq_hook_raw_here() within the regular raw hook (or the same spytask loop where the raw hook is called)
get_next_chunk_data_for_ptp also looks like it doesn't need to be in capt_seq, but not sure where it goes.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / September / 2012, 19:18:51
Most of the stuff add to generic/capt_seq.c should be in thumb code somewhere.
It might make more sense to do most of the stuff in capt_seq_hook_raw_here() within the regular raw hook (or the same spytask loop where the raw hook is called)
get_next_chunk_data_for_ptp also looks like it doesn't need to be in capt_seq, but not sure where it goes.
I added the code to generic/capt_seq.c because that seemed to be somewhat related. Since the thumb-arm barrier in CHDK is not entirely clear to me, is there something I should watch out for when moving functions into thumb code?
edit:
Answer: platform/generic/shooting.c :)
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / September / 2012, 20:12:44
Most of the stuff add to generic/capt_seq.c should be in thumb code somewhere.
It might make more sense to do most of the stuff in capt_seq_hook_raw_here() within the regular raw hook (or the same spytask loop where the raw hook is called)
get_next_chunk_data_for_ptp also looks like it doesn't need to be in capt_seq, but not sure where it goes.
I added the code to generic/capt_seq.c because that seemed to be somewhat related. Since the thumb-arm barrier in CHDK is not entirely clear to me, is there something I should watch out for when moving functions into thumb code?
The main point is thumb code is smaller, so anything that's not tightly tied to the ARM asm could should usually be in thumb. If you are using a __attribute__((naked)) function to save and restore registers, that should be in arm.

edit:
note if you use ASM_SAFE in the call (or don't need to save extra registers), then you can go directly to the thumb function, e.g. core_spytask_can_start is a thumb function and most dryos cams call it with just
"BL core_spytask_can_start" in boot.c, and the toolchain converts it to core_spytask_can_start_from_arm
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / September / 2012, 21:05:50
note if you use ASM_SAFE in the call (or don't need to save extra registers), then you can go directly to the thumb function, e.g. core_spytask_can_start is a thumb function and most dryos cams call it with just
"BL core_spytask_can_start" in boot.c, and the toolchain converts it to core_spytask_can_start_from_arm
I think that's what I wanted to know.

Something (not) completely unrelated:
How should I handle this (http://chdk.setepontos.com/index.php?topic=8600.msg90038#msg90038) situation? Two of the earliest cameras are affected (I plan to release my Ixus30/SD200 port soon). send_resp() has only 2 parameters in every other camera. Would it be better to create a new #define in camera.h for this, or can I just do what I did here (http://chdk.setepontos.com/index.php?topic=8600.msg90081#msg90081)? That would cause a 2 or 4 byte size increase in every port, but - as I understand - would be safe otherwise.
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / September / 2012, 21:31:27
note if you use ASM_SAFE in the call (or don't need to save extra registers), then you can go directly to the thumb function, e.g. core_spytask_can_start is a thumb function and most dryos cams call it with just
"BL core_spytask_can_start" in boot.c, and the toolchain converts it to core_spytask_can_start_from_arm
I think that's what I wanted to know.

Something (not) completely unrelated:
How should I handle this (http://chdk.setepontos.com/index.php?topic=8600.msg90038#msg90038) situation? Two of the earliest cameras are affected (I plan to release my Ixus30/SD200 port soon). send_resp() has only 2 parameters in every other camera. Would it be better to create a new #define in camera.h for this, or can I just do what I did here (http://chdk.setepontos.com/index.php?topic=8600.msg90081#msg90081)? That would cause a 2 or 4 byte size increase in every port, but - as I understand - would be safe otherwise.
Yeah, I think sending an extra arg is fine. If I remember right we already send deta->recv_data more than (some ?) firmwares actually use.

Regarding remote capture, I was thinking about putting the init stuff in lua, but I don't want to duplicate effort.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / September / 2012, 21:56:54
Regarding remote capture, I was thinking about putting the init stuff in lua, but I don't want to duplicate effort.
If you have time to do it, just go ahead.
How about moving most of generic/capt_seq.c into (say) core/hooks.c?
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / September / 2012, 22:11:34
Regarding remote capture, I was thinking about putting the init stuff in lua, but I don't want to duplicate effort.
If you have time to do it, just go ahead.
How about moving most of generic/capt_seq.c into (say) core/hooks.c?
I'd probably put the remote capture related stuff in it's own file (core/ remote_capture.c or something, some of the stuff in the main ptp.c could probably go there too). Without that, capt_seq_hook_raw_here is very small.  capt_seq_hook_set_nr needs defines from the cameras capt_seq.c

None of this is urgent.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / September / 2012, 15:36:07
I started to move code from generic/capt_seq.c to core/remote_capture.c in a temporary repo
( https://subversion.assembla.com/svn/chdk-s1.remotecapture/ ). It's still in progress. I'm a bit unsure about the handling of affected variables. I changed some from static to volatile (to be able to access them from multiple source modules), and I created "setter" and "getter" functions for some others.
My later plan includes using the dng module to get the CHDK exif (optionally).
I'm not completely sure about naming the new file "remote_capture.c", because the filewritetask hook could possibly be used for more.
To do the separation, I had to move the declaration of the struct "cam_ptp_data_chunk" into platform_camera.h. As platform_camera.h only holds #define's in current CHDK code, this looks pretty ugly to me.
"cam_ptp_data_chunk" may turn out to be the same in a large number of camera generations, but this is only a suspicion.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / September / 2012, 16:57:44
I started to move code from generic/capt_seq.c to core/remote_capture.c in a temporary repo
( https://subversion.assembla.com/svn/chdk-s1.remotecapture/ ).
I started doing something similar when I tried to put the init stuff in Lua cleanly, ran into similar issues and ran out of time before I got to the point of having anything to check in.
Quote
I changed some from static to volatile (to be able to access them from multiple source modules), and I created "setter" and "getter" functions for some others.
I'd say getters/setters is probably cleaner, neither one is really safe to communicate across tasks, but for simple state variables it should be OK. Overall, the current code (in remote-capture-test) is quite convoluted with the different globals and statics. I think it can be made much more modular, but it's a bit tricky.
Quote
I'm not completely sure about naming the new file "remote_capture.c", because the filewritetask hook could possibly be used for more.
Agreed. The direction I was going was to have minimal filewrite_main_hook in capt_seq.c which currently just called into the remote capture code, but could have other stuff later.

Quote
To do the separation, I had to move the declaration of the struct "cam_ptp_data_chunk" into platform_camera.h. As platform_camera.h only holds #define's in current CHDK code, this looks pretty ugly to me.

"cam_ptp_data_chunk" may turn out to be the same in a large number of camera generations, but this is only a suspicion.
If there is only one known variant, it might be better to just start out assuming it's always that way, and deal with it later if it turns out not to be. If there are only a few variants, they are likely to correspond to DryOS revs (old vxworks like a410 and more recent like a540 seem to be the same), so you could just have a few different ones using existing DryOS ifdefs.

In my code, started putting in a function to copy from the platform defined one into the generic one in generic/capt_seq.c

Quote
My later plan includes using the dng module to get the CHDK exif (optionally).
I'm not sure it's even worth making this optional, if the client doesn't want it they can just throw it out.

On question does arise, if you do a sub-image, what dimensions go in the header ?

Another thing I noticed trying to work on the init stuff is that startline, numlines could have different possible values for raw vs YUV (raw buffer being a bit bigger than max size jpeg, and jpeg potentially being lower res.)

Have you found / verified that a YUV buffer is actually available ? If not, maybe V1 should just be jpeg and raw, and not worry about any of the YUV stuff for now.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 06 / September / 2012, 17:10:46
I'd say getters/setters is probably cleaner, neither one is really safe to communicate across tasks


Why is that ?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / September / 2012, 21:43:05
I'd say getters/setters is probably cleaner, neither one is really safe to communicate across tasks, but for simple state variables it should be OK.
What I don't like about the getters/setters is the overhead (especially when the variable is shared between arm and thumb code).
Quote
Overall, the current code (in remote-capture-test) is quite convoluted with the different globals and statics. I think it can be made much more modular, but it's a bit tricky.
I know ...
  • code is ugly and imperfect (suggestions / improvements are welcome)
Quote
In my code, started putting in a function to copy from the platform defined one into the generic one in generic/capt_seq.c
How does it look like?
Quote
I'm not sure it's even worth making this optional, if the client doesn't want it they can just throw it out.
On question does arise, if you do a sub-image, what dimensions go in the header ?
I assumed that if somebody needs a subrange of the RAW, a header may not be needed anyway. Or do you think the output should be valid DNG? If so, the byteswapping should probably be done in the client.
Quote
Another thing I noticed trying to work on the init stuff is that startline, numlines could have different possible values for raw vs YUV (raw buffer being a bit bigger than max size jpeg, and jpeg potentially being lower res.)

Have you found / verified that a YUV buffer is actually available ? If not, maybe V1 should just be jpeg and raw, and not worry about any of the YUV stuff for now.
It should be available. Otherwise the camera would need to decode the jpeg again to provide the recreview. I think I'm going to dump the RAM in the FileWriteTask hook to look for the buffer, its pointers and the image dimensions. Then look them up in the firmware.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / September / 2012, 23:26:50
Why is that ?
Which one ?
I should clarify the "not safe". It's possible to use either in ways that are safe for us, but they aren't a safe way to do inter-task communication in general.
As far as using volatile vs getters/setters
- getters/setters are more flexible: If you want to do something more complicated later, the calling code doesn't have to change
- people tend to attribute magic to volatile that it doesn't have.
What I don't like about the getters/setters is the overhead (especially when the variable is shared between arm and thumb code).

I wouldn't worry too much about this, especially if it's a case like the write hook polling something waiting for another task. The polling will only happen every 10ms at most, a simple functions call is very quick. Something that only happens a few times in a ptp transaction or shot will also be no concern.
Quote
How does it look like?
Unfinished ;)
I had function like
Code: [Select]
void filewrite_get_jpeg_chunk(remotecap_data_chunk *dest,void *src,int n) {
    cam_ptp_data_chunk *pdc = src;
    dst[n].address=pdc[n].address;
    dst[n].length=pdc[n].length;
}
void filewrite_main_hook(char *name, cam_ptp_data_chunk *pdc)
{
    remotecap_jpeg_available(name,MAX_CHUNKS_FOR_JPG,pdc);
...
but after I wrote that it seemed like it might be better to just leave the loop in filewrite_main_hook.

Quote
I assumed that if somebody needs a subrange of the RAW, a header may not be needed anyway. Or do you think the output should be valid DNG? If so, the byteswapping should probably be done in the client.
I agree byteswapping should be left to the client. For subframe, I think having the exif could be useful, but we could just send the full-frame exif and let the client adjust it or pad the missing data to the expected size.
Hmm, DNG usually has a thumbnail too.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / September / 2012, 14:18:12
Quote
Have you found / verified that a YUV buffer is actually available ? If not, maybe V1 should just be jpeg and raw, and not worry about any of the YUV stuff for now.
It should be available. Otherwise the camera would need to decode the jpeg again to provide the recreview. I think I'm going to dump the RAM in the FileWriteTask hook to look for the buffer, its pointers and the image dimensions. Then look them up in the firmware.
Some preliminary trials show that the YUV source is indeed available during "recreview". Its pixel format is UYVY in A410 (and probably in every other camera too). Getting it correctly may require some scripting magic (like pressing SET to hold the cam in review mode and halfshoot after the transfer has finished) OR a long enough review time.

edit:
This could get interesting. At max. resolution I seem to get no sign of a (full sized) yuv image, only the raw. There is always a lower resolution y411 in another buffer, its size and pixel shape varies with the selected picture size. The uncompressed source yuv is always present at M and S picture sizes.

edit2:
The UYVY image seems to have only one use: source for the compression engine. Activating the record review (by pressing SET) causes immediate decoding of the JPEG to another buffer with y411 as pixel format. I see no point in getting that.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / September / 2012, 17:26:06
The UYVY image seems to have only one use: source for the compression engine. Activating the record review (by pressing SET) causes immediate decoding of the JPEG to another buffer with y411 as pixel format. I see no point in getting that.
So if I understand right, on this camera (a410 ?) the full res YUV buffer seems to be needed only for reduced size jpeg, otherwise the image processor does the raw->jpeg all in one step ? This would match well with the observation that reduced res jpeg is slower than full res on some (mostly older, digic II maybe digic III) cameras.
I suppose a possible alternative is that the full res case does create a YUV buffer, but it's destroyed before the point you are making the dump ?

Recreview decoding doesn't surprise me, they have fast decode for play mode anyway.

As an aside, the normal viewport buffer addresses don't seem to work in recreview mode. I'm not sure if this is true for all cameras, it is for d10 and a540. These cameras both have vid_get_viewport_live_fb, it's possible the correct address is returned by one of the other existing functions (I think someone tested this and found it wasn't but I'm not 100% sure.) If you find a reliable way to get it, we could make recreview work in ptp live view, which would be nice. Showing chdk zebra/histogram in recreview could also be useful.

Quote
I started to move code from generic/capt_seq.c to core/remote_capture.c in a temporary repo
( https://subversion.assembla.com/svn/chdk-s1.remotecapture/ ).
I'm not really sure how to coordinate work with this branch and the one main CHDK svn repo.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / September / 2012, 22:46:25
So if I understand right, on this camera (a410 ?) the full res YUV buffer seems to be needed only for reduced size jpeg, otherwise the image processor does the raw->jpeg all in one step ?
It appears to be so.
Quote
I suppose a possible alternative is that the full res case does create a YUV buffer, but it's destroyed before the point you are making the dump ?
I would think that's unlikely. At least I can't see any sign of that buffer. The RAW buffer seems to still contain the RAW data, and of course there is the JPEG data.
Quote
As an aside, the normal viewport buffer addresses don't seem to work in recreview mode. I'm not sure if this is true for all cameras, it is for d10 and a540. These cameras both have vid_get_viewport_live_fb, it's possible the correct address is returned by one of the other existing functions (I think someone tested this and found it wasn't but I'm not 100% sure.) If you find a reliable way to get it, we could make recreview work in ptp live view, which would be nice. Showing chdk zebra/histogram in recreview could also be useful.
By looking at some dumps, there is an active viewport buffer (still talking about review mode right after shooting), vid_get_viewport_fb_d() points to it. In another dump, which was created after shooting AND pressing SET (recreview hold), vid_get_viewport_fb_d() still seems to be valid.

Quote
Quote
I started to move code from generic/capt_seq.c to core/remote_capture.c in a temporary repo
( https://subversion.assembla.com/svn/chdk-s1.remotecapture/ ).
I'm not really sure how to coordinate work with this branch and the one main CHDK svn repo.

Take a look at that repo. If you find that the code I committed there should go into ptp-remote-capture-test, then I'll update that repo too. I started this because you mentioned
Quote
Regarding remote capture, I was thinking about putting the init stuff in lua, but I don't want to duplicate effort.
and I didn't want to clash with that. Moreover, my code still sucks (not optimal, needs cleanup).
BTW, I used a (full, unnecessarily) dump of the main CHDK repo (rev. 2133) for mine (I'm practicing with svn).

How should I continue with work?
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / September / 2012, 23:12:32
By looking at some dumps, there is an active viewport buffer (still talking about review mode right after shooting), vid_get_viewport_fb_d() points to it. In another dump, which was created after shooting AND pressing SET (recreview hold), vid_get_viewport_fb_d() still seems to be valid.
OK, so we could check recreview in vid_get_viewport_active_buffer. I'll try that and report back.

Quote
Take a look at that repo. If you find that the code I committed there should go into ptp-remote-capture-test, then I'll update that repo too. I started this because you mentioned
Quote
Regarding remote capture, I was thinking about putting the init stuff in lua, but I don't want to duplicate effort.
and I didn't want to clash with that. Moreover, my code still sucks (not optimal, needs cleanup).
BTW, I used a (full, unnecessarily) dump of the main CHDK repo (rev. 2133) for mine (I'm practicing with svn).
Yes, I that confused me a bit. A branch in the same repo makes it easier to compare and move changes around, and doesn't really cost any space.

I got the re-work I started last weekend working (on a540 at least), in the attached patch. There's still some loose ends but I think it's going in the right direction. If it looks OK to you, I'll put it in the ptp-remote-capture-test branch. If you think your branch is a better starting point, I can live with that too.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / September / 2012, 03:21:11
Updated patch.
- initial lua based init implementation. Untested, need to set up the client stuff.
- much simplified ptp.c code. Error returns may change slightly, but current rs command seems to work
- now compiles if camera doesn't have filewritetask
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / September / 2012, 03:51:53
By looking at some dumps, there is an active viewport buffer (still talking about review mode right after shooting), vid_get_viewport_fb_d() points to it. In another dump, which was created after shooting AND pressing SET (recreview hold), vid_get_viewport_fb_d() still seems to be valid.
OK, so we could check recreview in vid_get_viewport_active_buffer. I'll try that and report back.
on d10, after switching the recreview_hold variable to the sig finder value, this seems to work. However, it only works in *hold* mode, you'd need some other variable to detect a fixed review time like 10 sec.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / September / 2012, 11:48:32
Updated patch.
- initial lua based init implementation. Untested, need to set up the client stuff.
- much simplified ptp.c code. Error returns may change slightly, but current rs command seems to work
- now compiles if camera doesn't have filewritetask
First (quick) impression: it works, the code looks much better organized now. I copied over YUV support from my version, also works, but it may have to be modified (it will produce 0 byte long files with cameras without explicit yuv support OR when L picture size is selected). I think you can commit this.
edit: there's still some cleanup to do (removed functions' declarations)
...
However, it only works in *hold* mode, you'd need some other variable to detect a fixed review time like 10 sec.
True. I haven't checked that yet.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / September / 2012, 16:31:54
First (quick) impression: it works, the code looks much better organized now. I copied over YUV support from my version, also works, but it may have to be modified (it will produce 0 byte long files with cameras without explicit yuv support OR when L picture size is selected). I think you can commit this.
Committed in changeset 2135. Please feel free to work in this branch.
Quote
edit: there's still some cleanup to do (removed functions' declarations)
Yes, there's still quite a bit to be done.

One thing that i'm not sure about is the
Code: [Select]
state_shooting_progress=SHOOTING_PROGRESS_DONE; //shoot() needs this...
In remotecap_get_data_chunk... since this can be called when remotecap is reset (on error or init(0)) it would happen at random times in the shooting process. Same for hook_raw_save_complete. I'm not clear exactly what the implications would be, but it seems like there could be problems.

init in Lua, also introduces some more potential synchronization issues, in theory a PTP_CHDK_RemoteCaptureGetData could be running at the same time a script decides to cancel remote capture. I guess the timeout could have the same problem too.

A few other thoughts:
- should the remote capture selection only apply to the next shot, like exposure overrides, or should you need to explicitly cancel it ? If it's left on after the PTP connection goes away, that could confuse users. We don't explicitly know whether there is a PTP connection, but I guess we could check USB power is present (and clear remotecap if it's not found ?).
Setting it once per shot shouldn't be much of a burden if you are using script to shoot, but I guess you could potentially set it once and have the user manually shooting with the shutter ?
Clearing it on script termination (like key presses and script overrides) is probably not good, because you could trigger the shot and have the script end before the data is retrieved (if you use button presses at least, shoot() may wait until everything is done). Users who do want it cleared on script exit could do so in restore().
- should we actually prohibit calling init in playback mode ? Since it just sets up some flags, this doesn't actually cause any harm. You can initialize it and switch to playback mode, so it's still possible to have remotecap enabled in play.
- hook_raw_save_complete() is only called after all the chunks are downloaded, meaning the the raw hook will be blocked until the jpeg is complete. This seems like it might have unwanted impacts, perhaps depending on where the raw hook is on a specific camera.
- The current raw remote capture implementation bypasses raw_savefile() completely, but this function also does some other stuff beyond raw saving, like handling bracketing in continuous mode and shot_histogram. It might be better to remove the remote_capture stuff to raw save_file. This would mean you'd block spytask, which in turn would block capt_seq thought
- The current implementation of remotecap_get_data_chunk requires an extra ptp transaction for each file type, because you only find out you are done by requesting another chunk and getting an empty response. This probably doesn't matter much, but if we can cleanly flag "this is the last chunk" it will save a little time. The status returned by this function could also possibly be made clearer.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / September / 2012, 16:46:29
Quite long post to answer, I'll update this post unless you reply.

One thing that i'm not sure about is the
Code: [Select]
state_shooting_progress=SHOOTING_PROGRESS_DONE; //shoot() needs this...
In remotecap_get_data_chunk... since this can be called when remotecap is reset (on error or init(0)) it would happen at random times in the shooting process. Same for hook_raw_save_complete. I'm not clear exactly what the implications would be, but it seems like there could be problems.
The reason for this was that when I first tried my monolithic rs command, I kept getting "script is already running" afterwards. If I remember correctly, this was needed for shoot() to finish (?). I'm going to take a look at this again. Maybe it's not needed anymore or is misplaced.
...
Quote
- hook_raw_save_complete() is only called after all the chunks are downloaded, meaning the the raw hook will be blocked until the jpeg is complete. This seems like it might have unwanted impacts, perhaps depending on where the raw hook is on a specific camera.
I assumed the two hooks to never overlap. If they do, the port is IMHO broken (imagine what would happen if FileWriteTask's open stage found an open file). That was the reason I used the same variable and status codes for the two hooks.
...
Quote
- The current implementation of remotecap_get_data_chunk requires an extra ptp transaction for each file type, because you only find out you are done by requesting another chunk and getting an empty response. This probably doesn't matter much, but if we can cleanly flag "this is the last chunk" it will save a little time. The status returned by this function could also possibly be made clearer.
Yes, the condition check could be shifted into remotecap_get_data_chunk() - it could return a value for example.
...
Quote
- should we actually prohibit calling init in playback mode ? Since it just sets up some flags, this doesn't actually cause any harm. You can initialize it and switch to playback mode, so it's still possible to have remotecap enabled in play.
This again was necessary for my version of rs, with the integrated shoot().
...
Quote
- The current raw remote capture implementation bypasses raw_savefile() completely, but this function also does some other stuff beyond raw saving, like handling bracketing in continuous mode and shot_histogram. It might be better to remove the remote_capture stuff to raw save_file. This would mean you'd block spytask, which in turn would block capt_seq thought
The reason of the bypass was exactly what you say, it would be complicated to do otherwise.
I've never tested how FileWriteTask acts in continuous mode...
...
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / September / 2012, 17:43:43
Quote
- hook_raw_save_complete() is only called after all the chunks are downloaded, meaning the the raw hook will be blocked until the jpeg is complete. This seems like it might have unwanted impacts, perhaps depending on where the raw hook is on a specific camera.
I assumed the two hooks to never overlap. If they do, the port is IMHO broken (imagine what would happen if FileWriteTask's open stage found an open file). That was the reason I used the same variable and status codes for the two hooks.
OK, the current issue is probably a problem in my understanding of the old code and change then. filewrite now doesn't use the raw status variable at all (more clear, I think), so hook_raw_save_complete can probably be called when the last raw chunk is collected. I'm actually surprised it works the way I have it.

edit:
More misunderstanding on my part, I was thinking all the chunks could be read before the end case, but of course raw has to be finished before jpeg starts. hook_raw_save_complete will get called redundantly for non-raw chunks, but as you said, raw hook should not be running when jpeg or yuv chunks are being handled. Still need to look at state_shooting_progresss

edit:
You had a comment
Quote
hook_raw_size() is sometimes different than CAM_RAW_ROWS*CAM_RAW_ROWPIX*CAM_SENSOR_BITS_PER_PIXEL/8
Do you know which cameras have this ? It seems like it should not ever be true. DNG will probably be corrupt if this happens (more / less data than given in exif...)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / September / 2012, 11:10:15
Quote
hook_raw_size() is sometimes different than CAM_RAW_ROWS*CAM_RAW_ROWPIX*CAM_SENSOR_BITS_PER_PIXEL/8
Do you know which cameras have this ? It seems like it should not ever be true. DNG will probably be corrupt if this happens (more / less data than given in exif...)
A470, the difference is 6 lines. I haven't tested RAW shooting on it too much  ;)

Quote
raw has to be finished before jpeg starts
Now that I think of it... What happens in continuous mode? There has to be some caching somewhere. Could it be a filesystem cache (meaning Open(), Write(), Close() finish before the data actually ends up on the card)?
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / September / 2012, 12:37:02
A470, the difference is 6 lines. I haven't tested RAW shooting on it too much  ;)
OK, this should be investigated. It may be that someone thought it was a good idea to discard the blank lines at the bottom of the sensor, but the values should be consistent.

Quote
Now that I think of it... What happens in continuous mode? There has to be some caching somewhere. Could it be a filesystem cache (meaning Open(), Write(), Close() finish before the data actually ends up on the card)?
When we write raw in continuous mode, I'm pretty certain it blocks until the write is finished, and very little if any caching is done with write().
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / September / 2012, 15:03:52
Quote
Now that I think of it... What happens in continuous mode? There has to be some caching somewhere. Could it be a filesystem cache (meaning Open(), Write(), Close() finish before the data actually ends up on the card)?
When we write raw in continuous mode, I'm pretty certain it blocks until the write is finished, and very little if any caching is done with write().
:-[ Canon DSLRs do this sort of thing (and maybe compacts of some other manufacturers). My mistake. Haven't found any PowerShot with this feature (caching).

I have committed some YUV related code to the test branch. It will have to be improved:
- Either a new #define in camera.h will be needed for this ability, or the client has to handle the case where YUV data has 0 length.
- As discussed earlier, YUV data is not always available. Picture sizes with one pass JPEG creation include "L" and "W" (every picture size with full width).
- The review time should last longer than the time required for transfer.

A question:
Shouldn't these
Code: [Select]
void filewrite_set_discard_jpeg(int state);
void filewrite_get_jpeg_chunk(char **ardr,unsigned *size, unsigned n);
declarations in core/remotecap.c be extern?

A470:
the values found by sigfinder are good.

About SHOOTING_PROGRESS_DONE:
core/action_stack.c
one of the last actions of AS_SHOOT is AS_WAIT_SAVE
AS_WAIT_SAVE will not finish until (state_shooting_progress == SHOOTING_PROGRESS_DONE)
state_shooting_progress normally gets this value in core/main.c, which is not happening when remote shooting is active.

It's true that
Code: [Select]
state_shooting_progress=SHOOTING_PROGRESS_DONE;in remotecap_get_data_chunk() is in an unfortunate place though...
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / September / 2012, 21:58:25
A question:
Shouldn't these
Code: [Select]
void filewrite_set_discard_jpeg(int state);
void filewrite_get_jpeg_chunk(char **ardr,unsigned *size, unsigned n);
declarations in core/remotecap.c be extern?
For functions, it doesn't make any difference, but I guess we mostly use extern elsewhere (including in the headers), so it would be more consistent.

Quote
state_shooting_progress normally gets this value in core/main.c, which is not happening when remote shooting is active.

It's true that
Code: [Select]
state_shooting_progress=SHOOTING_PROGRESS_DONE;in remotecap_get_data_chunk() is in an unfortunate place though...
That makes sense, and I agree that it's not ideal at the moment. Especially in the case where it could get set at an arbitrary time to clear hooks.

It may be wroth tracking what stage we are in  (waiting for raw to be read, waiting for jpeg/yuv) and only having the appropriate once canceled. Something like state_remotecap_stage = IDLE | RAW | FILEWRITE
Title: Re: CHDK PTP interface
Post by: srsa_4c on 12 / September / 2012, 15:02:11
Still experimenting with state_shooting_progress. Also inspected core/main.c again. Unlike what I wrote above, some shooting related conditional parts of spytask are effective even in remote target mode. Many - raw related - parts of CHDK set state_shooting_progress to SHOOTING_PROGRESS_PROCESSING. Doing this in remotecap.c (or at the start of the raw hook in generic/capt_seq.c) works, with one drawback: shoot() won't finish until review time is over (issue observed on the A410, and is probably unrelated to these experiments). The block is caused by PROPCASE_SHOOTING, see shooting_in_progress(). This doesn't prevent another rs from executing, but other scripts will not run until PROPCASE_SHOOTING becomes 0 again.

#1
Code: (diff) [Select]
Index: core/remotecap.c
===================================================================
--- core/remotecap.c   (revision 2141)
+++ core/remotecap.c   (working copy)
@@ -212,7 +212,7 @@
         // allow raw hook to continue
         // TODO could do like filewrite wait
         hook_raw_save_complete();
-        state_shooting_progress=SHOOTING_PROGRESS_DONE; //shoot() needs this... TODO
+        state_shooting_progress=SHOOTING_PROGRESS_PROCESSING;
     }
 }
or
#2
Code: (diff) [Select]
Index: platform/generic/capt_seq.c
===================================================================
--- platform/generic/capt_seq.c   (revision 2141)
+++ platform/generic/capt_seq.c   (working copy)
@@ -50,10 +50,12 @@
     }
     else if ( (remotecap_get_target() & 2) > 0 ) //chdk raw requested
     {
+        state_shooting_progress=SHOOTING_PROGRESS_PROCESSING;
         remotecap_raw_available();
     }
     else
     {
+        state_shooting_progress=SHOOTING_PROGRESS_PROCESSING;
         raw_save_stage = RAWDATA_SAVED;
     }
 #else

- should the remote capture selection only apply to the next shot, like exposure overrides, or should you need to explicitly cancel it ?
My initial code used the latter (rs sets it up at start and resets it when it has finished). Probably both approach should deal with the possibility of PTP connection problems.
Quote
If it's left on after the PTP connection goes away, that could confuse users. We don't explicitly know whether there is a PTP connection, but I guess we could check USB power is present (and clear remotecap if it's not found ?).
Could be good enough, until somebody decides to allow usb remote and ptp at the same time if that's possible at all (physw bit override or eventprocs like ConnectUSBCable, etc.)
Quote
Setting it once per shot shouldn't be much of a burden if you are using script to shoot, but I guess you could potentially set it once and have the user manually shooting with the shutter ?
Maybe. There are also some G series cams with proper remote control socket.

Committed my changes (changeset 2144), chose #1 from above.
The client (the code I know) was already prepared, so it will continue to work. RemoteCaptureGetData's Param2 returned parameter has slightly changed in its interpretation: it no longer shows the transferred chunk's type. I chose to increment PTP_CHDK_VERSION_MINOR to 104 (the hundreds shall reflect test revisions :) )

Tried and failed miserably to split the code part marked with //TODO turn this into a function in core/remotecap.c, remotecap_get_data_chunk(). With that code in a separate function (6 params), called by the raw and yuv cases, the asm code size almost doubled. Leaving it as it is, it's ugly but saves space...
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / September / 2012, 19:26:50
In chdkptp r301, I've started making a lua-based remoteshoot command. It's pretty messy at the moment, but it seems to work. This uses remotecap_init() on the camera to set up.

I understand the "script is already running" problem a bit a better now, of course the 'shoot()' command doesn't finish until the remote capture is done, so you can't cancel with script. The jpeg timeout works at least ;) In the new command, I get around this by using button presses instead of shoot, so the script can end as soon as shoot_full has been clicked.

Eventually, the rs2 command should be rolled into options for the regular shoot command, and the supporting code should be moved into re-usable functions in one of the lua modules.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / September / 2012, 16:36:27
In chdkptp r301, I've started making a lua-based remoteshoot command. It's pretty messy at the moment, but it seems to work. This uses remotecap_init() on the camera to set up.
Will try it soon.
Quote
I understand the "script is already running" problem a bit a better now, of course the 'shoot()' command doesn't finish until the remote capture is done, so you can't cancel with script. The jpeg timeout works at least ;) In the new command, I get around this by using button presses instead of shoot, so the script can end as soon as shoot_full has been clicked.
If this approach is the way to go, can we get rid of setting state_shooting_progress?

I plan to commit a few changes soon (raw hook, consistent file number request), if testing confirms that they work.

There may be a new issue: right now it's assumed that there is only one filewritetask activity after shooting. Cameras with Canon RAW are usually capable of storing a separate jpeg beside the native RAW (when the camera is set up to do so). In that case, only the first Canon file (my guess: RAW) will be retrieved and/or prevented from being written. Should we ignore this or support it? I don't have access to such camera, so can't try myself.

Changes committed (changeset 2163). rs2 works well if it encounters no problems.
I'm considering returning some useful data for debug use (chunk's memory address, could provide useful info about the jpeg or native raw buffers).
Title: Re: CHDK PTP interface
Post by: FREE Spirit on 24 / September / 2012, 12:23:02
Hi
I have sx40hs and I installed the latest CHDK version: sx40hs-100i-1.2.0-2171-full_BETA
I tried both (ptpCamGui2.0.131) and (chdkptp-r291-win32)
in CHDK PTP, everything seems to be fine, even live view. But unfortunately, there are 2 problems:

1) when I press "shoot" to capture a picture, the shot is taken but the camera freezes and the viewfinder on PC becomes white noise (pic attached). The only thing can be done is to shut the camera off manually.
Same thing occurs in PTP Cam, except of course, there's no viewfinder.

2) I can't view files under the files tab. I tried copying the contents and got the following error message:
Code: [Select]
...hy\CHDK\LiveCapture\chdkptp-r291-win32\lua\chdku.lua:162: attempt to index local 'opts' (a nil value)
stack traceback:
...hy\CHDK\LiveCapture\chdkptp-r291-win32\lua\chdku.lua:162: in function 'mdownload'
...CHDK\LiveCapture\chdkptp-r291-win32\lua\gui_tree.lua:110: in function 'do_dir_download_dialog'
...CHDK\LiveCapture\chdkptp-r291-win32\lua\gui_tree.lua:273: in function <...CHDK\LiveCapture\chdkptp-r291-win32\lua\gui_tree.lua:272>
(tail call): ?
[C]: in function 'Popup'
menu.lua:15: in function 'popup'
...CHDK\LiveCapture\chdkptp-r291-win32\lua\gui_tree.lua:288: in function <...CHDK\LiveCapture\chdkptp-r291-win32\lua\gui_tree.lua:241>
(tail call): ?
[C]: in function 'MainLoop'
...aphy\CHDK\LiveCapture\chdkptp-r291-win32\lua\gui.lua:673: in function <...aphy\CHDK\LiveCapture\chdkptp-r291-win32\lua\gui.lua:659>
(tail call): ?
...phy\CHDK\LiveCapture\chdkptp-r291-win32\lua\main.lua:226: in main chunk
[C]: in function 'require'
[string "require('main')"]:1: in main chunk
However, on PTP Cam, I can copy the files


any solution?
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / September / 2012, 16:36:05
1) when I press "shoot" to capture a picture, the shot is taken but the camera freezes and the viewfinder on PC becomes white noise (pic attached). The only thing can be done is to shut the camera off manually.
Same thing occurs in PTP Cam, except of course, there's no viewfinder.
Do you have review mode set to "hold" on the camera ? Or a long time ?
Quote
2) I can't view files under the files tab. I tried copying the contents and got the following error message:
Code: [Select]
...hy\CHDK\LiveCapture\chdkptp-r291-win32\lua\chdku.lua:162: attempt to index local 'opts' (a nil value)
stack traceback:
This bug is fixed in the latest chdkptp svn. If you replace lua/chdku.lua with the one found here http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293 (http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293) it should be fixed.

I haven't put up another snapshot because I'm in the middle of some messy changes for remotecapture...
Title: Re: CHDK PTP interface
Post by: FREE Spirit on 25 / September / 2012, 09:38:14
Thanx for the reply
yes I had my review mode set to "hold", disabling this got things working :)

Quote
This bug is fixed in the latest chdkptp svn. If you replace lua/chdku.lua with the one found here http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293 (http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293) it should be fixed
I replaced the file, but it didn't solve the problem. Now I get this error message:
"error: A/ں뫧ں§~1.PPT: error"
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / September / 2012, 16:12:11
Thanx for the reply
yes I had my review mode set to "hold", disabling this got things working :)

Quote
This bug is fixed in the latest chdkptp svn. If you replace lua/chdku.lua with the one found here http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293 (http://trac.assembla.com/chdkptp/browser/trunk/lua/chdku.lua?rev=293) it should be fixed
I replaced the file, but it didn't solve the problem. Now I get this error message:
"error: A/ں뫧ں§~1.PPT: error"
That is very strange. Are you using non-latin character set on the camera or PC ?

If you enter
ls -l
in the console, what does it do ?
Title: Re: CHDK PTP interface
Post by: FREE Spirit on 28 / September / 2012, 14:32:32
sorry for the delay
I have non-latin character on my laptop *only* as typing language.
Both my camera and my laptop's OS (Windows 7 x64 Home Premium) have English UI

I tried entering
ls -l
in the console. Nothing happened
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / September / 2012, 14:39:08
I tried entering
ls -l
in the console. Nothing happened
You need to enter that line in the text box beside the Execute button, and of course hit enter afterwards (or click Execute).

Quote
Now I get this error message:
"error: A/ں뫧ں§~1.PPT: error"
Are you sure you don't have a PowerPoint file on that card (copied there with a card reader)?
Title: Re: CHDK PTP interface
Post by: FREE Spirit on 28 / September / 2012, 14:43:48
yea that's what I did... nothing happened
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / September / 2012, 14:55:14
My experience with a different camera
http://chdk.setepontos.com/index.php?topic=8600.msg90086#msg90086 (http://chdk.setepontos.com/index.php?topic=8600.msg90086#msg90086)
The camera was not prepared to correctly handle a long filename.
What happens if you execute this:
Code: [Select]
=return os.listdir('A/')?
In your case the problem might be caused by a filename with non-latin characters.
Title: Re: CHDK PTP interface
Post by: FREE Spirit on 28 / September / 2012, 15:05:20
I entered the code
=return os.listdir('A/')
and it displayed the list of files on the card root... and indeed there were2 files with non-latin names which I forgot about... and even if I remembered them I wouldn't have thought they can cause total failure of the whole thing

Thanx for taking the time to solve the problem :)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 05 / October / 2012, 12:42:52
As a result of the recent filewritetask investigation on the S90 (http://chdk.setepontos.com/index.php?topic=8613.msg91579#msg91579) (thx to SticK) and A810 (http://chdk.setepontos.com/index.php?topic=8450.msg91609#msg91609) (thx to nafraf), it looks like many of my previous assumptions were wrong.
It looks like that
- filewritetask only writes jpeg files (!), native raw is written elsewhere
- earlier cameras (including the S90) usually write the files in two chunks, first one is the exif part, second one is the main jpeg. On the A810 this is different, the whole file appears in one or two chunks, the exif is presumably embedded in the first chunk.
- another oddity on the A810: the chunks of the jpeg seem to come from non-contiguous buffers
edit:
... and of course there's no such thing as multiple filewritetask invocations for a single file, according to the collected data.
edit, A810: Now it looks like that Canon has started doing some parallel processing. Sometimes, the jpeg file is starting to get written when only a part of the (L sized) compressed image is present. When an additional part of the image becomes available, it gets appended to the partial file on card!
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / October / 2012, 23:06:21
@reyalp

Changeset 2203:
My (uncommitted) version was like this:
Code: [Select]
int register_pt_hooks() {
#if (!CAM_DRYOS) || defined(CAMERA_s5is)
    /*
     * System.Create -> SystemEventInit
     * SS.Create -> ?
     * PT_CompleteFileWrite -> no equivalent?
     */
    return -1;
#else
    if(_ExecuteEventProcedure("System.Create") == -1) {
        return 1;
    }
    if(_ExecuteEventProcedure("SS.Create") == -1) {
        return 2;
    }
    if(_ExecuteEventProcedure("ExportToEventProcedure","PT_CompleteFileWrite",overridden_PT_CompleteFileWrite) == -1) {
        return 3;
    }
    //_LogPrintf(0x120,"pt hook(s) registered");
    return 0;
#endif
}
All DryOS >= r23 cameras seem to have System.Create, SS.Create, PT_CompleteFileWrite. This is based on searching through a few dozen firmware files I have on my HDD.

Which (kind of) functions are not supposed to be called from thumb?
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / October / 2012, 23:26:43
All DryOS >= r23 cameras seem to have System.Create, SS.Create, PT_CompleteFileWrite. This is based on searching through a few dozen firmware files I have on my HDD.
Calling the eventprocs in the sequence I used and checking for -1 should be OK, the romlog code does the same thing.

Edit:
Oops, I didn't realize (or forgot, since I listed them before) until now that the older cams didn't have PT_CompleteFileWrite. That explains why this code didn't work right on a540 ;)

So in this case, we don't need to fall back to the older registration functions, unless we decide to use other eventproc "hooks".
Quote
Which (kind of) functions are not supposed to be called from thumb?
The firmware code doesn't always return with a BX LR, so it might return to your thumb code without switching back to thumb mode. This is most common on vxworks cameras, but happens in some cases newer cameras do it too. So generally you shouldn't call a firmware function directly without a wrapper.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / October / 2012, 00:00:26
So in this case, we don't need to fall back to the older registration functions, unless we decide to use other eventproc "hooks".
I haven't found anything obvious. Close() could be wrapped in filewritetask, but that obviously needs that task hook implemented.
Quote
The firmware code doesn't always return with a BX LR, so it might return to your thumb code without switching back to thumb mode. This is most common on vxworks cameras, but happens in some cases newer cameras do it too. So generally you shouldn't call a firmware function directly without a wrapper.
I see, just looked at a main.dump.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / October / 2012, 00:14:22
So in this case, we don't need to fall back to the older registration functions, unless we decide to use other eventproc "hooks".
I haven't found anything obvious. Close() could be wrapped in filewritetask, but that obviously needs that task hook implemented.
I actually meant for other purposes, not detecting file write complete. I agree, none of the others look like good candidates for that.

Edit:
Note we should be able to detect if the camera has PT_CompleteFileWrite. The original firmware version (on D10 at least) returns 0. If we call it before registering our own, -1 will indicate the firmware doesn't support, while 0 will indicate it does.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / October / 2012, 22:47:00
Note we should be able to detect if the camera has PT_CompleteFileWrite. The original firmware version (on D10 at least) returns 0. If we call it before registering our own, -1 will indicate the firmware doesn't support, while 0 will indicate it does.
I implemented this in changeset 2212.

One other "hook" that might be worth looking into is PT_CompleteSynchroWrite, although in a540, I don't see where that would be called.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 14 / October / 2012, 17:54:31
Small status update.
Cameras with DryOS >= r50 have a more complicated filewritetask. Depending on the recording mode and image resolution, the camera can start to write the file before the whole jpeg appears in memory. This means that a protocol change and a change of the hooking method will be needed to successfully retrieve those files.

@reyalp
On the A470, the event procedure registration consumes 5352 bytes according to core_get_free_memory() - tested with the first version of register_pt_hooks().

You may have already noticed, there's a typo in changeset 2212.
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / October / 2012, 18:59:45
On the A470, the event procedure registration consumes 5352 bytes according to core_get_free_memory() - tested with the first version of register_pt_hooks().
That's not too bad, but if we end up using this, it the final version should probably only register the first time it's needed, rather than in startup. I wouldn't worry about this for now.

Quote
You may have already noticed, there's a typo in changeset 2212.
Thanks for pointing that out. I didn't notice since a540 doesn't have PT_CompleteFileWrite, and I haven't implemented filewrite task in D10 yet.
Title: Re: CHDK PTP interface
Post by: RAD-X on 19 / October / 2012, 20:43:17
@reyalp and srsa_4c.
Thanks guys for very nice work on chdkptp and remote shoot feature.

In my project cam take pictures every minute 24/7 which is more than a half milion shots in one year. I think that so much shots is big stress for camera HW and even bigger for flash card even if is used card with SLC and ECC card erorr correcting.
For now I using old cams with gphoto2 - here is function/parameter --capture-image-and-download thats allow shoot photo to buffer then download directly using PTP.
But now I want to use newer Canon cam (old one has been damaged - sensor KO) and new Digic don't have feature for PTP capture - ofcourse if isn't used CHDK.  :)

Now I have IXUS 870IS (FW 1.01a) and I want to test your new feature.
I have compiled chdkptp r311 and downloaded branch ptp-remote-capture-test2216

I am CHDK beginner so can somebody please update needed sources for my cam? FW dump is at https://www.box.com/s/tscho3m30j/9/55272271/536293935/1 (https://www.box.com/s/tscho3m30j/9/55272271/536293935/1)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 20 / October / 2012, 01:08:48
I am CHDK beginner so can somebody please update needed sources for my cam?
Please be a bit patient. I also have this camera and, out of curiosity, created the necessary modifications for it. However, remote shooting appears to eat up its memory for some reason (unlike on other cameras), and causes it to crash after a few shots. As I'm curious whether it's my fw version (1.00e) that makes problems, I'll make the necessary mods for your fw too - soon.
If you're unlucky, the cam will be as unstable as mine.
Check back in a day or so.

Support code added (check svn).
Keep in mind that
- this whole thing is subject to change (client commands, protocol)
- due to some unknown factors on this camera, do not repeat the rs command too fast (2-3 seconds should work), or the camera will crash
- you'll need the ptp.h header from ptp-remote-capture-test for chdkptp, or else the necessary commands will not appear
- to reduce camera wear, you may need to do some additional scripting (like activating focus lock, setting desired operating mode, ...)
Title: Re: CHDK PTP interface
Post by: reyalp on 20 / October / 2012, 15:44:45
As I'm curious whether it's my fw version (1.00e) that makes problems
I think it's very unlikely that the Canon firmware version would make a difference.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 20 / October / 2012, 16:18:18
As I'm curious whether it's my fw version (1.00e) that makes problems
I think it's very unlikely that the Canon firmware version would make a difference.
True, it was a silly idea. Incidentally, the 1.00e fw revision for this camera has a bad bug that made Canon issue a firmware upgrade (to 1.01a).

After some testing I found that I had to increase the delay between rs calls. It works normally with a delay of ~2-3 seconds. There may be a camera setting that causes this.

The event procedure registration costs 0 bytes of RAM on this cam, according to calls to core_get_free_memory().
Title: Re: CHDK PTP interface
Post by: philmoz on 20 / October / 2012, 16:50:19
The event procedure registration costs 0 bytes of RAM on this cam, according to calls to core_get_free_memory().

Keep in mind that core_get_free_memory returns the size of the largest free block currently in the heap, not the total amount of free memory available.

If the event registration required a small amount of memory and there was a small free block on the heap available you would not see any change in the return value from core_get_free_memory.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 20 / October / 2012, 17:36:38
Keep in mind that core_get_free_memory returns the size of the largest free block currently in the heap, not the total amount of free memory available.

If the event registration required a small amount of memory and there was a small free block on the heap available you would not see any change in the return value from core_get_free_memory.
Re-did the test with core_get_free_memory() adjusted to return camera_meminfo.free_size.

Ixus870:  5944 bytes
A470:     6256 bytes

The values vary depending on the starting mode (rec/play, ptp, tv-out), other parallel tasks also allocate/free memory...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 22 / October / 2012, 00:40:28
Cameras with DryOS >= r50 have a more complicated filewritetask. This means that a protocol change and a change of the hooking method will be needed to successfully retrieve those files.
In changeset 2226 (https://trac.assembla.com/chdk/changeset/2226/) I have checked in support code for this. It hasn't been tested on a DryOS r50 camera yet, so it may contain some errors.
Remote capture protocol:
I had to add (back) param3 as "position" value in PTP_CHDK_RemoteCaptureGetData. R50 and newer cameras will need it.

Some background info about the behaviour of new cameras:
The jpeg data is either completely present in memory when filewritetask is notified (similarly as in older cameras), or appears like this:
- first filewritetask invocation: file is opened, seek is performed to skip over the (future) exif data, first chunk of jpeg written, file left open
- second, third invocation: additional chunks (one per invocation) are written sequentially, file left open
- last invocation: seek to position 0, exif written, file closed
According to my observations, exif is placed into the same buffer as the second jpeg chunk. There is some delay between the availability of the big jpeg chunks, my code tries to wait when needed.

I have created a new #define in camera.h, with the name CAM_EXTENDED_FILEWRITETASK. As indicated by my comment, this could be substituted by a (not yet created) CAM_DRYOS_2_3_R50 define.

I'm considering to change the filewrite hook function to only require the pointer to the start of the task's data block as argument, and use #define'd offsets to the values of interest.

edit:
The r50 code is not working as expected, needs to be fixed. However, the camera-specific part is OK.
edit2:
After analyzing the code (and the debug data provided by nafraf) I concluded that there must be some multitasking issue between the ptp and filewrite tasks. If that's the case, changeset 2243 (https://trac.assembla.com/chdk/changeset/2243/) should fix it.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 02 / November / 2012, 20:35:08
After analyzing the code (and the debug data provided by nafraf) I concluded that there must be some multitasking issue between the ptp and filewrite tasks. If that's the case, changeset 2243 (https://trac.assembla.com/chdk/changeset/2243/) should fix it.
The change has now been tested, and it appears to work correctly. Many thanks to nafraf for helping me to make this happen!
The final step towards supporting DryOS r50+ cameras (A810 only at the moment) will be the implementation of seek when writing the file - in chdkptp.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / November / 2012, 21:50:13
Temporary patch for chdkptp to handle seek while remote shooting (also prints some debug info).
update: The patched chdkptp is confirmed to work with a DryOS r50 client (A810).

@reyalp
Somehow ptp.Nparam doesn't get updated after ptp_transaction().
Title: Re: CHDK PTP interface
Post by: ntstatic on 05 / November / 2012, 06:52:48
hello phil,

i am still using your CHDKPTPRemote (posted by you around page  38 - around a year back) along with  Mweerden's liveview patch.

as liveview is already included in the trunk and as it has been implemented as a top level patch, i have been unable to make the old code (c# solution) work with the new live view. if you still using the code and if  it is not to much effort can you upload a new version.

thanks
Title: Re: CHDK PTP interface
Post by: philmoz on 05 / November / 2012, 07:26:19
hello phil,

i am still using your CHDKPTPRemote (posted by you around page  38 - around a year back) along with  Mweerden's liveview patch.

as liveview is already included in the trunk and as it has been implemented as a top level patch, i have been unable to make the old code (c# solution) work with the new live view. if you still using the code and if  it is not to much effort can you upload a new version.

thanks

The live view code was revamped by reyalp to sort out issues and make it a lot more useable.

I didn't update my code because reyalp also created a really good client.
You can get it at https://www.assembla.com/spaces/chdkptp/documents. (https://www.assembla.com/spaces/chdkptp/documents.)

Phil.
Title: Re: CHDK PTP interface
Post by: ntstatic on 05 / November / 2012, 08:16:22
thanks,
but  link gives me a 404, (can you pls check that the link is ok !)
is it a .net client or a c/c++ (dot net would be better for me)
Title: Re: CHDK PTP interface
Post by: Microfunguy on 05 / November / 2012, 09:23:16
thanks,
but  link gives me a 404


Try this https://www.assembla.com/spaces/chdkptp/documents (https://www.assembla.com/spaces/chdkptp/documents)
Title: Re: CHDK PTP interface
Post by: Taka on 06 / November / 2012, 11:10:27
Hello! 

Sorry, I'd like to know how to use the CHDK PTP interface available in https://www.assembla.com/spaces/chdkptp/documents (https://www.assembla.com/spaces/chdkptp/documents) with my Canon PowerShot SX130 IS. I need to use the remote capture feature, but I don't know which procedure to follow. I tried to follow the old posts in this forum, but I really understand very little programming... I'm understanding nothing  :'( Can anyone help me with this, please?

Thankfully :)
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / November / 2012, 16:57:49
Sorry, I'd like to know how to use the CHDK PTP interface available in https://www.assembla.com/spaces/chdkptp/documents (https://www.assembla.com/spaces/chdkptp/documents) with my Canon PowerShot SX130 IS. I need to use the remote capture feature, but I don't know which procedure to follow.
Thankfully :)
You don't need do any programming. Assuming you are using windows:
- Install a recent  (1.1 or later) version of CHDK on the camera
- Install the libusb inf driver for your camera
- Download and unzip the latest chdkptp binary the link you quoted.
- Plug in the camera and run the chdkptp executable.
Title: Re: CHDK PTP interface
Post by: Taka on 07 / November / 2012, 08:04:39
Thank you  reyalp!

I have tried to do this but when I click on the button "Connect" in the interface, the message "error: no devices available" appears.

I think that I'm doing something wrong, but I don't know what.  :(

Thanks again  :)
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / November / 2012, 23:41:38
I have tried to do this but when I click on the button "Connect" in the interface, the message "error: no devices available" appears.
Perhaps you haven't successfully installed the libusb driver.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / November / 2012, 22:21:34
I need some advice. I'm trying to make DNG available as RAW format for ptp remote capture. Doing this requires the use of the DNG module. However, existing exported functions are not appropriate for this use, so I needed to create some new ones.
What would be the better solution?
- Extend the DNG module with the new functions.
- Create a new module using the source of the DNG module (with #ifdefs, etc.). The problem is that the DNG module is treated special by other code (modules.c for example), so doing this seems a bit hard.
Title: Re: CHDK PTP interface
Post by: philmoz on 10 / November / 2012, 22:41:29
I need some advice. I'm trying to make DNG available as RAW format for ptp remote capture. Doing this requires the use of the DNG module. However, existing exported functions are not appropriate for this use, so I needed to create some new ones.
What would be the better solution?
- Extend the DNG module with the new functions.
- Create a new module using the source of the DNG module (with #ifdefs, etc.). The problem is that the DNG module is treated special by other code (modules.c for example), so doing this seems a bit hard.

If you mean you want to call functions in the DNG module from the core CHDK code then just add them to the end of the  'struct libdng_sym' structure.

Remember to update both the definition in dng.h and the instance in dng.c.

If you also update the version in the libdng variable in dng.c you can check the version in your code before calling any of the functions to make sure the new module version is loaded.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / November / 2012, 22:46:57
If you mean you want to call functions in the DNG module from the core CHDK code then just add them to the end of the  'struct libdng_sym' structure.

Remember to update both the definition in dng.h and the instance in dng.c.

If you also update the version in the libdng variable in dng.c you can check the version in your code before calling any of the functions to make sure the new module version is loaded.
Thanks, I'll do it like this then.
Title: Re: CHDK PTP interface
Post by: Taka on 13 / November / 2012, 08:31:16
Hi! I'm here again  :) rsrs

I followed the installation steps, but when I run the chdkptp executable and  I click any button, the message "unexpected return code 0x2005" appears. Is there any incompatibility with my camera model (SX 130 IS)?

Thanks

Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / November / 2012, 08:47:50
I followed the installation steps, but when I run the chdkptp executable and  I click any button, the message "unexpected return code 0x2005" appears. Is there any incompatibility with my camera model (SX 130 IS)?
You can get error 0x2005 when you try to connect to a camera on which CHDK is not loaded. Download a fresh CHDK release from the autobuild server (http://mighty-hoernsche.de/), and install it on the camera. Use the "Bootable SD card method" (http://chdk.wikia.com/wiki/Bootable_SD_card).
Title: Re: CHDK PTP interface
Post by: Taka on 13 / November / 2012, 11:44:24
Thank you srsa_4c!

But there's a problem: for use the Bootable SD Card Method I need to set the card's lock switch to the "LOCK" position. But when I make it, the message "error: no devices available" appears in the interface. Before I try to use CHDK PTP interface, I tried to use ptpCamGui, but I had this same problem  :(

Thanks again :)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / November / 2012, 19:10:25
But there's a problem: for use the Bootable SD Card Method I need to set the card's lock switch to the "LOCK" position.
Let's start again.
- You have installed CHDK and set it to autoboot with the lock switch on the card.
- If you start the camera in play mode, do you see the CHDK splash screen showing up for a few moments? Can you enter ALT mode (I think you need to use the "face" button for that)? If you see either the splash screen and/or you are able to enter ALT mode (watch the bottom of the screen), then CHDK is running.
- If you are sure CHDK is running, you can expect chdkptp to be able to connect to the camera.
- Start the cam in play mode if you want to connect.

If anybody else has an idea what could be wrong, don't be afraid to post ;)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / November / 2012, 22:11:44
My later plan includes using the dng module to get the CHDK exif (optionally).
I have implemented dng as raw format in changeset 2270 (https://trac.assembla.com/chdk/changeset/2270/). It completely relies on CHDK settings, i.e. DNG has to be activated in CHDK. If DNG support is switched off, only the usual RAW buffer will be transferred. I did it like this because scripts can alter CHDK settings when needed.
Some of you may not like the way I changed dng.h and dng.c (I mean the added #ifdefs), if I should change it, just ask :)


edit:
I don't think #ifdef code in a module is a good idea. As far as possible the modules should be platform and version independent.
Done in changeset 2271 (https://trac.assembla.com/chdk/changeset/2271/).
Title: Re: CHDK PTP interface
Post by: philmoz on 14 / November / 2012, 03:57:14
Some of you may not like the way I changed dng.h and dng.c (I mean the added #ifdefs), if I should change it, just ask :)

I don't think #ifdef code in a module is a good idea. As far as possible the modules should be platform and version independent.

Phil.
Title: Re: CHDK PTP interface
Post by: Taka on 14 / November / 2012, 08:09:08
- You have installed CHDK and set it to autoboot with the lock switch on the card. OK!
- If you start the camera in play mode, do you see the CHDK splash screen showing up for a few moments? Yes, I do. Can you enter ALT mode (I think you need to use the "face" button for that)? Yes, I can. If you see either the splash screen and/or you are able to enter ALT mode (watch the bottom of the screen), then CHDK is running. OK!
- If you are sure CHDK is running, you can expect chdkptp to be able to connect to the camera.
- Start the cam in play mode if you want to connect.


I start the camera in play mode and I see the CHDK splash screen showing up for a few moments. So I connect camera and computer with the USB cable. I execute chdktp and click in "connect". So, the message "error: no devices available" appears.

I am using one computer Windows 7 Ultimate 32 Bits and other computer Windows 7 professional 32 Bits.

Thanks  :P

Title: Re: CHDK PTP interface
Post by: srsa_4c on 14 / November / 2012, 09:57:01
I execute chdktp and click in "connect". So, the message "error: no devices available".
You get this when the libusb driver is not installed for your camera. You need to install it for every camera(model) you'd like to use on the PC.
The install procedure on XP is like this, assuming you are using the unpacked "libusb-win32-bin-1.2.6.0.zip" from the sourceforge site:
- start libusb-win32-bin-1.2.6.0\bin\inf-wizard.exe
- do as it says (before clicking "Next" make sure that your device is connected to the system)
"connected" means the camera is connected on USB and is switched on in play mode. Close any windows that pop up (wizard or whatever).
- click "next"
- select the camera from the list, click "next"
- you can rename your "device" in the "Device Name" field, then click "next"
- save the config (and the customized driver files) in a separate directory (create one if needed)
- click "install now"
- after you get the confirmation message, switch off then switch on the camera
- the usual Windows wizard will no longer appear
- start chdkptp and connect

On Win7, you will get the usual UAC screen a few times, I guess.
Title: Re: CHDK PTP interface
Post by: Taka on 14 / November / 2012, 10:10:36
I already did it :( but didn't work
Title: Re: CHDK PTP interface
Post by: srsa_4c on 14 / November / 2012, 10:16:01
I already did it :( but didn't work
Can you find a "libusb-win32 device" in the device manager when the camera is connected? Is it your SX130IS?
Don't know what else could cause problems. Some kind of a "smart" antivirus or personal firewall? Do you have the necessary user rights to install a device driver on the PC?
Title: Re: CHDK PTP interface
Post by: msl on 14 / November / 2012, 10:59:12
@Taka

Some questions:
Did you uninstalled (or deactivated) all other camera related USB driver functions (e.g. Zoombrowser installation)?
Have you installed the libusb driver for your SX130 successfully (see device manager)?
Did you installed a recent CHDK version for your camera?
Have you started the camera in play mode?
Have you turn off the USB remote control option in the CHDK menu?

Can you answer all questions with yes then the PTP connection should be run.

msl
Title: Re: CHDK PTP interface
Post by: Taka on 16 / November / 2012, 09:00:20
It worked!! \o/

I was using USB remote control option enabled  ::)

Thanks srsa_4c and msl!  :)
Title: Re: CHDK PTP interface
Post by: chakphanu on 18 / December / 2012, 12:33:33
Hello, i'm add CHDK Liveview 2.1 to CHDKPTPRemote for dotNET dev.

forked from mweerden/CHDKPTPRemote:   https://github.com/chakphanu/CHDKPTPRemote
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / December / 2012, 20:00:11
@reyalp
Somehow ptp.Nparam doesn't get updated after ptp_transaction().
In fact, the ptpcam based ptp.c code did not fill in this value (see ptp.c ptp_usb_getresp)

According to Universal Serial Bus Still Image Capture Device Definition, 7.1.4 Response Block Payload Structure
Quote
Parameters are always 4 bytes in length. The number of parameters can be determined
from the Container length. (Length – 12)/4
I've added this code in chdkptp changeset 312. If anything relied on Nparam continuing to hold the number of input params after a transaction, it will be broken, but I didn't see anything like that from a quick inspection.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 29 / December / 2012, 13:26:29
@reyalp
Somehow ptp.Nparam doesn't get updated after ptp_transaction().
In fact, the ptpcam based ptp.c code did not fill in this value (see ptp.c ptp_usb_getresp)

According to Universal Serial Bus Still Image Capture Device Definition, 7.1.4 Response Block Payload Structure
Quote
Parameters are always 4 bytes in length. The number of parameters can be determined
from the Container length. (Length – 12)/4
I've added this code in chdkptp changeset 312. If anything relied on Nparam continuing to hold the number of input params after a transaction, it will be broken, but I didn't see anything like that from a quick inspection.
Thanks for that, I wanted to use Nparam for an additional check, not sure whether it will still be needed when the protocol becomes final.

I'm considering the simplification of filewrite_main_hook()'s arguments. If the FileWriteTask data block is mapped to a camera-specific structure, only a pointer would be needed as a single argument. It would also make the assembly (glue) part simpler and the code less ugly.
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / December / 2012, 19:30:46
Thanks for that, I wanted to use Nparam for an additional check, not sure whether it will still be needed when the protocol becomes final.
Yeah, I'm not sure varying the number of return parameters is a great idea, but it seemed like something the PTP code should provide.

Quote
I'm considering the simplification of filewrite_main_hook()'s arguments. If the FileWriteTask data block is mapped to a camera-specific structure, only a pointer would be needed as a single argument. It would also make the assembly (glue) part simpler and the code less ugly.
Reducing the amount of glue sounds good.

A question about fwt_open etc. Is there a reason these can't be C code? Since they are called as a replacement for a normal function call, it seems like you should just be able to make normal C function with the appropriate number of parameters. The registers will be preserved or not according to the ARM ABI, just like the replaced call.

eg:
Code: [Select]
int fwt_open(char *name,int  flags,int mode) {
 if(ignore_current_write) {
  current_write_ignored = ignore_current_write;
  return 0xff;
 }
 return _Open(name,flags,mode);
}
not promising I understood the current asm correctly... which is a good reason to do it in C

Some more general thoughts, (thinking out loud, not saying anything has to change)
YUV:
Is this really worth the effort? What situations would the jpeg not be good enough, but the raw too much much? I know it is relatively easy to get, but it's still several functions that have to be added to each lib.c and then it isn't available in all shooting modes. I guess the YUV may be nice because some third party libraries would already be able to deal with it directly, with even less overhead than jpeg. I'm not against including it, just wondering if there is a specific use that makes it important.

DNG:
For applications that want to maximize speed, it would be useful to be able to get the DNG header without having the DNG data bytes reversed. This could also provide a way for dealing with reduced cropped images. You would get the full header (with the dimensions set normally) and the client application could reverse the bytes and pad it to the desired size, or adjust the dng dimensions.

Getting a fully ready to use DNG is still convenient, so I think that capability should be preserved even if we make non-reversed available.

I'm not sure I like relying the chdk UI DNG setting to decide if raw returns plain raw or DNG, especially since you have to use set_config_value / get_config_value to modify it from script. It seems like the client should explicitly ask for what it wants.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / December / 2012, 20:42:39
Reducing the amount of glue sounds good.

A question about fwt_open etc. Is there a reason these can't be C code? Since they are called as a replacement for a normal function call, it seems like you should just be able to make normal C function with the appropriate number of parameters. The registers will be preserved or not according to the ARM ABI, just like the replaced call.

eg:
Code: [Select]
int fwt_open(char *name,int  flags,int mode) {
 if(ignore_current_write) {
  current_write_ignored = ignore_current_write;
  return 0xff;
 }
 return _Open(name,flags,mode);
}
not promising I understood the current asm correctly... which is a good reason to do it in C
You're probably right. Those functions started out as part of the "glue" and I wanted full control over the saved registers, so I haven't even thought about doing them in C :)
I don't know how the compiler decides over which registers should be preserved. If you think it's safe to do, then I'll re-write them.
Quote
Some more general thoughts, (thinking out loud, not saying anything has to change)
YUV:
Is this really worth the effort? What situations would the jpeg not be good enough, but the raw too much much? I know it is relatively easy to get, but it's still several functions that have to be added to each lib.c and then it isn't available in all shooting modes. I guess the YUV may be nice because some third party libraries would already be able to deal with it directly, with even less overhead than jpeg. I'm not against including it, just wondering if there is a specific use that makes it important.
Well, this part is a bit neglected at the moment, with only one of the cameras supporting it. It's true that it's of no use to most of the expected user base (which may not be very high either), and getting the YUV is a bit troublesome (it's not present when the JPEG is L or W sized, needs activated review to not get erased before transfer). I thought it would be interesting to have it, because 1) you get to see which part of the image deterioration is the result of the camera's JPEG compression 2) if you'd like to pre-process the image somehow (say, you want some text or image overlay on it) before storing or using it, you evidently lose quality when your source is already JPEG compressed 3) it might be good sometimes that the camera is doing demosaicing for you (sadly excluding full size).
Cons: 1) takes some space in memory 2) many things to watch out for before getting it 3) might be non-trivial to do on a new port 4) some disappointed users in case it's not implemented for a port
Quote
DNG:
For applications that want to maximize speed, it would be useful to be able to get the DNG header without having the DNG data bytes reversed.
Yes, the current code is the first try (I think there are comments indicating this possibility)
Quote
This could also provide a way for dealing with reduced cropped images. You would get the full header (with the dimensions set normally) and the client application could reverse the bytes and pad it to the desired size, or adjust the dng dimensions.
I probably wanted to avoid dealing with both sides of this, to keep the first implementation simple and not having to code more :)

Quote
I'm not sure I like relying the chdk UI DNG setting to decide if raw returns plain raw or DNG, especially since you have to use set_config_value / get_config_value to modify it from script. It seems like the client should explicitly ask for what it wants.
No objections, I did it so, because it seemed easy for a shooting script to include set_config_value. Should this be handled by a new script command setting some static variables, or ...?
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / December / 2012, 21:23:56
I don't know how the compiler decides over which registers should be preserved. If you think it's safe to do, then I'll re-write them.
In general if you are replacing a canon firmware function call with another function call, it should be safe. Which registers are preserved is defined by the ABI, the compiler doesn't look at the called/calling code (it can't since they could be in different object files.) The ARM function call ABI (http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0042e/index.html) is pretty standard (+/- different floating point modes and arm/thumb interworking) unlike the PC world where different compilers have used wildly different conventions.

Quote
I probably wanted to avoid dealing with both sides of this, to keep the first implementation simple and not having to code more :)
Understood, and agreed that it's better to get something simple working first :)

Quote
No objections, I did it so, because it seemed easy for a shooting script to include set_config_value.
Yes I see the attraction of this. It's not clear how this would work if we wanted to allow the DNG header separately or byte reversing control though.
Quote
Should this be handled by a new script command setting some static variables, or ...?
I would expect it to be part of init_remotecap. Logically I'd expect it to just be a format option, but having raw and dng be separate bitflags doesn't really make sense.

Thinking out loud, maybe format bits should be something like
jpeg, yuv, raw, dng header, raw byte order

dng header without raw might be useful, for example if you wanted to turn yuv into some sort of file with exif-like data. Raw byte order wouldn't really make sense if raw was disabled, but it could just be ignored.
Title: Re: CHDK PTP interface
Post by: reyalp on 31 / December / 2012, 00:55:00
I added YUV support for a540. As expected, it does not work in wide or large modes.

I didn't find a program that would convert the YUV data to nice looking image, but yuv2pnm (http://netpbm.sourceforge.net/doc/yuvtoppm.html) from netpbm does good enough to verify that the data is valid and dimensions are correct. Loading the yuv data into gimp as raw RGB565 produces amusing results ;)
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / January / 2013, 15:41:58
Added FileWriteHook for D10. No YUV, not sure if it exists on digic > 2, or how to find it.

I also wasn't clear how MAX_CHUNKS_FOR_JPEG is determined. 3 seems to work. I assume the structure is OK, since I get a valid jpeg.

@srsa
I was thinking about removing the all in one "remoteshoot" command and associated functions from chdkptp, so we only have to keep the lua based one up to date. Let me know if this is a problem for you.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / January / 2013, 17:13:53
No YUV, not sure if it exists on digic > 2, or how to find it.
I plan to do this on a DryOS cam sooner or later. I simply dumped all RAM from the filewrite hook routine, used the usual hex editor with the visualization, and after that I looked up the found address in fw. That said, it's easier to do on a camera with 16MB of RAM than on another with 64 or 128... .

Quote
I also wasn't clear how MAX_CHUNKS_FOR_JPEG is determined. 3 seems to work. I assume the structure is OK, since I get a valid jpeg.
Again, I dumped that specific piece of RAM from the filewrite hook (on D10, sub_FFA26268_my gets a pointer to it in R0), length is less than 0x80. Actually, that pointer is received by the task via ReceiveMessageQueue (sub_FF826C30).
Do you have a idea how a "message" handled by the *MessageQueue functions should be called? I usually just call it message, but I don't know whether it's good enough terminology...
edit: The VxWorks programmer's guide also uses "message", so it is correct.

After seeing several cam's filewritetask code, I can usually identify MAX_CHUNKS_FOR_JPEG, look at the code sub_FFA263B4_my starts with.

Quote
I was thinking about removing the all in one "remoteshoot" command and associated functions from chdkptp, so we only have to keep the lua based one up to date. Let me know if this is a problem for you.
No problem, just do it.

For YUV, there's libyuv (http://code.google.com/p/libyuv/). Yeah, it's just a library, and I haven't checked whether it actually supports the YUV variants we deal with here.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / January / 2013, 19:24:47
I've removed the old "remoteshoot" function along with the support functions and PTP_CHDK_RemoteCaptureInit protocol command. Development version bumped since this changes the numbers. chdkptp >= r319 supports this version.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / January / 2013, 19:47:41
For YUV, there's libyuv (http://code.google.com/p/libyuv/). Yeah, it's just a library, and I haven't checked whether it actually supports the YUV variants we deal with here.
It would be nice to get a proper conversion of this YUV to see how it really compares to jpeg. Given that it's only available in reduced size (for cameras so far), it seems like it's unlikely to be better than full res jpeg. I can imagine automation projects that wanted to look quickly look at a small part of the images might like YUV, since we can't really return a sub-range of jpeg. OTOH, the YUV actually comes out bigger than the correspond raw...

ImageMagic will convert some YUV formats, but the one I tried (-sampling-factor 4:2:2) gave basically the same result yuv2pnm. I always get lost looking at the imagemagick documentation...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / January / 2013, 20:24:13
I'm considering the simplification of filewrite_main_hook()'s arguments. If the FileWriteTask data block is mapped to a camera-specific structure, only a pointer would be needed as a single argument. It would also make the assembly (glue) part simpler and the code less ugly.
It looks like this (camera specific capt_seq.c):

For DryOS>=r50
Code: [Select]
typedef struct {
    unsigned int address;
    unsigned int length;
} cam_ptp_data_chunk; //camera specific structure

#define MAX_CHUNKS_FOR_JPEG 7 // filewritetask is prepared for this many chunks
/*
 * fwt_data_struct: defined here as it's camera dependent
 * unneeded members are designated with unkn
 * file_offset, full_size, seek_flag only needs to be defined for DryOS>=r50 generation cameras
 * pdc and name are always needed
 */
typedef struct
{
    int unkn1;
    int file_offset;    // needed for DryOS>=r50
    int full_size;      // needed for DryOS>=r50
    int unkn2, unkn3, unkn4;
    cam_ptp_data_chunk pdc[MAX_CHUNKS_FOR_JPEG];
    int seek_flag;      // needed for DryOS>=r50
    char name[32];
} fwt_data_struct;
#define FWT_MUSTSEEK    2   // value of seek_flag indicating seek is required
#define FWT_CONDSEEK    3   // value of seek_flag indicating seek is required when file_offset not 0
Example of an earlier DryOS camera
Code: [Select]
typedef struct {
    unsigned int address;
    unsigned int length;
} cam_ptp_data_chunk; //camera specific structure

#define MAX_CHUNKS_FOR_JPEG 3 //model specific
/*
 * fwt_data_struct: defined here as it's camera dependent
 * unneeded members are designated with unkn
 * file_offset, full_size, seek_flag only needs to be defined for DryOS>=r50 generation cameras
 * pdc and name are always needed
 */
typedef struct
{
    int unkn1, unkn2, unkn3, unkn4, unkn5;
    cam_ptp_data_chunk pdc[MAX_CHUNKS_FOR_JPEG];
    char name[32];
} fwt_data_struct;
Which makes the assembly glue simpler:
Code: [Select]
//place hook here
      "STMFD SP!, {R4-R12,LR}\n"
      "MOV R0, R4\n"
      "BL filewrite_main_hook\n"
      "LDMFD SP!, {R4-R12,LR}\n"
//hook end
I guess it's better. I have a feeling that cam_ptp_data_chunk will go into a common header as it's always the same.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / January / 2013, 20:48:04
I guess it's better. I have a feeling that cam_ptp_data_chunk will go into a common header as it's always the same.
Agreed. I would expect  fwt_data_struct is very likely tied to dryos rev, so could be in a common header with a minimal number of ifdefs.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / January / 2013, 19:49:36
I've checked in the above mentioned changes. It's worth to note that converting offsets to structure members is a small additional challenge.

Also done some tests, and found that the new rs command doesn't work reliably with the A410. Reason not yet known (it's not related to my latest changes). It usually works after the camera is switched to rec mode, but fails with timeout after the camera goes to powersave mode (rs wake up the cam as usual and the half press phase is OK, but then nothing happens). I don't remember experiencing this with the monolithic rs, hopefully it's not related to the completefilewrite replacement. OTOH the A470 is working normally, no problems.
There's another small bug in rs, it fails to append the received file name when a target directory is given (I can probably figure out how to solve this one).
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / January / 2013, 00:35:20
It usually works after the camera is switched to rec mode, but fails with timeout after the camera goes to powersave mode (rs wake up the cam as usual and the half press phase is OK, but then nothing happens). I don't remember experiencing this with the monolithic rs, hopefully it's not related to the completefilewrite replacement. OTOH the A470 is working normally, no problems.
One difference is that this one uses shoot_half, wait for get_shooting etc, instead of shoot() Full camera side code is in lua/rlibs.lua rs_shoot

I seem to remember having had other weird problems when the camera goes to screen off mode, I usually disable it when I'm doing ptp stuff.
Quote
There's another small bug in rs, it fails to append the received file name when a target directory is given (I can probably figure out how to solve this one).
Whoops, I left that half finished, should be better in changeset 321.
rs (no file) = use camera filename
rs foo = if foo is a directory, use foo/<camera filename>, otherwise foo.jpg, foo.raw
rs foo/  = create foo if it doesn't exist, use foo/<camera filename>
Title: Re: CHDK PTP interface
Post by: srsa_4c on 04 / January / 2013, 19:25:57
I seem to remember having had other weird problems when the camera goes to screen off mode, I usually disable it when I'm doing ptp stuff.
I don't remember anything weird in connection with powersave mode. During earlier testing I left the cameras in rec mode sleeping for hours and rs always succeeded when executed later. I guess I'll investigate this stuff.
Quote
Whoops, I left that half finished, should be better in changeset 321.
rs (no file) = use camera filename
rs foo = if foo is a directory, use foo/<camera filename>, otherwise foo.jpg, foo.raw
rs foo/  = create foo if it doesn't exist, use foo/<camera filename>
Thanks :)
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / January / 2013, 01:04:29
I updated the ptp-remote-capture-test up to the last change before phils reorg merge. Because of the file moves, it's not really practical to merge in the normal way. I suspect the best approach is going to be to make a new branch from the trunk, and manually port over the changes from the moved files. I'll try that this weekend.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / January / 2013, 22:26:33
New remote capture branch is ptp-remote-capture-test2, all future development should go there.

Note that CAM_CHDK_PTP_REMOTESHOOT can't be turned off at the moment, because ptp.c is now in platform independent code. I'm not sure it's worth keeping this as an option at all, since all cameras should at least support raw. It would save a small amount of memory.

I split remotecap.h into into two parts,
 remotecap.h is now the "public" interface available to modules (lua)
 remotecap_core.h is only for core code.

Please don't check anything into ptp-remote-capture-test. I'll delete it soon (only removes it from the list of current branches)
Title: Re: CHDK PTP interface
Post by: philmoz on 05 / January / 2013, 22:42:39
Note that CAM_CHDK_PTP_REMOTESHOOT can't be turned off at the moment, because ptp.c is now in platform independent code. I'm not sure it's worth keeping this as an option at all, since all cameras should at least support raw. It would save a small amount of memory.

If it needs to be turned off because the functionality is not available then it should be done at runtime. Add a new entry to camera_info.h/.c and check that in the code.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / January / 2013, 22:58:06
If it needs to be turned off because the functionality is not available then it should be done at runtime. Add a new entry to camera_info.h/.c and check that in the code.
The minimum functionality (raw only) is available on any camera, so there's really no point in turning it off at runtime. The only reason to keep the #ifdef would be to reduce the core executable size slightly. This can be done, it would just require moving some of the code out of ptp.c and stubbing out the public functions when it's not available. I don't really think this is worthwhile.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / January / 2013, 09:26:31
Also done some tests, and found that the new rs command doesn't work reliably with the A410.
It's puzzling, but after putting in larger amounts of debug code, it appears that the problem is related to flash. In other words, it's probably the same issue that skrylten is experiencing (http://chdk.setepontos.com/index.php?topic=9118.0). I usually disable flash when testing, but haven't always done so recently, hence the issue...

Even when operated manually, a short full shutter press often fails to take a shot. When pressed for longer, the camera shoots.

The only reason to keep the #ifdef would be to reduce the core executable size slightly.
Not fully related, but I'd consider putting the whole filewritetask related code inside #ifdefs, including the copied task code and the lines related to task replacement.
The same would be good for other standard tasks we replace (capt_seq, movie_record, ...), but that's probably not feasible. Conditionally compiled task replacements would enable one to create a smaller sized CHDK that excludes unwanted (or unstable) features. Space-wise, on low memory ports even a few kBytes could matter.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / January / 2013, 18:07:38
Some news.
I've been trying to implement YUV support for the A470. Looks like it's a no-go with the filewrite hook. It appears that by the time the filewritetask hook is reached, the YUV source of the JPEG is overwritten by the decompressed Y411 version of the fresh JPEG (unless 640x480 size is selected). So, either a new hook or no YUV support on this camera...
The interesting find is that in addition to the resized YUV, there are remnants of a full sized YUV image, regardless of the selected image dimensions.

For the rs "bug" I came up with the following (it's probably influenced by lapser's findings)
Code: [Select]
function rs_shoot(opts)
local rec,vid = get_mode()
if not rec then
return false,'not in rec mode'
end
if type(init_remotecap) ~= 'function' then
return false, 'remotecap not supported'
end
if bitand(get_remotecap_support(),opts.fformat) ~= opts.fformat then
return false, 'unsupported format'
end
if not init_remotecap(opts.fformat,opts.lstart,opts.lcount) then
return false, 'init failed'
end
press('shoot_half')
local shtimeout = get_tick_count()
repeat
sleep(10)
until ( get_shooting() ) or ( (get_tick_count()-shtimeout)>5000 )
reset_shoot_ok()
press('shoot_full')
local gsrtime = get_tick_count()
repeat
sleep(10)
until  ( get_shoot_ok() ) or ( (get_tick_count()-gsrtime)>5000 )
release('shoot_full')
return true
end
reset_shoot_ok() and get_shoot_ok() are new functions. They use a new static variable which is set in the raw hook capt_seq_hook_set_nr() . This approach appears to work on the A410 and 470 - even with flash. My trials included putting arbitrary delays after pressing shoot_full, but that method was unreliable (unless the delay was set to like 2 seconds).
edit: not raw hook, capt_seq_hook_set_nr()
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / January / 2013, 22:29:27
Some news.
I've been trying to implement YUV support for the A470. Looks like it's a no-go with the filewrite hook. It appears that by the time the filewritetask hook is reached, the YUV source of the JPEG is overwritten by the decompressed Y411 version of the fresh JPEG (unless 640x480 size is selected). So, either a new hook or no YUV support on this camera...
Unless there is some really compelling use for the YUV, this doesn't seem like it would justify adding a new task hook. Even at full size, I'm have trouble seeing one.

Quote
For the rs "bug" I came up with the following (it's probably influenced by lapser's findings)
...
reset_shoot_ok() and get_shoot_ok() are new functions. They use a new static variable which is set in the raw hook. This approach appears to work on the A410 and 470 - even with flash. My trials included putting arbitrary delays after pressing shoot_full, but that method was unreliable (unless the delay was set to like 2 seconds).
did you check get_flash_ready() ?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / January / 2013, 12:29:04
did you check get_flash_ready() ?
Yes.
Code: (lua) [Select]
function rs_shoot(opts)
local rec,vid = get_mode()
if not rec then
return false,'not in rec mode'
end
if type(init_remotecap) ~= 'function' then
return false, 'remotecap not supported'
end
if bitand(get_remotecap_support(),opts.fformat) ~= opts.fformat then
return false, 'unsupported format'
end
if not init_remotecap(opts.fformat,opts.lstart,opts.lcount) then
return false, 'init failed'
end
press('shoot_half')
local shtimeout = get_tick_count()
local gfrtime = 0
repeat
sleep(10)
if get_flash_ready() and (gfrtime==0) then
gfrtime=get_tick_count()-shtimeout
end
until ( get_shooting() and ( get_flash_ready() or (get_flash_mode()==2) ) ) or ( (get_tick_count()-shtimeout)>5000 )
shtimeout=get_tick_count()-shtimeout
reset_shoot_ok()
press('shoot_full')
local gsrtime = get_tick_count()
repeat
sleep(10)
until  ( get_shoot_ok() ) or ( (get_tick_count()-gsrtime)>5000 )
gsrtime=get_tick_count()-gsrtime
release('shoot_full')
return true, 'get_shooting: ' .. shtimeout .. 'ms , gfr: ' .. gfrtime .. 'ms, gsr: ' .. gsrtime .. 'ms'
end
Above version (I haven't removed the debug related lines) works, tried on the A410 and A460 this time.
The below one however frequently fails with flash (A460 is worse).
Code: [Select]
function rs_shoot(opts)
local rec,vid = get_mode()
if not rec then
return false,'not in rec mode'
end
if type(init_remotecap) ~= 'function' then
return false, 'remotecap not supported'
end
if bitand(get_remotecap_support(),opts.fformat) ~= opts.fformat then
return false, 'unsupported format'
end
if not init_remotecap(opts.fformat,opts.lstart,opts.lcount) then
return false, 'init failed'
end
press('shoot_half')
    local shtimeout = get_tick_count()
    local gfrtime = 0
repeat
sleep(10)
        if get_flash_ready() and (gfrtime==0) then
            gfrtime=get_tick_count()-shtimeout
        end
until ( get_shooting() and ( get_flash_ready() or (get_flash_mode()==2) ) ) or ( (get_tick_count()-shtimeout)>5000 )
shtimeout=get_tick_count()-shtimeout
local gsrtime = get_tick_count()
click('shoot_full')
return true, 'get_shooting: ' .. shtimeout .. 'ms , gfr: ' .. gfrtime .. 'ms, gsr: ' .. gsrtime .. 'ms'
end
Of course I'm not trying to say that my "solution" is ideal, especially not when the exposure time is seconds long.
According to the logs, get_shooting() and get_flash ready() seem to become true at the same time.
edit: I'm using capt_seq_hook_set_nr(), not the raw hook, I just forgot about that...
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / January / 2013, 00:07:04
Please don't check anything into ptp-remote-capture-test. I'll delete it soon (only removes it from the list of current branches)
I have removed the old branches.

Note that the changes in ptp.h and live_view.h in the trunk made the headers no longer directly usable by chdkptp source. For now I've added an define clients can use CHDK_PTP_PROTOCOL_ONLY to exclude everything that isn't strictly related to the ptp protocol. It might make more sense to split the chdk specific stuff into separate headers.

I would like to keep the ability of clients to use the CHDK header directly, since it minimizes the risk of copy/paste errors and the headers act as the protocol specification.
Title: Re: CHDK PTP interface
Post by: philmoz on 13 / January / 2013, 00:39:29
It might make more sense to split the chdk specific stuff into separate headers.

For the trunk version, I'd prefer to do things that way, to avoid #ifdef's in the header files used by platform independent code.

I think, the live_view.h file change is best fixed by moving the 'extern int live_view_get_data(ptp_data *data, int flags);' definition into ptp.c - which is the only place where this function is referenced.

I'm doing some other cleanup in the trunk at the moment, so I'll split the ptp.h file in two and move the function reference out of live_view.h as part of the change.

Phil.
Title: Re: CHDK PTP interface
Post by: Cahuila on 29 / March / 2013, 14:19:38
Hey guys... I am fairly new, but I had a couple of questions about PTP.

I have a Canon SX210 is, and I was able to get CHDK running on it. I was also able to get the PTP inteface to run off it as well. I am able to only perform a few functions on it, but the only function I really care about it "taking a picture" and using "liveview". The shoot feature works but the live view does not display the screen correctly. The picture is distorted, showing 1/4 of the picture four times. Is this a known issue? Does anyone have any suggestions on what can be causing this problem?

Your help is greatly appreciated...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 29 / March / 2013, 17:12:06
... but the live view does not display the screen correctly. The picture is distorted, showing 1/4 of the picture four times. Is this a known issue?
Now it is. Can you show a screenshot?
Title: Re: CHDK PTP interface
Post by: Cahuila on 01 / April / 2013, 14:20:20
... but the live view does not display the screen correctly. The picture is distorted, showing 1/4 of the picture four times. Is this a known issue?
Now it is. Can you show a screenshot?

Yeah, here is the screen shot of what is happening...
(https://chdk.setepontos.com/proxy.php?request=http%3A%2F%2Fi282.photobucket.com%2Falbums%2Fkk252%2Fcahuila%2FBlogs%2FScreenShot.png&hash=53c929423b2945db3011519e2b430e6a)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 02 / April / 2013, 16:03:45
Yeah, here is the screen shot of what is happening...
I see. The reason is that not all liveview related code is implemented in this port. I can probably help with this, but since I don't have access to this camera, I will need feedback. Are you ready to do some testing?
If so, please post your answer to the SX210IS porting thread (http://chdk.setepontos.com/index.php?topic=5045.0).
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / April / 2013, 22:00:33
I updated the remote capture branch with philmoz module re-work. It seems to work, but I haven't tested it carefully. This will probably make it hard to merge back (because there were changes needed to make it build checked in at the same time), but I guess we'll deal with that when we get there...
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / April / 2013, 16:08:20
I updated the remote capture branch with philmoz module re-work. It seems to work, but I haven't tested it carefully. This will probably make it hard to merge back (because there were changes needed to make it build checked in at the same time), but I guess we'll deal with that when we get there...
Had second thoughts about this, made a new branch ptp-remote-capture-test3. Future changes should go there.

The issue is that merging the module rework required resolving conflicts and making changes in the new remote cap code. But the checkin to do this also includes the merge of all the trunk changes, so merging it back would be problematic.

Making a new branch from the trunk merging the existing remote cap changes into it resolves this, but makes the history more confusing. This is all a product of my slacking on the remote capture branch :(

I would like to "land" the remote cap branch fairly soon. The main outstanding item is to re-work how DNG is handled so we can get can control header and byte reversing separately. This also requires re-working how chdkptp handles it.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 08 / April / 2013, 16:54:10
A PTP query in another thread prompted me to comment on PTP support in the forthcoming SDM 1.86 release.
A friend and myself spent a lot of time working on this and it has many useful features including image gallery editor, on-th-fly creation of stop-motion movies, uploading of images one-at-a-time or after a burst sequence, image stacks, stereo image stacks,time-lapse, hdr,etc.etc.

See attached image.

Having seen the sort of problems that people attracted to CHDK can have, it would be far more difficult for the average SDM user to cope with and would require never-ending support.

So, I have removed support for PTP.
I will tell people that if they are convinced they need it, just download the CHDK DISKBOOT.BIN file and Modules folder.

It is that easy  ....  and gives me far more  time to get back to photography.

Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / April / 2013, 21:24:56
I would like to "land" the remote cap branch fairly soon.
Would it make sense to implement querying/reporting camera related quirks, so that the client can take appropriate measures to avoid known problems?
I'm thinking about
- the USB transfer size related bugs (this is not really remote capture related)
- this (the a470 seems not to be affected for example):
I've also had weirdness / failed connections when the camera goes into powersave mode.
- when the camera can't tolerate remote shooting in too fast succession (ixus870)
- ...
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / May / 2013, 17:53:00
Moved from the chdkptp thread

FWIW, one of my long term ideas for PTP is to expose file operations like read(), write() etc directly in the PTP protocol (without lua). This should make write a FUSE (http://en.wikipedia.org/wiki/Filesystem_in_Userspace) (and/or gvfs) module for CHDK cameras quite easy, which would allow linux systems to effectively mount the entire filesystem. If anyone wants to have a go at this, I have some ideas...

from some discussion in irc
the way I imagine the chdk side working is there would be ptp opcodes for the basic operations fuse expects. I'm not totally sure what those are, but I guess open, read, write etc
open / close present some problems because of the limited number of filehandles available on the cam
you'd probably want to store your own structure on the cam and only open when needed


A further issue is that there can only be one connection to a camera, so if the fuse module talked ptp directly to the camera, you would not be able to use other clients. The "right" solution to this would probably be a daemon that handles all the PTP communicaton, and the fuse module and clients would talk to the daemon.

The low level file operations would be useful even without the fuse portion.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 19 / May / 2013, 10:47:07
A few potential PTP issues:

- PTP (or the whole USB subsystem) gets shut down somehow when the number of "camera objects" grows beyond a certain limit. This might be related to that "communication error" message which is mentioned in the manual (I personally have not seen it yet). This is not directly file system related, I managed to trigger it by doing 8k shots with JPEG disabled. (a410, the camera could not even start the "erase all" operation in the Canon menu afterwards).

- at least on DryOS cameras, a certain amount of exmem (1MB in cases I've seen) gets allocated when usb is connected which may or may not interfere with record mode.

In a separate note, recent trunk changes can't be easily merged into the v3 remote capture branch. I was able to - sort of - merge it into current trunk code, with the exception of platform *.S files, but I would need a full rebuild with all fw dumps to correct it. The usual "cherry-picking" method seems more painful.

For fuse, there's this: http://www.gphoto.org/proj/gphotofs/ (http://www.gphoto.org/proj/gphotofs/)
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / May / 2013, 15:22:07
- PTP (or the whole USB subsystem) gets shut down somehow when the number of "camera objects" grows beyond a certain limit. This might be related to that "communication error" message which is mentioned in the manual (I personally have not seen it yet).
Yes, I saw the "communication error" when I was chasing the Lua bug. It's annoying, would be nice if we could block the camera from whatever triggers this. I guess building the list of PTP objects?

Quote
- at least on DryOS cameras, a certain amount of exmem (1MB in cases I've seen) gets allocated when usb is connected which may or may not interfere with record mode.
Yes, EXMEM_COM is in the firmware exmem view output.

At a minimum, the cameras that have quality issues when CHDK is in exmem will probably suffer the same problem. Worse if CHDK is already in exmem.

I wonder if video recording clobbers the EXMEM_COM section like it does CHDK allocations? If not, maybe we can figure out how. And if it does, I assume PTP will become very unreliable if you try to record video
Quote
In a separate note, recent trunk changes can't be easily merged into the v3 remote capture branch.
Yeah, would be good to land this branch soon. I'll try to have a look at updating.

Quote
For fuse, there's this: http://www.gphoto.org/proj/gphotofs/ (http://www.gphoto.org/proj/gphotofs/)
Yes, this sort of thing is what brought up the discussion in the first place. The idea is to expose the full filesystem, vs what is already accessible via regular PTP. Also, as I mentioned earlier it would be a lot more flexible than the current options. However, this isn't something I think is urgent to do now, it's just an idea that I've had kicking around for a while. I posted it here because nafraf expressed some interest in working on it.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 19 / May / 2013, 16:27:06
Yes, I saw the "communication error" when I was chasing the Lua bug. It's annoying, would be nice if we could block the camera from whatever triggers this. I guess building the list of PTP objects?
I don't know how these object representations are related (the camera's internal list of its known files vs the same for ptp). If my memory is correct, the camera hasn't even shown up as USB device when plugged in, so it got overwhelmed before any ptp connection attempt.
Unfortunately this part of the firmware seems rather complex (lots of related tasks). I have only one idea that could provide some help in certain cases: if that "erase all" routine is found, it could be run once for like every few hundred images - only usable if remote shooting OR when the saved files are redirected (in filewritetask) to a path the camera doesn't know.
Quote
Yes, EXMEM_COM is in the firmware exmem view output.

At a minimum, the cameras that have quality issues when CHDK is in exmem will probably suffer the same problem. Worse if CHDK is already in exmem.

I wonder if video recording clobbers the EXMEM_COM section like it does CHDK allocations? If not, maybe we can figure out how. And if it does, I assume PTP will become very unreliable if you try to record video
PTP acts unstable on certain cameras (regardless of movie recording), but I have no clue why, I can never reproduce.
Quote
I'll try to have a look at updating.
Not too important at the moment, I mentioned it as a hint why I haven't done the update.
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / May / 2013, 16:31:11
If my memory is correct, the camera hasn't even shown up as USB device when plugged in, so it got overwhelmed before any ptp connection attempt.
When I got the "communication error" it appeared when plugging the camera in, and the camera was not recognized at all on USB.

I think one time when I left it running (taking 10k shots) while plugged into ptp it also died (without showing communication error), but I don't remember the exact symptom  :-[
Title: Re: CHDK PTP interface
Post by: philmoz on 31 / May / 2013, 21:31:49
In a separate note, recent trunk changes can't be easily merged into the v3 remote capture branch. I was able to - sort of - merge it into current trunk code, with the exception of platform *.S files, but I would need a full rebuild with all fw dumps to correct it. The usual "cherry-picking" method seems more painful.

The attached patch should bring the branch up to the trunk-2822 revision.

It builds for all cameras, and runs on my G1X; but I haven't implemented the ptp-remote extensions so I can't test that part.

I was able to build for all cameras using GCC 4.6.2 (on Windows).
However on the Linux environment I have set up with hacki's 4.4.3 toolchain it fails on some cameras. For example the A495 capt_seq.c file gives the error below:
Code: [Select]
/tmp/ccxjW2Jc.s: Assembler messages:
/tmp/ccxjW2Jc.s:166: Error: invalid literal constant: pool needs to be closer
/tmp/ccxjW2Jc.s:175: Error: invalid literal constant: pool needs to be closer
/tmp/ccxjW2Jc.s:176: Error: invalid literal constant: pool needs to be closer
make[2]: *** [capt_seq.o] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [batch-zip-complete] Error 1

I suspect the source file is too big and will need to be split up.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 31 / May / 2013, 22:12:14
a .pool in the ASM will probably resolve that error. http://sourceware.org/binutils/docs/as/ARM-Directives.html (http://sourceware.org/binutils/docs/as/ARM-Directives.html)

You will have to arrange to jump over it if it's in the normal flow of code.

edit:
and thank you very much for doing that.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / June / 2013, 21:13:10
I don't get these "pool needs to be closer" errors using my 4.5.1 and 4.6.4 toolchains. Is this 4.4.3 toolchain available somewhere?

and thank you very much for doing that.
+1

BTW, it might be my fault, but patch generated 0 sized files instead of removing those. I've removed all CRs from the patch before applying, maybe that's why.
Title: Re: CHDK PTP interface
Post by: waterwingz on 01 / June / 2013, 22:06:06
Is this 4.4.3 toolchain available somewhere?
https://www.box.com/s/2bs0i77srru9d68cy6j5 (https://www.box.com/s/2bs0i77srru9d68cy6j5)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / June / 2013, 17:18:25
Is this 4.4.3 toolchain available somewhere?
https://www.box.com/s/2bs0i77srru9d68cy6j5 (https://www.box.com/s/2bs0i77srru9d68cy6j5)
Thanks. Unfortunately it's x86-64, so I can't currently use it. Can you show the output of
arm-elf-objdump -v
and
arm-elf-gcc -v
?
I wonder whether a toolchain with these binutils and gcc versions will act the same as the autobuild's...
Title: Re: CHDK PTP interface
Post by: waterwingz on 07 / June / 2013, 19:41:20
arm-elf-objdump -v
Code: [Select]
[build]$ arm-elf-objdump -v
GNU objdump (GNU Binutils) 2.18
Copyright 2007 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) any later version.
This program has absolutely no warranty.

Quote
arm-elf-gcc -v
Code: [Select]
[build]$ arm-elf-gcc -v
Using built-in specs.
Target: arm-elf
Configured with: ../configure --target=arm-elf --prefix=/home/hacki/newenv/ --enable-languages=c --disable-shared --disable-newlib --disable-libssp
Thread model: single
gcc version 4.4.3 (GCC)
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / June / 2013, 21:24:18
Thanks. Unfortunately it's x86-64, so I can't currently use it.
FWIW, I have a x64 system and a similar generation toolchain I built, so I should be able to check on the pool issue.
Title: Re: CHDK PTP interface
Post by: waterwingz on 07 / June / 2013, 22:04:54
I wonder whether a toolchain with these binutils and gcc versions will act the same as the autobuild's...
FWIW ... the values I posted are from the toolchain that hacki uses for the autobuild - or at least they were when he shared them with me.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / June / 2013, 08:32:27
I managed to build a 4.4.3 toolchain (thx WW for the config data), and it does show the same pool issue. Looks like it will be a must to use it before committing code that will end up in autobuild.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / June / 2013, 17:09:47
I tried to apply phils patch using tortoise. It didn't really work, there are rejects and files that end up "missing" rather deleted, things that should be added that aren't, and where things are added they of course show up as new files rather copies, so the history will be lost and make a further mess if we try to do merges later. I'm going to try an alternate approach of making a new branch from the trunk and merging over the remote capture changes.

This whole remote capture branch has been a disaster. I am unsure what to do about it. IMO, the current implementation is too much of a mess to accept as is, it should not be in the trunk. It needs significant work both in the protocol and on the client side. However, maintaining an invasive change like this in parallel to other invasive reorganizations in the trunk is wasting a large amount of our time and making the whole thing so frustrating I'm not motivated to work on it. On the rare occasions I actually have a large enough chunk of free time to actually do something, I end up spending it trying to get it up to date rather than working on the actual code.
Title: Re: CHDK PTP interface
Post by: waterwingz on 08 / June / 2013, 18:49:14
This whole remote capture branch has been a disaster. I am unsure what to do about it. IMO, the current implementation is too much of a mess to accept as is, it should not be in the trunk. It needs significant work both in the protocol and on the client side.
Easy for me to say this,  but sometimes its just worth chucking the code and using the knowledge gained to start again cleanly?
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / June / 2013, 19:21:45
Easy for me to say this,  but sometimes its just worth chucking the code and using the knowledge gained to start again cleanly?
I don't think that's the case here. The code we have is stuff we need, there is just more to be done.

The new branch is merge seems to have worked pretty well, I should have it checked in shortly.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / June / 2013, 20:11:56
https://tools.assembla.com/svn/chdk/branches/ptp-remote-capture-test4

This should bring the remotecap stuff fully up to date with the trunk, including the dng changes.

I tested this on my cams and it seems to be working. I rebuilt all the cams with file write hook.

Two minor changes were needed from the test3 branch:

In generic/capt_seq.c fwt_lseek I changed _Lseek to _lseek. This was needed to get a810 to build, since Lseek is marked as unused. On a810 (and from a quick look, most if not all dryos cams), Lseek and lseek are identified with the same address, so this should be OK.

In modules/dng.c I removed fill_gama_buf since it no longer exists in the new dng code.

edit:
Seems I've broken something with DNG capture, works on a540 but on d10 just returns framebuffer dump without header ???

Oops, DNG_SUPPORT went away, didn't actually work on a540, just irfanview was just able to load the framebuffer raw...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / June / 2013, 22:20:08
Some thoughts.

CHDK side:
I agree that most of the rc related code looks like an unorganized mess, and is certainly not ready for inclusion. This is mostly a result of my work - I haven't done much beyond changing stuff to make it work.
Some things that I would do to make the mess a little less:
- Remove functionality that is unneeded at this point: YUV. I was going to say DNG too, since the RAW/DNG code has always been file-centered, and I had to butcher an existing DNG function (done in January(?), many things have happened since) to make DNG available for rc.
- Split every possible piece of rc related code into separate files - looks like choosing capt_seq.c for holding the additional code was a bad idea.
- The rc related variables may need reorganization.
- Remove the usage of event procedures. It's AFAIK not needed for rc to work.
- ...?

Client side:
The problem is, any advanced usage of Lua is beyond me, which prevents me from doing any useful work on CHDKPTP.

Seeing the turbulent changes in CHDK trunk, it makes me wonder whether it would have been a better idea to continue development on the stable 1.1 codebase.

I still think that this kind of remote capture support is much better than retrieving the most recently shot image from the card.
Title: Re: CHDK PTP interface
Post by: waterwingz on 08 / June / 2013, 22:22:23
Seeing the turbulent changes in CHDK trunk, it makes me wonder whether it would have been a better idea to continue development on the stable 1.1 codebase.
Or it might be time to bump the revs?  The UI changes in 1.2.0 are probably enough to justify moving it to "stable" status,  retiring 1.1.0,  rewriting the user guide,  and putting the ptp stuff into a newly created 1.3.0?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / June / 2013, 22:44:03
Seeing the turbulent changes in CHDK trunk, it makes me wonder whether it would have been a better idea to continue development on the stable 1.1 codebase.
Or it might be time to bump the revs?  The UI changes in 1.2.0 are probably enough to justify moving it to "stable" status,
Probably.
Quote
rewriting the user guide,
Badly needed, but  :blink:
Quote
putting the ptp stuff into a newly created 1.3.0?
Without restructuring the rc code, it will become the same pain to maintain.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / June / 2013, 22:55:35
- Remove functionality that is unneeded at this point: YUV. I was going to say DNG too, since the RAW/DNG code has always been file-centered, and I had to butcher an existing DNG function (done in January(?), many things have happened since) to make DNG available for rc.
I agree about YUV. It's a bit of a pity having done the work, but I don't see any real use for it, especially considering you can't get it full res.

I think DNG, or at least the DNG header is worthwhile. But this requires some changes to be usable on the client.

I also think that a subimage of raw is still worthwhile.

Quote
- Split every possible piece of rc related code into separate files - looks like choosing capt_seq.c for holding the additional code was a bad idea.
I was thinking about this today too. Putting filewrite in it's own C file would make sense, but then we need somewhere for the generic filewrite stuff.

edit:
this will probably also avoid the pool problem, though in the long run it would be better to update the compiler on the autobuild server to something more recent.
Quote
- The rc related variables may need reorganization.
Agree, there's some cleanup that could be done.
Quote
- Remove the usage of event procedures. It's AFAIK not needed for rc to work.
Agreed.

Quote
Client side:
The problem is, any advanced usage of Lua is beyond me, which prevents me from doing any useful work on CHDKPTP.
That's understood, I have been slow working on this, and some changes need to happen simultaneously on both sides.
Quote
Seeing the turbulent changes in CHDK trunk, it makes me wonder whether it would have been a better idea to continue development on the stable 1.1 codebase.
I don't think so, getting it into the trunk would have been an even bigger problem then. We might have been better trying to to keep updated with the trunk, but that also would have made the final merge horrendous.

Quote
I still think that this kind of remote capture support is much better than retrieving the most recently shot image from the card.
I agree. However, getting from the card is needed as a fallback unless we implement filewrite for every camera.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 02:49:44
I've removed the PT_ hooks along with the imagesavecomplete logic and YUV support. I've left some parts of this commented in case we want to use it later. I think the imagesavecomplete stuff and the PT hooks might be useful at some point in the future, but they don't need to be done to finish the remote capture stuff.

I also split the filewrite code into separate files. I have built all the affected cameras but only tested a540 and d10 of course.

Splitting the filewrite code into it's own file does appear to resolve the literal pool issues.
Title: Re: CHDK PTP interface
Post by: Microfunguy on 09 / June / 2013, 06:13:13
I still think that this kind of remote capture support is much better than retrieving the most recently shot image from the card.

Maybe so, and this is an interesting excercise for those who enjoy code development, but realistically what is the PTP feature actually being used for in real life (rather than day-dreaming) and what percentage of CHDK users would be inconvenienced if it did not exist ?

Just curious.

A beautiful Summers day in the UK, will try to 'film' butterflies if it cools down ......
Title: Re: CHDK PTP interface
Post by: waterwingz on 09 / June / 2013, 10:52:46
Maybe so, and this is an interesting excercise for those who enjoy code development, but realistically what is the PTP feature actually being used for in real life (rather than day-dreaming) and what percentage of CHDK users would be inconvenienced if it did not exist ?
I would argue that once you get past basic setup & configuration issues,  the next most popular requests on this forum relate to projects that need to be able to coordinate activities between a PC and the camera. So ptp support is a lot more than just an interesting coding concept - there is as strong interest and demand for the capability.   And as that capability will apparently not be available in any other hacks, that just leaves CHDK.

Title: Re: CHDK PTP interface
Post by: Microfunguy on 09 / June / 2013, 11:28:57
as that capability will apparently not be available in any other hacks, that just leaves CHDK.

Yes, there is that.
In future versions of SDM I will be removing Zebra, histogram and edge overlay just to make it 'leaner' and reduce work for myself.

I would also prefer to remove raw but will probaly leave it in place.

Title: Re: CHDK PTP interface
Post by: rkomar on 09 / June / 2013, 15:03:40
Maybe so, and this is an interesting excercise for those who enjoy code development, but realistically what is the PTP feature actually being used for in real life (rather than day-dreaming) and what percentage of CHDK users would be inconvenienced if it did not exist ?
I would argue that once you get past basic setup & configuration issues,  the next most popular requests on this forum relate to projects that need to be able to coordinate activities between a PC and the camera. So ptp support is a lot more than just an interesting coding concept - there is as strong interest and demand for the capability.   And as that capability will apparently not be available in any other hacks, that just leaves CHDK.

That is pretty much how I do my shooting.  My cameras are in a rig and tethered to my netbook.  I use PTP for setting up the cameras, taking the shots, downloading and deleting images,...  I also use chdkptp to determine what the best camera settings are for each new setup.  I would certainly miss it if this functionality was removed.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / June / 2013, 15:06:44
I agree about YUV. It's a bit of a pity having done the work
Well, my assumption about it turned out to be not true - it's not available in every camera anyway. Seeing ML's progress with EDMACs, this may change one time in the future.

I've removed the PT_ hooks along with the imagesavecomplete logic and YUV support. I've left some parts of this commented in case we want to use it later. I think the imagesavecomplete stuff and the PT hooks might be useful at some point in the future, but they don't need to be done to finish the remote capture stuff.

I also split the filewrite code into separate files. I have built all the affected cameras but only tested a540 and d10 of course.
Thanks for doing all this work. My a470 also works, including dng.
Quote
Splitting the filewrite code into it's own file does appear to resolve the literal pool issues.
I think that too large contiguous blocks of naked asm functions cause this kind of error.

The code in filewrite.c and remotecap.c is still kind of messy. The most irritating part is the huge number of #ifdef's, but I have no idea how to get rid of those.
Title: Re: CHDK PTP interface
Post by: nafraf on 09 / June / 2013, 15:31:55
I also split the filewrite code into separate files. I have built all the affected cameras but only tested a540 and d10 of course.
I tested on a495(100f) and a810(100d), it works.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 16:08:26
]I think that too large contiguous blocks of naked asm functions cause this kind of error.
I agree. I suspect older versions of GCC are not smart enough to put pools between functions, while the new  ones are.
Quote
The code in filewrite.c and remotecap.c is still kind of messy. The most irritating part is the huge number of #ifdef's, but I have no idea how to get rid of those.
Yes, agreed. Splitting is only a first step. Somehow the ifdefs and variables need to be cleaned up, but it's not obvious how.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 17:00:43
My current thinking for handling DNG

- DNG header is an option like raw and jpeg. This is independent from the CHDK menu DNG option, and at the protocol level, independent of whether raw is requested.
- No thumbnail is included, but header is generated normally (as if there were a 128x96 thumb). Client can create a thumb or blank data.
- Raw data is always returned in native byte order, no bad pixel patching etc
- Client is responsible for constructing a valid DNG if desired.
- If a sub-image is requested, the client can adjust the header, or pad the image to full size.

This keeps the options and protocol very simple, and minimizes overhead on the camera side. It requires more work in the client code, but it feels like the right way to do it.

Issues:
- Need to ensure the dng module gets loaded if needed, and preferably unloaded when no longer needed. It seems like the logical place to do this is when the option is set, but loading/unloading the module for very shot is undesirable.
- DNG version of the header? If the DNG option is independent of the menu, it seems like this should be set explicitly as well. It would be tempting to just pick one, but I think we might regret that later.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / June / 2013, 18:39:11
- DNG header is an option like raw and jpeg. This is independent from the CHDK menu DNG option, and at the protocol level, independent of whether raw is requested.
Makes sense, no separate state variable needed.
Quote
- No thumbnail is included, but header is generated normally (as if there were a 128x96 thumb). Client can create a thumb or blank data.
- Raw data is always returned in native byte order, no bad pixel patching etc
- Client is responsible for constructing a valid DNG if desired.
- If a sub-image is requested, the client can adjust the header, or pad the image to full size.
This will require work on the dng module - create_dng_header() is not suitable for this, unless it gets changed. Making a copy of it would again create maintainability problems.

Quote
This keeps the options and protocol very simple, and minimizes overhead on the camera side. It requires more work in the client code, but it feels like the right way to do it.
An additional downside is that whoever implements a new client, may not feel like messing with this - but at least headerless RAW will always be available.

Quote
Issues:
- Need to ensure the dng module gets loaded if needed, and preferably unloaded when no longer needed. It seems like the logical place to do this is when the option is set, but loading/unloading the module for very shot is undesirable.
The module's unload checker currently bases its decision on the two RAW related config values. What else should it check when rc is involved? Play mode? Timeout? USB presence?
Quote
- DNG version of the header? If the DNG option is independent of the menu, it seems like this should be set explicitly as well. It would be tempting to just pick one, but I think we might regret that later.
Bad pixel treatment* depends on this, so it does matter which version is chosen. I don't think that this(*) task belongs to the client side. You wrote above that "no bad pixel patching". Hmmm. That's DNG 1.3

The other way of completing RAW/DNG could be:
DNG and its version is sent as an option (these bits would need to be treated differently, not as another data type of course). This would require a ptp-local state variable (where should these be kept?). Leave create_dng_for_ptp() almost as it is now (byte reversal and badpixel patching would become optional). In case of partial raw, the client patches the header.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 19:55:36
In chdkptp changeset 350 (http://trac.assembla.com/chdkptp/changeset/350/trunk) I've moved the handling of chunks into lua. This is in preparation for changing DNG, but the protocol isn't changed yet.

I would like to know if this works on the cameras that require seek in the jpeg chunks.

If someone with one of these cameras can show me the output of
Code: [Select]
set cli_verbose=2
rs -f=3
that would be helpful.

This will require work on the dng module - create_dng_header() is not suitable for this, unless it gets changed. Making a copy of it would again create maintainability problems.
I think it will be fairly simple to make create_dng_header() take some options.

Quote
An additional downside is that whoever implements a new client, may not feel like messing with this - but at least headerless RAW will always be available.
and sample code will be available in chdkptp, though likely split between C and Lua which may not be clear to many users.

Quote
-The module's unload checker currently bases its decision on the two RAW related config values. What else should it check when rc is involved? Play mode? Timeout? USB presence?
Yes, this is the question. USB present seems like the most logical, but we really want to know if there is a USB connection, not USB power. A timeout that resets whenever a DNG remote shoot is requested should be fairly simple.

Quote
Bad pixel treatment* depends on this, so it does matter which version is chosen. I don't think that this(*) task belongs to the client side. You wrote above that "no bad pixel patching". Hmmm. That's DNG 1.3
My proposal is they get pure raw data + a DNG header, not DNG data. Since the client is responsible for reversing, it could just as easily patch badpixels too.

That said, I guess if client patches the badpixels, then a 1.3 would load just fine in most programs, and the opcodes would be just be ignored or have no effect.  So maybe just forcing 1.3 is fine.
Quote
The other way of completing RAW/DNG could be:
DNG and its version is sent as an option (these bits would need to be treated differently, not as another data type of course). This would require a ptp-local state variable (where should these be kept?). Leave create_dng_for_ptp() almost as it is now (byte reversal and badpixel patching would become optional). In case of partial raw, the client patches the header.
Yes, I thought about a few variants of this, but they all seemed to end up messy.
Title: Re: CHDK PTP interface
Post by: nafraf on 09 / June / 2013, 20:04:39
In chdkptp changeset 350 (http://trac.assembla.com/chdkptp/changeset/350/trunk) I've moved the handling of chunks into lua. This is in preparation for changing DNG, but the protocol isn't changed yet.

I would like to know if this works on the cameras that require seek in the jpeg chunks.

If someone with one of these cameras can show me the output of
Code: [Select]
set cli_verbose=2
rs -f=3
that would be helpful.
Code: [Select]
connected: Canon PowerShot A810, max packet size 512
con> set cli_verbose=2
con> rs -f=3
ERROR: not in rec mode
con 1> rec
con 2> rs -f=3
got name IMG_0042
rcgetfile IMG_0042.raw 1
rcgetchunk IMG_0042.raw 1
rcgetchunk size:1536 offset:nil last:false
rcgetchunk IMG_0042.raw 1
rcgetchunk size:36864 offset:nil last:false
rcgetchunk IMG_0042.raw 1
rcgetchunk size:24724224 offset:nil last:true
rcgetfile IMG_0042.jpg 0
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1042944 offset:17920 last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:1060864 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:993297 offset:nil last:false
rcgetchunk IMG_0042.jpg 0
rcgetchunk size:17920 offset:0 last:true
With -f=1 jpeg file is fine. 
With -f=2 raw is corrupted
With -f=3 raw is corrupted, jpeg is corrupted (magenta)

RAW was disabled, now it works.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 20:48:01
Thanks nafraf.

It turns out the raw disabled issue happens due to a module loading problem. The dng module will be autoloaded with
Code: [Select]
libdng->capture_data_for_exif();
but
Code: [Select]
int _module_can_unload()
{
    return (running == 0) && ((conf.save_raw == 0) || (conf.dng_raw == 0));
}
will cause it to unload right away if raw isn't on in the menu.

So we need to address this issue anyway, even without my dng proposal.

Alternately, we could just require raw to be enabled, and fail init_remotecap if it isn't, but that seems pretty ugly. I wouldn't want to set it in the config there, since it would change the users saved values unless we also save and restore it...
Title: Re: CHDK PTP interface
Post by: philmoz on 09 / June / 2013, 21:16:09
Thanks nafraf.

It turns out the raw disabled issue happens due to a module loading problem. The dng module will be autoloaded with
Code: [Select]
libdng->capture_data_for_exif();
but
Code: [Select]
int _module_can_unload()
{
    return (running == 0) && ((conf.save_raw == 0) || (conf.dng_raw == 0));
}
will cause it to unload right away if raw isn't on in the menu.

So we need to address this issue anyway, even without my dng proposal.

Alternately, we could just require raw to be enabled, and fail init_remotecap if it isn't, but that seems pretty ugly. I wouldn't want to set it in the config there, since it would change the users saved values unless we also save and restore it...

In the current raw code:
Code: [Select]
    if (conf.save_raw && conf.dng_raw && is_raw_enabled())
    {                             
        libdng->capture_data_for_exif();
    }

So capture_data_for_exif is only called when raw & dng are enabled - so module unloading doesn't happen and isn't an issue.

If you want to use raw & dng without enabling it in the normal manner, you need to provide some other flag to the dng module to stop it unloading.

You also need to take care of the modes where raw/dng doesn't work - currently handled by the is_raw_enabled() call above.

Phil.
Title: Re: CHDK PTP interface
Post by: nafraf on 09 / June / 2013, 21:18:33
Two patches to add remote capture support for a1300 and a4000.
- a1300 (tested on A810 100d) - this includes small change to a810 boot.c, to use task_FileWrite name in taskHook()
- a4000 (tested on A4000 101b by rkomar)



Title: Re: CHDK PTP interface
Post by: reyalp on 09 / June / 2013, 21:57:13
So capture_data_for_exif is only called when raw & dng are enabled - so module unloading doesn't happen and isn't an issue.
Right, and the remotecap variant is called in a remotecap.c remotecap_raw_savefile and doesn't do this, which is the problem.

On a semi-related note, the whole business of having the remotecap have it's own butchered variant of raw_savefile called from capt_seq also bothers me. raw_savefile does more than just saving, it's involved in bracketing, shot histogram, curves etc.  Not all of those make sense for remotecap, but it's an ugly duplication.
Quote
You also need to take care of the modes where raw/dng doesn't work - currently handled by the is_raw_enabled() call above.
That's a good point. Which leads to the question of whether remotecap raw should honor or ignore the "raw exceptions" settings. I would say no, but that means that is_raw_enabled() would need to be split into mandatory and preference conditions.

OTOH, if someone uses remotecap for raw and gets garbage, then maybe that's their problem...

edit:
Two patches to add remote capture support for a1300 and a4000.
- a1300 (tested on A810 100d) - this includes small change to a810 boot.c, to use task_FileWrite name in taskHook()
- a4000 (tested on A4000 101b by rkomar)
Thanks. Added in changeset 2853 (http://trac.assembla.com/chdk/changeset/2853).
Title: Re: CHDK PTP interface
Post by: hwntw on 10 / June / 2013, 06:26:41
I do my capturing hand held. I also rarely take 2000 RAW shots at a sitting so my savings of microseconds will not be great. Fascinated by these coding exercises, tho'.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / June / 2013, 01:10:02
Quote
DNG header is an option like raw and jpeg. This is independent from the CHDK menu DNG option, and at the protocol level, independent of whether raw is requested.
I've started implementing this in chdk changeset 2861 (http://trac.assembla.com/chdk/changeset/2861) chdkptp changeset 352 (http://trac.assembla.com/chdkptp/changeset/352/trunk)

This is very much work in progress, but it does produce a valid DNG file with -f=6

I still think this is the right direction.

Some things left to do
* fix the module load / unload stuff, currently raw and dng must be enabled in menu
* add option to the create_dng_header so it doesn't pad or allocate space for the thumb, force version
* handle sub-images on the client, by padding the data to full size
* create thumbnail on the client
Title: Re: CHDK PTP interface
Post by: srsa_4c on 12 / June / 2013, 10:47:30
I still think this is the right direction.
I'm sorry if I caused the impression that I'm objecting against this rework. I'm fine with the changes.
BTW
On a semi-related note, the whole business of having the remotecap have it's own butchered variant of raw_savefile called from capt_seq also bothers me. raw_savefile does more than just saving, it's involved in bracketing, shot histogram, curves etc.  Not all of those make sense for remotecap, but it's an ugly duplication.
I agree, I just wanted to spare changing another source file when I did that. Wasn't even sure about which calls to keep in that function.
On a separate note, you can correct my comments and variable names in case they're confusing or inappropriate (there are quite a few misspelled words / sentences in the CHDK source, I suspect that they are not corrected due to respect :) ).
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / June / 2013, 13:12:03
I'm sorry if I caused the impression that I'm objecting against this rework. I'm fine with the changes.
No, you didn't. I just meant it still seems ok after I started coding it. Sometimes ideas that sound good in theory end up being ugly when you actually try to implement them.
I agree, I just wanted to spare changing another source file when I did that. Wasn't even sure about which calls to keep in that function.
Ok, that makes sense. I will look at integrating it in raw_savefile, though there's some weird cases there too.
Quote
On a separate note, you can correct my comments and variable names in case they're confusing or inappropriate (there are quite a few misspelled words / sentences in the CHDK source, I suspect that they are not corrected due to respect :) ).
Probably more lazyness than respect ;) I did change notlastchunk to morechunks, because negatives in variable names make my head spin...
Title: send PTP commands over usb?
Post by: tommykay on 15 / June / 2013, 13:11:21
If this question is in the wrong place, please forgive me.

I want to sent PTP over USB to control focus, zoom, ISO, etc. My plan is to use an Arduino host shield over USB. Is that possible?   I am planning to shoot time lapse by controlling various camera settings over USB.

I could do all this with pre2007 powershots, but not since then.  I want to use a modern camera like the S100 for the increased ISO.

If there is a better place to ask this question, just let me know.
Title: Re: send PTP commands over usb?
Post by: waterwingz on 15 / June / 2013, 13:14:23
I want to sent PTP over USB to control focus, zoom, ISO, etc. My plan is to use an Arduino host shield over USB. Is that possible?   I am planning to shoot time lapse by controlling various camera settings over USB.
Yes - its very possible.  Although you might be able to do everything you need with a CHDK script and save yourself a lot of work.
Title: Re: send PTP commands over usb?
Post by: tommykay on 15 / June / 2013, 19:35:01
I want to sent PTP over USB to control focus, zoom, ISO, etc. My plan is to use an Arduino host shield over USB. Is that possible?
Yes - its very possible.

Could you suggest a beginning point to investigate how to use PTP with CHDK? This thread is four years old, but I can't find any tutorials or detailed instructions anywhere.

What CHDK build is recommended for this? What is the best source of information on how to pursue this?

Thanks!
Title: Re: send PTP commands over usb?
Post by: waterwingz on 15 / June / 2013, 19:49:17
Could you suggest a beginning point to investigate how to use PTP with CHDK?
http://chdk.wikia.com/wiki/PTP_Extension (http://chdk.wikia.com/wiki/PTP_Extension)

Quote
This thread is four years old, but I can't find any tutorials or detailed instructions anywhere.
Technically,  this thread has been running for four years. The information in the recent posts is current.

Quote
What CHDK build is recommended for this? What is the best source of information on how to pursue this?
The latest build of the dev trunk is usually best - but there is a dedicated build for dev testing as well.
http://chdk.setepontos.com/index.php?topic=6231.0 (http://chdk.setepontos.com/index.php?topic=6231.0)
reyalp will probably chime in shortly with some good suggestions so I'll defer on posting further ...
Title: Re: send PTP commands over usb?
Post by: reyalp on 15 / June / 2013, 19:58:15
Could you suggest a beginning point to investigate how to use PTP with CHDK? This thread is four years old, but I can't find any tutorials or detailed instructions anywhere.
In addition to the wiki page waterwingz linked, here are some other useful references

The canonical reference for the protocol is in ptp.h:
http://trac.assembla.com/chdk/browser/branches/release-1_1/core/ptp.h (http://trac.assembla.com/chdk/browser/branches/release-1_1/core/ptp.h) (1.1 stable)
http://trac.assembla.com/chdk/browser/trunk/core/ptp.h (http://trac.assembla.com/chdk/browser/trunk/core/ptp.h) (1.2 trunk)

Documentation of PTP specific lua functions and issues http://chdk.wikia.com/wiki/Lua/PTP_Scripting (http://chdk.wikia.com/wiki/Lua/PTP_Scripting)

I maintain an example client application which can be found at: https://www.assembla.com/spaces/chdkptp/wiki (https://www.assembla.com/spaces/chdkptp/wiki)

Another user has previously implemented at least some of the protocol for Arduino http://chdk.setepontos.com/index.php?topic=6969.0 (http://chdk.setepontos.com/index.php?topic=6969.0)

Quote
What CHDK build is recommended for this?
The 1.1 stable build should work fine. The 1.2 trunk should also work, but doesn't currently add any additional PTP functionality.
Title: Re: CHDK PTP interface
Post by: tommykay on 15 / June / 2013, 21:03:36
Thanks, waterwingz and reyalp! I'm digging into it right now.

Tom
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / June / 2013, 02:53:40
I've made some progress on the chdkptp side of the remote capture stuff.  As of changeset 374, chdkptp supports sub-images with dng. The area outside the requested range is filled with whitelevel.

I've changed the syntax of the remoteshoot command a bit, so you can now request the dng header and raw as separate files or combined into a DNG.
-jpg  get jpeg, default if no other options given
-dng get raw data, dng header, combine into a valid dng file
-raw get raw framebuffer data. ignored if -dng is present
-dnghdr get dng header as a standalone file, ignored if -dng is present

One oddity I noticed is that the jpeg code will sometimes return a zero size chunk as the last chunk. This isn't specifically a problem by itself, but I'm not sure how it crops up.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / June / 2013, 15:05:54
One oddity I noticed is that the jpeg code will sometimes return a zero size chunk as the last chunk. This isn't specifically a problem by itself, but I'm not sure how it crops up.
Looks like a check inside filewrite_get_jpeg_chunk() was not complete. Following patch should correct that.
Code: [Select]
Index: platform/generic/filewrite.c
===================================================================
--- platform/generic/filewrite.c (revision 2877)
+++ platform/generic/filewrite.c (working copy)
@@ -34,6 +34,9 @@
             return 0; // last chunk
         }
     }
+    else {
+        return 0; // last chunk
+    }
     return 1; // not last chunk
 #else
     if ( jpeg_chunks == NULL ) { //do we have a valid queue?
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / June / 2013, 21:38:18
Thanks srsa, I added that fix.

In chdkptp changeset 375 I added an option to the rs command to shoot in continuous mode. This is mainly just to test that the remote capture code works in continuous mode. It appears to on both my cameras.

Use
rs -cont=<n>
to shoot N shots. You must set the camera to continuous mode in the canon UI yourself. It should work with any combination of raw/dng and jpeg.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / June / 2013, 22:43:23
In changeset 2896 (http://trac.assembla.com/chdk/changeset/2896/branches/ptp-remote-capture-test4) I moved the raw / dng part out of capt_seq into raw.c (raw_process, formerly raw_savefile)

There's still plenty of ugly but I think it's an improvement overall.

Bracketing, curves, manual bad-pixel should all happen normally for remote cap now. You can now use the continuous mode remotecap with bracketing if you want.

Trying to do DNG badpixel generation or raw develop will make remote capture raw/dng fail, but I think that's OK.

This was the last significant code reorganization I wanted to do before merging to the trunk.

One bit of script api / protocol that I'm still not sure about is how file writing is handled:

Currently, if any remote cap options are used, all writing to the card is suppressed, except for jpeg on cameras that don't have filewrite task (edit: or canon raw on cams that have it). Being able to turn off jpeg is something that has been requested in the past, unrelated to remote capture. So it might be tempting to make it an option and/or scriptable setting.

I can also imagine situations where someone would want to use remoteshoot for some data and keep some on the card. Right now, if you request only dng header, all the image data is thrown away. OTOH, maybe people who data on the card should just use shoot+download?

Another minor thing:
The timeouts for the camera waiting for the PTP client to fetch data are currently hard coded. Does this need to be adjustable?


There's also a some non-PTP specific stuff I ran into while mucking around in the raw code, but I'll start another thread for that.

edit:
One more thing I've been thinking about: Is it worth sending the filename? It would be simpler to just send the exposure number as a param with each chunk (or as part of the RemoteCaptureIsReady response?), and that's essentially all we are using right now anyway. It would include the directory name/number, but that can be obtained lua if someone really wants it.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 24 / June / 2013, 19:05:31
You can now use the continuous mode remotecap with bracketing if you want.
I was afraid of continuous mode when remote shooting, so I never even tried that before. Now, after seeing what a dryos r51 camera is doing, it looks like there's a caching layer between filesystem operations (open, close, read, write) and real card accesses. The whole thing can change if Canon decides to cache the raw data before/during processing, which is not currently happening on P&S models AFAIK.

Quote
This was the last significant code reorganization I wanted to do before merging to the trunk.
Thanks for doing that.

Quote
Being able to turn off jpeg is something that has been requested in the past, unrelated to remote capture. So it might be tempting to make it an option and/or scriptable setting.
Makes sense, although I think that throwing away the jpeg in favour of dng is not a good idea for the average shooter.

Quote
I can also imagine situations where someone would want to use remoteshoot for some data and keep some on the card.
I think there may be problems with simultaneous sd card AND usb transfer (in a series of early tests nafraf's a810 was acting unstable when I managed to enable file operations while remote shooting on that test build), so we should avoid that.
Quote
Right now, if you request only dng header, all the image data is thrown away. OTOH, maybe people who data on the card should just use shoot+download?
That should still work, so yes. I think Canon's official remote shooting support included both scenarios (remote file only, remote+local file).

Quote
The timeouts for the camera waiting for the PTP client to fetch data are currently hard coded. Does this need to be adjustable?
I can imagine situations where it could be needed (slow usb host, slow transfer, 16MP raw + jpeg).

Quote
One more thing I've been thinking about: Is it worth sending the filename? It would be simpler to just send the exposure number as a param with each chunk (or as part of the RemoteCaptureIsReady response?), and that's essentially all we are using right now anyway. It would include the directory name/number, but that can be obtained lua if someone really wants it.
Makes sense, one round trip less. I originally thought that this task is responsible for writing native raw too, but that assumption turned out to be false (according to an experiment done by SticK last year).

Once these changes get into trunk, there are some other possible uses for that filewritetask hook (I have collected some ideas here (http://chdk.wikia.com/wiki/User:Srsa_4c/FileWriteTask_possible_uses) - note that the list is old).
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / June / 2013, 20:41:06
You can now use the continuous mode remotecap with bracketing if you want.
I was afraid of continuous mode when remote shooting, so I never even tried that before. Now, after seeing what a dryos r51 camera is doing, it looks like there's a caching layer between filesystem operations (open, close, read, write) and real card accesses. The whole thing can change if Canon decides to cache the raw data before/during processing, which is not currently happening on P&S models AFAIK.
Of course. I was a bit surprised that continuous mode worked, but it does on my cams at least. I think in general it should work with raw, because we hold up the whole shooting process until it's done. jpeg... I'm less sure.
Quote
Quote
Being able to turn off jpeg is something that has been requested in the past, unrelated to remote capture. So it might be tempting to make it an option and/or scriptable setting.
Makes sense, although I think that throwing away the jpeg in favour of dng is not a good idea for the average shooter.
Agreed. To save space, you could just use a small size / low quality jpeg. Time saved by skipping jpeg isn't very significant. People have asked for it a few times, but maybe it doesn't need to be added with remotecap.

Quote
I can imagine situations where it could be needed (slow usb host, slow transfer, 16MP raw + jpeg).
Good point. I'll add this. I think one timeout value for all the phases is sufficient.

Quote
Quote
One more thing I've been thinking about: Is it worth sending the filename? It would be simpler to just send the exposure number as a param with each chunk (or as part of the RemoteCaptureIsReady response?), and that's essentially all we are using right now anyway. It would include the directory name/number, but that can be obtained lua if someone really wants it.
Makes sense, one round trip less.
On the other hand, nothing requires the client to ask for the file name.
edit: but the current code doesn't actually give you the full path (since the jpeg name isn't available yet when we do raw), so I'm going to take it out.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 30 / June / 2013, 18:53:00
@reyalp

I'm a bit concerned about calling get_target_file_num() directly in PTP_CHDK_RemoteCaptureIsReady. Some cameras have a flaky counter (or the implementation of getting that number is not optimal), file numbering may become less reliable (my method was to store the counter at the start of the raw hook).

Tried to play with rs a bit (a470), it's still working, even in continuous mode.
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / June / 2013, 19:25:43
I'm a bit concerned about calling get_target_file_num() directly in PTP_CHDK_RemoteCaptureIsReady. Some cameras have a flaky counter (or the implementation of getting that number is not optimal), file numbering may become less reliable (my method was to store the counter at the start of the raw hook).
You're right, it probably shouldn't call this when no datatypes are available yet. I'll change this in the next version.

Calling after the first one becomes available should be OK, since that always has to happen after the raw hook is called.

I'm currently in process of re-organizing the hook wait / timeout / cancel code, since after I implemented the adjustable timeout I found the behavior wasn't well defined. I'll probably break something...

Another thought:
PTP_CHDK_RemoteCaptureIsReady currently returns a special value if you call when no target is selected. I wonder if it should use PTP_RC_GeneralError instead. On the other hand, remotecap can get turned off by various errors, so maybe it should be different.
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / June / 2013, 22:38:16
I'm currently in process of re-organizing the hook wait / timeout / cancel code, since after I implemented the adjustable timeout I found the behavior wasn't well defined. I'll probably break something...
This is done (or at least started...) in changeset 2917 (http://trac.assembla.com/chdk/changeset/2917)

I've tried to make it so any error condition including timeouts will free all the hooks, clear all the chunk types, and clear the remotecap settings. I also tried to clean up the logic in PTP_CHDK_RemoteCaptureGetData a bit.

One thing that is not very well defined is what happens if the timeout happens in the middle of a download. What will happen is that the (spytask/filewrite) hook will be unblocked as soon as the timeout expires, and continue on it's way. The ptp task will continue transferring data, which could potentially get corrupted. There will be no error status, unless the client expected to get more chunks or data types. I'm not really sure how we could make this safe. I don't think this is likely to crash or corrupt memory on the cam, but I could be wrong.

We do want the timeout to be possible even if the transfer has started, because the client could lose connection or crash etc. We might be able to make the ptp command return an error status, but it would be convoluted.

There's a fair chance I broke CAM_FILEWRITETASK_SEEKS (dryos >= r50) cams. I'd appreciate if anyone with those cams can test.

Some things to check

rs with the various format options. Be sure to check the actual jpeg and dng to make sure they are valid.

Timeout error status:
Code: [Select]
=set_remotecap_timeout(10)
rs
This should shoot a shot without any delay and return something like
ERROR: remote shoot error

Timeout, data not downloaded
Code: [Select]
=set_remotecap_timeout(10000)
=init_remotecap(1) ; shoot()
This should shoot, and then wait 10 seconds, doing whatever LED activity would be normal when writing a jpeg.

Cancel remotecap from script:
Code: [Select]
=set_remotecap_timeout();init_remotecap(1);press('shoot_half');repeat sleep(10) until get_shooting();click('shoot_full');sleep(3000);init_remotecap(0)
This should shoot, wait 3 seconds and then finish. No files should be written.

Note that set_remotecap_timeout state is global, and stays set until you change it. To reset back to default, you can use set_remotecap_timeout() with no arguments.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 02 / July / 2013, 12:10:36
Calling after the first one becomes available should be OK, since that always has to happen after the raw hook is called.
This counter is currently only used for raw (in vanilla CHDK), and is probably 'optimized' for that. I think that on at least a few Vx ports a delay of a few tens of msecs will produce a much less reliable result (you can take a look at the respective platform function of my ports for example (a410..) and the note beside it)
Code: [Select]
long get_file_next_counter() { //looks like this hack is needed for old vxworks
    return ((get_file_counter()>>4)+1)<<4;
}
You could put in a duplicate file (or counter) check in the client - at least for debug reasons.
Quote
PTP_CHDK_RemoteCaptureIsReady currently returns a special value if you call when no target is selected. I wonder if it should use PTP_RC_GeneralError instead. On the other hand, remotecap can get turned off by various errors, so maybe it should be different.
Since errors usually produce PTP_RC_GeneralError, maybe this one should also. Would it be possible (at some point) to return a more descriptive error sub-code?

The ptp task will continue transferring data, which could potentially get corrupted. There will be no error status, unless the client expected to get more chunks or data types. I'm not really sure how we could make this safe. I don't think this is likely to crash or corrupt memory on the cam, but I could be wrong.
I don't have a clear overview over this ATM, but:
In case of jpeg, the chunk descriptor structure is part of the filewritetask's message structure. If the task continues, it may get corrupted. We could either make a copy of it and use that, or we could plant some kind of an 'emergency brake' ... uhmm ... somewhere. We never send information about the file size, so it's up to the user to recognize a truncated file...

Can't help with r50+, but your examples appear to work on the a470.

edit:
You have a comment in remotecap.c:
remotecap_jpeg_chunks_done(); // make jpeg_chunks NULL, immediately. TODO needed?
This was (and probably is) needed for r50+ cameras, due to multitasking issues (can't be done from another task, because it's too late by then).
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / July / 2013, 13:18:44
Calling after the first one becomes available should be OK, since that always has to happen after the raw hook is called.
This counter is currently only used for raw (in vanilla CHDK), and is probably 'optimized' for that. I think that on at least a few Vx ports a delay of a few tens of msecs will produce a much less reliable result (you can take a look at the respective platform function of my ports for example (a410..) and the note beside it)
It's also exposed in script as get_exp_count(). But you've convinced me, I'll save it in the raw hook so it will behave the same as raw.
Quote
Since errors usually produce PTP_RC_GeneralError, maybe this one should also. Would it be possible (at some point) to return a more descriptive error sub-code?
Good idea. Something to look into.

Quote
I don't have a clear overview over this ATM, but:
In case of jpeg, the chunk descriptor structure is part of the filewritetask's message structure. If the task continues, it may get corrupted. We could either make a copy of it and use that, or we could plant some kind of an 'emergency brake' ... uhmm ... somewhere. We never send information about the file size, so it's up to the user to recognize a truncated file...
The current code gets the address and size once for each chunk. If the timeout expires while that chunk is being transferred, the transfer will continue using that address/size (which may no longer contain valid data). If the chunk wasn't the last chunk, it will get an error because the remotecap state has been cleared.

Quote
Can't help with r50+, but your examples appear to work on the a470.
Nafraf reported it worked on sx160. But I'm thinking that the situation above may have additional problems, because there could be calls to the filewrite hook after the remotecap state is cleared... but maybe it's ok because the ignore write flag is still set? I'll have to look at this again.

Quote
You have a comment in remotecap.c:
remotecap_jpeg_chunks_done(); // make jpeg_chunks NULL, immediately. TODO needed?
This was (and probably is) needed for r50+ cameras, due to multitasking issues (can't be done from another task, because it's too late by then).
I'm not sure I follow. This would get called from the ptp task at the end of it's chunk. Meanwhile, filewritetask is waiting. When filewritetask is finished waiting, it will immediately set jpeg_chunks null. I guess there could be another call from ptp before it gets there?

Thanks very much for looking at these changes. I didn't really want to change this much code again, but I started trying to simplify things and then realized I hadn't understood how it was really working before...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 02 / July / 2013, 14:05:44
The current code gets the address and size once for each chunk. If the timeout expires while that chunk is being transferred, the transfer will continue using that address/size (which may no longer contain valid data). If the chunk wasn't the last chunk, it will get an error because the remotecap state has been cleared.
OK then, I thought that it can't halt in the middle of a certain datatype. In this case, the user will get corrupted/truncated file.

Quote
Nafraf reported it worked on sx160.
That's good :)
Quote
But I'm thinking that the situation above may have additional problems, because there could be calls to the filewrite hook after the remotecap state is cleared... but maybe it's ok because the ignore write flag is still set?
To prevent confusing crashing the camera, writes should not be re-enabled in the middle of the 'jpeg save' operation. I think the 'current_write_enabled' flag should take care of this, as it only gets cleared when all data chunks are 'written' from the filewritetask's perspective.

Quote
I'm not sure I follow. This would get called from the ptp task at the end of it's chunk. Meanwhile, filewritetask is waiting. When filewritetask is finished waiting, it will immediately set jpeg_chunks null. I guess there could be another call from ptp before it gets there?
Can't recall what exactly happened, but this (https://trac.assembla.com/chdk/changeset/2243) change was the solution (the commit is a bit noisy).
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / July / 2013, 16:51:37
Thanks for the comments
Quote
In this case, the user will get corrupted/truncated file.
Yes. Not good, but better than crashing. I'm tempted to add a timeout flag, so we can check after the send_data is complete and set a ptp error. Or maybe check if the data available flag is cleared? I'm worried it will get too complicated...
Quote
I think the 'current_write_enabled' flag should take care of this, as it only gets cleared when all data chunks are 'written' from the filewritetask's perspective.
Yeah, I think that is right.

Another concern:
Can the raw hook be entered for the next shot before the jpeg from the previous is downloaded? I haven't set up a test for this but it seems like it might be possible, depending on how much overlap canon firmware allows (and might change between cameras or shooting modes). A check for remotecap_get_available_data_type at the start of the raw hook should catch this, but the correct response is not clear. Maybe wait the timeout length for it to clear? That should guarantee any previous request had finished or timed out. If timed out, the remote cap settings would have been cleared by the timeout, so the new shot won't use remotecap.
Title: Re: CHDK PTP interface
Post by: nafraf on 03 / July / 2013, 00:25:18
I tested on A810, without flash, remote capture works.  If flash enabled it returns timeout.  Same behavior on sx160. It seems that if flash is not ready, capture is interrupted.
Code: [Select]
connected: Canon PowerShot A810, max packet size 512
con> rec
con 1> =set_prop(require("propcase").FLASH_MODE,2)
con 2> rs -jpg
con 5> =set_prop(require("propcase").FLASH_MODE,1)
con 6> rs -jpg
ERROR: timed out
A495 works without problems in both cases.  Am I missing something?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / July / 2013, 13:45:06
I tested on A810, without flash, remote capture works.  If flash enabled it returns timeout.  Same behavior on sx160. It seems that if flash is not ready, capture is interrupted.
I had similar experience on some cameras, see http://chdk.setepontos.com/index.php?topic=4338.msg95368#msg95368 (http://chdk.setepontos.com/index.php?topic=4338.msg95368#msg95368) . I'll re-check with one of them.
Still happens on the a410.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 03 / July / 2013, 15:32:16
Can the raw hook be entered for the next shot before the jpeg from the previous is downloaded?
This should probably be tested. Cameras with 2 raw buffers could in theory take advantage of the extra buffer, but... wouldn't that kind of parallelism already cause problems with CHDK raw/dng? We block filewritetask before its "open" stage, so anything that would signal "next shot is available" from there is also blocked. BTW, there are event procedures that could be used for testing (one or more of those around 'completefilewrite').
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / July / 2013, 23:12:39
I tested on A810, without flash, remote capture works.  If flash enabled it returns timeout.  Same behavior on sx160. It seems that if flash is not ready, capture is interrupted.
Does shooting raw/dng without using PTP work in this situation?

How about a (non-ptp) script that just does

Code: [Select]
press('shoot_half')
repeat sleep(10) until get_shooting()
click('shoot_full')

The rs command use something like the above rather than shoot().

shoot() has a shooting_is_flash_ready() check.
but looking back at the old discussion, that wasn't it...
Title: Re: CHDK PTP interface
Post by: Hardware_Hacker on 04 / July / 2013, 04:36:37
ChdkPtp-r330 Demo on Windows Blue Pe [PreView version] is now partly working ... Also See this Post.

http://chdk.setepontos.com/index.php?topic=10256.msg102410#msg102410 (http://chdk.setepontos.com/index.php?topic=10256.msg102410#msg102410)

Happy-Hacking By  H-H
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2013, 17:24:56
Can the raw hook be entered for the next shot before the jpeg from the previous is downloaded?
This should probably be tested. Cameras with 2 raw buffers could in theory take advantage of the extra buffer, but... wouldn't that kind of parallelism already cause problems with CHDK raw/dng? We block filewritetask before its "open" stage, so anything that would signal "next shot is available" from there is also blocked. BTW, there are event procedures that could be used for testing (one or more of those around 'completefilewrite').
I can confirm this happens on both a540 and d10. Both only have a single raw buffer, so I guess this means the final jpeg buffer does not overlap the raw buffer. The canon firmware is happy to start a new exposure before the previous one has finished writing.

The following code demonstrates.
In remotecap.c
Code: [Select]
Index: D:/chdk/remotecap4/core/remotecap.c
===================================================================
--- D:/chdk/remotecap4/core/remotecap.c (revision 2921)
+++ D:/chdk/remotecap4/core/remotecap.c (working copy)
@@ -133,6 +133,16 @@
 extern long hook_raw_size(void); // TODO should use camera_sensor, but see note on size mismatch!
 
 void remotecap_raw_available(char *rawadr) {
+// temp sanity check
+    while(remotecap_get_available_data_type()) {
+        int i;
+        for(i=0; i<10; i++) {
+            started();
+            msleep(250);
+            finished();
+            msleep(250);
+        }
+    }
 // TODO this should probably just be noop if hook doesn't exist
 #ifdef CAM_HAS_FILEWRITETASK_HOOK
     filewrite_set_discard_jpeg(1);
In chdkptp:
Code: [Select]
con 1> rec
con 2> =return init_remotecap(1)
3:return:true
con 3> .shoot(); press('shoot_half'); repeat sleep(10) until get_shooting(); click('shoot_full') sleep(100)
I will add the timeout logic I described earlier.

edit:
done in changeset 2922 (http://trac.assembla.com/chdk/changeset/2922)
Title: Re: CHDK PTP interface
Post by: nafraf on 04 / July / 2013, 19:39:06
Does shooting raw/dng without using PTP work in this situation?
Yes, it works.


Quote
How about a (non-ptp) script that just does

Code: [Select]
press('shoot_half')
repeat sleep(10) until get_shooting()
click('shoot_full')
It does not work. but changing sleep(10) to sleep(500) it works. ???
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2013, 19:56:53
It does not work. but changing sleep(10) to sleep(500) it works. ???

ok, try
Code: [Select]
press('shoot_half')
repeat sleep(10) until (get_flash_ready() and get_shooting())
click('shoot_full')
On my a540 get_flash_ready() only goes true if the flash is enabled and would fire, so "real" usage requires a more complicated check.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 04 / July / 2013, 20:26:57
Code: [Select]
press('shoot_half')
repeat sleep(10) until (get_flash_ready() and get_shooting())
click('shoot_full')
This one works better (using the a410 this time), but still not completely reliable.
I think this issue can be simulated by hand, the camera sometimes fails to notice short shutter presses when flash is involved. It's also camera dependent, happens only rarely on the a470.
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2013, 21:16:38
This one works better (using the a410 this time), but still not completely reliable.
I think this issue can be simulated by hand, the camera sometimes fails to notice short shutter presses when flash is involved. It's also camera dependent, happens only rarely on the a470.
What if you use a
press('shoot_full')
sleep(500)
release('shoot_full')

edit:
I get the same thing on a540. Now I understand the timeout is client timeout, not remotecap timeout
Title: Re: CHDK PTP interface
Post by: srsa_4c on 04 / July / 2013, 21:28:01
What if you use a
press('shoot_full')
sleep(500)
release('shoot_full')
It doesn't shoot (so it's worse than the previous script). It's still the a410, and I'm commanding it through ptp. Increasing the delay increases the success rate (1000 ms sometimes works, 5000ms probably always works...).
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2013, 21:34:56
It doesn't shoot (so it's worse than the previous script). It's still the a410, and I'm commanding it through ptp. Increasing the delay increases the success rate (1000 ms sometimes works, 5000ms probably always works...).
In case it wasn't clear, I meant the above instead of click('shoot_full') in the previous code.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 04 / July / 2013, 21:47:40
In case it wasn't clear, I meant the above instead of click('shoot_full') in the previous code.
I see. That seemed to have increased the success rate, but still tends to fail when it wakes the camera from  'sleep'. I wonder what nafraf's cameras will do.
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2013, 22:06:23
In changeset 2924 (http://trac.assembla.com/chdk/changeset/2924) I made it so a PTP error is generated if timeout occurs while a chunk is being transferred. The resulting file will be corrupt, but at least the client can notice.

Regarding the previous discussion of PTP_CHDK_RemoteCaptureIsReady status when remotecap has not been initialized (or has been cleared by a timeout etc) I've decided to leave it as a status value rather than a PTP error. In changeset 2923 I renamed the constant to PTP_CHDK_CAPTURE_NOTSET to make this distinction clearer. My reasoning is this is something you might want to query as a status, not treat as an error, although it does mean that the treatment of timeouts is a bit weird.

I think this completes all the significant structure / logic / protocol I wanted to do before merging to the trunk. A final cosmetic change is to rename the script functions to *usb_capture* to match the read/write_usb_msg. After that, I'm going to merge it into the trunk unless there are objections.
Title: Re: CHDK PTP interface
Post by: nafraf on 04 / July / 2013, 22:44:37
In case it wasn't clear, I meant the above instead of click('shoot_full') in the previous code.
I see. That seemed to have increased the success rate, but still tends to fail when it wakes the camera from  'sleep'. I wonder what nafraf's cameras will do.
I'm testing with script. 15 shoots on each camera (a810, sx160) 100% worked.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / July / 2013, 02:40:17
Remote capture support merged to trunk in changeset 2927 (http://trac.assembla.com/chdk/changeset/2927).

Any further work on this should be done in the trunk.

Raw/dng capture should work on all cameras, but the jpeg will be saved to the card. To support jpeg and and suppressing jpeg writes, filewritetask needs to be implemented. Patches adding filewrite support for more cameras are welcome. Requests for filewrite support on specific cameras are also welcome.

You will need the chdkptp from the latest svn (r382 or later) to use. I'll release a new snapshot build soon. There are still some things to do on the client, but they don't need to hold up the initial release.

edit:
Apparently I broke the build... working on it

edit:
OK, I guess hook_raw_size went away while I wasn't paying attention.

This means that the workaround in remotecap for the stupidity with a470 having raw size != raw_rows * raw_rowpix is gone.

I suggest we update a470 to use the actual sensor size values from the firmware.
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / July / 2013, 06:32:24
G12 seems ok.

G1X & IXUS310 timeout if flash enabled 90% of the time.

(The flashtest.lua script works on both cameras without any problems.)

Edit:
Problem with flash appears to be twofold.
 - rs_shoot_single (rlibs.lua) is not waiting for get_flash_ready()
 - luaCB_get_flash_ready() is calling shooting_is_flash(); but should be calling shooting_is_flash_ready()

Making these two changes fixes IXUS310 & G1X.
Note sure if the above change to luaCB_get_flash_ready is the right thing to do or if it should be a new function (might break other scripts).

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / July / 2013, 15:57:42
- luaCB_get_flash_ready() is calling shooting_is_flash(); but should be calling shooting_is_flash_ready()
Ah, that makes sense.

Ubasic also uses shooting_is_flash() ....

It looks like this snuck in in changeset 1632, so I'd say we should fix both.

The fact that no one complained probably means it is rarely used.

edit:
Ugh, it gets more complicated:
shooting_is_flash returns:
shooting_get_prop_int(PROPCASE_IS_FLASH_READY), which is what the old ubasic code did.

shooting_flash_is_ready checks more stuff.
Title: Re: CHDK PTP interface
Post by: blackhole on 06 / July / 2013, 16:28:04
Quote
Requests for filewrite support on specific cameras are also welcome.
Can you please make a filewrite support for a590 101b, when you have free time.
-raw and -dng works great.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / July / 2013, 18:05:43
edit:
Ugh, it gets more complicated:
shooting_is_flash returns:
shooting_get_prop_int(PROPCASE_IS_FLASH_READY), which is what the old ubasic code did.

shooting_flash_is_ready checks more stuff.
Checking PROPCASE_IS_FLASH_READY on a540 and D10, it appears to behave pretty much as expected. I would expect there's some situations where the additional checks in shooting_is_flash_ready() are required.

Also,  shooting_is_flash_ready() returns true if the flash is not selected, which is desirable if you are waiting to shoot.

If it were just additional checks, I'd be tempted to add a parameter to get_flash_ready (e.g. default uses current behavior, get_flash_ready(1) uses shooting_is_flash_ready(), but the difference in return logic makes that even uglier.

Since the current get_flash_ready just checks a propcase, removing it wouldn't be a big deal for Lua, whereas shooting_is_flash_ready cannot be replicated in lua.

searching the wiki (using google, I don't trust wiki search) with
site:http://chdk.wikia.com get_flash_ready
only returns reference pages, not actual scripts. Googling without site restriction also doesn't turn up a whole lot.

 :'(
Title: Re: CHDK PTP interface
Post by: philmoz on 06 / July / 2013, 18:59:32
Ugh, it gets more complicated:
shooting_is_flash returns:
shooting_get_prop_int(PROPCASE_IS_FLASH_READY), which is what the old ubasic code did.

shooting_flash_is_ready checks more stuff.

The 'shoot' command uses 'shooting_is_flash_ready' which is how I found the problem.

Phil.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / July / 2013, 23:16:11
In changesets trunk 2944 and 2945, I've changed the way alt mode is handled when running PTP scripts.

Previously, it would just set kbd_blocked. This is required to allow sending key presses (e.g. click('set')) but it isn't full alt mode, and left the camera in a state where you need to press alt once to get canon firmware keys, or twice to get back to real alt mode.

I changed to use enter_alt() and, if the camera wasn't in alt when the script started, use exit_alt() when the script ends. Calling enter_alt() or exit_alt() from script overrides the saved state, so that when the script exits it will stay in whatever state the script set.

Aside form fixing the issue mentioned above, the main visible impact is that the alt indicator will flash when you run a script.
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / July / 2013, 22:20:43
Regarding this from the 1.2 release thread
Quote
* Make PTP not use 50% of available RAM for buffer if there's lots available.
I did some investigation. Conclusion is basically that download performance is better with larger buffer size, up to at least 1mb or so. I tested both downloading a DNG file (which does file IO in units of the "buffer size") and using GetMemory (which still sends in "buffer size" units, even though it doesn't do any actual buffering)

Attached patch is the code I used for testing.

To time, i used the following in chdkptp
Code: [Select]
set cli_xferstats=true
set cli_time=true
To adjust the (max) size of the buffer
Code: [Select]
=set_usb_buf_max(1024*1024)
note it will still be capped at 1/2 ram, so you need to check how much you have free. For 1mb or more, exmem is recommended...

to test download speed
Code: [Select]
d -nolua DCIM/100CANON/CRW_nnnn.DNG

to test rmem speed
Code: [Select]
!con:getmem(0x1900,1024*1024)

Some results on D10
DNG file (18,801,888 ),
32k buf = 4.8 sec
64k buf = 4.2 sec
128k buf = 3.8 sec
512k buf = 3.5 sec
1m buf = 3.4 sec

Above is all with camera in playback mode, record mode is notably slower (~6 sec with a 32k buffer). I've seen the same effect in other situations, so this isn't a surprise.

I tested uploads too, but the difference was much smaller, possibly due SD writes being significantly slower.

rmem
1m data, 1m buf = 0.032 sec
1m data, 64k buf = 0.059 sec

In the end, I decided not make any changes in the trunk for now. It would be nice to be able to control it, but doing something useful would be a bit complicated. For max performance, you might want to allow > 1/2 free mem, while if you had a complicated script or shooting running at the same time, you might want to limit it to less.

I did notice that remote capture is using send_ptp_data (which always writes in buffer_size chunks) rather than calling data->send_data like live view. I suspect it could be sped noticeably using the latter, unless it all has to fit in some internal buffer.
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / July / 2013, 23:30:55
I did notice that remote capture is using send_ptp_data (which always writes in buffer_size chunks) rather than calling data->send_data like live view. I suspect it could be sped noticeably using the latter, unless it all has to fit in some internal buffer.
I changed this to use data->send_data, which makes dng remoteshoopt about 200ms quicker on my D10.

I think the original reason for send_ptp_data using fixed data size was on the theory that it might have a limited size buffer somewhere, and not know what to do with larger values. However, given that D10 happily sends a ~18mb raw buffer in one go, I don't think this could be true. EXMEM_COM on D10 is 1mb. I assume this is the PTP data buffer since it is allocated when PTP is present.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 24 / July / 2013, 19:11:04
I think the original reason for send_ptp_data using fixed data size was on the theory that it might have a limited size buffer somewhere, and not know what to do with larger values.
:-[ Actually, I don't know why I used that call. It was there since my first implementation. I probably copy-pasted some lines, and hadn't noticed the possible adverse effects. So, thanks for fixing it.
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / July / 2013, 01:31:27
I've noticed chdkptp remoteshoot sometimes returning a corrupt dng header, with either -dng or -dnghdr. Rather than the 0x4949 byte order marker it has 0xcd68. A bit more of the header seems corrupt too, but much of it is normal

I'm not clear yet whether it is happening on the camera side or chdkptp side, although checking immediately after the data is received shows it is corrupted, so I think it's on the camera side.

It might be something in my chdkptp development code, but I thought I'd post in case anyone else sees it.

The current chdkptp code in SVN won't notice a corrupt header unless you are using sub-image dng (rs -s and/or -c options) so that may explain why I haven't noticed it before.

edit:
May have found the culprit, create_dng_header_for_ptp returned an uncached address, but did not clean. I changed it to a cached address in r2990.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / August / 2013, 02:16:19
remote shoot in continuous mode seems to fail frequently on a540.
The output cli_verbose output when it happens looks something like this:
Code: [Select]
get data 16
rc file IMG_7576.jpg 1
rc chunk get IMG_7576.jpg 1 0
rc chunk size:7680 offset:nil last:false
rc chunk get IMG_7576.jpg 1 1
rc chunk size:1536116 offset:nil last:true
time 8.6325 0.4710
get data 17
rc file IMG_7578.jpg 1
rc chunk get IMG_7578.jpg 1 0
rc chunk size:7680 offset:nil last:false
rc chunk get IMG_7578.jpg 1 1
rc chunk size:1533559 offset:nil last:true
time 9.4095 0.7770
get data 18
rc file IMG_7578.jpg 1
rc chunk get IMG_7578.jpg 1 0
rc chunk size:0 offset:nil last:true
ERROR: d:\chdk\chdkptp\lua\chdku.lua:1015: invalid offset
Each get data should be an image. Note that 16 is image #7576, 17 is #7578 (skipping one) then 18 is 7578 again, but zero sized with last set, which triggers the actual error. The actual error is caused by lbuf:fwrite trying to write a zero sized chunk. This is likely not related to the actual problem, but may have been missed before because it used to allow 0 sized chunks.

This frequently seems to hit between 10-20 shots, though I've done runs of 60 without hitting it.

I haven't seen on d10 yet, but I haven't tried many long continuous sequences either.
Title: Re: CHDK PTP interface
Post by: tpont on 09 / August / 2013, 03:51:54
Hi reyalp, I've been trying out test versions of CHDK from nafraf for A490 with filewrite. We've run into an error that appears after a (variable) number of rs (or rs -jpg) photos that save jpg files to a connected computer. Sometimes it takes 8 photos for the error to appear, sometimes 18 and sometimes many more. To reproduce the problem, just run separate rs commands many time in a row. I've reproduced the problem on the A2300 and nafraf encounters it on the A495. For the A2300 nafraf has a test version of CHDK ( a2300-100f-1.3.0-noexmem.zip ) that seems to fix the problem. At least 100  photos in a row using rs was successful when I tested it. But nafraf suspects the error may be from a memory issue (the A490 has little internal memory compared to some other cameras).

The error looks like this in interactive mode
Code: [Select]
con 89> rs
time 21.3564
ERROR: timed out uninit a script is already running
Every command sent after that gets the script "already running error" and no photo is taken. After a power off/on the camera works again.
Title: Re: CHDK PTP interface
Post by: nafraf on 09 / August / 2013, 05:16:56
@reyalp,
Patch in attachment is required to rs -jpg work in A490 continuous mode shoot.  tpont is testing with this patch applied.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / August / 2013, 12:27:35
To reproduce the problem, just run separate rs commands many time in a row.
I had experienced something similar on the Ixus870/SD880. That camera has relatively small available memory. When I was attempting to use rs from a script, it failed in a few shots due to excessive memory consumption (something ate up the available RAM, without releasing it). With delays (1-2 sec?) between the rs attempts, the gradual memory leak seemed to vanish. I don't know whether your problem has anything to do with this though.
Title: Re: CHDK PTP interface
Post by: tpont on 09 / August / 2013, 17:11:28
When I was attempting to use rs from a script, it failed in a few shots due to excessive memory consumption
Could you do rs commands after the error or did you have to power the camera off and on first?

Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / August / 2013, 17:17:06
Could you do rs commands after the error or did you have to power the camera off and on first?
The memory was permanently lost, I think the cam usually crashed when the rs cycle was left running.
Try to print the available camera memory after every shot. OR see whether shooting in a slower pace helps.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / August / 2013, 17:22:03
remote shoot in continuous mode seems to fail frequently on a540.
I'm afraid I can't be much help, but I suspect that the cause is a task synch issue - something isn't happening in the expected order.
Title: Re: CHDK PTP interface
Post by: reyalp on 09 / August / 2013, 17:28:22
I'm afraid I can't be much help, but I suspect that the cause is a task synch issue - something isn't happening in the expected order.
No problem. I just posted here so people can be aware of the issue. I'll try to have a closer look this weekend.

I have only seen this issue when doing jpeg only, but I haven't tried a lot with raw. I ran two 60 shot sequences on D10 and didn't see the problem.
Title: Re: CHDK PTP interface
Post by: tpont on 09 / August / 2013, 18:06:16
Try to print the available camera memory after every shot.
When I after each photo run this (found earlier in this thread)
Code: [Select]
!return con:execwait('return get_meminfo()')I get this
Code: [Select]
con 142>
=true,{
 start_address=1363912,
 chdk_start=2212572,
 free_size=204752,
 chdk_size=147072,
 allocated_size=996624,
 total_size=1201376,
 allocated_peak=999872,
 name="system",
 allocated_count=1364,
 chdk_malloc=true,
 free_block_max_size=202696,
 end_address=2565288,
 free_block_count=15,
}
The values doesn't seem to change. They are the same right before the error appears as they were many shots earlier. Is there some other memory command I should use?
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / August / 2013, 01:37:14
OK, I think I understand how the issue on a540 happens. It appears that the raw hook for the next shot can be called before the filewrite hook for the preceding one has even started. For some reason, this seems to happen more frequently on the first shooting sequence after booting up.

It is likely the problem happens more with fast exposure times and small images. It probably won't happen if raw is also requested, because that will leave plenty of time for the filewrite hook to catch up.

The check I added in http://chdk.setepontos.com/index.php?topic=4338.msg102447#msg102447 (http://chdk.setepontos.com/index.php?topic=4338.msg102447#msg102447) isn't sufficient, because in that assumes the data has at least become available.

Attached debug patch shows this, by flashing the debug LED when the condition is hit. Note this is not a full solution, since it would clear the flag after every file type. It will only work if you are capturing only jpeg.

I'm not clear if this is related to the issue others have seen with continuous mode.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / August / 2013, 13:01:46
I have done some (not proper) testing. A410 (USB speed limited), S size images (around 64kB each).
I did get errors like
> rs /tmp -cont=1000
WARNING: timed out waiting for shot script
wait time 31,3551

before the patch, I think it did happen after the patch too. May depend on shutter speed - which has a big influence on the continuous shooting rate.
When shutter speed is high, I tend to find some files on the SD card - files, which have also been transferred.
Haven't noticed any blue LED activity.

@tpont
If you get "script is already running", you can stop the script the usual way (full shutter press in ALT mode, on camera).
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / August / 2013, 17:54:38
I have done some (not proper) testing. A410 (USB speed limited), S size images (around 64kB each).
I did get errors like
> rs /tmp -cont=1000
WARNING: timed out waiting for shot script
wait time 31,3551

I've had instances like this where the script didn't start  shooting at all, I'm not clear why it happens yet. I don't think it's directly remoteshoot related. The current remoteshoot camera side script in chdkptp doesn't handle this well either, I'll try to check in a better behaved one in a bit.

edit:
If there is an error on the client during shooting but the script is still running, it will block until remotecap times out, and then shoot the remaining shots locally. It would be good to have a way to know from script if remotecap had been canceled by a timeout.

edit2:
but I'm seeing images being saved when they shouldn't be. This may have something to do with filewrite_set_discard_jpeg(1) being after the "pending" wait, but I would expect it to still be set from the previous shot...

edit3:
My earlier patch was insufficient, since it would clear the "pending" flag after the first chunk rather than when the transfer was complete. This was masked the delays I added to make the LED blinking visible.

I've moved on to logging to the camera log from all the different tasks with LogPrintf.

edit4:
One problem that leads to the jpegs being saved on the card is that the filewrite hook for shot N can finish *after* the raw hook sets ignore_current_write for shot N+1
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / August / 2013, 23:32:26
Current debug patch. This does not completely fix the problem. It will only work on a540 as is, posting as a reference for camera log debugging.

On many vxworks cameras,  CAM_CONSOLE_LOG_ENABLED sends the camera console to stdout.txt using fwrite. This is very slow and can cause crashes, so you don't want to use it for individual debug messages. The "Camera Log" is buffered and fast, and can be written to stdout with the ShowCameraLog eventproc.

So the debug procedure goes like this:
Code: [Select]
# truncate the existing stdout
=f=io.open('A/stdout.txt','wb');f:write('init\n');f:close()
# make the camera log buffer larger, so we get a reasonable number of lines
# should return 3 zeros if everything worked. ShowCameraLogInfo records the new camera log config in stdout
=return call_event_proc('StopCameraLog'),call_event_proc('StartCameraLog',0x20,0x4000),call_event_proc('ShowCameraLogInfo')
# shoot
rec
rs -cont=20
# download the ouput
d stdout.txt

An example of the problem. Lines beginning with > are my commentary.
Code: [Select]
> ... my log wasn't big enough to see the start of this shot
00150350: DSI_ControlShootInfo( 0x44, 0 )
00150360: LogicalEvent:0x311e:adr:0x0,Para:0
> filewrite hook signals image 107 is available
00150370: jpg av 107 A/DCIM/106CANON/IMG_0107.JPG ign 1
> raw hook signals raw 108 is available
00150590: raw av 108
> raw hook sees jpeg is still pending, so it stalls
00150590: raw av pend fmt 1 ign 1
> jpeg junk requested
00150630: rc chunk 1 ign 1
> completed with status "more chunks"
00150640: rc send comp 1 status 1 ign 1
00150650: rc chunk 1 ign 1
> second chunk completed, status last chunk, this clears the pending flag
00150660: rc send comp 1 status 2 ign 1
> raw hook sees pending flag clear after 6 sleep iterations,
00150670: raw av pend done wait 6 fmt 0 ign 1
> raw hook exits, this has called filewrite_set_discard_jpeg(1) for shot 108
00150670: raw av done no raw
> filewrite hook finally notices it is done with 107. After this, it will clear ignore_current_write!
00150720: jpg av done 108 A/DCIM/106CANON/IMG_0107.JPG ign 1
00150750: DSI_ControlShootInfo( 0x27, 0 )
> ... next shot (#109)
00150830: SS:ShootPicture
00150840: DSI_ControlShootInfo( 0x43, 0 )
00150850: ShootSeqToUI:0x2008:adr:0x272040,Para:2564160
00150850: _EntryPrepareRecreviewOff
00150850: ShtCon_StopReview
00150850: StopRecReviewController
00150860: SS:StopRecreview
00150860: LogicalEvent:0x3120:adr:0x0,Para:0
00150860: ShtCon_StartReview
00150860: SS:StartRecreview
00150870: ShootSeqToUI:0x2001:adr:0x211470,Para:2167920
00150880: ShootSeqToUI:0x2021:adr:0x0,Para:0
00150880: LogicalEvent:0x311f:adr:0x0,Para:0
00150880: Sht_CancelStrobeChargeTimer
00150880: DSI_ControlShootInfo( 0x2b, 0 )
00150880: DSI_ControlShootInfo( 0x44, 0 )
00150890: LogicalEvent:0x311e:adr:0x0,Para:0
> filewrite signals image 108 available, but notice the ignore write flag is zero. IMG_0108 was saved on the card
00150900: jpg av 108 A/DCIM/106CANON/IMG_0108.JPG ign 0
00151040: rc chunk 1 ign 0
00151050: rc send comp 1 status 1 ign 0
00151060: rc chunk 1 ign 0
00151080: rc send comp 1 status 2 ign 0
00151080: jpg av done 108 A/DCIM/106CANON/IMG_0108.JPG ign 0
> filewrite hook ended quickly this time, before raw hook
00151120: raw av 109
00151120: raw av done no raw
The solution to this seems to be to clear the jpeg pending flag from filewrite hook, after ignore_current_write is cleared.
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / August / 2013, 18:36:17
Test code with proposed fix attached.

Using this code, I have done successful runs of 1000 continuous mode remotshoots on both a540 and d10. I didn't observe any memory leaks. On d10, free memory was only 64 bytes less than at the start of the sequence.

The fix is generic for dryos cameras, but for cameras like A540, a minor change in the filewrite hook will be needed. Only the a540 is updated in the patch.

This is untested on CAM_FILEWRITETASK_SEEKS cameras.

The patch includes debug logging code, but it will only be used if you #define DEBUG_LOGGING in platform.h  In this case, you will need to ensure that _LogPrintf is available. This shouldn't be needed unless you encounter problems.

The basic approach is to make the raw hook wait for filewrite to clear ignore_current_write before allowing the hook to continue for the next image.

To do this, I added pending_image_data which tracks the data types that have been requested, and only clears them when the relevant hook is completely done with them. For jpeg, this is clearly only after the jpeg hook is done with ignore_current_write for the current image.

Tracking the "pending" status of raw and DNG header isn't strictly needed right now, but I think it may be useful in the future.

Note that we could probably get slightly better performance if there was a way not to block waiting for filewrite, but it would mean raw N+1 potentially being transferred before jpeg N was complete. Even if we had a way to do this, the current protocol couldn't support it.

As an aside, I noticed that chdkptp continuous shoot doesn't handle the file counter wrapping... the chdkptp side will end, but the camera will keep shooting.

edit:
updated patch to include a410, which is the only other vxworks cam with filewrite.

Also, we may be able to get rid of current_write_ignored for dryos cameras with this logic.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 11 / August / 2013, 19:27:53
Test code with proposed fix attached.
Thanks, will test when I get some time.
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / August / 2013, 19:38:26
Slightly updated patch, to fix compile error on FILEWRITETASK_SEEKS cams and clear  fwt_bytes_written for all dryos.
Title: Re: CHDK PTP interface
Post by: reyalp on 11 / August / 2013, 20:47:13
Based on my testing and feedback from nafraf in irc, I've checked a version of this without the debug code (+ fixed vxworks compile error in the previous patch) into the trunk changeset 3026 (http://trac.assembla.com/chdk/changeset/3026). I'd like to get a bit more testing before moving it over to the release branch.

I've attached a debug patch based on this in case anyone needs it.

Also, chdkptp r397 should handle the timeout errors better. This probably doesn't fix the underlying issue where -cont fails to start shooting, but after the timeout everything should return to a usable state.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / August / 2013, 15:47:02
@reyalp

I have done a few test runs (without the additional debug code) on the a410 in continuous mode. It easily made 9800 photos. But there's some weirdness.
You have mentioned that counter wraparound is not handled. One of my test runs started with IMG_0106. I used rs -cont=9800, to avoid counter wrap. I got the 9800 images, but the last image numbers were 9900, 9901, 0002, 0003, 0004, 0005. The camera kept on shooting after this and saved the jpegs to the card (you mentioned this will happen in case of a wraparound), until I stopped the script manually.
At this point, USB connection was still available (!).

Could it be that the wrapping happens earlier than 9999?
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / August / 2013, 16:18:55
Could it be that the wrapping happens earlier than 9999?
From what I understand the canon firmware can create a new folder before 9999 (depending on number of images present, I think?)

I'm not sure if this resets numbering. Honestly I'm not totally clear how all this is supposed to work, and it's a bit annoying to find out by testing.

Anyway, I think 9800 continuous shots is a pretty good result ;)

It's interesting (and nice) that this seems to avoid running into limit where having ~1000 images on the card kills Canon PTP...
Title: Re: CHDK PTP interface
Post by: srsa_4c on 13 / August / 2013, 16:51:24
From what I understand the canon firmware can create a new folder before 9999 (depending on number of images present, I think?)
I don't know. This amount of pictures could be unexpected by the fw, thus the weird numbering?
We could return the "shot count" param as-is, for debug use.

Quote
It's interesting (and nice) that this seems to avoid running into limit where having ~1000 images on the card kills Canon PTP...
I wonder how. Perhaps I should test non-continuous mode too.
Title: Re: CHDK PTP interface
Post by: tpont on 14 / August / 2013, 17:37:16
nafraf sent me compiled test versions for A490 and A2300 that included reyalp's remotecap-cont-debug-8.patch However the problem with rs not working after a variable number of photos is still there in tests with both cameras.
Title: Re: CHDK PTP interface
Post by: reyalp on 14 / August / 2013, 22:19:56
nafraf sent me compiled test versions for A490 and A2300 that included reyalp's remotecap-cont-debug-8.patch However the problem with rs not working after a variable number of photos is still there in tests with both cameras.
The debug patch doesn't have any fixes that aren't in the trunk, it just has some debug logging calls, and to use those, you need DEBUG_LOGGING defined in platform.h have the _LogPrintf function found.

If you are referring to the error described in http://chdk.setepontos.com/index.php?topic=4338.msg103854#msg103854 (http://chdk.setepontos.com/index.php?topic=4338.msg103854#msg103854) this seems like it is just the shooting part of the script failing to take a shot and getting stuck (discussed earlier with the flash related issues). This shouldn't happen with the current chdkptp code in svn, though the shot would still fail. I'll try to get a new chkdptp snapshot build up soon.
Title: Re: CHDK PTP interface
Post by: tpont on 15 / August / 2013, 06:39:57
Ok, I misunderstood things. I will testrun the chkdptp snapshot once it is up.
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / August / 2013, 18:30:03
Based on my testing and feedback from nafraf in irc, I've checked a version of this without the debug code (+ fixed vxworks compile error in the previous patch) into the trunk changeset 3026 (http://trac.assembla.com/chdk/changeset/3026). I'd like to get a bit more testing before moving it over to the release branch.
I merged this and the a490 changes into the 1.2 branch in changeset 3034 (http://trac.assembla.com/chdk/changeset/3034)
Title: Re: CHDK PTP interface
Post by: lapser on 19 / August / 2013, 22:42:50
Could it be that the wrapping happens earlier than 9999?
From what I understand the canon firmware can create a new folder before 9999 (depending on number of images present, I think?)

I'm not sure if this resets numbering. Honestly I'm not totally clear how all this is supposed to work, and it's a bit annoying to find out by testing.
From the multi-thousands of images I've taken with my time lapse script, I've figured out the number scheme, at least on all my cameras.

The Image number goes from 0001 to 9999 and wraps back to 1.

The camera creates a new folder when there are 2,000 images in the current folder. No folder ever contains more than 2,000 images.

The camera creates a new folder when the image number wraps back to 1. Thus, IMG_0001 is always the first file in its folder. This insures that sorting a folder by filename also sorts by time taken.
Title: Re: CHDK PTP interface
Post by: tpont on 20 / August / 2013, 15:42:08
If you are referring to the error described in http://chdk.setepontos.com/index.php?topic=4338.msg103854#msg103854 (http://chdk.setepontos.com/index.php?topic=4338.msg103854#msg103854) this seems like it is just the shooting part of the script failing to take a shot and getting stuck (discussed earlier with the flash related issues). This shouldn't happen with the current chdkptp code in svn, though the shot would still fail. I'll try to get a new chkdptp snapshot build up soon.
Post when you do and I'll try it. nafraf helped me narrow down the problem a bit more. It only appears when sending separate rs commands in a row. So doing rs -jpg pretty rapidly over and over will cause the problem sooner or later. But rs -jpg -cont=200 works fine. But I wish to send single photo rs -jpg commands and vary the time inbetween each command somewhat so -cont=200 won't do.
Title: Re: CHDK PTP interface
Post by: tpont on 29 / August / 2013, 12:19:26
Hi, I have tested the new chdkptp-r426 with the A2300. The problem with timeout after a variable number of rs commands remains. I get  error "WARNING: capture_get_data error timed out". I then have to restart the camera to get any commands to work again.
Title: Re: CHDK PTP interface
Post by: reyalp on 31 / August / 2013, 00:18:51
Hi, I have tested the new chdkptp-r426 with the A2300. The problem with timeout after a variable number of rs commands remains. I get  error "WARNING: capture_get_data error timed out".
This means that chdkptp never saw remote capture data become available.

Does the camera shoot when this happens?
Quote
I then have to restart the camera to get any commands to work again.
What happens if you try to use other commands? Is it the "script is already running" error, or something else?

If camera side shoot() fails, you would get the timeout but then everything should work normally afterword. If you were using lua files from an old version you might get the behavior you describe.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / December / 2013, 19:24:40
While writing this description, I've realized there are some unresolved issues, so this should not be considered final :(

In trunk changeset 3266 (http://trac.assembla.com/chdk/changeset/3266) I added the ability to cleanly kill a running script, or return an error if you try to execute a script while one is already running.

This is a minor protocol change (2.6), backwards compatible with existing clients.

The corresponding chdkptp changes are in changeset 467 (http://trac.assembla.com/chdkptp/changeset/467)

In addition allowing you to kill a script remotely, this allows compatible to clients to run a script without first doing a ScriptStatus query, which should improve performance slightly.

Up to now, PTP_CHDK_ExecuteScript param2 has been defined as "script language" which currently only accepts 0 for lua. In 2.6, only the lowest byte indicates language, and the remaining bits are flags.

If no flags are set, the behavior is equivalent to the old behavior, so earlier clients can connect to 2.6 cameras without any change. As in prior versions, calling PTP_CHDK_ExecuteScrip will cause any running script to be killed. However, in 2.6 this is safe, and does not cause memory corruption. Setting any of the flags for a pre-2.6 camera will result in an error, because it will be interpreted as an unknown scripting language. 2.6 aware clients should only send flags cameras running 2.6 or greater, since the error for a bad script language does not handle the data phase.

The added flags are
PTP_CHDK_SCRIPT_FL_NOKILL
If set, this causes PTP_CHDK_ExecuteScript to return PTP_CHDK_S_ERRTYPE_INIT in param2, and add a script message of the same type with the string "script running".

PTP_CHDK_SCRIPT_FL_FLUSH_CAM_MSGS
If set this causes the camera to discard any existing unread cam->host messages before starting the new script.

PTP_CHDK_SCRIPT_FL_FLUSH_HOST_MSGS 
Discard unread host->cam messages before starting.

The flush flags only take effect if the new script is started, if PTP_CHDK_SCRIPT_FL_NOKILL finds a script running, it's messages will not be affected.

The flush flags are added because the most common case is to not want any messages from old scripts floating around, and getting rid of them would otherwise require additional PTP calls to check state and read the messages (for cam->host) or leave them in memory until the script reads messages (for host->cam).

Issues:
Unsafe for ptp task to add a message when a script is running
Script ID will get incremented in the PTP_CHDK_SCRIPT_FL_NOKILL case
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / December / 2013, 20:40:27
I updated this in chdk changeset 3268 (http://trac.assembla.com/chdk/changeset/3268) and chdkptp changeset 468 (http://trac.assembla.com/chdkptp/changeset/468)

PTP_CHDK_SCRIPT_FL_NOKILL now makes  PTP_CHDK_ExecuteScript return a status value PTP_CHDK_S_ERR_SCRIPTRUNNING without adding a script message. This makes more sense anyway, because unlike a syntax or runtime error, it doesn't really need additional information.

The script ID is not incremented in this case.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 15 / February / 2014, 20:31:52
I have to correct my earlier statement.
Quote
It looks like that
- filewritetask only writes jpeg files (!), native raw is written elsewhere
Native RAW files are also written by filewritetask. In RAW + JPEG case, native RAW is saved first - the code doesn't currently handle this, rs -jpg will simply retrieve the native RAW file and let the camera save the JPEG to the card.

I wonder whether I manage to submit this post, the forum is nearly unusable in recent days/hours...
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / March / 2014, 01:10:14
I have to correct my earlier statement.
Quote
It looks like that
- filewritetask only writes jpeg files (!), native raw is written elsewhere
Native RAW files are also written by filewritetask. In RAW + JPEG case, native RAW is saved first - the code doesn't currently handle this, rs -jpg will simply retrieve the native RAW file and let the camera save the JPEG to the card.
Late reply :-[ I guess it would be nice to support this. Right now we don't have a consistent way to tell if a port supports canon raw, or if it is enabled. We'd also need a way of selecting Canon raw for remote shoot, while running through the same code jpeg.

An unrelated remotecap note, working on the rsint stuff made me realize there should be a way to tell on the camera side if remotecap has timed out, so a script can end gracefully if the PC side goes away.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 15 / March / 2014, 17:36:51
Continuing here, since it's a CHDK-side problem.
First chunk, but last=true?
This sounds like it could match multiple invocations of filewrite, where the first "session" only has one chunk.
It seems you're right. Fwt data blocks below, sampled in filewrite_main_hook(), a3200

Good JPEG
Code: [Select]
Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000  09 00 00 00 00 00 00 00 01 03 00 00 9A BB 24 53  ............š»$S
00000010  00 00 20 09 00 64 A6 43 00 E4 13 00 00 F4 74 43  .. ..d¦C.ä...ôtC
00000020  B9 36 1D 00 00 00 00 00 00 00 00 00 00 00 00 00  Ä…6..............
00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000050  41 2F 44 43 49 4D 2F 32 31 39 5F 5F 5F 30 33 2F  A/DCIM/219___03/
00000060  49 4D 47 5F 30 30 32 38 2E 4A 50 47 00 00 00 00  IMG_0028.JPG....
Bad JPEG, 4 fwt invocations
Code: [Select]
Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000  09 00 00 00 00 00 00 00 01 83 00 00 A8 BB 24 53  ............¨»$S
00000010  00 00 20 09 00 F4 74 43 00 AA 22 00 00 00 00 00  .. ..ôtC.Åž".....
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000050  41 2F 44 43 49 4D 2F 32 31 39 5F 5F 5F 30 33 2F  A/DCIM/219___03/
00000060  49 4D 47 5F 30 30 32 39 2E 4A 50 47 00 00 00 00  IMG_0029.JPG....

00000000  09 00 00 00 00 00 00 00 09 80 00 00 A8 BB 24 53  .........€..¨»$S
00000010  00 00 20 09 00 A0 97 43 00 A8 22 00 00 00 00 00  .. .. —C.¨".....
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000050  41 2F 44 43 49 4D 2F 32 31 39 5F 5F 5F 30 33 2F  A/DCIM/219___03/
00000060  49 4D 47 5F 30 30 32 39 2E 4A 50 47 00 00 00 00  IMG_0029.JPG....

00000000  09 00 00 00 00 00 00 00 09 80 00 00 A8 BB 24 53  .........€..¨»$S
00000010  00 00 20 09 00 F4 74 43 49 FB 09 00 00 00 00 00  .. ..ôtCIű......
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000050  41 2F 44 43 49 4D 2F 32 31 39 5F 5F 5F 30 33 2F  A/DCIM/219___03/
00000060  49 4D 47 5F 30 30 32 39 2E 4A 50 47 00 00 00 00  IMG_0029.JPG....

00000000  09 00 00 00 00 00 00 00 01 00 00 00 A8 BB 24 53  ............¨»$S
00000010  00 00 20 09 00 A0 97 43 00 40 00 00 00 00 00 00  .. .. —C.@......
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000040  00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00  ................
00000050  41 2F 44 43 49 4D 2F 32 31 39 5F 5F 5F 30 33 2F  A/DCIM/219___03/
00000060  49 4D 47 5F 30 30 32 39 2E 4A 50 47 00 00 00 00  IMG_0029.JPG....
The trick is that the first chunk starts with garbage, the exif block will be written there - in the final fwt invocation for that file.

I'm not sure yet how to handle this...

Right now we don't have a consistent way to tell if a port supports canon raw, or if it is enabled. We'd also need a way of selecting Canon raw for remote shoot, while running through the same code jpeg.
'Native RAW support' will probably be a define, there are at least 2 propcases that have to do with native raw / raw+jpeg selection.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 16 / March / 2014, 16:25:08
Proposed fix for cameras with multipass JPEG writes. Affected cameras are probably:
a490, a495, ixus1000, sx40, g12, ixus310, sx220, sx230, s90, sx30, ixus230, a2200, g1x, ixus200, a3200 (the list only includes models which already have filewritetask support).
The patch only includes support for a3200, a490, a495 at the moment, I'll probably do the rest too.
For affected cameras, 'fwt_data_struct' will have an additional member, 'oflags'. 'oflags' is the second argument to open (fwt_open), so it isn't hard to recognize.

Comments on the patch are welcome.
Title: Re: CHDK PTP interface
Post by: nafraf on 16 / March / 2014, 20:36:25
fwt_multipass_support patch tested on A495, it works!! Thanks.
Maybe oflags could be renamed as open_flags?
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / March / 2014, 21:47:41
Here's an a490 100f build for jpq5588

The patch makes sense to me. It seems like it might be possible to clean up the ifdef code a bit so there is less duplicated code. It might also be clearer to have CAM_FILEWRITETASK_SEEKS automatically define multipass, so the common parts only check one ifdef.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / March / 2014, 13:16:46
Proposed fix for cameras with multipass JPEG writes.
I'm still getting partial JPEGs occasionally, it's either an unhandled saving pattern or a bug...  :(

It seems like it might be possible to clean up the ifdef code a bit so there is less duplicated code. It might also be clearer to have CAM_FILEWRITETASK_SEEKS automatically define multipass, so the common parts only check one ifdef.
Will do this in the next patch.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / March / 2014, 18:18:54
Proposed fix for cameras with multipass JPEG writes.
I'm still getting partial JPEGs occasionally, it's either an unhandled saving pattern or a bug...
It was a bug. New (still incomplete) patch is attached, along with a new test build for that camera.

edit:
Turns out, there's still something wrong. Last chunk is not recognized when the cam is set to continuous mode...


late edit:
test build removed
Title: Re: CHDK PTP interface
Post by: nafraf on 20 / March / 2014, 14:30:04
It was a bug. New (still incomplete) patch is attached, along with a new test build for that camera.
Patch tested on A495, I did not find problems.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 21 / April / 2014, 16:39:58
Turns out, there's still something wrong. Last chunk is not recognized when the cam is set to continuous mode...
It looks like this can't be solved easily. The code is working when in single shot mode. In continuous mode, there is simply nothing in fwt_data_struct that would indicate whether there will be further fwt invocations for a given file. Therefore, the current code always expects another invocation and causes every rs attempt to fail (and makes the cam lock up afterwards sometimes due to unexpected behaviour in filewritetask)*.
"Solutions"
- fail every rs attempt in continuous mode for these cams
- add code and fw hooks to better deal with the issue (this could end up pretty hacky)
- rewrite the code to mirror filesystem operations (ouch)

Any thoughts on how to proceed?

edit:
* that's a different issue, the cause is not the CHDK fwt modification
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2014, 17:06:32
In continuous mode, there is simply nothing in fwt_data_struct that would indicate whether there will be further fwt invocations for a given file.
:(
Thanks for working on this.

Quote
- fail every rs attempt in continuous mode for these cams
Better than nothing I guess, but unfortunate, because rs in continuous is actually pretty useful for a some applications.

Quote
- add code and fw hooks to better deal with the issue (this could end up pretty hacky)
Not sure what this entails? An example of what it looks like when it fails might be helpful.

Quote
- rewrite the code to mirror filesystem operations (ouch)
Does that even help if we don't know when it's done? Maybe I'm not understand the the suggestion.

Other ideas:
Is the total size available somewhere else in memory so we can check if we are done? Or does seeking mess this up?
Could we use a timeout to signal the last chunk? If we are waiting for a jpeg, what is the max time between one chunk completing and the next being available? It seems like it could potentially be pretty short.
Reverse engineer the code that sends the chunks, there must be some loop or variable that knows when it's done.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 21 / April / 2014, 17:38:45
Quote
- add code and fw hooks to better deal with the issue (this could end up pretty hacky)
Not sure what this entails? An example of what it looks like when it fails might be helpful.
small file
Code: [Select]
con 19> rs
rs_init
rs_shoot
get data 1
rc file IMG_0197.jpg 1
rc chunk get IMG_0197.jpg 1 0
rc chunk size:321042 offset:nil last:false
rc chunk get IMG_0197.jpg 1 1
RemoteCaptureGetData: unexpected return code 0x2002
WARNING: capture_get_data error rcgetchunk failed
script wait time 1.5299
ERROR: rcgetchunk failed
large file, fwt (and its related tasks) locked after this
Code: [Select]
con 15> rs
rs_init
rs_shoot
get data 1
rc file IMG_0207.jpg 1
rc chunk get IMG_0207.jpg 1 0
rc chunk size:2271744 offset:nil last:false
rc chunk get IMG_0207.jpg 1 1
rc chunk size:2271232 offset:nil last:false
rc chunk get IMG_0207.jpg 1 2
rc chunk size:1473745 offset:nil last:false
rc chunk get IMG_0207.jpg 1 3
rc chunk size:16384 offset:nil last:false
rc chunk get IMG_0207.jpg 1 4
RemoteCaptureGetData: unexpected return code 0x2002
WARNING: capture_get_data error rcgetchunk failed
script wait time 1.5360
ERROR: rcgetchunk failed
etc...
The code hasn't changed since my last attached patch.
Quote
Quote
- rewrite the code to mirror filesystem operations (ouch)
Does that even help if we don't know when it's done? Maybe I'm not understand the the suggestion.
fwt doesn't seek in this camera generation. It opens and closes the file multiple times (either in append or in overwrite mode) when needed.

Quote
Other ideas:
Is the total size available somewhere else in memory so we can check if we are done?
As far as I know, fwt doesn't have information about the total file size. It may exist somewhere else, didn't try to check yet...
Quote
Could we use a timeout to signal the last chunk? If we are waiting for a jpeg, what is the max time between one chunk completing and the next being available? It seems like it could potentially be pretty short.
A timeout was one of my ideas that I referred to as "hacky". Other "hacks" include signaling from the raw hook.
I don't yet know how the "fix" for this issue should look.
Quote
Reverse engineer the code that sends the chunks, there must be some loop or variable that knows when it's done.
I gave up on understanding "filescheduletask", it looks much more difficult than the filewritetask code.
Title: Re: CHDK PTP interface
Post by: jpq5588 on 27 / May / 2014, 10:07:56
Here's an a490 100f build for jpq5588


Thank you very much for that built, reyalp.
(I haven't seen it before... )

It is ok with A490 and rs, also in Chdk SuperFine mode and -dng mode.

Many thanks to srsa_4c who fixed the problem.


By the way, what is the command to apply .diff file to a local copy of a trunk ? (with chdk-shell win32 and gcc)
(I applied the patch by hand... :( )
Title: Re: CHDK PTP interface
Post by: srsa_4c on 27 / May / 2014, 15:19:16
By the way, what is the command to apply .diff file to a local copy of a trunk ? (with chdk-shell win32 and gcc)
I don't use that shell, but it has a "source tools" button. "patch" should be available from there.

Attached the 'completed'(= for all affected cams) patch for this problem - which is, as the last posts show, only a partial fix. The patch may not apply cleanly, as it's a bit dated.
Title: Re: CHDK PTP interface
Post by: philmoz on 16 / June / 2014, 08:53:39
By the way, what is the command to apply .diff file to a local copy of a trunk ? (with chdk-shell win32 and gcc)
I don't use that shell, but it has a "source tools" button. "patch" should be available from there.

Attached the 'completed'(= for all affected cams) patch for this problem - which is, as the last posts show, only a partial fix. The patch may not apply cleanly, as it's a bit dated.

Been playing with this on my G12.

What I've found so far:
- CAM_FILEWRITETASK_MULTIPASS is not needed on the G12, only one call to 'filewrite_main_hook' is made per file (regardless of mode)
- OFLAG_APPEND (not sure this is a good name) is always set in continuous mode, and never set in single shot
- 'fwt_close' is never called in continuous mode, this seems to be a major source of problems and lockups

Will update this post if I find more.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 16 / June / 2014, 14:51:21
- CAM_FILEWRITETASK_MULTIPASS is not needed on the G12, only one call to 'filewrite_main_hook' is made per file (regardless of mode)
"multipass" is relatively hard to trigger on my a3200, a very detailed scene and/or superfine quality override is needed for it to happen.
Quote
- OFLAG_APPEND (not sure this is a good name) is always set in continuous mode, and never set in single shot
the name (which can be changed) is based on the variable's single mode behaviour, I only noticed the continuous mode ill-behaviour later
Quote
- 'fwt_close' is never called in continuous mode, this seems to be a major source of problems and lockups
There are like 3 different places in the Canon code to close the file, continuous mode uses a different one.
Thanks for the notes, btw.
Title: Re: CHDK PTP interface
Post by: philmoz on 16 / June / 2014, 16:11:34
- CAM_FILEWRITETASK_MULTIPASS is not needed on the G12, only one call to 'filewrite_main_hook' is made per file (regardless of mode)
"multipass" is relatively hard to trigger on my a3200, a very detailed scene and/or superfine quality override is needed for it to happen.
Might also depend on camera resolution the G12 is only 10MP compared to the A3200 14MP.
Quote
Quote
- OFLAG_APPEND (not sure this is a good name) is always set in continuous mode, and never set in single shot
the name (which can be changed) is based on the variable's single mode behaviour, I only noticed the continuous mode ill-behaviour later
Quote
- 'fwt_close' is never called in continuous mode, this seems to be a major source of problems and lockups
There are like 3 different places in the Canon code to close the file, continuous mode uses a different one.
Thanks for the notes, btw.

Ok, missed one of the Close calls.

In limited testing today it seems to work ok - except after using chdkptp 'rs' or 'rsint' the camera crashes when switching to playback mode with 'unidentified image' displayed.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 16 / June / 2014, 18:09:46
Might also depend on camera resolution the G12 is only 10MP compared to the A3200 14MP.
Could be, or some related Canon code can be different. My identification was based on the presence of '0x8000' in that part of the fwt code. I managed to make a multipass JPEG at the camera's 7MP setting - I'm using a fine black/white grid displayed on the monitor to torture the JPEG engine.
Quote
In limited testing today it seems to work ok - except after using chdkptp 'rs' or 'rsint' the camera crashes when switching to playback mode with 'unidentified image' displayed.
I have updated nafraf's table (http://chdk.wikia.com/wiki/User:Nafraf/RemoteShootIssues).
Title: Re: CHDK PTP interface
Post by: philmoz on 16 / June / 2014, 20:56:12
Might also depend on camera resolution the G12 is only 10MP compared to the A3200 14MP.
Could be, or some related Canon code can be different. My identification was based on the presence of '0x8000' in that part of the fwt code. I managed to make a multipass JPEG at the camera's 7MP setting - I'm using a fine black/white grid displayed on the monitor to torture the JPEG engine.

Haven't reproduced it yet, will keep testing.

I think the OFLAG_APPEND bit (0x8000) may be more related to calling a different version of Close, than indicating that the file is being appended. Perhaps an optimised code path.

Have you tried checking the 'flags' parameter to 'open' to see if the O_APPEND flag is set or not? (Don't forget the value of O_APPEND differs between VxWorks and DryOS).

For a multi-pass image save, I would expect the final file update would not have O_APPEND set, since it would need to re-write the file header.

If you combine OFLAG_APPEND, 'flags' & O_APPEND, and a test of the very first chunk for a JPEG file header, then there might be enough information to determine if a multi-pass save is happening and detect the last segment.
This is all speculation at the moment, I'll do some more experiments and testing when I get a chance.

Phil.

Edit: back at a computer now, and looking at this in more detail. In this post http://chdk.setepontos.com/index.php?topic=4338.msg111230#msg111230 (http://chdk.setepontos.com/index.php?topic=4338.msg111230#msg111230) you show the fwt_data from a normal and multi-pass image save.

From these it looks like:
- oflags & 0x300 == 0x300 --> first or only invocation for file
- oflags & 0x308 == 0x008 --> appending to file (O_APPEND)
- oflags & 0x308 == 0x000 --> last invocation for file

So the problem is how to determine if this is a single or multi-pass file save - in this case examining the first chunk of memory for a JPEG header should work.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / June / 2014, 15:11:04
So the problem is how to determine if this is a single or multi-pass file save
No, the problem is with continuous mode (http://chdk.setepontos.com/index.php?topic=4338.msg112314#msg112314). My last patch is already able to deal with single shot mode (at least I believe so).
However, if you don't ever get a multipass JPEG, your cam may not be affected by any of these issues. The playback mode crash is a separate thing, unrelated to our fwt code (reyalp mentioned somewhere that it's also happening when JPEGs are erased after shooting).
Title: Re: CHDK PTP interface
Post by: philmoz on 17 / June / 2014, 16:02:18
So the problem is how to determine if this is a single or multi-pass file save
No, the problem is with continuous mode (http://chdk.setepontos.com/index.php?topic=4338.msg112314#msg112314). My last patch is already able to deal with single shot mode (at least I believe so).
However, if you don't ever get a multipass JPEG, your cam may not be affected by any of these issues. The playback mode crash is a separate thing, unrelated to our fwt code (reyalp mentioned somewhere that it's also happening when JPEGs are erased after shooting).

Why would the logic not work for continuous mode as well as single-shot?
Is there a different pattern for oflags (ignoring the 0x8000 bit)?

I would have thought continuous mode would work the same with regard to the actual file saving.

A single-pass save would have:
    - oflags & 0x300 == 0x300
    - a valid JPEG header in the first chunk of memory

A multi-pass file save would have:
    - oflags & 0x300 == 0x300 on the first invocation
    - an in-valid JPEG header in the first chunk of memory
    - oflags & 0x308 == 0x008 for each append to the file
    - oflags & 0x308 == 0 for the last invocation that re-writes the header

I'm unsure whether checking the first memory chunk for a JPEG header would be reliable, you mentioned in a previous post that it contains random data; but there is always a chance it could contain a JPEG header from a previous image.

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / June / 2014, 18:33:29
Thanks for the idea, I'll see whether it can be used in practice.
Side note: The 'ff d8 ff e1' byte sequence appears more than once in JPEGs of some new models (ixus115: twice, sx280: 3 times).
Title: Re: CHDK PTP interface
Post by: philmoz on 17 / June / 2014, 18:56:28
Thanks for the idea, I'll see whether it can be used in practice.
Side note: The 'ff d8 ff e1' byte sequence appears more than once in JPEGs of some new models (ixus115: twice, sx280: 3 times).

Hopefully we would really only care about the contents at the very start of the first chunk being saved.

Probably need to check for more that just these four bytes.

0xFF 0xD8 = SOI marker (Start Of Image)
0xFF 0xE1 = APP1 marker (EXIF header)

Following these are the APP1 size, EXIF header, TIFF header, IFD0, etc.

It's possible there could be multiple APP1 segments in the file, for thumbnail images.
If one of these is generated and saved first, then we are probably screwed.

Phil.
Title: Re: CHDK PTP interface
Post by: philmoz on 21 / June / 2014, 02:18:41
I have to correct my earlier statement.
Quote
It looks like that
- filewritetask only writes jpeg files (!), native raw is written elsewhere
Native RAW files are also written by filewritetask. In RAW + JPEG case, native RAW is saved first - the code doesn't currently handle this, rs -jpg will simply retrieve the native RAW file and let the camera save the JPEG to the card.

Noticed this as well when testing the G12.

It seems we need two changes to support this:
- send a flag to chdkptp to tell it whether to expect 1 file (JPEG, or RAW) or 2 files (RAW+JPEG). Property 214 on the G12 & G1X could be used to determine this (RAW=0, JPEG=1, RAW+JPEG=2).
- send the filename from the fwt_data_stuct.name field, instead just sending the file number from target_file_num

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 26 / June / 2014, 18:46:07
A single-pass save would have:
    - oflags & 0x300 == 0x300
    - a valid JPEG header in the first chunk of memory

A multi-pass file save would have:
    - oflags & 0x300 == 0x300 on the first invocation
    - an in-valid JPEG header in the first chunk of memory
    - oflags & 0x308 == 0x008 for each append to the file
    - oflags & 0x308 == 0 for the last invocation that re-writes the header
A small update on this: I have encountered a variation in which a multipass JPEG starts with a big chunk of the final JPEG (with its exif in place). Of course no flags help with the indication (oflags is 0x8301 for the 1st pass).
I wonder if we should assume multipass for all cases which can't be pre-determined and use either the timeout (while waiting for the next pass) and/or filename-check to deal with the situation gracefully...
Title: Re: CHDK PTP interface
Post by: philmoz on 26 / June / 2014, 19:02:42
A single-pass save would have:
    - oflags & 0x300 == 0x300
    - a valid JPEG header in the first chunk of memory

A multi-pass file save would have:
    - oflags & 0x300 == 0x300 on the first invocation
    - an in-valid JPEG header in the first chunk of memory
    - oflags & 0x308 == 0x008 for each append to the file
    - oflags & 0x308 == 0 for the last invocation that re-writes the header
A small update on this: I have encountered a variation in which a multipass JPEG starts with a big chunk of the final JPEG (with its exif in place). Of course no flags help with the indication (oflags is 0x8301 for the 1st pass).

Is it the correct EXIF for the image (correct segment length and filename)?

There's a chance the memory could contain the data from a previous save - which would make things somewhat difficult.

Another thought I had was maybe we could move the problem to the host computer instead of the camera.
The process might work something like this:
- host tells camera to send next filewrite invocation to PC, camera just sends all the data without trying to figure anything out (including oflags and filename)
- host uses oflags and filename to open/create/append and write data to file
- if this is a new file (oflags & 0x300 == 0x300), then examine file content to see if it is complete (EXIF header is correct and consistent), if complete then we are done
- if file is not complete, then request more filewrite invocations from the camera until we get the final one (oflags & 0x8 == 0)

Phil.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 27 / June / 2014, 18:26:00
Is it the correct EXIF for the image (correct segment length and filename)?
The question is good. Some of the exif data seems final, but some of its parts are missing: the halfword after the first ff d8 ff e1 is zero, the thumbnail image is not there yet. The "file number" (as exiftool calls it) is there and is correct. Since this was the first photo taken in that session, it may not happen regularly (apparently, chunks of the JPEG are allocated separately).

Quote
There's a chance the memory could contain the data from a previous save - which would make things somewhat difficult.
Seems unavoidable (unless we erase some sensitive parts after transfer), but wouldn't happen very often.

Quote
Another thought I had was maybe we could move the problem to the host computer instead of the camera.
I don't know. So much trouble to support this camera generation.
On the a3200, only continuous mode has these problems, single mode is working well (with the current multipass code).

Your recent commit seems to suggest that none of your cameras is "multipass". If so, I don't have an idea how to detect which cameras have this problem (other than getting bugreports from users).
Title: Re: CHDK PTP interface
Post by: reyalp on 19 / August / 2014, 16:52:42
So the problem is how to determine if this is a single or multi-pass file save
No, the problem is with continuous mode (http://chdk.setepontos.com/index.php?topic=4338.msg112314#msg112314). My last patch is already able to deal with single shot mode (at least I believe so).
If this still holds, I'd be tempted to say use this code for 1.3 and disable remote capture in continuous mode. It turns out that most of the benefits of continuous mode can be achieved by holding half press and clicking full, so the need for continuous mode is less. Assuming this doesn't also trigger the bug... which I guess we need to test.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 20 / August / 2014, 16:24:54
So the problem is how to determine if this is a single or multi-pass file save
No, the problem is with continuous mode (http://chdk.setepontos.com/index.php?topic=4338.msg112314#msg112314). My last patch is already able to deal with single shot mode (at least I believe so).
If this still holds, I'd be tempted to say use this code for 1.3 and disable remote capture in continuous mode. It turns out that most of the benefits of continuous mode can be achieved by holding half press and clicking full, so the need for continuous mode is less. Assuming this doesn't also trigger the bug... which I guess we need to test.
I have since made some changes to my experimental code (plus it's stuffed with debug lines), I'll try to determine which one works better.

My other problem is that not all cameras from the affected generations appear to have this issue (see Phil's posts).
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / August / 2014, 18:44:58
I have rediscovered ( :-[ ) that the patch attached to this (http://chdk.setepontos.com/index.php?topic=4338.msg113100#msg113100) post does appear to solve the problems on my a3200 when the camera is not in continuous mode. If this fix should be the official one then I should probably change some names in it (as suggested by philmoz).
We'll also have to determine somehow which cameras need the fix...
It turns out that most of the benefits of continuous mode can be achieved by holding half press and clicking full, so the need for continuous mode is less. Assuming this doesn't also trigger the bug... which I guess we need to test.
Can you suggest a way to test this situation?
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / August / 2014, 23:23:05
We'll also have to determine somehow which cameras need the fix...
We could just apply it to cameras known to suffer from the problem.

Quote
It turns out that most of the benefits of continuous mode can be achieved by holding half press and clicking full, so the need for continuous mode is less. Assuming this doesn't also trigger the bug... which I guess we need to test.
Can you suggest a way to test this situation?
The new rs -quick=n option described here http://chdk.setepontos.com/index.php?topic=6231.msg116242#msg116242 (http://chdk.setepontos.com/index.php?topic=6231.msg116242#msg116242) should do it.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 31 / August / 2014, 17:32:07
The new rs -quick=n option described here http://chdk.setepontos.com/index.php?topic=6231.msg116242#msg116242 (http://chdk.setepontos.com/index.php?topic=6231.msg116242#msg116242) should do it.
Done, the camera does not show the continuous mode anomalies (as expected) when using that command.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / September / 2014, 18:57:34
New patch for "multipass" cameras. Should allow remote shooting when drive mode is not continuous and custom timer is not active. (I did not test custom timer mode on other cameras, but I suspect that it will only cause trouble in connection with remote shooting.)
I have renamed OFLAG_APPEND to OFLAG_NOFLUSH because the latter seems closer to the flag's real purpose. I am also specifically disallowing remote shooting for affected cameras when drive mode is not single (see remotecap_set_target()). I could only test this on my a3200. The other 2 cams that will probably also work with this patch are the a490 and 495 (these were tested with the previous patch which was functionally the same except for the drive mode check).
The patch is not meant to be committed as-is, needs to be tested on each affected model:
We could just apply it to cameras known to suffer from the problem.
The patch includes support for these cams: a2200, a3200, a490, a495, ixus1000_sd4500, ixus200_sd980, ixus230_elph310, s90, sx220, sx230, sx30.
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / September / 2014, 20:35:22
This seems reasonable to me.

When I suggested this, I was only really thinking about rs -cont, but of course it will affect anyone who happens to leave their camera in continuous mode, even if they are only trying to take single shots. Nothing we can do about that, and still better than having it fail completely.

Other thoughts:
Should remotecap_set_target only fail if they requested jpeg? Presumably CHDK raw should be fine, but I guess the jpeg would have to be written to the card and filewrite might get more complicated. I haven't seen too many people interested in remoteshoot with raw, so maybe a non-issue.

Another question is if it should affect the return value of remotecap_get_target_support. I'm not sure, currently it's returns what the port is capable of regardless of the current state (e.g if you are in playback or movie mode it returns the supported formats)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / September / 2014, 18:15:01
it will affect anyone who happens to leave their camera in continuous mode, even if they are only trying to take single shots. Nothing we can do about that, and still better than having it fail completely.
We might be able to switch drive mode with UI properties - once/if the necessary research is done.
Quote
Should remotecap_set_target only fail if they requested jpeg? Presumably CHDK raw should be fine, but I guess the jpeg would have to be written to the card and filewrite might get more complicated.
I did not try, but I think the current approach of suppressing JPEG may fail to work in continuous mode for multipass cams. So, IMHO all targets should fail.
Quote
Another question is if it should affect the return value of remotecap_get_target_support. I'm not sure, currently it's returns what the port is capable of regardless of the current state (e.g if you are in playback or movie mode it returns the supported formats)
The code could be reorganized by moving the "possibilities" check from the beginning of remotecap_set_target() to remotecap_get_target_support() and making the latter function accept a parameter. remotecap_get_target_support() could then be used for querying both "what does the cam support" and "what does the cam support right now".
Title: Re: CHDK PTP interface
Post by: nafraf on 08 / September / 2014, 20:15:24
it will affect anyone who happens to leave their camera in continuous mode, even if they are only trying to take single shots. Nothing we can do about that, and still better than having it fail completely.
We might be able to switch drive mode with UI properties - once/if the necessary research is done.
Code: [Select]
A495        - Propset 3   - 0x8009
A810/SX160  - Propset 5   - 0x800D
A1400       - Propset 6   - 0x800D
SX170/SX510 - Propset 6?  - 0x800E
0=Single,
1=Continuous,
2=Continuos shooting AF (valid on some models)

Title: Re: CHDK PTP interface
Post by: reyalp on 08 / September / 2014, 23:49:26
We might be able to switch drive mode with UI properties - once/if the necessary research is done.
That would be useful in a lots of other situations too.

Quote
I did not try, but I think the current approach of suppressing JPEG may fail to work in continuous mode for multipass cams. So, IMHO all targets should fail.
Yeah, makes sense.
Quote
The code could be reorganized by moving the "possibilities" check from the beginning of remotecap_set_target() to remotecap_get_target_support() and making the latter function accept a parameter. remotecap_get_target_support() could then be used for querying both "what does the cam support" and "what does the cam support right now".
Hmm. That could work. Somewhat tempting just stick with your original patch to keep it simple, but allowing the client to distinguish between not implemented and something that just needs a mode change would be more user friendly. The Lua function could just return both bitmasks, like
available, supported = get_usb_capture_support()

remotecap_set_target() should still do all the checks anyway (because you don't know if the client checked or what changed in between), but it could just call the "what does the cam support right now" variant.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / September / 2014, 17:35:59
Somewhat tempting just stick with your original patch to keep it simple
That would be my intention for now, the code reorganization can be done later. The check will then have to be extended to disallow rs when custom timer is active - on all cameras.

@nafraf
If you still have the a495 and some time, can you recheck remote shooting with the latest patch (just to be sure)? I think the models which get CAM_FILEWRITETASK_MULTIPASS are the a3200, a490 and a495 initially. The rest will be added when camera owners report rs failure (i.e. maybe never). If cameras from the DryOS r39..r49 range get filewritetask support from now on, multipass will have to be considered and tested for.
And we should start collecting those UI properties somewhere...
Title: Re: CHDK PTP interface
Post by: nafraf on 09 / September / 2014, 19:51:45
A495 patch tests.  If you need more tests, just let me know. 
Title: Re: CHDK PTP interface
Post by: srsa_4c on 09 / September / 2014, 20:02:03
A495 patch tests.
Pretty big files for a 10MP cam and many small chunks. Do small picture sizes / higher compression also work? Are the files OK (including their exif)?
Title: Re: CHDK PTP interface
Post by: nafraf on 10 / September / 2014, 08:08:24
A495 tests: L, M2 and S size.  Fine and Superfine quality.
JPGs are fine. Logs and exif data in attachment.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 10 / September / 2014, 19:07:22
A495 tests: L, M2 and S size.  Fine and Superfine quality.
JPGs are fine. Logs and exif data in attachment.
Thanks. Unless there's objection, I'll check in the above patch (limited to a3200, a490, a495 for now) in a few days.
Title: Re: CHDK PTP interface
Post by: reyalp on 10 / September / 2014, 21:54:56
Thanks. Unless there's objection, I'll check in the above patch (limited to a3200, a490, a495 for now) in a few days.
OK with me.

Quote
A495 tests: L, M2 and S size.  Fine and Superfine quality.
FWIW, when testing it's probably a good idea to use a scene with a lot of detail.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 14 / September / 2014, 16:07:56
Thanks. Unless there's objection, I'll check in the above patch (limited to a3200, a490, a495 for now) in a few days.
OK with me.
Done: https://www.assembla.com/code/chdk/subversion/commit/3611 (https://www.assembla.com/code/chdk/subversion/commit/3611)
Title: Re: CHDK PTP interface
Post by: amit on 26 / February / 2015, 15:46:24
Hello,

I have a setup where I use a Powershot S110 connected to an Odroid, controlled by the chdkptp code. I activate 'remoteshoot -cont'. I have two cameras. In one camera the 'remoteshoot -cont' works fine. In the other I can use the 'remoteshoot' command but when I try to use it in continuous mode (i.e. with the -cont option) the camera makes noise of shooting two images and then stops. No image is transferred to the Odroid. After half a minute the chdkptp throws the following error message:
ERROR: .../chdkptp/lua/chdku.lua:1339: timed out

Any clue why there would be a difference between the cameras?
I have got CHDK 1.3.0-4029 installed and the latest chdkptp version.

Thanks in advance,
Amit
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / February / 2015, 16:58:27
Hello,

I have a setup where I use a Powershot S110 connected to an Odroid, controlled by the chdkptp code. I activate 'remoteshoot -cont'. I have two cameras. In one camera the 'remoteshoot -cont' works fine. In the other I can use the 'remoteshoot' command but when I try to use it in continuous mode (i.e. with the -cont option) the camera makes noise of shooting two images and then stops. No image is transferred to the Odroid. After half a minute the chdkptp throws the following error message:
ERROR: .../chdkptp/lua/chdku.lua:1339: timed out

Any clue why there would be a difference between the cameras?
I have got CHDK 1.3.0-4029 installed and the latest chdkptp version.
Are you trying to use both cameras simultaneously, or does one camera always work and the other not?

If cameras of the same model behave differently, it is probably due to differences in CHDK settings, Canon settings, or the CHDK version.

What canon firmware versions are S110? If they are different, it's possible there is a bug in one CHDK port but not the other.

Title: Re: CHDK PTP interface
Post by: amit on 26 / February / 2015, 22:16:39
Its hard to tell what firmware was on the working camera as it was completely destroyed in a drone crash yesterday :). STICK reports that the non working camera has firmware version 102b. Btw, the jpeg I used (for the determining  the firmware version) was taken while the camera had a CHDK card in it. Can this interfere with the firmware detection?
So now I have only one camera with firmware 102b and CHDK 1.3.0, where 'remoteshoot -cont' doesn't work ('remoteshoot' in non continuous mode works). What CHDK settings can interfere with the operation? And how can I debug this? For example can I change the firmware of the camera and test another port of CHDK?

Thanks,
Amit
Title: Re: CHDK PTP interface
Post by: nafraf on 26 / February / 2015, 22:36:22
Its hard to tell what firmware was on the working camera as it was completely destroyed in a drone crash yesterday :).
If you have a photo taken with destroyed camera, it is possible to determine its fw version from exif data.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / February / 2015, 22:50:05
Btw, the jpeg I used (for the determining  the firmware version) was taken while the camera had a CHDK card in it. Can this interfere with the firmware detection?
No, it won't interfere.

Quote
So now I have only one camera with firmware 102b and CHDK 1.3.0, where 'remoteshoot -cont' doesn't work ('remoteshoot' in non continuous mode works).
Out of curiosity, does remoteshoot -quick work?
Quote
What CHDK settings can interfere with the operation? And how can I debug this?
I don't know any off the top of my head, my suggestion was that if two identical cameras behave differently, compare the settings in both CHDK and the canon firmware.

If the card from the destroyed camera is still usable, you could copy the cfg files onto the card for the working camera to get identical CHDK settings.

Quote
For example can I change the firmware of the camera and test another port of CHDK?
No.

edit:
If you can get the version of the destroyed cam from an old picture as nafraf suggested, that would be helpful.
Title: Re: CHDK PTP interface
Post by: amit on 27 / February / 2015, 08:22:31
Thanks for the replies.

'remoteshoot -quick' has the same effect as 'remoteshoot -cont', i.e., the camera makes the sound of two shoots, the camera screen gets stuck on the histogram drawing (black background), about 15 seconds later I get a sign Busy and a second later the camera screen goes back to the 'Play' mode and I get the error I mentioned previously.

I tried the card from the destroyed camera (CHDK 1.4.0) and I get the same behavior.

I used STICK and an image from the destroyed camera to check its firmware: 102b, which is the same as the firmware of the buggy camera.

Regarding the settings of the destroyed camera. I don't remember its settings, but from what I remember the camera dial button was set on 'Tv' (or maybe 'Av'). This is strange as the chdkptp docs clearly state that the camera should be set to continuous mode, which is in the 'SCN' dial mode. Maybe this gives some clue?

Btw, the camera (the buggy one) works correctly in continuous mode (of the camera, not of chdkptp). I can grab several images very quickly into the SD card.

The cameras are used in a drone, due to that they might be subject to physical pressure, especially the usb plug. Can this be attributed to a hardware malfunction (possibly in the usb connection).

Thanks,
Amit
Title: Re: CHDK PTP interface
Post by: srsa_4c on 27 / February / 2015, 15:03:17
Regarding the settings of the destroyed camera. I don't remember its settings, but from what I remember the camera dial button was set on 'Tv' (or maybe 'Av'). This is strange as the chdkptp docs clearly state that the camera should be set to continuous mode, which is in the 'SCN' dial mode. Maybe this gives some clue?
Yes, don't use that scene mode. There is a problem with the terminology, we use the word "mode" for many different things. What we call 'continuous mode' is actually available in many camera modes, including Av, Tv, M, P. The manual calls it "Continuous Shooting", press SET when the camera is in shooting mode and find it in the menu that appears.
Title: Re: CHDK PTP interface
Post by: amit on 28 / February / 2015, 10:11:20
Thanks a lot, that solved the problem :-)

I have another question regarding a different model, the Powershot N. We are considering buying it also for the drone. I have posted a question on the 'Powershot N porting thread' but got no reply. Does anyone have experience with this camera? i.e. I need to know if it is possible, with 'chdkptp', to:
1) Control the focus (no manual focus in the camera)
2) Control the exposure (no manual mode in the camera)
3) Use it with 'remoteshoot -cont'

Thanks in advance,
Amit
Title: Re: CHDK PTP interface
Post by: waterwingz on 28 / February / 2015, 14:36:11
I have another question regarding a different model, the Powershot N. We are considering buying it also for the drone. I have posted a question on the 'Powershot N porting thread' but got no reply
Sorry - I guess that I'm as close as you get to the resident expert on the N as I did the port. However I'm currently traveling without my computer or much access to the internet until the second week of March.

Quote
. Does anyone have experience with this camera? i.e. I need to know if it is possible, with 'chdkptp', to:
1) Control the focus (no manual focus in the camera)
2) Control the exposure (no manual mode in the camera)
3) Use it with 'remoteshoot -cont'
I've used the CHDK port for the N extensively with chdkptp. Off hand, I see no reason this will not work. And if it doesn't, we will fix it.  Having said that, i can't remember if MF works - there may be a comment in the poriting thread for the N or the large thread on fixing MF for 1.3.0. (sorry - no links- to hard to do on my mobile device)

If you can wait a week, I can check this properly and get back to you?
Title: Re: CHDK PTP interface
Post by: amit on 08 / March / 2015, 22:15:31
Hi,

Is it possible to set the datetime of the camera (specifically S110) using chdkptp?

Thanks,
Amit
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / March / 2015, 23:58:02
Is it possible to set the datetime of the camera (specifically S110) using chdkptp?
You can probably do this using event procs (http://chdk.wikia.com/wiki/Event_Procedure). To use event procs, you need "native function calls" in the CHDK miscellaneous menu.

There is an example of how to do this http://chdk.setepontos.com/index.php?topic=7280.msg97087#msg97087 (http://chdk.setepontos.com/index.php?topic=7280.msg97087#msg97087) but beware that event proc names could be different on your camera. In this case, some of the return values will be -1 and the date won't get set. If that happens, we can probably find the correct names.


Title: Re: CHDK PTP interface
Post by: mk on 01 / April / 2015, 17:09:28
Hello,

I've tried to set the datetime of the camera Canon S110 using event procs as suggested in the previous comment and received -1. Unfortunately, I couldn't find the correct event proc names. Can you help me with that?

Thank you,
Michael
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / April / 2015, 19:46:22
I've tried to set the datetime of the camera Canon S110 using event procs as suggested in the previous comment and received -1.
Can you copy and paste the lines from the chdkptp console? Would be useful to know which step failed.
Title: Re: CHDK PTP interface
Post by: KNEi on 14 / May / 2015, 06:37:11
Hi!
Is it possible to add in chdkptp something like "onion skin" for making stop motin movies?
Thank's!
Title: Re: CHDK PTP interface
Post by: msl on 14 / May / 2015, 09:45:13
CHDK has nice function for this task - edge overlay. chdkptp is not absolutely necessary.

=> http://chdk.wikia.com/wiki/CHDK_1.3.0_User_Manual#Edge_Overlay_.28panorama_tool.29 (http://chdk.wikia.com/wiki/CHDK_1.3.0_User_Manual#Edge_Overlay_.28panorama_tool.29)

msl
Title: Re: CHDK PTP interface
Post by: KNEi on 15 / May / 2015, 09:54:57
Thank you! Edge overlay is great thing.
But I still interest of onion skin in chdkptp or make visible canon SX 230 hs in Dragonframe or Stop motion Pro.
But if it is impossible I'll use edge overlay  :)
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / May / 2015, 17:21:05
Thank you! Edge overlay is great thing.
But I still interest of onion skin in chdkptp or make visible canon SX 230 hs in Dragonframe or Stop motion Pro.
But if it is impossible I'll use edge overlay  :)
There is no feature like this in chdkptp. If you have some programming skill, you might be able to implement it. The live view drawing is mostly done with IUP and CD from Lua, see lua/gui_live.lua. You do not need to re-build chdkptp if you modify the Lua code. You can also interactively execute Lua from the console with the ! command.
Title: Re: CHDK PTP interface
Post by: KNEi on 16 / May / 2015, 04:14:18
I haven't any programmer skills :( But I found a way to make something like onion skin using chdkptp and ghostwin. It's not perfect and takes a lot of time to make 1 photo.
Here photo :)
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / May / 2015, 15:26:47
I haven't any programmer skills :( But I found a way to make something like onion skin using chdkptp and ghostwin. It's not perfect and takes a lot of time to make 1 photo.
Here photo :)
If there is a simple way chdkptp could make it easier to do what you want, feel free to suggest it in the chdkptp thread http://chdk.setepontos.com/index.php?topic=6231.780 (http://chdk.setepontos.com/index.php?topic=6231.780)

I can't promise to implement it.

Keep in mind I know essentially nothing about stop motion, onion skinning etc. As far as I understand, you want to overlay the current live view on a previous frame?
Title: Re: CHDK PTP interface
Post by: KNEi on 16 / May / 2015, 15:52:08
Yes, it is exactly that I want  :) 
What is the probability that they will do it?
Title: Re: CHDK PTP interface
Post by: kamal1210 on 26 / January / 2016, 12:28:34
I am trying to perform remote capture with PowerShot SX170IS (Firmware Version: 1.01, CHDK Version: 1.4.1 and SVN build of CHDK-PTP).

Other commands are working but when I type rec, the chdk-ptp terminal returns error:switch failed and camera hangs. It does not even turn off.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / January / 2016, 13:27:07
I am trying to perform remote capture with PowerShot SX170IS (Firmware Version: 1.01, CHDK Version: 1.4.1 and SVN build of CHDK-PTP).

Other commands are working but when I type rec, the chdk-ptp terminal returns error:switch failed and camera hangs. It does not even turn off.
Are you using linux? Does the physical camera screen go black when you plug in the camera?

If so, I would guess it's the "Interactions with default software" described on https://www.assembla.com/spaces/chdkptp/wiki/Install (https://www.assembla.com/spaces/chdkptp/wiki/Install)
Title: Re: CHDK PTP interface
Post by: kamal1210 on 27 / January / 2016, 01:31:31
Thanks :) That was the problem. I thought un-mounting should do it but it didn't.
Title: Re: CHDK PTP interface
Post by: kamal1210 on 27 / January / 2016, 03:37:53
I was wondering if  it is possible to remote shoot in burst mode. If yes how?
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / January / 2016, 13:04:51
I was wondering if  it is possible to remote shoot in burst mode. If yes how?
If you mean shoot several shots quickly without re-focusing, you can use -quick=N or -cont=N. N is the number of shots to take. Quick simulates holding the shutter half way and clicking full. This should work on all cameras that support remoteshoot. Cont uses Canon continuous mode. This requires that you set the camera to continuous mode in the Canon UI first, and has problems on some cameras. If you are using quick, you should turn off review in the canon settings.

If you mean the Canon firmware "burst" mode that some cameras have, there's no specific support for it. It might work with -cont.
Title: Re: chdkptp - alternative ptp client
Post by: Ant on 14 / April / 2017, 17:44:53
reyalp
I am asking you again to enable memory reading from address 0.
Title: Re: Re: chdkptp - alternative ptp client
Post by: reyalp on 14 / April / 2017, 22:47:33
reyalp
I am asking you again to enable memory reading from address 0.
I didn't spend much time on it, but it appears to me that the canon send_data function fails on NULL pointer. On G7X, If I take out the param2 == 0 check in PTP_CHDK_GetMemory I still get the same

"ERROR: Protocol error: data expected"

I'd suggest using the uncached address, but it seems return different values, probably due to TCM being mapped to 0.

edit:
If you want to experiment the check is in the CHDK code core/ptp.c.
Title: Re: Re: chdkptp - alternative ptp client
Post by: srsa_4c on 16 / April / 2017, 10:37:20
Quick hack that lets getting camera memory from places that are not PTP friendly (I wanted to get a copy of the 0xbfe10000 TCM content). It uses buffered read. Still not suitable for reading MMIO because it uses memcpy.

It's available via the d (download) chdkptp command, using a special filename:
Code: [Select]
d -nolua MEM<start addr>,<length> [memdump.bin]where <start addr> is the starting address in decimal or hex, <length> is the dump length in bytes.
Code: [Select]
Index: core/ptp.c
===================================================================
--- core/ptp.c (revision 4794)
+++ core/ptp.c (working copy)
@@ -495,6 +495,60 @@
         free(temp_data.str);
         temp_data_kind = 0;
 
+        // hack, parse filename for special operation (gets camera memory range)
+        // format: MEM<start addr>,<length>
+       
+        char *comma = 0;
+        // check for special file name (starts with MEM)
+        if (strstr(fn, "A/MEM"))
+        {
+            comma = memchr(fn+5, ',', temp_data_extra-5);
+        }
+        if (comma)
+        {
+            *comma = 0;
+            unsigned long start = strtoul(fn+5, 0, 0);
+            unsigned long length = strtoul(comma+1, 0, 0);
+           
+            // some protection against typos
+            if (length > camera_info.maxramaddr+1)
+            {
+                length = camera_info.maxramaddr+1;
+            }
+           
+            buf = (char *) malloc(buf_size);
+            if ( (buf == NULL) || (length == 0) )
+            {
+              // send dummy data, otherwise error hoses connection
+              send_ptp_data(data,"\0",1);
+              ptp.code = PTP_RC_GeneralError;
+              if (buf)
+              {
+                free(buf);
+              }
+              free(fn);
+              break;
+            }
+            tmp = t = length;
+            while (t > 0)
+            {
+              r = (t<buf_size)?t:buf_size;
+              t -= r;
+              memcpy(buf, (void*)start, r);
+              start += r;
+              // cannot use send_ptp_data here
+              data->send_data(data->handle,buf,r,tmp,0,0,0);
+              tmp = 0;
+            }
+            free(fn);
+            free(buf);
+            ptp.num_param = 1;
+            ptp.param1 = length;
+            // we're finished
+            break;
+        }
+        // hack end
+
         f = fopen(fn,"rb");
         if ( f == NULL )
         {
edit:
fixed 2 memory leaks
Title: Re: Re: chdkptp - alternative ptp client
Post by: reyalp on 16 / April / 2017, 14:44:43
I wasn't convinced of the need for code changes to read address zero, but a general buffered option for GetMemory seems like it would be useful. I'll try to add something a bit less hacky.
Title: Re: Re: chdkptp - alternative ptp client
Post by: Ant on 16 / April / 2017, 14:58:33
I wasn't convinced of the need for code changes to read address zero
Every time I work with RAM dumps made with chdkptp I need to recalculate addresses. This is inconvenient.
Title: Re: Re: chdkptp - alternative ptp client
Post by: 62ndidiot on 17 / April / 2017, 11:09:11
Just need to output a place holder. 
Title: Re: Re: chdkptp - alternative ptp client
Post by: reyalp on 17 / April / 2017, 13:26:31
Quick hack that lets getting camera memory from places that are not PTP friendly (I wanted to get a copy of the 0xbfe10000 TCM content). It uses buffered read. Still not suitable for reading MMIO because it uses memcpy.
One slight complication http://pubs.opengroup.org/onlinepubs/009695399/functions/memcpy.html

Quote
If copying takes place between objects that overlap, the behavior is undefined.
This will obviously happen if you are dumping the whole RAM using a buffered copy. Whether this applies to dryos or actually matters is unclear. Obviously no RAM dump is going to be fully consistent instantaneous snapshot.
Title: Re: Re: chdkptp - alternative ptp client
Post by: srsa_4c on 17 / April / 2017, 14:02:31
Quote
If copying takes place between objects that overlap, the behavior is undefined.
This will obviously happen if you are dumping the whole RAM using a buffered copy. Whether this applies to dryos or actually matters is unclear. Obviously no RAM dump is going to be fully consistent instantaneous snapshot.
TBH, I did this because I needed it, and wanted to get it done fast. As you say, this (in its current form) may not be what Ant wants, because it can mess up the copied version of the Canon heap.
A more proper implementation would only use memcpy for areas that can't be safely transmitted directly via the PTP send function. An even more proper implementation would also use a single-word-at-a-time copy routine for MMIO areas.
Title: Re: Re: chdkptp - alternative ptp client
Post by: reyalp on 17 / April / 2017, 16:32:55
TBH, I did this because I needed it, and wanted to get it done fast. As you say, this (in its current form) may not be what Ant wants, because it can mess up the copied version of the Canon heap.
Yes, understood and thanks for posting it. I wasn't criticizing the hack, just trying to figure out what to add to the protocol.

My first thought was to just add a "buffered" option to GetMemory , but as you say this isn't great for whole memory dumps. Then again, even with DMA whole memory dumps aren't going to be totally consistent. I suspect the "undefined" is refers to the content copied in overlapping regions, which really isn't a problem since looking at the PTP transfer buffer in a PTP memory dump wouldn't make sense.

Ideally you'd want GetMemory to automatically identify the different regions and use DMA, memcpy or word by word as required, but analyzing the CP15 values at run time seems excessive.
Title: Re: Re: chdkptp - alternative ptp client
Post by: srsa_4c on 17 / April / 2017, 20:24:22
Ideally you'd want GetMemory to automatically identify the different regions and use DMA, memcpy or word by word as required, but analyzing the CP15 values at run time seems excessive.
Perhaps allowing the user to specify the method would be the optimal solution.
Except for RAM dumps, where we'd want to copy the zero mapped TCM buffered (RAM between 0..MEMBASEADDR, to avoid detection).
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / April / 2017, 00:51:15
I moved this to the PTP interface thread, since it's was more of a protocol / camera side issue than a chdkptp client issue.

In r4798, I committed the following:
ptp - updates to PTP_CHDK_GetMemory, based on discussion in https://chdk.setepontos.com/index.php?topic=6231.msg132332#msg132332
* Automatically work around Canon data->send_data failing on NULL source, by sending any bytes in first word buffered if source address is < 4
* Update to use data->send_data instead of send_ptp_data. Better performance, same strategy already used for live view, remote shoot
* Update protocol to 2.8: PTP_CHDK_GetMemory input param4 is option which defines whether transfer should be buffered or unbuffered, independent of address 0 workaround. Default (0) is unbuffered, compatible with previous versions

I went through a few different approaches before I settled on this.

On my cameras, the problem with NULL really seems to be only that the Canon function treats NULL as an error. So I made the default GetMemory function just detect that and transfer any bytes in the first word separately. (First word rather than first byte because of https://chdk.setepontos.com/index.php?topic=13101.0)

This means that existing clients should now be able to do RAM dumps from address zero, although it's possible some will still fail because due to the first 4 or 16 kb being TCM.

I also changed the unbuffered GetMemory to use a single send_data call, unlike the original version which sent in buffer_size chunks despite not being buffered. This is noticeably faster (33 MB/s vs 28 MB/s on D10) I believe the original logic was based on the idea that the firmware might try to allocate internal buffers for the whole transfer, but this is clearly not true, because live view and remote capture send all at once.

Separate from this, I added the mode option to PTP_CHDK_GetMemory to do the entire transfer buffered. This requires client support, chdkptp r741 or later

It currently uses memcpy. Originally, I was going to have another option for word-by-word copy, but in my testing memcpy worked fine for MMIO addresses. If it turns out word-by-word is needed, it's easy to add. Note that many MMIOs are write only, and reading them may have side effects, so dumping the whole MMIO space may not be a great idea in any case.

Buffered is noticeably slower than unbuffered, ~17 vs 35 MB/s for G7X. Oddly, D10 suffers less of a penalty (18 vs 33)

While mentioning speed
On a540 cached addresses are much slower than uncached, 5 vs 15 MB/s. ROM is in between at 12. I these old cameras buffer internally if the address isn't in uncached RAM. This was noted long ago.

Interestingly on newer cameras (d10 onward) there seems to be little difference between cached an uncached. ROM is somewhat slower than RAM (26 MB/s on G7x, 13  on D10)
Title: Re: CHDK PTP interface
Post by: dmitrys on 27 / June / 2017, 16:41:18
Has there been any progress on the PTP event front beyond mweerden's findings (http://www.mweerden.net/chdk_ptp2.html)?

The reason I'm asking is I've been looking into implementing some debugging capabilities (https://chdk.setepontos.com/index.php?topic=13177) on the Initiator side, and polling CHDK_PTP_GetMemory doesn't seem like an optimal approach.
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / June / 2017, 23:58:24
Has there been any progress on the PTP event front beyond mweerden's findings (http://www.mweerden.net/chdk_ptp2.html)?
Note that I am aware of.
Title: Re: CHDK PTP interface
Post by: reyalp on 18 / March / 2019, 00:56:36
I ran into a weird bug on D10.
PTP commands that send specific lengths of data fail.
Some data (seems to be consistently 5032 bytes in my tests) is received, but the remainder is mostly filled with other junk from RAM. The PTP command then fails with I/O error on the chdkptp side, after a significant time.
Aside from the stalled PTP connection, everything seems fine with the camera, it can be reconnected after issuing
Code: [Select]
!chdk.reset_device(con.condev)
This can happen with file upload, or sending messages. For files, the length includes the filename and 4 bytes for the filename length in addition to the data itself. Messages send exactly the message content length. I assume other bulk sends are affected as well.

None of my other cameras (a540, sx160, elph130, g7x, sx710, elph180) appear to be affected.

Lengths of data that fail (tested exhaustively with extras/msgtest.lua) are
0x23f4
0x25f4
0x27f4
0x29f4
0x2bf4
0x2df4
0x2ff4
0x31f4
...and further increments of 512

I only ran into this because a file I was trying to upload ended up with name info and contents being exactly 0x2bf4. This happens on multiple different hubs from a PC and on a raspberry pi, so it's not a host or hub issue.

The sizes above are not close to the limit of available memory, and it happens with or without a script running, so it's not dependent on some exact memory layout on the camera.

A simple way to test for the issue is:
Code: [Select]
!con:write_msg(('x'):rep(0x23f4))
If the bug isn't present, you will immediately get
Code: [Select]
ERROR: call failed:no script running
If it is present, it will hang for several seconds and you will get:
Code: [Select]
ERROR: call failed:I/O error

To exhaustively test a range of sizes, you can use something like
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=1,sizemax=0x3000,sizeinc=1,gc='step'}
It will stop if it hits the error.
Note that prior to chdkptp r846 it would stop one before sizemax.

I would be interested to know if cameras similar to D10 are affected (DryOS 31, 2009, Digic IV)

This is somewhat reminiscent of the old digic 2 alignment bug: https://chdk.setepontos.com/index.php?topic=6730.msg76676#msg76676 but the specifics are obviously different.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 18 / March / 2019, 19:10:21
I would be interested to know if cameras similar to D10 are affected (DryOS 31, 2009, Digic IV)
Tested my r31 and r23 cams. The one affected is the ixus110/sd960 (r31). Unaffected: sx100 (r23), a470 (r23), g10 (r31), ixus870/sd880 (r31). The a470 crashed once, but not at those sizes and I could not reproduce.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / March / 2019, 17:15:27
I would be interested to know if cameras similar to D10 are affected (DryOS 31, 2009, Digic IV)
Tested my r31 and r23 cams. The one affected is the ixus110/sd960 (r31). Unaffected: sx100 (r23), a470 (r23), g10 (r31), ixus870/sd880 (r31). The a470 crashed once, but not at those sizes and I could not reproduce.
Thanks. I assume you were using the msgtest test when a470 crashed? If there's a romlog, I'd be interested to see it.

> r31 cams could be interesting too, after D10, the next oldest I have is SX160 (DryOS 51, digic IV, 2012)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 23 / March / 2019, 19:01:45
I assume you were using the msgtest test when a470 crashed?
Yes. Romlog attached (a470 102c) (edit: date is wrong, of course). My theory is that one of the Canon libraries had a bug that was relatively quickly fixed and only affected a few models.

Quote
> r31 cams could be interesting too, after D10, the next oldest I have is SX160 (DryOS 51, digic IV, 2012)
a490 (r43), a3200 (r47): no failures, tested range 0x2300...0x3000.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / March / 2019, 02:18:52
Yes. Romlog attached (a470 102c) (edit: date is wrong, of course).
Thanks. That's deep in the Canon PTP code, which suggests it could be an actual PTP problem, rather than say, running out of memory or some other unrelated CHDK issue.

Quote
My theory is that one of the Canon libraries had a bug that was relatively quickly fixed and only affected a few models.
Or chdkptp is doing something not quite correct that other versions tolerate. There are some weird rules about sending a zero-length packets when the data length is an exact multiple of the max packet size.

Looking for ways to debug this, I was reminded there appears to be a separate logging system connected to PTP, which maybe writes to "A/BulkTrns.Log"

The logging function is FF9F7AF0 on d10 (sub_FFD9A06C on your a470)

I haven't yet figured out how to enable it. figured it out while writing this post ;)  It appears to be set up in sub_FFD9A268 based on a call to FF9FA8F8

This seems to be checking some kind of system with named values, but "PtpBulkLogFlag" is only mentioned in that one place, so it's not clear how to set it. Maybe it's compile time in Canon code. Other names used by the same system (PlatformWrapper.c apparently) are referenced in other places, e.g "PTPConfig.SupportedSlideShow", "PTPConfig.VenderExtensionVerrsion", "PTP GetDeviceInfo Configuration"

There appears to be 3 functions associated with this system:
A set / register function sub_FF9FA7D0 ("name",value)
Value seems to be a pointer or arbitrary constant
A clear / unset function sub_FF9FA85 ("name")
and the above mentioned get function
status =  sub_FF9FA8F8("name",*value)
which returns 0 if value is present, or has bit 1 set if not. The original value saved is returned in *value.

The name, value pairs are stored sequentially in memory, starting at 0x785A4 on d10.

Based on the code that checks "PtpBulkLogFlag" the value doesn't matter, as long as it's not 0.

Putting this all together, I made a Lua script that enables the bulk log flag. This appears to only take effect on next physical USB connection (i.e. USB bit being set) and isn't flushed until disconnection. The log is appended between session. The function pointer values are obviously camera specific, but if they turn out to be useful, they should be easy to add to the sigfinders.

In the failed case, the log looks like this
Code: [Select]
00024920: Op.[0x1002], P1[0x00000001]

00024930: Res.Comp

00024930: Op.[0x1001]

00024930: SendData,Len=385

00024930: Res.Comp

00024930: Op.[0x9999], P1[0x00000000]

00024940: Res.Comp

00035250: Op.[0x9999], P1[0x0000000b]

00035250: ReceiveData,Len=9204

00035250: WaitNullPacket fNullEnd = 1, Total=9216, Current=512, SendLen=87
00048970: DoTransactionCanceled()
Op 0x9999 P1 = 0xb is PTP_CHDK_WriteScriptMsg
Title: Re: CHDK PTP interface
Post by: srsa_4c on 24 / March / 2019, 17:02:22
Tried 2 cams, one with the issue, one without.
Enabled the ptp log via the script, connected usb, pressed "connect" on chdkptp gui, executed the !con:write_msg(('x'):rep(0x23f4)) one-liner, after a few seconds pressed "disconnect", and finally I disconnected usb before shutting down the cam.
g10, has no issue:
Code: [Select]
00028010: Op.[0x9999], P1[0x0000000a]
00028010: SendData,Len=758
00028010: Res.Comp
00028020: Op.[0x9999], P1[0x00000008]
00028020: Res.Comp
00028020: Op.[0x9999], P1[0x0000000a]
00028020: SendData,Len=4
00028030: Res.Comp
00028030: Op.[0x9999], P1[0x00000008]
00028040: Res.Comp
00033370: Op.[0x9999], P1[0x0000000b]
00033370: ReceiveData,Len=9204
00033370: WaitNullPacket fNullEnd = 1, Total=9216, Current=512, SendLen=87
00033370: Res.Comp
00041990: Op.[0x1003]
00041990: Res.Comp
00042050: DoTransactionCanceled()
00044170: DoTransactionCanceled()
ixus110, has the issue:
Code: [Select]
00016630: Op.[0x9999], P1[0x00000008]
00016630: Res.Comp
00016790: Op.[0x9999], P1[0x00000008]
00016790: Res.Comp
00016790: Op.[0x9999], P1[0x0000000a]
00016790: SendData,Len=667
00016790: Res.Comp
00016800: Op.[0x9999], P1[0x00000008]
00016800: Res.Comp
00016800: Op.[0x9999], P1[0x0000000a]
00016800: SendData,Len=4
00016800: Res.Comp
00016810: Op.[0x9999], P1[0x00000008]
00016810: Res.Comp
00022040: Op.[0x9999], P1[0x0000000b]
00022040: ReceiveData,Len=9204
00022040: WaitNullPacket fNullEnd = 1, Total=9216, Current=512, SendLen=87
00036370: DoTransactionCanceled()
00038320: DoTransactionCanceled()
On the Ixus, USB communication after the test message is disrupted. I'm not 100% sure, but I think the first DoTransactionCanceled() appears after the (unsuccessful?) chdkptp disconnection attempt, the second one comes after the USB physical disconnection.
On the g10, I'd guess Op.[0x1003] initiates the disconnection and DoTransactionCanceled() appears when disconnect is done and again when the cam is physically disconnected.

Would it be possible to send that null packet?
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / March / 2019, 17:59:10
Some additional notes (written at the same time as srsa_4c...):
Output on non-affected cam is similar. Elph130, with 0x23f3 and 0x23f4 length messages:
Code: [Select]
00026150: Op.[0x1002], P1[0x00000001]
00026150: Res.Comp
00026150: Op.[0x1001]
00026150: SendData,Len=417
00026160: Res.Comp
00026160: Op.[0x9999], P1[0x00000000]
00026160: Res.Comp
00040640: Op.[0x9999], P1[0x0000000b]
00040640: ReceiveData,Len=9203
00040640: Res.Comp
00051980: Op.[0x9999], P1[0x0000000b]
00051980: ReceiveData,Len=9204
00051980: WaitNullPacket fNullEnd = 1, Total=9216, Current=512, SendLen=87
00051980: Res.Comp
00055710: Op.[0x1003]
00055710: Res.Comp
00055720: DoTransactionCanceled()
00058660: DoTransactionCanceled()
(1001 = PTP_OC_GetDeviceInfo, 1002 = PTP_OC_OpenSession, 1003 = PTP_OC_CloseSession)

Total is +12 bytes for the request, which makes the failed cases 9216 = 18*512.
I'm not clear what the SendLen=87 refers to.
Also noteworthy multiples of 512 from 2 to 17 trigger the WaitNullPacket message without issue. I don't see anything obvious in chdkptp that would depend on whether the size was >= 18*512. The chdkptp code does *not* break writes in to 512 byte chunks. It does send the null packet when the total is a multiples of 512. This logic is unchanged from ptpcam.

chdkptp side logging on D10
Code: [Select]
con> !con:write_msg(('x'):rep(512*18-12))
ptp_usb_sendreq trans=5 len=0x14 (20) code=0x9999 nparam=2 param1=0x0000000b
USB_BULK_WRITE returned 20, size=20
ptp_usb_senddata trans=5 len=0x2400 (9216) code=0x9999
USB_BULK_WRITE returned 512, size=512
USB_BULK_WRITE returned 8704, size=8704
USB_BULK_WRITE returned 0, size=0
usb_bulk_read: No error
ERROR: call failed:I/O error
Elph130 is similar except it except it doesn't end with IO error.

On separate topic, the "PlatformWrapper" code could potentially give us a way to override other things, like the DeviceInfo information or supported events.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / March / 2019, 19:16:19
On the Ixus, USB communication after the test message is disrupted. I'm not 100% sure, but I think the first DoTransactionCanceled() appears after the (unsuccessful?) chdkptp disconnection attempt, the second one comes after the USB physical disconnection.
On the g10, I'd guess Op.[0x1003] initiates the disconnection and DoTransactionCanceled() appears when disconnect is done and again when the cam is physically disconnected.
I think the double DoTransactionCanceled() in both cases is due to the chdkptp disconnection code issuing usb_reset(). Commenting this this out seems to eliminate it, without obvious ill effect. (I've actually meant to make this optional for a long time...)

Quote
Would it be possible to send that null packet?
The log in my previous post seems to indicate that it is sent, and the whole sequence succeeds from the host POV, and the I/O error comes from reading the response. I guess ptp.c ptp_usb_senddata could be modified to send another one if the data is the magic length (to avoid messing up the transactions required to make the connection).
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / March / 2019, 00:22:15
Some notes on capturing USB traffic. This wasn't immediately productive for the current issue, but I'm writing it down while it's fresh in my mind.

I did this on linux (ubuntu 18.04) because wireshark has some scary warnings on the windows USB capture driver.

Attempting to capture directly from wireshark failed with a permission issue.  It suggested
Code: [Select]
sudo dpkg-reconfigure wireshark-common
... check allow regular users to capture...
sudo usermod -a -G wireshark <user>
and re-logging in, but this didn't resolve the issue.

I captured as root instead using the command line program dumpcap instead

The capture interfaces are per bus, so usbmon1 is for devices on bus 1. While dumpcap has a filter parameter, it's not clear to me if or how you could filter to a specific USB device at capture time.

To capture everything on bus 1 to a file
Code: [Select]
dumpcap -i usbmon1 -w file.pcap
I could then open the file in wireshark.
To filter traffic involving the device (bus 1, device 9) I used
Code: [Select]
usb.addr contains "1.9"
The actual destination will show up as 1.9.x where x is the endpoint for the specific traffic. addr means it matches either source or destination.

This was successful and shows the requests, but wireshark doesn't appear to include a dissector for USB PTP (there is one for PTP/IP, and some work on a USB one a long time ago https://wiki.wireshark.org/USB-PTP https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=8431).

The > 512 writes show up as single USB_BULK packets. This is also seen on camera to host traffic. I assume we just aren't seeing things at the level that would show it broken up into separate packets.

edit:
I tried making ptp_usb_write_func call USB_BULK_WRITE with no more than 512 at a time, but this had no effect on the problem or the BulkTrns.Log output.
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / March / 2019, 02:09:48
I guess ptp.c ptp_usb_senddata could be modified to send another one if the data is the magic length (to avoid messing up the transactions required to make the connection).
I tried this, and the write for the second NULL packet timed out.

The error we normally see is the read for get_resp timing out. So it appears the camera state gets hosed during the writes, even though both the data write and null packet appear to succeed from the host POV.

From the camera side, we don't actually check check status on the data transfer function data->recv_data... I sometimes returns partial results, and is just waiting to be called again? At the start of this, I noticed that the data was only partially received.

edit:
recv_data returns 1 in the failed case, 0 on others.


The buf_size logic in recv_ptp_data is also weird.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / March / 2019, 14:33:47
Turns out we spent quite a bit of time digging around the same areas in 2012 (:o) for the original  NULL packet / length bug, discussed starting around https://chdk.setepontos.com/index.php?topic=4338.msg87093#msg87093

When I have a bit more time I'll poke around to see which of the several cases in recv_data that can return 1 is failing.

edit:
In fact, I even saw the d10 failure (https://chdk.setepontos.com/index.php?topic=4338.msg87354#msg87354) after we fixed the original problem, but didn't realize that it was reproducible at that length.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / April / 2019, 02:17:30
A bit more:
When the problem happens, recv_data itself takes a long time (~5 sec) to complete, so presumably it's waiting for something that times out. This isn't surprising since the actual communication is done in other tasks.

I confirmed that forcing the camera to do recv_data in chunks smaller than the problem size avoids the problem. Doing one read that isn't a 512 multiple first and then trying to do all the rest still fails.

Title: Re: CHDK PTP interface
Post by: reyalp on 14 / April / 2019, 18:44:03
I confirmed that forcing the camera to do recv_data in chunks smaller than the problem size avoids the problem.
I was about to check in a workaround based on this, but it turns out it only delays the problem to 0x45f4  >:(

edit:
One thing I'd like to test is whether the stock Canon code suffers the same issue. If so, then at least we know it's a Canon firmware bug, and if not, maybe there would be clues how they avoid it.

Standard PTP commands I found that send data are
SendObjectInfo
SendObject
SetDevicePropValue

Of these, SendObject seems the most likely to allow a problem size file, but it requires a SendObjectInfo first and seems complicated to set up. The original ptpcam code for SendObject and SendObjectInfo, but didn't implement code to actually use them. The Canon code does appear to implement them.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / April / 2019, 00:54:40
gphoto2 supports upload, so I thought I could get the problem size by padding the exif description of a 640x480 camera jpeg. Unfortunately, attempting to upload an unmodified jpeg from the camera fails with "Invalid Object Format Code"

This happens in response to the SendObjectInfo operation, so doesn't have anything to do with the content on the file.

When gphoto2 encounters an error, it suggests a command to provide a debug log, like

Code: [Select]
env LANG=C gphoto2 --debug --debug-logfile=my-logfile.txt ...
which produce a very nice log of device info, supported operations and each PTP operation used.

Based the fact that SendObjectInfo and SendObject are listed as supported and the amount of code associated with the handlers, I don't think it's just stubbed out in the Canon firmware, but maybe there's some details in the SendObjectInfo that need to be set a particular way.


Title: Re: CHDK PTP interface
Post by: srsa_4c on 16 / April / 2019, 13:27:08
gphoto2 supports upload, so I thought I could get the problem size by padding the exif description of a 640x480 camera jpeg. Unfortunately, attempting to upload an unmodified jpeg from the camera fails with "Invalid Object Format Code"
File upload with gphoto used to work on old cameras. Back in the days, I successfully used it on my first PowerShot (A200). I tested it on my s3is now, with success (card root was not accepted, but one of the image dirs worked). Same thing doesn't work on a more recent cam (g10).

I have no experience with the Windows built-in ptp/mtp support or Canon's utilities, does upload work with them?

The 0x100c handler can be found by looking up references to add_ptp_handler, the 0x100c one is located in a table.
Title: Re: CHDK PTP interface
Post by: reyalp on 16 / April / 2019, 23:33:46
I have no experience with the Windows built-in ptp/mtp support or Canon's utilities, does upload work with them?
Not windows 10 built in at least, haven't tried Canon yet.

Quote
The 0x100c handler can be found by looking up references to add_ptp_handler, the 0x100c one is located in a table.
Yeah, looking at those was part of reason I thought it wasn't just disabled, since it's fairly complicated. But maybe it's dead code.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / April / 2019, 13:15:28
Yeah, looking at those was part of reason I thought it wasn't just disabled, since it's fairly complicated. But maybe it's dead code.
Found the following in it (using ghidra's decompiler).
Code: [Select]
      if (local_c0 == 0x3002) {
        uVar5 = (uint)local_c0;
        if (param_7 != -1) {
          uVar5 = local_9c;
        }
        if (param_7 == -1 || uVar5 == 0xffffffff) {
          local_ec[0] = 0x201a;
          goto LAB_ff8c3ce4;
        }
      }
      else {
        if (local_c0 != 0xbf01) {
          local_ec[0] = 0x200b;
          goto LAB_ff8c3ce4;
        }
      }
local_c0: seems to be the ptp object format code (this code is loaded in other local vars too, but those copies seem unreferenced)
The constants:
From libgphoto ptp.h
Code: [Select]
#define PTP_OFC_Script 0x3002

#define PTP_RC_InvalidObjectFormatCode  0x200B
#define PTP_RC_InvalidParentObject      0x201A
Google found 0xbf01 in our svn, tools/patches/libptp2-1.1.0-canon-upload.diff
Code: [Select]
+// ((int*)data)[1]=0xbf01; // canon firmwareSo, could it be that uploading firmware files is supported? The upload patch is from vitalyb and pre-dates DryOS cameras.
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / April / 2019, 13:33:23
So, could it be that uploading firmware files is supported? The upload patch is from vitalyb and pre-dates DryOS cameras.
PS2 files are listed in PTP (even on windows), with type 0xbf01. I tried uploading with gphoto2 and windows, but it presumably doesn't set the type.

Interesting that "script" is another supported type...
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2019, 02:02:02
I added support in chdkptp r849 for the necessary operations to test upload.

On SX710, I can upload arbitrary files using the FI2 type. The actual file doesn't need to have an FI2 extension. The following works
Code: [Select]
!newfi2={ Filename="TEST.FI2", ObjectFormat=48897, ObjectCompressedSize=80448 }
!return con:ptp_send_object_info(newfi2)
=65537,0,262185
!con:ptp_send_object(('x'):rep(80448))
The 3 numbers are storage ID, parent handle and object handle, but we don't need them. SendObject just needs to send the size specified in the earlier SendObjectInfo.

The same sequence of commands on D10 crashes with ASSERT!! OpObjHdl.c Line 2645 in PTPSessionTA0, regardless of size  :-[ (edit: this is because some generations of cam expect 'A/' on the name https://chdk.setepontos.com/index.php?topic=4338.msg140115#msg140115)

I initially tried modifying an object info of an existing FI2 return by GetObjectInfo, just setting the name and size. This also works on SX710, and fails on D10.

Using GetObjectHandles puts the camera into the black screen PTP mode. The GetStorage* and SendObject* do not.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 21 / April / 2019, 07:31:35
The same sequence of commands on D10 crashes with ASSERT!! OpObjHdl.c Line 2645 in PTPSessionTA0, regardless of size  :-[
I tested a few DryOS cameras (did not test file content).
sx100 (r23): test executed
a470 (newer r23): the ptp_send_object command failed with "ERROR: call failed:Transaction Canceled", no fi2 file created
ixus110, g10, ixus870 (r31): all cams crashed on ptp_send_object
a490 (r43), a3200 (r47), a3400 (r50), ixus150 (r54): test executed
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / April / 2019, 17:05:10
Thanks for the reports.

Some more random notes:

On A540 (vxworks) PS.FIR is not listed as an object.  GetStorageIDs returns 2 items, with volume labels A and V. V is empty and has filesystem type 0x8001 (vendor extension)

The D10 firmware code related to SendObject also contains references to V/... (e.g. sub_FF8D1BA8) but only returns one storage, but only returns one storage, with a null volume label.

code snippets
list storage
Code: [Select]
!info={} for i,id in ipairs(con:ptp_get_storage_ids()) do info[i]=con:ptp_get_storage_info(id) end return info

list objects on all storage
Code: [Select]
!handles=con:ptp_get_object_handles()
!info={} for i,h in ipairs(handles) do info[i]=con:ptp_get_object_info(h) end return info

The OpObjHdl.c Line 2645 assert happens in the SendObject handler, related to the return value of sub_FF9F6458 (in ObjMethdRW.c). This function appears to reference the extension .RPC

The gihidra "Version Tracking" feature might help untangle the differences between R31 and later, but I still haven't dug into it.

I've been thinking about adding the various PTP handlers, send/recv etc functions to the sig finder csv for easier analysis.

edit:
The SendObjectInfo and SendObject handlers are also used for Canon extension opcodes 0x9024 and 0x9025, respectively (table starting at FFAE1924 on d10). Neither appears to check the opcode parameter in R2, but it's also probably in some of the data structures.
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / April / 2019, 01:29:20
OK, I figured out the assert on D10. It wants a full path like A/TEST.DAT  :haha (edit: This is somewhat odd since according to the PTP spec, one would set the directory with parent handle, and the returned objects have no path in the filename)

It does not appear to suffer from 512 multiple transfer problem.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / April / 2019, 01:10:19
Using uncached memory for the receiving buffer appears to fix the issue. This can be handled in recv_ptp_data by fiddling the cache bit, but we need a data cache flush function.

Making all the callers umalloc seems like a worse option.

Other notes:
On newer cameras, using A/ on SendObject crashes, so you have to know which form a camera wants before using it.

SendObject has some logic to do buffering with multiple reads, but it appears to have a pretty large buffer so it only used one in the problem case. It's possible this buffer is dedicated and could be re-used by our PTP code without taking away regular RAM, but I didn't track it down. d10 sub_FF8C9374 seems to be connected to the read (and presumably, buffer) size.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 23 / April / 2019, 13:24:58
SendObject has some logic to do buffering with multiple reads, but it appears to have a pretty large buffer so it only used one in the problem case. It's possible this buffer is dedicated and could be re-used by our PTP code without taking away regular RAM, but I didn't track it down. d10 sub_FF8C9374 seems to be connected to the read (and presumably, buffer) size.
The first routine that has a ComMemMan.c assert allocates 1MB uncached exmem (type 1, probably EXMEM_COM). I'd guess the buffer is there.
I wonder if that allocation can clash with those video buffers that need to be skipped when CHDK is loaded in exmem - most new-ish models don't support native remote shooting (except for the newest models that do).

Nice investigation, btw.
Title: Re: CHDK PTP interface
Post by: reyalp on 23 / April / 2019, 16:54:07
The first routine that has a ComMemMan.c assert allocates 1MB uncached exmem (type 1, probably EXMEM_COM). I'd guess the buffer is there.
Thanks for that.
Quote
I wonder if that allocation can clash with those video buffers that need to be skipped when CHDK is loaded in exmem - most new-ish models don't support native remote shooting (except for the newest models that do).
Good point. Seems likely since we weren't able to find a way to avoid those when allocating exmem. I guess if CHDK is already using EXMEM, the allocation for EXMEM_COM should fall outside it, but non-exmem enabled cams could see corruption.
Title: Re: CHDK PTP interface
Post by: philmoz on 24 / April / 2019, 20:22:08
Small patch for chdkptp to fix a crash on MacOS with libusb.
Also fixes a compiler warning in properties.c
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / April / 2019, 23:44:20
Small patch for chdkptp to fix a crash on MacOS with libusb.
Also fixes a compiler warning in properties.c
Thanks. Added in r859
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / April / 2019, 01:28:21
Using uncached memory for the receiving buffer appears to fix the issue. This can be handled in recv_ptp_data by fiddling the cache bit, but we need a data cache flush function.
This turns out to be more annoying than I had hoped. The cached address passed to recv_ptp_data isn't necessarily aligned to a cache line, so simply flushing or cleaning and flushing can corrupt neighboring data.

The attached patch cleans before the transfer (ensuring everything is written out from cache to RAM before the transfer starts) and cleans+flushes after, ensuring that subsequent reads will see the data that was DMAd to RAM. It's not applied to digic 6, but digic 6 cams don't appear to have the original problem.

This appears to "work" based on intensive msgtest testing, but AFAIK is still incorrect, because other tasks could write to cache in the in between. E.g. if malloc related structures happen to share a cache line with buffer, and another task malloc's something, it could get hosed. Stack buffers could also be problematic, since context switches put stuff on the tasks stack.

AllocateUncacheableMemory pads allocations with an extra 64 bytes, likely to avoid this kind of thing.

The patch doesn't seem to have any measurable performance impact.

tl;dr
It's probably better to use dedicated buffers or umalloc. This is kind of unfortunate, since transfers of files or large scripts can use a significant fraction of free memory. umalloc may also have less memory available, since it only allocates from the Canon heap.

It's also annoying that this only appears to be need for a small subset of camera, and only at specific transfer size. I guess we could use a small uncached buffer only on those cameras when needed, but that seems pretty hokey. ptp.c is also current platform independent code.

edit 2019 04 25:
Patch updated to fix digic 6 ifdef.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 25 / April / 2019, 18:53:24
tl;dr
It's probably better to use dedicated buffers or umalloc. This is kind of unfortunate, since transfers of files or large scripts can use a significant fraction of free memory. umalloc may also have less memory available, since it only allocates from the Canon heap.

It's also annoying that this only appears to be need for a small subset of camera, and only at specific transfer size. I guess we could use a small uncached buffer only on those cameras when needed, but that seems pretty hokey. ptp.c is also current platform independent code.
We could also make a umalloc implementation that could use all memory available to CHDK, and use that on cameras thought to be affected (replacing mallocs in ptp code, if that's even possible). The change you made in recv_ptp_data() is quite large (took out that while block), but I can't say I'm familiar with that code. One of the ifdefs has a typo.

I took a look at the ComMemMan routines. The first(?) two inits and uninits the communication memory, the following two look like an allocator and a de-allocator. But, as previously mentioned, we don't necessarily want to use memory from there due to corruption risk.
Title: Re: CHDK PTP interface
Post by: reyalp on 25 / April / 2019, 22:30:16
The change you made in recv_ptp_data() is quite large (took out that while block), but I can't say I'm familiar with that code. One of the ifdefs has a typo.
Yeah, that loop was the "buffering" logic I mentioned earlier. It was a leftover that didn't really make sense: in practice size was almost always <= buffer_size (half of the largest free block at the start of the PTP operation), and there appears to be no reason to operate in smaller chunks.

Thanks for catching the typo, I hadn't got around to testing it on digic 6. Patch updated.

I've now tested on a540, d10, sx160, and elph180, sx710, g7x like
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=1,sizeinc=1,count=10000,gc='step'}
!m.test{size=500,sizeinc=128,count=400,gc='step'}
The first tests single byte increments. The second covers a larger range including the problem (0x23f4 +n*512) values. It might fail on low memory cams trying to send a ~50k message.

Quote
I took a look at the ComMemMan routines. The first(?) two inits and uninits the communication memory, the following two look like an allocator and a de-allocator. But, as previously mentioned, we don't necessarily want to use memory from there due to corruption risk.
Agreed. I guess we could maybe use a similar approach to CHDK exmem and allocate an unused amount to cover the video buffers (if it allocates in a predictable way), or only use it in playback, but neither seems attractive for the amount of work.

Quote
We could also make a umalloc implementation that could use all memory available to CHDK, and use that on cameras thought to be affected (replacing mallocs in ptp code, if that's even possible).
It's not that bad, but in the case of script messages, the memory is passed on and freed elsewhere. When I was testing, I made a version of memmgmt.c free() that detected uncached memory and called ufree on it. Any processing on the allocated buffer would be slow, but it's likely insignificant compared to the transfer. Script is compiled directly from the buffer. Messages are copied into Lua strings.

uses of recv_ptp_data

flush_recv_ptp_data
mallocs/frees buffer. Discards results.

PTP_CHDK_SetMemory
Target address passed direct. Not implemented in chdkptp

PTP_CHDK_CallFunction
mallocs and frees a typically very small buffer for function arguments

PTP_CHDK_TempData
mallocs buffer for filename used with subsequent camera->pc transfer. Freed by additional TempData operation

PTP_CHDK_UploadFile
mallocs up to half largest free block, transfers in chunks, frees when complete. Currently uses fopen, but could be switched to open/write which also want uncached memory.

PTP_CHDK_ExecuteScript
mallocs and frees buffer with script source. Lua is compiled from the buffer, so performance impact could be relatively significant. Potentially large.

PTP_CHDK_WriteScriptMsg
mallocs message, which includes header and content. Freed by lua when de-queued. Potentially large
Title: Re: CHDK PTP interface
Post by: srsa_4c on 26 / April / 2019, 13:43:39
Thanks for the recv_ptp_data details.

I found something in disassemblies that might be related to the r31 problem.
There is a cpu cache library of some sort in the firmware. It has approx. 4 routines, the last one is unused in many cameras. Routine #3 (FF810750 in d10) is used in usb-related functions. The first routine is called from the MemoryChecker eventproc (that's one way to find them).
From a not too large sample, I found that an older version of #3 is used in
a470 (r23), g10 (r31). A newer version is used in ixus110 (r31 with problem), d10 (r31 with problem), a3200 (r47).
Now, I did not check whether the old and new #3 are doing exactly the same, but if they differ in operation that might be the reason behind the problem.
In case they do operate the same, this could still be used to identify the possible problem models, I think.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / April / 2019, 17:10:24
Now, I did not check whether the old and new #3 are doing exactly the same, but if they differ in operation that might be the reason behind the problem.
In case they do operate the same, this could still be used to identify the possible problem models, I think.
Nice catch. I had sort of assumed it was a hardware difference, but could easily be a difference in the code that handles the transfer. I'll take a closer look at those cache functions later.
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / April / 2019, 01:12:09
Function 3 is something like
cache_control(cachetype,address,length)

If cachetype is 1, it jumps into the middle of the preceding function and flushes the instruction cache

If length is -1 or > 0x2000 (== 8k == size of the caches)
it disables interrupts, cleans and flushes the data caches by iterating index/segment, and then drains the write buffer.

Otherwise, it flushes and cleans the specified range (without disabling interrupts) and drains the write buffer.

In the < 0x2000 case, D10 uses separate instructions for clean and flush:
Code: [Select]
MCR     p15, 0, R1,c7,c10, 1
MCR     p15, 0, R1,c7,c6, 1
while g10 uses the combined instruction:
Code: [Select]
MCR     p15, 0, R1,c7,c14, 1
It seems like this difference should be cosmetic, but maybe there's a subtle difference with interrupts or something.

In the whole cache (length >0x2000 or -1) case, d10  the drains the write buffer for every iteration, before calling the flush and clean function  :blink:
Code: [Select]
MCR     p15, 0, R4,c7,c10, 4
MCR     p15, 0, R2,c7,c14, 2
G10 just does flush and clean. Both drain write buffer at the end. Draining for every iteration seems weird to me.

ELPH130 seems identical to the D10 code, while ELPH180 is quite different. It looks like they got rid of the cache type argument.
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / April / 2019, 02:29:26
It occurred to me that the workaround in https://chdk.setepontos.com/index.php?topic=4338.msg140130#msg140130 is only unsafe at the ends, where it could potentially not be aligned on a cache line boundary.

To avoid this, we could allocate a small uncached buffer just for the ends.
1) Read the first little bit into the temp buffer
2) clean dcache
3) read main buffer + however much was read, up to the last full cache line, uncached,
4) clean and flush dcache
5) memcpy the first bit into the start of the buffer
6) read the last bit, memcpy that in.

This is annoyingly complicated to work around a corner case on a few cameras, but should be safe, negligible impact on performance or available memory, and completely contained in recv_ptp_data without requiring changes in the callers. For small transfers, it could just use the temp buffer and memcpy into whatever was passed to recv_ptp_data.

edit: or I guess transfers smaller than 0x23f4 could not do any cache workarounds, but but I'm somewhat hesitant to trust it.
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / April / 2019, 01:27:06
I implemented the idea in the previous post. It works great on d10... and fails miserably on a540.

Having platform specific versions would be OK, but it's hard to guess which they should be applied to.

On further investigation, a540 seems to have problems with multiple recv_data calls at certain sizes, and appears to have more problems that I haven't fully figured out when the memory is uncached, even when using umalloc and not doing any of the cache manipulation stuff.

Reading in blocks of 512, connection fails at sizes
1013-1015
1525-1527
etc
It only occurs on the second or later read, so with a 1024 block size, the first error happens at 1525

I tried changing the first read to 500 rather than 512, and the error occurred at the same points.

I haven't verified yet, but I expect the trunk code suffers from this, it just doesn't get hit often because it only affects multiple reads and certain magic sizes. The only time the trunk code does multiple reads is for file uploads that are > 1/2 max free block. On a540, diskboot.bin comes in less than that.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / April / 2019, 15:28:44
The only time the trunk code does multiple reads is for file uploads that are > 1/2 max free block.
Perhaps it's time to see how the 100d handler is doing it? I tried uploading files that are larger than the fw's usb buffer, and it worked. No idea whether it suffers from similar problems though.
I think it's possible to remove that handler at runtime and add our own.

Side note: r54 and newer cams use a dedicated fw usb buffer instead of exmem.
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / April / 2019, 18:48:30
Perhaps it's time to see how the 100d handler is doing it? I tried uploading files that are larger than the fw's usb buffer, and it worked
Yeah, that's definitely something to look at. I didn't try SendObject on A540 when I was playing with it earlier, because it doesn't list FIR files as objects, so it's not obvious what the ObjectInfo should contain. But I didn't dig into it much.

A540 (and likely other vxworks cameras) appear to have another, unrelated problem, present in the current trunk. Rapid fire messages like
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=1,sizeinc=1,count=10000,gc='step'}
occasionally crash (often after 3000-5000 iterations, but variable, sometimes it goes 10k without problems)

I got a couple romlogs for this in memPartInfoGet, (LR = 0xffee1444, ultimately from core_get_free_memory in handle_ptp) which looks related detecting memory corruption. I wondered if memPartInfoGet / malloc / free need to be protected with a semaphore or something, but they don't appear to be in the Canon code, and the VxWorks documentation doesn't obviously suggest that they should be.

Trying to reproduce this today, I got failures
Code: [Select]
send 7445 size:7445 0x1d15...Protocol error: data expected
After one of those, the camera crashed with an "Assert Memory.c line 67" which appears to be from malloc returning 0.

It's unclear whether these are related to PTP, or two tasks rapidly malloc/freeing, or some other memory corruption.

Quote
I think it's possible to remove that handler at runtime and add our own.
Another thing I've been thinking about is hooking the ptp_data functions, either by hooking TrnsCtrlTask which sets them up, or just replacing them on the first ptp call (this does not work). My impression is that the ptp_data structure is set up once per session at most. This would allow logging what the stock operations do.
Title: Re: CHDK PTP interface
Post by: reyalp on 28 / April / 2019, 20:43:49
Despite not listing FIR files, uploading format BF01 works on A540. Like newer dryos cameras, it asserts if the path includes "A/".

The following successfully creates a 4 MB TEST.DAT in the SD root.
Code: [Select]
!newf={ Filename="TEST.DAT", ObjectFormat=0xBF01, ObjectCompressedSize=1024*1024*4 } return con:ptp_send_object_info(newf)
!return con:ptp_send_object(('x'):rep(newf.ObjectCompressedSize))
Title: Re: CHDK PTP interface
Post by: reyalp on 29 / April / 2019, 00:06:20
I think it's possible to remove that handler at runtime and add our own.
This works. Attached patch hooks opcode 0x100d (SendObject) for A540.

The stock handlers get installed when when the USB cable is detected (PTPRspnd_StartUpPTPFrameworkClient) and removed when it is disconnected (PTPRspnd_ShutDownPTPFrameworkClient). So you have to replace it later after boot. It this case, I modified the rmem handler so rmem 1 4 installs the hook.

PTP session connect/disconnect and reset don't reset the handlers.

calling ptp_add_handler without removing first returns 0x13, but seems to still replace the handler.

On a540, the SendObject handler appears to have 256K buffer in uncached memory. Every call to recv_data gets the same address (0x11f80000). It does not appear to have the n*512 - 11 problem our code has.

Unrelated to the current problems:
Hooking the handlers (specifically GetObjectHandles) might provide us a way to avoid the black screen / no rec issue that happens when non-CHDK software access the cameras.

On a540 at least, GetObjectInfo and GetObject still work if GetOjectHandles hasn't been called, even in rec mode (the handles appear to just be sequential numbers starting at 2), which suggests the black screen mode isn't deeply tied to the rest of the PTP code.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 29 / April / 2019, 18:32:40
On a540, the SendObject handler appears to have 256K buffer in uncached memory. Every call to recv_data gets the same address (0x11f80000).
I experimented a bit on the a3200, and found that there are code paths using cached and uncached memory, so both are "legal" there. The uncached buffer is also 256k. The return value of recv_data is checked (bit0).
Quote
It does not appear to have the n*512 - 11 problem our code has.
How can I test this?
Title: Re: CHDK PTP interface
Post by: reyalp on 30 / April / 2019, 00:04:28
Quote
It does not appear to have the n*512 - 11 problem our code has.
How can I test this?
To test if it happens with CHDK code, you can use the attached patch, which buffers reads in TBUF_SIZE chunks.  You can switch between malloc/free and umalloc/ufree.

On a540, running msgtest with
Code: [Select]
m.test{size=1,sizeinc=1,count=10000,gc='step'}
will fail at 1013 with a stalled connection and IO error on the chdkptp side. If you change the size to 1024, it will then fail at 1525, and so on for multiples of 512.

You could of course just test around that size (start with size=1000) but given the different magic values on different cameras, covering a larger range seems like a good idea.

To reproduce this in unmodified, stock code, you'd have to arrange a file upload that was n*512-11 (including filename and size int) and larger than half the largest free block. I haven't done this for a540.

To see if the Canon code was affected, I tried SendObject with sizes that would result in multiple reads and fall on a 512-11 boundary, like

Code: [Select]
!newf={ Filename="TEST.DAT", ObjectFormat=0xBF01, ObjectCompressedSize=256*3*1024-11 } con:ptp_send_object_info(newf) con:ptp_send_object(('x'):rep(newf.ObjectCompressedSize))
which did not fail.

On d10, the patch works fine with with 512 buffer size, albeit slowly with either malloc or umalloc.  I expected this to fail at 0x23f4 or 0x43f4 but ...

With a buffer size of 0x3000 in cached memory, it fails at 0x23f4. Uncached works fine.

With a 0x23f0 buffer, both cached and uncached crash with an ASSERT!! BulkTrns.c Line 1549 at 0x23f5

Sorry for the random notes on d10, I went to confirm it behaved as I expected from previous tests and it didn't  :-[
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / May / 2019, 23:24:39
I looked at the PTP buffer functions some on D10.

As srsa_4c mentioned earlier, the first ComMemMan function (d10 sub_FF8C9114) allocates a 1 MB uncached exmem buffer.
This appears to be done in PTP startup, it's already allocated once a chdkptp connection is established.

On d10 (without CHDK exmem enabled) the buffer address is 0x43E42E00 0x43E02E00
Comments in makefile.inc indicate the video buffer starts at 0x43F02E00, exactly 1MB after the start of the PTP buffer. This raises the question of whether some exmem types automatically stay clear of the video buffer.

The second ComMemMan (d10 sub_FF8C91A4) function frees the exmem buffer.

The third (d10 sub_FF8C9228) is called by individual PTP functions that need a buffer. My impression is the big exmem buffer is split up into 7 "slots" used for different things. The main buffer for SendObject is slot 4 (edit: or 5, for dryos 43 through 52).

sub_FF8C9374 appears to return a size for each slot
Code: [Select]
con 1> =return call_func_ptr(0xFF8C9374,0)
2:return:8192
con 2> =return call_func_ptr(0xFF8C9374,1)
3:return:2048
con 3> =return call_func_ptr(0xFF8C9374,2)
4:return:16384
con 4> =return call_func_ptr(0xFF8C9374,3)
5:return:235520
con 5> =return call_func_ptr(0xFF8C9374,4)
6:return:524288
con 6> =return call_func_ptr(0xFF8C9374,5)
7:return:0
con 7> =return call_func_ptr(0xFF8C9374,6)

sub_FF9F6B28 is used by the SendObject code. It allocates slot 4 if needed (using the size from sub_FF8C9374 above), and returns the address. In my testing it was always the start of the exmem buffer 0x43e42e00.

This suggests that it would be fairly easy to use the stock Canon buffer, at least where it doesn't conflict with video stuff. Only one PTP operation can be in progress at a given time, so I think there's little risk of conflicting with Canon firmware code for slot 4. (other slots are used by other parts of the PTP code, e.g. something in BulkTrns.c uses slot 1)

Test patch for D10 attached. Unsurprisingly, the various msgtest tests work fine with this, since the buffer is uncached and far larger than usable message sizes.

It's probably not practical switch all ports to this approach. My current thought platform specific functions that fall back to malloc in the default case, but for cameras without a dedicated buffer, it's desirable to transfer directly to the destination address for script messages.

edit:
The same approach works for A540 using
Code: [Select]
NHSTUB(get_ptp_buf_size,            0xFFE38264)
NHSTUB(get_ptp_file_buf,            0xFFE57498)
Title: Re: CHDK PTP interface
Post by: srsa_4c on 05 / May / 2019, 18:42:53
On d10 (without CHDK exmem enabled) the buffer address is 0x43E42E00
Comments in makefile.inc indicate the video buffer starts at 0x43F02E00, exactly 1MB after the start of the PTP buffer.
If there's no typo here, the difference of the two addresses is only 0xc0000.
Title: Re: CHDK PTP interface
Post by: reyalp on 05 / May / 2019, 20:37:03
On d10 (without CHDK exmem enabled) the buffer address is 0x43E42E00
Comments in makefile.inc indicate the video buffer starts at 0x43F02E00, exactly 1MB after the start of the PTP buffer.
If there's no typo here, the difference of the two addresses is only 0xc0000.
Good catch. It was mistake. The exmem buffer is at 0x43e02e00. The
0x43e42e00 is the address returned for slot 4, which I mistakenly thought was at the start.
Title: Re: CHDK PTP interface
Post by: reyalp on 12 / May / 2019, 21:32:38
A540 (and likely other vxworks cameras) appear to have another, unrelated problem, present in the current trunk. Rapid fire messages like
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=1,sizeinc=1,count=10000,gc='step'}
occasionally crash (often after 3000-5000 iterations, but variable, sometimes it goes 10k without problems)
I worked on this a bit more. It appears that protecting Canon malloc/free/GetMemInfo with a semaphore avoids the issue.
It didn't crash in ten runs of m.test{size=1,sizeinc=1,count=10000,gc='step'} with the attached patch, where it usually crashes within one or two with the unpatched code.

The patch is just a proof of concept. DryOS malloc, free and GetMemInfo are clearly protected by their own semaphore internally, so the real fix would only need to apply to vxworks. Where to initialize the semaphore is also a bit unclear.

There are a couple things that make this a bit weird:
* Scheduling on vxworks cameras appears to mostly non-preemptive. However, my impression from the vxworks docs is that an interrupt can still result in a task switch (ie interrupt handler changes a semaphore etc that makes a different task the highest priority ready to run), which would make sense with it happening in PTP.
* The semaphore only protects CHDK calls, so presumably the Canon firmware routines could suffer the same problem. Maybe the Canon firmware doesn't do enough rapid fire malloc/frees for it be an issue, or maybe it's only memPartInfo that gets confused when it gets called in the middle of a malloc/free. I didn't come up with a simple way to test this. The (mostly) non-preemptive scheduling makes it hard to come up with a test case that really hammers it.

My inclination is to implement this for vxworks. It's pretty rare in normal usage, but it makes testing the other transfer issues difficult, and I think I have run into with the chdkptp image download commands and lots of files.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / May / 2019, 00:38:30
Proposed patch. I'll check this in if there aren't objections.

I built all the vx cams and checked the stubs for the semaphore functions seem reasonable (take and give are already used for FileIO, create probably wasn't used in CHDK on most vx cameras)

edit:
Added in trunk 5205
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / May / 2019, 02:39:28
Here's my initial patch to find the PTP handlers in pre-digic 6 cams (corresponding to the d6 one in https://chdk.setepontos.com/index.php?topic=12714.msg140348#msg140348

It turns out that on vxworks cams, the compiler canon used pretty much always put 0x1000 or 0x9000 in one register, and then used ORR or ADD to make the operation ID for a bunch of subsequent add_ptp_handler calls. So the finsig_vxworks code only finds handlers that are in a table of object / storage related operations (GetObject, SendObject etc) rather than trying to scrape all the calls.

This is OK since my immediate use for this is to get the PTP buffer related functions.

The dryos firmwares have a few instances of the ADD/ORR logic, but mostly use LDR.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 22 / May / 2019, 18:50:56
It turns out that on vxworks cams, the compiler canon used pretty much always put 0x1000 or 0x9000 in one register, and then used ORR or ADD to make the operation ID for a bunch of subsequent add_ptp_handler calls.
Attached modified patch adds (incomplete) support for this - vx only. Might be duplicated effort.
I found an ID (0x9028) that seems to have two different handlers in some firmwares.
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / May / 2019, 22:56:26
Attached modified patch adds (incomplete) support for this - vx only. Might be duplicated effort.
Nice  :D
I wasn't planning to tackle it for the initial version at least, so not duplicated.

Quote
I found an ID (0x9028) that seems to have two different handlers in some firmwares.
The thumb2 sig finder ends up with some event procs and tasks like this too. I was thinking about making it rename them like foo_FW_2 or something.
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / May / 2019, 20:37:56
I checked in the ptp handlers stuff, with minor updates.  I obviously haven't verified most of them, but I didn't see any false positives in the ones I did check.
Title: Re: CHDK PTP interface
Post by: reyalp on 27 / May / 2019, 23:25:58
Here's a patch that finds the ptp buffer size function for pre-digic 6 dryos and vxworks.

It seems to work for all but the very oldest vxworks (ixus30 - ixus50, ixus700 and s2is) which seem to use a constant 0x40000 instead of a function.

The function to get the buffer address (d10 FF9F6B28, a540 FFE57498) seems a bit more complicated to match, so any clever ideas for that are welcome.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / June / 2019, 16:21:55
The function to get the buffer address (d10 FF9F6B28, a540 FFE57498) seems a bit more complicated to match, so any clever ideas for that are welcome.
No code this time, but
Vx:
- [ObjMethdRW]Error:PrepareSubstancePTPObject, Open[%s] reference though not all cams have it
- ObjMethdRW.c string reference can still help with those cams that don't have the above string
both:
- get_ptp_buf_addr references get_ptp_buf_size
- get_ptp_buf_addr also references one of the commemman routines
- bic instruction
Title: Re: CHDK PTP interface
Post by: reyalp on 02 / June / 2019, 02:24:10
Thanks. I ended up matching the instruction sequence with get_ptp_buf_size and bic. It seems work on all cams except the very old vxworks that don't have get_ptp_buf_size (which is fine, there's few enough that they could be dealt with manually if needed)
Title: Re: CHDK PTP interface
Post by: reyalp on 03 / June / 2019, 02:22:06
Here's an initial patch that allows use of either the canon PTP buffers or heap malloc'd buffers. It also includes the earlier sig finder patches.

* ptp.c is compiled as platform code, instead of generic
* camera.h define CAM_PTP_USE_NATIVE_BUFFER uses the canon buffer. Requires get get_ptp* functions
* New ptp.c function get_ptp_temp_buf takes the total transfer size, and returns a buffer and buffer size. If using CAM_PTP_USE_NATIVE_BUFFER, the max buffer size is from get_ptp_file_buf_size, otherwise it's the half the largest free block.
* free_ptp_temp_buf frees the buffer, if using heap buffer.
* Code that *only* needs a temporary buffer (flush_recv_ptp_data and PTP_CHDK_UploadFile) uses get_ptp_temp_buf and data->recv_data directly
* Other code uses recv_ptp_data, which uses get_ptp_temp_buf only if the camera is using CAM_PTP_USE_NATIVE_BUFFER and otherwise uses the destination buffer.

The last two items are to unnecessary buffering that could be problematic on low memory cameras that don't use the native buffer.

There are still some loose ends to clean up, but it does seem to solve the problems on D10, and not break cameras using the heap buffer. I still need to make some easy to run tests. I'd also like to get rid of the last of the global buf_size logic for camera->pc transfers too.

edit:
Oops, missed some files in the first patch. Update attached.
Title: Re: CHDK PTP interface
Post by: reyalp on 17 / June / 2019, 02:31:50
I spent some more time trying to understand the issues on A540

The crash is "Assert BulkTrns.c line 1544", which happens in sub_FFE4DBDC
This is called from sub_FFE50B50, which comes from some table of BulkTrns related functions at FFE50BAC. The condition being checked in the assert isn't obvious to me.

The crash happens when
1) data->recv_data is called more than once
2) total size is (512*n) - 11 to (512*n) - 1 i.e. 0x...1f5 through 1ff.

Additionally, when using the native buffer (maybe any uncached) a stalled connection happens for something like 512*n to 512*(n+1)-13. Larger sizes appear to be OK, though I haven't checked exhaustively.

These problems happen even using native PTP operations, so
Code: [Select]
!newfi2={ Filename="BAD.DAT", ObjectFormat=0xbf01, ObjectCompressedSize=1024*256+512-11}
!return con:ptp_send_object_info(newfi2)
!return con:ptp_send_object(('x'):rep(newfi2.ObjectCompressedSize))
Triggers the assert, and size 1024*256+512 triggers the stalled connection, while 1024*257 works fine.  I previously thought native operations weren't affected, but my test was incorrect. This is reproducible without CHDK running.

Note as I posted earlier some cameras require A/ on the path and crash with an different assert if it is not present. Others, including A540 (and likely all vxworks cameras) crash if it is present.

Also, although get_ptp_buf_size(4) returns 512K, the camera divides this value by 2 for transfers. I previously verified by hooking data->recv_data and logging the values that it's really doing 256K chunks. Based on the total ComMemMan size and other code, it seems likely the actual buffer is 512K, so why the firmware uses size/2 is unclear.

With CHDK, the problem will only occur if the total transfer is larger than 1/2 free memory and one of the magic sizes. Using a fixed 256K buffer, the following reproduce it

file upload
Code: [Select]
!fh=io.open('TEST.DAT','wb') fh:write(('x'):rep(1024*255+1525-14)) fh:close()
u test.dat
The -14 accounts for the file name and file name length.

Flushed script message (no script running):
Code: [Select]
!con:write_msg(('x'):rep(1024*255+1525))

The problem also occurs if the first read isn't a multiple of 512, e.g. if the first recv_data is 4000, it fails at 4085.

tl;dr
1) I'd be interested to see results on other vxworks cameras for the SendObject test.
2) This doesn't seem fixable for A540, and the current trunk style code doesn't seem worse than other options
Title: Re: CHDK PTP interface
Post by: srsa_4c on 17 / June / 2019, 19:00:26
Code: [Select]
!newfi2={ Filename="BAD.DAT", ObjectFormat=0xbf01, ObjectCompressedSize=1024*256+512-11}
!return con:ptp_send_object_info(newfi2)
!return con:ptp_send_object(('x'):rep(newfi2.ObjectCompressedSize))
Triggers the assert, and size 1024*256+512 triggers the stalled connection
Same experience (crash, hang) on s80 (older vx).
No problem executing with either size on a460 (late vx), file gets created in both cases.
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / July / 2019, 00:22:50
I checked in the sigfinder changes to ad get_ptp_buf_size and get_ptp_file_buf in r5231-5232

I added tests to chdkptp camtests to check for these issues in chdkptp r864.

original d10 bug (recv_data to uncached at 0x23f4 +N*512)
Code: [Select]
chdkptp -c -e'exec require"camtests".run("xferbug_0x23f4")'

Unresolved A540 bug (multiple recv_data calls, total size = the first 512*N-11 that results in multiple recv_data)
Code: [Select]
chdkptp -c -e'exec require"camtests".run("xferbug_0x1f5")'

However, the above test fails on ALL my cameras, with a similar assert (I think it's the same but the line number vary slightly). Like a540, I was able to reproduce it with SendObject, so this isn't an unrelated problem with the test. (The test uses CHDK messages rather than SendObject, because I don't know which cameras require A/ or not on the SendObject path)

This does raise the question why a460 apparently wasn't affected, and also gets me back to wondering if it is something in our our PTP/USB code. If anyone can get another program to PTP upload a 262645 byte file, that would be interesting.

a540
Assert BulkTrns.c line 1544

d10
ASSERT!! BulkTrns.c Line 1549

sx160
ASSERT!! BulkTrns.c Line 1596

elph130
ASSERT!! BulkTrns.c Line 1595

elph180
ASSERT!! BulkTrns.c Line 1595

g7x
ASSERT!! BulkTrns.c Line 1595
Title: Re: CHDK PTP interface
Post by: srsa_4c on 01 / July / 2019, 19:10:54
original d10 bug (recv_data to uncached at 0x23f4 +N*512)
Code: [Select]
chdkptp -c -e'exec require"camtests".run("xferbug_0x23f4")'

Unresolved A540 bug (multiple recv_data calls, total size = the first 512*N-11 that results in multiple recv_data)
Code: [Select]
chdkptp -c -e'exec require"camtests".run("xferbug_0x1f5")'
Both of these tests execute successfully on a460.

If anyone can get another program to PTP upload a 262645 byte file, that would be interesting.
I don't know whether gphoto qualifies. Tried on ixus65_sd630 (old vx with working gphoto upload), cam crashed with that size. Assert is the same as on your a540.
Code: [Select]
gphoto2 -u /tmp/camou.fir --folder=/store_00010001/DCIM/100CANON
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / July / 2019, 19:08:10
Both of these tests execute successfully on a460.
Weird. Early DryOS like sx100 and a470 might be interesting.

Quote
I don't know whether gphoto qualifies. Tried on ixus65_sd630 (old vx with working gphoto upload), cam crashed with that size. Assert is the same as on your a540.
Code: [Select]
gphoto2 -u /tmp/camou.fir --folder=/store_00010001/DCIM/100CANON
I think the gphoto code is related to ptpcam, but it's better than nothing.

There was a Canon uploader that worked for some old vxworks A series cams (ps_uploader on https://drive.google.com/drive/folders/0B08pqRtyrObjSmFqSV8yRUlqbnM note the exe/dlls are the same in each folder, it's just premade config files for different cams)
I'll see if I can make that work with A540.

edit:
I was able to upload a 256K + 501 size file to A540 using Canon UploadFirmware.exe on windows 10.

Pretty much just need to edit the FirmInfo.txt to have the file name and camera name you want to upload, and make sure libusb drivers are removed.

Uploading the same file with SendObject in chdkptp triggers the expected BulkTrns.c 1544 assert.

Next step I guess is to either hook and log PTP functions and/or capture USB traffic. Reversing the uploader program could also maybe be interesting.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / July / 2019, 12:26:49
Early DryOS like sx100 and a470 might be interesting.
sx100: xferbug_0x23f4 executes normally, xferbug_0x1f5 causes ASSERT!! BulkTrns.c Line 1568 .
a470: both tests execute normally

May or may not be related: the low end a4xx series has crippled USB ("full speed"), up to and including a470.
Title: Re: CHDK PTP interface
Post by: reyalp on 15 / July / 2019, 00:41:49
Next step I guess is to either hook and log PTP functions and/or capture USB traffic.
I went with hooking. Canon UploadFirmware.exe doesn't trigger the crash because it uses OC 0x9019, identified as "PTP_OC_CANON_SendPartialObject" in the gphoto source.

Attached is a log from uploading a 262645 byte file with and corresponding patch. The patch is only set up for A540, but provides a generic mechanism for hooking PTP handlers which could be useful in the future.

Most of the chatty stuff in the log is initializing the hooks and the Canon program querying storage and object handles. The actual upload is
SendObjectInfo
Code: [Select]
00011830 DBG:ptp h:0x001fb6ac d:0x00008d94 oc:0x100c s:0x1 t:0x21 0x0 0x0 0x0 0x0 0x0
00011870 DBG:recv h:0x001bb09c b:0x0021e490 s:0x8d (141) u1:0x0 u2:0x0

2x PTP_OC_CANON_SendPartialObject
Code: [Select]
00011960 DBG:ptp h:0x001fb6ac d:0x00008d94 oc:0x9019 s:0x1 t:0x22 0x0 0x40000 0x1 0x0 0x0
00012000 DBG:recv h:0x001bb09c b:0x11f80000 s:0x40000 (262144) u1:0x0 u2:0x0
00012220 DBG:ptp h:0x001fb6ac d:0x00008d94 oc:0x9019 s:0x1 t:0x23 0x40000 0x1f5 0x3 0x0 0x0
00012270 DBG:recv h:0x001bb09c b:0x11f80000 s:0x1f5 (501) u1:0x0 u2:0x0

Note only object related calls are logged (the ones in the table at 0xffe5bacc on A540) are logged. The transaction ID indicates some other operations were done.

Given that Canon uses this approach, the it seems likely our only fix would be to extend the CHDK protocol to allow similarly splitting uploads over multiple transactions.

This is somewhat complicated for CHDK since with the current code, we don't know in advance how big a chunk can be sent at a time. If we switched to using the Canon PTP buffer, it would be simpler.

I'm not sure this is worth fixing given the lack of complaints in the last 10 years, but at least we have an option.

May or may not be related: the low end a4xx series has crippled USB ("full speed"), up to and including a470.
Wow, I thought that was only the really old ones. Interesting.
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / July / 2019, 02:10:51
Given that Canon uses this approach, the it seems likely our only fix would be to extend the CHDK protocol to allow similarly splitting uploads over multiple transactions.
Thinking about this more, I realized it should be possible to work around without resorting multiple transactions or protocol changes. My previous observation was
Quote
The crash happens when
1) data->recv_data is called more than once
2) total size is (512*n) - 11 to (512*n) - 1 i.e. 0x...1f5 through 1ff.

Additionally, when using the native buffer (maybe any uncached) a stalled connection happens for something like 512*n to 512*(n+1)-13. Larger sizes appear to be OK
So if the size is in the magic range (0x...1f4 < size < 0x...3f4), reducing the size of the next-to-last read to ensure the final one is > 0x3f3 should avoid the problem.

From initial testing, this appears to work. 

My current test code is attached. I have more testing and cleanup to do, so this is just in case anyone is interested.
Title: Re: CHDK PTP interface
Post by: reyalp on 04 / August / 2019, 23:44:38
I finally checked this in, trunk 5235

The recv_data logic is completely re-worked. I found that problem size varies in a complicated way depending on the size of the preceding chunks (see attached csv), so for simplicity, I just forced the buffer size to be a multiple of 512. The current code also errors if less than 2kb is available for the buffer. This shouldn't be problem in practice because a camera with free memory that low will be unstable anyway.

PTP host to cam transfers now work as follows:
For cases where you want to transfer all the data into a buffer for use later (e.g. script messages, script content) allocate the final buffer yourself and use recv_ptp_data. It will take care of reading correctly sized chunks and buffering through the Canon buffer if CAM_PTP_USE_NATIVE_BUFFER is defined

For cases where you want process the data in the PTP task without copying elsewhere (like file upload)
* recv_ptp_data_init initializes a recv_ptp_data_state_t and gets/allocates a transfer buffer if needed
* recv_ptp_data_chunk receives a chunk of data, as determined by buffer size and other size requirements
* when it's all done (can be detected with recv_ptp_data_state_t total_read == total_size) use recv_ptp_data_finish to free any temp buffer and clear the struct.

CAM_PTP_USE_NATIVE_BUFFER causes the above functions to use 256KB of the Canon firmware file transfer buffer for PTP transfers. This buffer is uncached, so avoids problems like the D10 has. It also appears to be a bit faster on old cameras like A540, and may be be useful on cameras with low free RAM. It should be available on all pre-Digic 6 cams, although it's probably a good idea to check whether the PTP buffer overlaps the EXMEM_HEAP_SKIP video region that causes problems with CHDK exmem (it does not appear to on D10 or SX160)

Other DryOS cams of similar era to D10 are likely to need it. If the chdkptp test xferbug_0x23f4 fails, it should be enabled.

I'd appreciate anyone who can test with the current svn chdkptp running the following:
Code: [Select]
chdkptp -e"exec require'camtests'.runbatch{bench=true,xfersizebugs=true,filexfer=true}"
Note that the xferbug_0x1f5 test may take something like a minute on some cameras.

Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / August / 2019, 15:23:28
I'd appreciate anyone who can test with the current svn chdkptp running the following:
Code: [Select]
chdkptp -e"exec require'camtests'.runbatch{bench=true,xfersizebugs=true,filexfer=true}"
a410 result attached (I used the GUI). I get the same log (with execution times differing somewhat) with or without CAM_PTP_USE_NATIVE_BUFFER. The ixus65_sd630 passes the test.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / August / 2019, 16:01:52
a410 result attached (I used the GUI). I get the same log (with execution times differing somewhat) with or without CAM_PTP_USE_NATIVE_BUFFER. The ixus65_sd630 passes the test.
Thanks. The initial failure is not in one of my new tests, but on sending a 52 byte message in the basic message test. Can you try
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=52,count=1}
If that works, try
Code: [Select]
!m=require'extras/msgtest' m.test{size=1,sizeinc=1,count=100}
It would also be good to know if builds before 5235 have the same problem.

The following errors in your log seem to be related to a stalled or disconnected camera rather than a crash, since it picks up again at the reconnect test. I should really make the test try to reconnect / reset between tests if needed.

Quote
I used the GUI
Do you mean you ran it using an executable with GUI support in CLI, or actually ran it in the GUI?
Title: Re: CHDK PTP interface
Post by: srsa_4c on 06 / August / 2019, 17:44:50
Can you try
Code: [Select]
!m=require'extras/msgtest'
!m.test{size=52,count=1}
Code: [Select]
___> !m=require'extras/msgtest'
___> c
connected: Canon PowerShot A410, max packet size 64
con> !m.test{size=52,count=1}
testing 1 messages size 52
send 1 size:52 0x34...I/O error
aborted at send 1 size:52 0x34, communication error
quit failed I/O error
ran 1 fail 1 time 10.0164 send time 0.0109
Quote
It would also be good to know if builds before 5235 have the same problem.
I get the same behaviour with r5204.

I don't actually expect you to fix all ptp problems on this model, I only picked it for this test because it has a history of ptp issues.
Quote
Do you mean you ran it using an executable with GUI support in CLI, or actually ran it in the GUI?
I copied this
Code: [Select]
exec require'camtests'.runbatch{bench=true,xfersizebugs=true,filexfer=true}to the gui window and pressed execute. chdkptp.sh starts the GUI by default.
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / August / 2019, 18:07:38
I don't actually expect you to fix all ptp problems on this model, I only picked it for this test because it has a history of ptp issues.
Understood. It would be good to fix or understand if we can, but this seems like a different problem from the other cameras. You could run without the 'bench' option to see if the others pass, like
Code: [Select]
exec require'camtests'.runbatch{xfersizebugs=true,filexfer=true}


Quote
I copied this
Code: [Select]
exec require'camtests'.runbatch{bench=true,xfersizebugs=true,filexfer=true}to the gui window and pressed execute. chdkptp.sh starts the GUI by default.
FWIW, if you pass any command line arguments without -g, it should start in CLI mode as long as the .sh script passes the arguments through like the one in SVN does. I really doubt this has anything to do with the error, but it should be easy to try.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / August / 2019, 18:25:32
You could run without the 'bench' option to see if the others pass, like
Code: [Select]
exec require'camtests'.runbatch{xfersizebugs=true,filexfer=true}
That executes with no failures.
Quote
I really doubt this has anything to do with the error
Me too. My previous post shows the results of the msgtest, run via cli.


Not completely off-topic as it is about PTP, taken from here (https://www.magiclantern.fm/forum/index.php?topic=24385.0).
https://www.usa.canon.com/internet/portal/us/home/support/product-advisories/detail/the-vulnerability-in-canon-digital-cameras
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-5994
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-5998
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-5999
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-6000
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-6001

Plus (off-topic), firmware update related vulnerability in both EOS and PowerShot firmwares...
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-5995
Title: Re: CHDK PTP interface
Post by: reyalp on 07 / August / 2019, 20:57:09
That executes with no failures.
Thanks. One more

Code: [Select]
!m=require'extras/msgtest'
!m.test{size=513,sizeinc=-1,count=512}

Quote
here (https://www.magiclantern.fm/forum/index.php?topic=24385.0).
Hmm. I've always operated on the assumption that it's game over if the PTP host is compromised.  CHDK is obviously vulnerable: PTP_CHDK_CallFunction PTP_CHDK_SetMemory, Lua poke and likely a lot of vulnerable Lua functions are all readily available. These could all be executed over PTP/IP too.

I would be very surprised if there aren't more vulnerabilities in the Canon PTP code too.

We could offer an option to disable CHDK PTP functionality, checking a conf setting and returning an error in handle_ptp would be easy.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / August / 2019, 17:34:17
One more
Code: [Select]
___> !m=require'extras/msgtest'
___> c
connected: Canon PowerShot A410, max packet size 64
con> !m.test{size=513,sizeinc=-1,count=512}
testing 512 messages size 513-1, inc -1 gc=step
send 1 size:513 0x201...ok
send 2 size:512 0x200...ok
(...)
send 461 size:53 0x35...ok
send 462 size:52 0x34...I/O error
aborted at send 462 size:52 0x34, communication error
quit failed I/O error
ran 462 fail 1 time 26.5785 send time 6.2933
Quote
We could offer an option to disable CHDK PTP functionality, checking a conf setting and returning an error in handle_ptp would be easy.
We could, although I'm not sure if it's worth it. The cameras only activate their wireless interface when the user enters the Wifi related dialogs. I find it hard to imagine that anyone (other than some 3-letter agencies and the like) will spend their time exploiting these firmware bugs. And only a very low percentage of cameras run CHDK.

I posted the links because the descriptions mention the problematic PTP handlers by name. And that we'll get to see the fixes (M3 and M10 are on the list).
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / August / 2019, 18:37:16
send 461 size:53 0x35...ok
send 462 size:52 0x34...I/O error
aborted at send 462 size:52 0x34, communication error
Thanks.
So it fails at exactly 52 (64 - 12 overhead?) and not nearby multiples. Not sure what we could do about this. Could try two reads, like 48 and 4.

Quote
We could, although I'm not sure if it's worth it. The cameras only activate their wireless interface when the user enters the Wifi related dialogs. I find it hard to imagine that anyone (other than some 3-letter agencies and the like) will spend their time exploiting these firmware bugs. And only a very low percentage of cameras run CHDK.
Yeah, this doesn't seem a high risk. OTOH, someone making a stink about "CHDK undoes Canon security fix" could be unfortunate.

Thinking about it more, we could check the USB bit (in physw_status, not the hardware state) and only allow CHDK operations if its set. Since there's no working PTP/IP client for CHDK, having it off when USB is not present shouldn't be a problem (unless there's threading issues that make it drop out momentarily when kbd_task runs  :-[). This could also be an option: CHDK PTP: [USB only, USB+wifi, off]

If there's exposure when the camera is paired with a phone, that could be a bigger risk, but my impression is that's totally separate.

Quote
I posted the links because the descriptions mention the problematic PTP handlers by name. And that we'll get to see the fixes (M3 and M10 are on the list).
That could be interesting.
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / September / 2019, 16:59:27
In trunk 5274, I re-organized the code that uses send_data (camera->host transfers). This shouldn't affect the actual operations. It mostly cleans up the logic around the old global buf_size. Some needless complexity in send_ptp_data goes away, and core_get_free_memory is only called when a buffer is actually needed. This could be extended to use native ptp buffers like recv_data, but there currently doesn't seem to be need.

The main motivation is to simplify the code before trying to address issues with >2gb files reported in https://chdk.setepontos.com/index.php?topic=13896.0
Title: Re: CHDK PTP interface
Post by: reyalp on 22 / September / 2019, 20:26:59
Here's my non-working attempt at a patch to make the CHDK code behave correctly for >2GB files.

Tested on sx710

camtests all pass, so sub 2 GB stuff seems fine.

Used a 2260826276 zip file to test.

Attempting to upload after running camtests resulted in IO Error on the chdkptp side. The camera appears to be running normally, but it is not possible to reconnect, even with reset_device.

I tried this twice. In one instance, powering off the camera seemed normal, but I was unable to power it on without pulling the battery. In another, the camera became unresponsive while still on.

Trying to upload on a fresh boot without running camtests first, I got an immediate "general error"

Copying the file to the SD card with a card reader trying to download in chdkptp, I get
read_data failed 0x2ff
ERROR: I/O error

The file from the failed download is 2145386496 bytes. This is 2^31 - 2 MB. chdkptp uses a 2MB buffer for file transfers, so it seems likely that the read request which hit 2^31 failed.

While it's quite possible there are bugs in my code, my suspicion is the Canon code uses signed values. I haven't tried standard ptp getobject or sendobject with a >2gb file yet.

If we want to support this, it would probably make more sense to add operations to do partial uploads and downloads: Read X bytes from offset, append X bytes or write X bytes at offset.

I'm not  sure this is worth doing. The case of downloading > 2gb files seems useful, but fairly rare.

There are additional issues in CHDK lua, since the stat size is negative for > 2gb files. chdkptp side code can work around this, but it would be on a case by case basis.

It may become more of an issue in the future, @srsa_4c suggested DryOS 59 extended the stat structure to support 64 bit sizes. >4 GB files would require a lot of changes, though probably not too common for CHDK until exFAT boot or multi-partition is supported.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 24 / September / 2019, 17:25:13
It may become more of an issue in the future, @srsa_4c suggested DryOS 59 extended the stat structure to support 64 bit sizes. >4 GB files would require a lot of changes, though probably not too common for CHDK until exFAT boot or multi-partition is supported.
I don't think there is a PowerShot firmware based camera that records movies exceeding the 4GB barrier - but I can't be sure as this limitation is often omitted from various literature.
Title: Re: CHDK PTP interface
Post by: reyalp on 24 / September / 2019, 21:43:31
I don't think there is a PowerShot firmware based camera that records movies exceeding the 4GB barrier - but I can't be sure as this limitation is often omitted from various literature.
Agreed, my impression is that they don't. My thought was extending the stat structure might be a hint that it was coming in future models, though of course it could be for other products that use DryOS, and of course it's possible future models will not be supportable by CHDK anyway.

My current thinking on >2gb files is just to provide a clean error, probably GeneralError in the protocol, something like "file too large" in chdkptp in cases where it would know.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 25 / September / 2019, 17:00:45
My current thinking on >2gb files is just to provide a clean error, probably GeneralError in the protocol, something like "file too large" in chdkptp in cases where it would know.
It's not like I see 2...4GB files very often, but they can be created on camera. I checked SendObject, it uses Open() rather than one of the fopen() variants. Download of >2GB files does work via libgphoto based software.
How about using open/read instead of fopen/fread when dealing with big files? I agree that files bigger than 4GB don't need to be supported (64bit versions of open etc. may not even exist in firmware).
Title: Re: CHDK PTP interface
Post by: reyalp on 26 / September / 2019, 00:14:29
How about using open/read instead of fopen/fread when dealing with big files? I agree that files bigger than 4GB don't need to be supported (64bit versions of open etc. may not even exist in firmware).
My impression was that the problems were in the PTP layer, not file IO, but I didn't dig deeply. If sendobject works, it might be worth investigating further.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 28 / September / 2019, 14:34:41
My impression was that the problems were in the PTP layer, not file IO, but I didn't dig deeply. If sendobject works, it might be worth investigating further.
It's possible that you're right and the problem is indeed caused by transferring >=2GB of data in one go. I guess this could be addressed by transferring them in multiple pieces, but that would not work with clients not implementing that addition to the protocol (in case that's a problem).
Title: Native ExecuteEventProc over PTP
Post by: srsa_4c on 06 / February / 2022, 17:50:24
Continuing petabyte's work (https://github.com/petabyt/sequoia-ptpy), I further reverse engineered a few Canon-specific PTP operations that can be used executing code on camera.
These could be useful for implementing card preparation without a card reader, and more. The operations are available on PowerShots running DryOS r31 (not all r31 cameras) and later. They are also available on EOS cameras (don't know which models). An additional check will prevent (ab)using these operations on DIGIC 8 and later cameras - until someone reverses the new 0x9050/0x905c handlers.

The operations are (names come from EOS debug strings, following is from here (https://github.com/reticulatedpines/magiclantern_simplified/blob/dev/contrib/ptpcam/ptp-eos-oc.h)):
#define PTP_OC_CANON_InitiateEventProc0 0x9050
#define PTP_OC_CANON_TerminateEventProc_051 0x9051
#define PTP_OC_CANON_ExecuteEventProc 0x9052
#define PTP_OC_CANON_GetEventProcReturnData 0x9053
#define PTP_OC_CANON_IsEventProcRunning 0x9057
#define PTP_OC_CANON_QuerySizeOfTransparentMemory 0x9058
#define PTP_OC_CANON_LoadTransparentMemory 0x9059
#define PTP_OC_CANON_SaveTransparentMemory 0x905a
#define PTP_OC_CANON_QuickLoadTransparentMemory 0x905b
#define PTP_OC_CANON_InitiateEventProc1 0x905c
#define PTP_OC_CANON_TerminateEventProc_05D 0x905d

InitiateEventProc 0x9050, 0x905c
TerminateEventProc 0x9051, 0x905d

These are for enabling and disabling operations between 0x9052 ... 0x905b. Some EOS cameras seem to register those handlers by default.

ExecuteEventProc 0x9052

Executes a registered event procedure. Parameter passing and more are detailed later. Returns the eventproc's one-word result as PTP param.

GetEventProcReturnData 0x9053

Returns data from a fixed buffer, but only after an appropriate ExecuteEventProc operation.

IsEventProcRunning 0x9057

Self-explanatory name, but I did not try calling it. Can return up to 3 params. reyalp's findings (https://chdk.setepontos.com/index.php?topic=4338.msg147759#msg147759)

QuerySizeOfTransparentMemory 0x9058
LoadTransparentMemory 0x9059
SaveTransparentMemory 0x905a
QuickLoadTransparentMemory 0x905b

Not researched, transparent memory is something like a named allocation from regular heap.



Now, ExecuteEventProc in details.

Eventproc name and its arguments are sent in the payload (data phase).

This operation has 2 PTP params that I know of:
- 1st parameter: async execution flag. When nonzero, the eventproc is executed in a separate task (so that it can run for longer).
- 2nd parameter: return data flag. When nonzero, the eventproc is expected to create data that can be returned in a GetEventProcReturnData operation.
  When this flag is set, the eventproc will get 3 fixed arguments first, followed by those specified by caller.
  - 1st arg will contain the available buffer space in bytes
  - 2nd arg will point to the return size (the eventproc can set the actual return data amount which defaults to zero)
  - 3rd arg will point to the return data buffer

Eventproc name and arguments are to be sent in an unaligned stream of bytes.
Encoding:
- evproc name as string of chars, terminated by 0 char
The rest comes right after, is not word-aligned, words are in LE byte order.
- 32bit value: num of args (10 or less)
- for each arg:
 - 5*4 bytes data:
  - word1: type, 4 for long arg (0=uint8, 1=int16, 2=(u)int32, 3=(u)int64), PS and EOS treat every non-4 type as (u)int32
  - word2: arg value when word1 isn't 4
  - word3: (ignored, treated as 0) (high-order word of 64-bit integer arg, but not on PS and EOS)
  - word4: (? picked up but not used?) index of long arg
  - word5: (size of data when word1=4)
- 32bit value: num of long args (not limited here, but has to be 10 or less)
- for each long arg:
 - 32bit value (? picked up, but unknown purpose) index of long arg, should match word4 above
 - variable length data (length specified by word5, must be larger than zero, size only limited by camera heap memory)

I expect the above to work on all (< DIGIC 8) cameras that implement these operations.
There might be details that I missed, corrections are welcome.

A demo is attached, in python (I have 3.6), along with a patch against https://github.com/petabyt/sequoia-ptpy . I'm not very familiar with python, it just seemed the easiest choice to make a demo.

edit:
description is fixed, plus link added that explains 0x9057 (also, read on for other findings)
Title: Re: CHDK PTP interface
Post by: reyalp on 06 / February / 2022, 19:13:30
Very nice work. I'll add support in chdkptp.

Interesting Canon issued a fix for https://chdk.setepontos.com/index.php?topic=13872.0 and left this ;)

I guess we don't need to worry too much about the security of the CHDK extension :haha
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / February / 2022, 17:08:53
Interesting Canon issued a fix for https://chdk.setepontos.com/index.php?topic=13872.0 and left this ;)
No CVE - no headache, I guess. They did make a step toward securing this backdoor, so current models are not in "danger". Or at least publicly not.
Title: Re: CHDK PTP interface
Post by: coon on 07 / February / 2022, 17:16:04
Hello, I am working on a Magic Lantern port for EOS RP and I am also doing some investigations on PTP. I have added these PTP codes to ptpcam recently and I am happy they are helping.

@srsa_4c nice findings about the execute event proc inner workings! RP does not register PTP_OC_CANON_ExecuteEventProc 0x9052 function by default. However, the decompiled code tells that PTP_OC_CANON_InitiateEventProc0 0x9050 and PTP_OC_CANON_InitiateEventProc1 0x905c do register the function, as you already mentioned but I don't know what the difference of them is. Both functions do call the same subroutine with the same arguments. The only difference is, that some some buffer on the stack is initialized with 1 or 0. I wasn't brave enough to call these functions on camera. Have you already tried this? Do you know what the difference between the functions is?

However, I've tried to register PTP_OC_CANON_ExecuteEventProc 0x9052 manually, which worked but the camera crashed when trying to call a function, so I think the initate functions do some necessary initialization to make it work properly.

I also don't know what the difference between PTP_OC_CANON_TerminateEventProc_051 0x9051 and PTP_OC_CANON_TerminateEventProc_05D 0x905d is. Those are probably the counterparts for the initiate pairs.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 07 / February / 2022, 17:37:52
the decompiled code tells that PTP_OC_CANON_InitiateEventProc0 0x9050 and PTP_OC_CANON_InitiateEventProc1 0x905c do register the function, as you already mentioned but I don't know what the difference of them is. Both functions do call the same subroutine with the same arguments. The only difference is, that some some buffer on the stack is initialized with 1 or 0. I wasn't brave enough to call these functions on camera. Have you already tried this? Do you know what the difference between the functions is?
No, I have not tried going after the changes they made to the registration function(s). I've seen that some magic sentences are involved (I'd prefer them not be published as is) and 0x9050/0x905c now has a data phase. Before DIGIC 8, the 0x9050/0x905c handlers were one and the same (as far as i've seen).

Quote
However, I've tried to register PTP_OC_CANON_ExecuteEventProc 0x9052 manually, which worked but the camera crashed when trying to call a function, so I think the initate functions do some necessary initialization to make it work properly.
If that is so then they really did put in some effort. Perhaps those CVEs were the motivation.
Quote
I also don't know what the difference between PTP_OC_CANON_TerminateEventProc_051 0x9051 and PTP_OC_CANON_TerminateEventProc_05D 0x905d is. Those are probably the counterparts for the initiate pairs.
Yes, they again used to be equal. They are still equal in sx740.
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / February / 2022, 02:21:39
A few observations:
1) The patch has been applied in https://github.com/petabyt/sequoia-ptpy, so is no longer required

2) As expected, these operations work over wifi (tested on elph130)

3) The long arg handling appears to fail with multiple long args (tested on elph130 and elph180). If I do

./demo.py Printf S'Hello %s' S'World'

The UART output is
Code: [Select]
Hello Hello %s
So the first argument gets passed twice. My chdkptp implementation based on srsa_4c's behaves the same (in fact, I hadn't tried demo.py until I ran into this)

Using chdkptp =call_event_proc("Printf", "Hello %s","World") gives the expected output.
Title: Re: CHDK PTP interface
Post by: petabyte on 08 / February / 2022, 12:10:01
srsa_4c thanks for posting your findings, I've implemented it in my mlinstall tool: https://github.com/petabyt/mlinstall/
Do you know of any quick evprocs with parameters to test it on?
Title: Re: CHDK PTP interface
Post by: reyalp on 08 / February / 2022, 12:54:10
srsa_4c thanks for posting your findings, I've implemented it in my mlinstall tool: https://github.com/petabyt/mlinstall/
Do you know of any quick evprocs with parameters to test it on?
FWIW, I used the following for P&S. I think these not useful on EOS, just posting since I I also needed test cases...
no parameters: System.Create - registers other useful ones, returns 0 on success
numeric parameter: Peek32 - registered by above, can check return value against ROM dump
arbitrary parameters: Printf - can use UART redirection to verify results


Another unrelated FWIW, the 9050 905c etc opcodes are also present on some Digic DV cams, such as xf605
Title: Re: CHDK PTP interface
Post by: srsa_4c on 08 / February / 2022, 15:32:36
3) The long arg handling appears to fail with multiple long args (tested on elph130 and elph180).
Fails here also, thanks for noticing. I have a custom eventproc for testing, but I did not try multiple long args. I was happy that memcpy succeeded and considered the case done. I'll try finding the missing piece.
Do you know of any quick evprocs with parameters to test it on?
I used memcpy due to its usefulness.
Another unrelated FWIW, the 9050 905c etc opcodes are also present on some Digic DV cams, such as xf605
Nice... I wonder if they used the same API and whether the eventprocs (if any) include known ones.
The only difference is, that some some buffer on the stack is initialized with 1 or 0.
On sx740, that seems to be an argument passed to an underlying function, its value appears to influence the way the challenge is evaluated.
Title: Re: Native ExecuteEventProc over PTP
Post by: reyalp on 09 / February / 2022, 02:19:41
IsEventProcRunning 0x9057

Self-explanatory name, but I did not try calling it. Can return up to 3 params.
I tested this a bit on elph130. it returns:
0 - if not running and no pending result / last call was not async
1 - if running
If async, the first call after it finishes running returns two or three values:
2, the function return value, and remote data length if remote data was used.

It appears you get a PTP "device busy" code (0x2019) if you do things out of sequence like
- Call Execute with return data before calling GetReturnData to get return data from a previous call
- Call Execute before an async is finished
- Call GetReturnData when there is no pending data, including while an async is running
- Call GetReturnData before calling IsRunning, if the previous call was async

I managed to hang the PTP connection a few times playing with these sequences, but that may be due to chdkptp's poor handling of errors /stalls in operations with data.

On elph130 and elph180, the return data buffer size is 4K.
Attached is a patch with eventprocs I used for testing.

Nice... I wonder if they used the same API and whether the eventprocs (if any) include known ones.
notes (https://chdk.setepontos.com/index.php?topic=1641.msg147757#msg147757)

edit: Feb 13, 2022
Updated patch compatible with thumb2 cams.
Title: Re: CHDK PTP interface
Post by: srsa_4c on 12 / February / 2022, 17:52:03
3) The long arg handling appears to fail with multiple long args
Thanks to a different firmware and reyalp's help, I could fix this. I updated (https://chdk.setepontos.com/index.php?topic=4338.msg147738#msg147738) the original "announcement". A patch for my script in petabyte's ptp-tool (https://github.com/petabyt/sequoia-ptpy) is attached to show the fix.
Title: Re: CHDK PTP interface
Post by: reyalp on 13 / February / 2022, 04:00:02
Thanks to a different firmware and reyalp's help, I could fix this. I updated (https://chdk.setepontos.com/index.php?topic=4338.msg147738#msg147738) the original "announcement". A patch for my script in petabyte's ptp-tool (https://github.com/petabyt/sequoia-ptpy) is attached to show the fix.
Nice work, with the new information long args are working in my chdkptp code. I've added "proper" support in chdkptp r1118-1120. Documentation can be found in chdkptp/lua/ptpevp.lua before con_methods:ptpevp_call. This should be usable with any cam that supports the API, regardless of whether CHDK is installed.

Briefly

con:ptpevp_initiate() calls 0x9050 x3

con:ptpevp_call(name,arg1,...argN,{options}) calls an eventproc with the given parameters, and by default returns the function return value, followed by return data if requested.

Numbers, strings and chdkptp lbufs are accepted as arguments. Note that string/lbuf arguments must be explicitly null terminated if the camera expects a C string for the argument.

options controls async, return data and various debugging option.
radata='string' specifies return data should be used and returned as a Lua string.
async=true specifies an async call
wait=true polls IsRunning until an async call finishes
verbose=true to be used to print details about each transaction

By default, if rdata is enabled (and wait is true, if async), the data is fetched and returned. This can be disabled by setting getrdata=false

other functions
con:ptpevp_wait - wait for async to finish, and get data if it returned data
chdku.ptpevp_prepare - generates an lbuf of the data to be sent with Execute

some examples can be found in lua/tests/ptpevp.lua
Title: Re: CHDK PTP interface
Post by: reyalp on 21 / February / 2022, 00:35:34
In chdkptp r1141, I added a devutil command 'dptpdevinfo' to display PTP information like supported opcodes, events, properties and so in.
 Constants and names are largely from current (as of Feb 2022) gphoto source (https://github.com/gphoto/libgphoto2/blob/master/camlibs/ptp2/ptp.h) with Canon opcodes supplemented from @coon's list (https://github.com/coon42/magiclantern_simplified/blob/ptpcam_add_more_canon_codes/contrib/ptpcam/ptp-eos-oc.h)  (I also used this combined list to update the CHDK sig finders in trunk r6071)

As usual, devutil is activated using
Code: [Select]
!require'extras/devutil'.init_cli()
After that, dptpdevinfo without options gives reasonable output. Adding -ptpevp calls InitiateEventProc0 before querying deviceinfo, which will add the related opcodes to the supported list. However, it won't work on cameras that expect a different handshake, or non-canon devices.

Output for my cameras and an iphone is attached.

Some observations:
- Cameras starting with early DryOS (D10, r31, at least) support MTP (https://en.wikipedia.org/wiki/Media_Transfer_Protocol), explaining why they report a Microsoft extension ID (6) rather than Canon's own ID (11). Gphoto comments suggest that 0xffffffff may also identify MTP, but I haven't seen it. The 0x980x opcodes are MTP. The PTP native extension system doesn't really support multiple / layered extensions, so there's no PTP standard way to identify a Canon's approach of supporting MTP and a bunch of their own opcodes, aside from theirs being outside the 0x980x range. MTP actually does define a mechanism (using the  VendorExtensionDesc string) but Canon doesn't use it.
- Most Canon operation codes are identified, although I don't know how reliable the names/descriptions from Gphoto are.
- Some of the known opcodes and properties might be useful or interesting for reverse engineering
- Aside from minor variations in order, returned info is essentially identical Wifi or USB.
- Calling MTP.GetObjectPropsSupported puts the camera in "black screen" state, like GetObjectHandles
Title: Re: CHDK PTP interface
Post by: reyalp on 01 / February / 2024, 01:23:29
Over in @RaduP's Camera Connect thread (https://chdk.setepontos.com/index.php?topic=14822.20), I noted that when using PTP/IP on SX730 through the mobile phone option
Oddly, the CHDK PTP opcode isn't reported as supported on the initial connection, although it's available subsequently and works.
The cause of this appears to be
- CHDK starts init_chdk_ptp_task in spytask at startup.
- init_chdk_ptp_task sits in loop sleeping for 250 ms until it successfully adds the CHDK handler, or more strictly, until add_ptp_handler doesn't return 0x17
- The 0x17 return is based on a variable that isn't set until PTP is initialized for the first time.

When a USB cable is used, the firmware initializes PTP when it detects a USB host (more or less), so the odds of starting a PTP connection within 250ms are extremely low, at least if connecting manually (could possibly be an issue if anyone makes a CHDK client that runs from udev).

For wifi in the cases where the UPnP handshake (https://chdk.setepontos.com/index.php?topic=10724.msg145439#msg145439) is required, PTP seems to be initialized based on the UPnP handshake. Again, very hard to connect within 250ms

For the direct connect without the UPnP handshake, PTP appears to be initialized when it sees the first PTP/IP packet, so CHDK has a very good chance of not adding its opcode before the client fetches device info.

It would be "better" for CHDK to hook into the stuff that registers all the other PTP handlers, but it's easy enough to work around in chdkptp by waiting 250ms and refreshing the devinfo if the CHDK opcode isn't detected the first time. This will slightly slow down connections to devices not running CHDK, but that should be a rare case.