Use TopfieldUSBEcode for received values too.
[MacTF.git] / TFDataFormat.m
blob86e4214d9a86111d1db6d44ad29ac881ce34c235
1 //
2 //  TFDataFormat.h
3 //  MacTF
4 //
5 //  Created by Kalle Olavi Niemitalo on 2007-10-23, based on:
6 //    TFUSBController.m
7 //    MacTF
8 //    Created by Nathan Oates on Sun Aug 01 2004.
9 //    Copyright (c) 2004-7 Nathan Oates nathan@noates.com All rights reserved.
10 //  May also include parts of:
11 //    uproar 0.1
12 //    Copyright (c) 2001 Kasima Tharnpipitchai <me@kasima.org>
14 // This source code is free software; you can redistribute it and/or
15 // modify it under the terms of the GNU Public License as published
16 // by the Free Software Foundation; either version 2 of the License,
17 // or (at your option) any later version.
19 // This source code is distributed in the hope that it will be useful,
20 // but WITHOUT ANY WARRANTY; without even the implied warranty of
21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
22 // Please refer to the GNU Public License for more details.
24 // You should have received a copy of the GNU Public License along with
25 // this source code; if not, write to:
26 // Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #import "TFDataFormat.h"
29 #import "Errors.h"
31 @implementation TFDataFormat
33 // ---------------------------------------------------------------------------
34 #pragma mark Framing of communication blocks
35 // ---------------------------------------------------------------------------
37 - (UInt16) findCRC:(const UInt8*)p length:(size_t)n
39         UInt16 m_crc16 = 0x0000;
40         static const UInt16 crc16Tbl[256] = {
41                 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
42                 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
43                 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
44                 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
45                 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
46                 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
47                 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
48                 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
49                 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
50                 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
51                 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
52                 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
53                 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
54                 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
55                 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
56                 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
57                 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
58                 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
59                 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
60                 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
61                 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
62                 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
63                 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
64                 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
65                 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
66                 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
67                 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
68                 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
69                 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
70                 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
71                 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
72                 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
73         };
74         size_t i;       
75         for(i = 0; i < n; i++)
76                         m_crc16 = (m_crc16 >> 8) ^ crc16Tbl[*p++ ^ (m_crc16 & 0xFF)];
77         return m_crc16;
80 - (NSMutableData*) swap:(NSData*)inData {
81         size_t len = [inData length];
82         size_t uneven = 0;
83         if (len % 2 != 0) {
84                 uneven = 1; // prepare space for padding
85         }
86         NSMutableData* outData = [NSMutableData dataWithLength:len+uneven];
87         swab([inData bytes], [outData mutableBytes], len-uneven);
88         if (uneven) {
89                 // swab() requires an even length.  The last byte was not given to
90                 // swab() above, so copy it separately.  Also clear the byte just
91                 // before the last one, even though the dataWithLength: class method
92                 // should have already cleared it.
93                 unsigned char final[2] = { 0, 0 };
94                 [inData getBytes:&final[1] range:(NSRange){len-1,1}];
95                 [outData replaceBytesInRange:(NSRange){len-1,2} withBytes:final];
96         }
97         return outData;
100 - (NSData*) prepareCommand:(TopfieldUSBCmd)cmd withData:(NSData*)inData {
101         NSMutableData* block = [NSMutableData dataWithLength:8];
102         if (inData != nil)
103                 [block appendData:inData];
104         size_t blockLength = [block length];
105         if (blockLength > 0xFFFF)
106                 return nil; // wouldn't fit in UInt16
108         UInt32 cmd_bigendian = EndianU32_NtoB(cmd);
109         [block replaceBytesInRange:(NSRange){4,4} withBytes:&cmd_bigendian];
111         UInt16 crc = [self findCRC:(const UInt8*)[block bytes]+4 length:blockLength-4];
112         UInt16 crc_bigendian = EndianU16_NtoB(crc);
113         [block replaceBytesInRange:(NSRange){2,2} withBytes:&crc_bigendian];
115         UInt16 blockLength_bigendian = EndianU16_NtoB(blockLength);
116         [block replaceBytesInRange:(NSRange){0,2} withBytes:&blockLength_bigendian];
118         return [self swap:block];
121 // Check the size and CRC of a received communication block.
122 - (BOOL) isCommunicationBlockValid:(NSData*)block
123         error:(NSError**)errorOut ecode:(TopfieldUSBEcode*)ecodeOut
125         NSError* error = nil;
126         TopfieldUSBEcode ecode = USB_OK;
128         if (block == nil) {
129                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
130                         @"ERR_COMMUNICATION_BLOCK_MISSING",
131                         nil, [NSBundle mainBundle],
132                         @"The PVR did not respond",
133                         @"A communication block was expected but not received");
134                 error = [NSError errorWithDomain:MacTFErrorDomain
135                         code:MACTF_ERR_COMMUNICATION_BLOCK_MISSING
136                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
137                                 forKey:NSLocalizedDescriptionKey]];
138                 ecode = USB_Err_RunFail;
139                 goto ret;
140         }
142         size_t length = [block length];
143         if (length < 8) {
144                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
145                         @"ERR_COMMUNICATION_BLOCK_LT_8_BYTES",
146                         nil, [NSBundle mainBundle],
147                         @"Received only %u bytes; eight are required",
148                         @"Topfield's USB protocol requires an 8-byte header in every"
149                          " communication block but the received block was too short"
150                          " for that");
151                 localizedDescription = [NSString stringWithFormat:localizedDescription,
152                         (unsigned) length];
153                 error = [NSError errorWithDomain:MacTFErrorDomain
154                         code:MACTF_ERR_COMMUNICATION_BLOCK_LT_8_BYTES
155                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
156                                 forKey:NSLocalizedDescriptionKey]];
157                 ecode = USB_Err_Size;
158                 goto ret;
159         }
161         UInt16 crc16_bigendian;
162         [block getBytes:&crc16_bigendian range:(NSRange){2,2}];
163         UInt16 crc = EndianU16_BtoN(crc16_bigendian);
164         UInt16 calcCrc = [self findCRC:(const UInt8*)[block bytes]+4
165                 length:length-4];
166         if (crc != calcCrc) {
167                 NSString* localizedDescription = NSLocalizedStringWithDefaultValue(
168                         @"ERR_COMMUNICATION_BLOCK_CRC",
169                         nil, [NSBundle mainBundle],
170                         @"CRC mismatch in received data.  The header claims %#.4x but"
171                          " the data computes to %#.4x.",
172                         @"CRC mismatch in a received communication block");
173                 localizedDescription = [NSString stringWithFormat:localizedDescription,
174                         (unsigned) crc, (unsigned) calcCrc];
175                 error = [NSError errorWithDomain:MacTFErrorDomain
176                                         code:MACTF_ERR_COMMUNICATION_BLOCK_CRC
177                                         userInfo:[NSDictionary dictionaryWithObject:localizedDescription
178                                                 forKey:NSLocalizedDescriptionKey]];
179                 ecode = USB_Err_Crc;
180                 goto ret;
181         }
183 ret:
184         if (ecodeOut != NULL)
185                 *ecodeOut = ecode;
186         if (errorOut != NULL)
187                 *errorOut = error;
188         return error == nil;
191 // Get the cmd field from a communication block.  The caller must already have
192 // checked the length of the block.
193 - (TopfieldUSBCmd) cmdFromCommunicationBlock:(NSData*)block {
194         UInt32 cmd_bigendian;
195         [block getBytes:&cmd_bigendian range:(NSRange){4,4}];
196         return EndianU32_BtoN(cmd_bigendian);
199 // ---------------------------------------------------------------------------
200 #pragma mark Common ingredients
201 // ---------------------------------------------------------------------------
203 - (BOOL) appendToData:(NSMutableData*)data fname:(NSString*)fname {
204         NSData* fnameData = [fname dataUsingEncoding:NSISOLatin1StringEncoding];
205         if (fnameData == nil) // fname contains characters unsupported by encoding
206                 return NO;
207         const size_t terminatorSize = 1;
208         [data appendData:fnameData];
209         [data increaseLengthBy:terminatorSize]; // fills with 0x00
210         return YES;
213 - (BOOL) appendToData:(NSMutableData*)data sizeAndFname:(NSString*)fname {
214         NSData* fnameData = [fname dataUsingEncoding:NSISOLatin1StringEncoding];
215         if (fnameData == nil) // fname contains characters unsupported by encoding
216                 return NO;
217         const size_t terminatorSize = 1;
218         const size_t nameSize = [fnameData length] + terminatorSize;
219         if (nameSize > 0xFFFF) // size would not fit in UInt16
220                 return NO;
221         const UInt16 nameSize_bigendian = EndianU16_NtoB(nameSize);
222         [data appendBytes:&nameSize_bigendian length:2];
223         [data appendData:fnameData];
224         [data increaseLengthBy:terminatorSize]; // fills with 0x00
225         return YES;
228 - (NSString*) fnameForFile:(NSString*)file atPath:(NSString*)path {
229         return [NSString stringWithFormat:@"%@\\%@", path, file];
232 // Convert a Topfield-defined command code to a string for logging.
233 // The string is not localized.
234 - (NSString*) nameOfCmd:(TopfieldUSBCmd)cmd {
235         switch (cmd) {
236                 case USB_CmdNone: return @"USB_CmdNone";
237                 case USB_Fail: return @"USB_Fail";
238                 case USB_Success: return @"USB_Success";
239                 case USB_Cancel: return @"USB_Cancel";
240                 case USB_CmdReady: return @"USB_CmdReady";
241                 case USB_CmdReset: return @"USB_CmdReset";
242                 case USB_CmdTurbo: return @"USB_CmdTurbo";
243                 case USB_CmdHddSize: return @"USB_CmdHddSize";
244                 case USB_DataHddSize: return @"USB_DataHddSize";
245                 case USB_CmdHddDir: return @"USB_CmdHddDir";
246                 case USB_DataHddDir: return @"USB_DataHddDir";
247                 case USB_DataHddDirEnd: return @"USB_DataHddDirEnd";
248                 case USB_CmdHddDel: return @"USB_CmdHddDel";
249                 case USB_CmdHddRename: return @"USB_CmdHddRename";
250                 case USB_CmdHddCreateDir: return @"USB_CmdHddCreateDir";
251                 case USB_CmdHddFileSend: return @"USB_CmdHddFileSend";
252                 case USB_DataHddFileStart: return @"USB_DataHddFileStart";
253                 case USB_DataHddFileData: return @"USB_DataHddFileData";
254                 case USB_DataHddFileEnd: return @"USB_DataHddFileEnd";
255                 default: return [NSString stringWithFormat:@"%#lx",
256                         (unsigned long) cmd];
257         }
260 // Convert a Topfield-defined error code to a string for logging.
261 // The string is not localized.
262 // The ecode parameter would normally be one of the values listed
263 // in enum TopfieldUSBEcode, but other values are allowed too.
264 - (NSString*) nameOfEcode:(TopfieldUSBEcode)ecode {
265         switch (ecode) {
266                 case USB_OK: return @"USB_OK";
267                 case USB_Err_Crc: return @"USB_Err_Crc";
268                 case USB_Err_UnknownCmd: return @"USB_Err_UnknownCmd";
269                 case USB_Err_InvalidCmd: return @"USB_Err_InvalidCmd";
270                 case USB_Err_Unknown: return @"USB_Err_Unknown";
271                 case USB_Err_Size: return @"USB_Err_Size";
272                 case USB_Err_RunFail: return @"USB_Err_RunFail";
273                 case USB_Err_Memory: return @"USB_Err_Memory";
274                 default: return [NSString stringWithFormat:@"%#lx",
275                         (unsigned long) ecode];
276         }
279 // ---------------------------------------------------------------------------
280 #pragma mark Communication blocks for various commands
281 // ---------------------------------------------------------------------------
283 - (NSData*) prepareFailWithECode:(TopfieldUSBEcode)ecode {
284         const UInt32 ecode_bigendian = EndianU32_NtoB(ecode);
285         NSData* data = [NSData dataWithBytes:&ecode_bigendian length:4];
286         if (data == nil) // out of memory presumably
287                 return nil;
288         return [self prepareCommand:USB_Fail withData:data];
291 - (TopfieldUSBEcode) ecodeFromFail:(NSData*)block {
292         if ([block length] < 12)
293                 return USB_Err_RunFail;
294         UInt32 ecode_bigendian;
295         [block getBytes:&ecode_bigendian range:(NSRange) {8,4}];
296         return EndianU32_BtoN(ecode_bigendian);
299 - (NSData*) prepareSuccess {
300         return [self prepareCommand:USB_Success withData:nil];
303 - (NSData*) prepareCancel {
304         return [self prepareCommand:USB_Cancel withData:nil];
307 // Prepare a communication block that asks the Toppy to list the files
308 // in a directory.  Return the communication block, or nil on error.
309 - (NSData*) prepareCmdHddDirWithPath:(NSString*)path {
310         NSMutableData* cmdData = [NSMutableData data];
311         if (cmdData == nil) // out of memory presumably
312                 return nil;
313         if (![self appendToData:cmdData fname:path])
314                 return nil;
315         return [self prepareCommand:USB_CmdHddDir withData:cmdData];
318 - (NSData*) prepareCmdHddFileSendWithDirection:(UInt8)direction
319                 fname:(NSString*)fname offset:(UInt64)offset
321         NSMutableData *cmdData = [NSMutableData dataWithBytes:&direction length:1];
322         if (cmdData == nil) // out of memory presumably
323                 return nil;
324         if (![self appendToData:cmdData sizeAndFname:fname])
325                 return nil;
326         const UInt64 offset_bigendian = EndianU64_NtoB(offset);
327         [cmdData appendBytes:&offset_bigendian length:8];
328         return [self prepareCommand:USB_CmdHddFileSend withData:cmdData];
331 - (SInt64) offsetFromDataHddFileData:(NSData*)block {
332         if ([block length] < 16)
333                 return -1;
334         SInt64 offset_bigendian;
335         [block getBytes:&offset_bigendian range:(NSRange) {8,8}];
336         return EndianS64_BtoN(offset_bigendian);
339 - (NSData*) prepareDataHddFileEnd {
340         return [self prepareCommand:USB_DataHddFileEnd withData:nil];
343 - (NSData*) prepareCmdTurboWithMode:(SInt32)mode {
344         const SInt32 mode_bigendian = EndianS32_NtoB(mode);
345         NSData* cmdData = [NSData dataWithBytes:&mode_bigendian length:4];
346         if (cmdData == nil) // out of memory presumably
347                 return nil;
348         return [self prepareCommand:USB_CmdTurbo withData:cmdData];
351 - (NSData*) prepareCmdHddDelWithFname:(NSString*)fname {
352         NSMutableData* cmdData = [NSMutableData data];
353         if (cmdData == nil) // out of memory presumably
354                 return nil;
355         if (![self appendToData:cmdData fname:fname])
356                 return nil;
357         return [self prepareCommand:USB_CmdHddDel withData:cmdData];
360 - (NSData*) prepareCmdHddRenameFromFname:(NSString*)oldFname toFname:(NSString*)newFname {
361         NSMutableData* cmdData = [NSMutableData data];
362         if (cmdData == nil) // out of memory presumably
363                 return nil;
364         if (![self appendToData:cmdData sizeAndFname:oldFname])
365                 return nil;
366         if (![self appendToData:cmdData sizeAndFname:newFname])
367                 return nil;
368         return [self prepareCommand:USB_CmdHddRename withData:cmdData];
371 - (NSData*) prepareCmdHddCreateDirWithFname:(NSString*)fname {
372         NSMutableData* cmdData = [NSMutableData data];
373         if (cmdData == nil) // out of memory presumably
374                 return nil;
375         if (![self appendToData:cmdData fname:fname])
376                 return nil;
377         return [self prepareCommand:USB_CmdHddCreateDir withData:cmdData];
380 @end