file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
C64.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/machine/C64.java | /**
* @(#)C64.java 1999/09/19
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.machine;
import sw_emulator.hardware.powered;
import sw_emulator.hardware.signaller;
import sw_emulator.hardware.bus.C64Bus;
import sw_emulator.hardware.memory.dinamic;
import sw_emulator.hardware.memory.DRAM;
import sw_emulator.hardware.memory.ColorRAM;
import sw_emulator.hardware.memory.ROM;
import sw_emulator.hardware.Clock;
import sw_emulator.hardware.cartridge.Cartridge;
import sw_emulator.hardware.cartridge.GameCartridge;
import sw_emulator.hardware.cpu.M6510;
import sw_emulator.hardware.chip.PLA82S100;
import sw_emulator.hardware.chip.M6569;
import sw_emulator.hardware.chip.M6526;
import sw_emulator.hardware.chip.Sid;
import sw_emulator.hardware.io.C64M6510IO;
import sw_emulator.hardware.io.C64VicII_IO;
import sw_emulator.hardware.io.C64Cia1IO;
import sw_emulator.hardware.io.C64Cia2IO;
import sw_emulator.hardware.io.C64CartridgeIO;
import sw_emulator.hardware.device.C64Keyboard;
import sw_emulator.hardware.device.TV;
import sw_emulator.hardware.device.C64Form;
import sw_emulator.util.AndPort;
import sw_emulator.software.cartridge.FileCartridge;
/**
* Emulate the Commodore 64 computer.
*
* @author Ice
* @version 1.00 19/09/1999
*/
public class C64 implements powered{
/** Path where the roms images are stored */
public static final String ROM_PATH="/rom/";
/** 8Kb of Ram memory address 0x0000 0x1FFF */
protected DRAM ram0=new DRAM(8*1024, 0x0000);
/** 8Kb of Ram memory address 0x2000 0x3FFF */
protected DRAM ram1=new DRAM(8*1024, 0x2000);
/** 8Kb of Ram memory address 0x4000 0x5FFF */
protected DRAM ram2=new DRAM(8*1024, 0x4000);
/** 8Kb of Ram memory address 0x6000 0x7FFF */
protected DRAM ram3=new DRAM(8*1024, 0x6000);
/** 8Kb of Ram memory address 0x8000 0x9FFF */
protected DRAM ram4=new DRAM(8*1024, 0x8000);
/** 8Kb of Ram memory address 0xA000 0xBFFF */
protected DRAM ram5=new DRAM(8*1024, 0xA000);
/** 8Kb of Ram memory address 0xC000 0xDFFF */
protected DRAM ram6=new DRAM(8*1024, 0xC000);
/** 8Kb of Ram memory address 0xE000 0xFFFF */
protected DRAM ram7=new DRAM(8*1024, 0xE000);
/** Dinamic memories that need refresh */
protected dinamic[] dinamicMemories={
ram0, ram1, ram2, ram3, ram4, ram5, ram6, ram7
};
/** The 8Kbyte of Basic ROM memory */
public ROM basic=new ROM(8*1024, 0xA000);
/** The 8Kbyte of Kernal ROM memory */
public ROM kernal=new ROM(8*1024, 0xE000);
/** The 4Kbyte of Char generator ROM memory */
public ROM chargen=new ROM(4*1024, 0xD000);
/** The bus of the C64 */
public C64Bus bus=new C64Bus();
/** The 1Kb of color ram */
public ColorRAM color=new ColorRAM(1024, 0xD800, bus);
/** The 8Mhz clock signal */
public Clock clock=new Clock(Clock.PAL);
/** The TV attached to the C64 Vic II output */
public TV tv=new TV();
/** The application menu bar */
public C64Form c64Form=new C64Form();
/** The M6569 Vic II */
public M6569 vic=new M6569(clock.monitor, bus, C64Bus.V_VIC, null,
dinamicMemories, tv);
/** The Mos 6510 cpu */
public M6510 cpu=new M6510(vic.intMonitor, bus, C64Bus.V_CPU, null);
/** The Mos SID chip */
public Sid sid=new Sid(); // to modify
/** The cartridge port */
public Cartridge exp=new Cartridge(null, vic.intMonitor, bus);
/** The Cia 1 chip */
public M6526 cia1=new M6526(M6526.PAL, vic.intMonitor, null);
/** The Cia2 chip */
public M6526 cia2=new M6526(M6526.PAL, vic.intMonitor, null, signaller.S_NMI);
/** Devices that will need tod signal */
protected signaller[] devicesTod={cia1, cia2};
/** The PLA82S100 chip of C64 */
public PLA82S100 pla=new PLA82S100(bus, exp,
ram0, ram1, ram2, ram3,
ram4, ram5, ram6, ram7,
basic, kernal, chargen,
vic, sid,
color, cia1, cia2);
/** The C64 keyboard */
public C64Keyboard keyb=new C64Keyboard(null);
/** The IO signals of C64 cpu */
public C64M6510IO cpuIO=new C64M6510IO(pla);
/**
* The 74LS08 And port with output pin 6.
* This give AEC signal to Cpu.
*/
protected AndPort and6=new AndPort(cpu, signaller.S_AEC, signaller.S_DMA,
signaller.S_AEC);
/**
* The 74LS08 And port with output pin 3.
* This give RDY signal to Cpu.
*/
protected AndPort and3=new AndPort(cpu, signaller.S_BA, signaller.S_DMA,
signaller.S_RDY);
/** The Vic IO signals connections */
public C64VicII_IO vicIO=new C64VicII_IO(cpu, exp, and6, and3);
/** The Cia 1 IO signals connections */
public C64Cia1IO cia1IO=new C64Cia1IO(cpu, exp, keyb.monitor, keyb.colLines);
/** The Cia 2 IO signals connections */
public C64Cia2IO cia2IO=new C64Cia2IO(cpu, exp, pla);
/** The expansion IO signals connections */
public C64CartridgeIO expIO=new C64CartridgeIO(cpu, pla, and6, and3);
/** Manage file cartridge */
public FileCartridge fileCart=new FileCartridge(expIO, vic.intMonitor, bus);
/** A game Cartridge */
public GameCartridge gameExp;
public C64() {
clock.registerTod(devicesTod); // register cia for using tod from the clock
initMemory();
c64Form.addTV(tv);
c64Form.setVisible(true);
// read cartridge:
//fileCart.setFileName("/mnt/new/home/ice/dig_dug.crt");
//System.out.println(fileCart.readFile());
//System.out.println(fileCart.determineCart());
//gameExp=(GameCartridge)fileCart.getCartridge(0);
//gameExp.setIO(expIO);
//pla.setExpansion(gameExp);
cpu.setIO(cpuIO); // set cpu IO signals
vic.setIO(vicIO); // set vic IO signals
keyb.setIO(cia1IO); // set keyb IO signals
exp.setIO(expIO); // set exp IO signals
cia1.setIO(cia1IO); // set cia 1 IO signals
cia2.setIO(cia2IO); // set cia 2 IO signals
bus.setColor(color); // set up color ram for Vic in bus
kernal.change(0xfd84, (byte)0xa0); // don't fill the memory
kernal.change(0xfd85, (byte)00);
System.out.println("Power ON the machine");
powerOn();
clock.setRealTime(1); ///debug: use slow clock
System.out.println("Start the clock...");
clock.startClock();
}
public static void main(String[] args) {
C64 c64 = new C64();
}
/**
* Initialize the C64 Memories chip (RAM and ROMs).
* If there's error, the program halt with error message.
*/
public void initMemory() {
System.out.println("Reading machine ROMs");
if (!(basic.load(ROM_PATH+"basic.rom") &&
kernal.load(ROM_PATH+"kernal.rom") &&
chargen.load(ROM_PATH+"char.rom"))) {
System.err.println("Error reading the ROM images.");
System.exit(1);
}
}
/**
* Power on the electronic component in the machine
*/
public void powerOn() {
//gameExp.powerOn();
//exp.powerOn();
pla.powerOn();
System.out.println(" Pla: power is on");
cpu.powerOn();
System.out.println(" Cpu: power is on");
vic.powerOn();
System.out.println(" VIC: power is on");
cia1.powerOn();
System.out.println(" CIA1: power is on");
cia2.powerOn();
System.out.println(" CIA2: power is on");
sid.powerOn();
System.out.println(" SID: power is on");
}
/**
* Power off the electronic component in the machine
*/
public void powerOff() {
pla.powerOff();
System.out.println("Pla: power is off");
cpu.powerOff();
System.out.println(" Cpu: power is off");
vic.powerOff();
System.out.println(" VIC: power is off");
cia1.powerOff();
System.out.println(" CIA1: power is off");
cia2.powerOff();
System.out.println(" CIA2: power is off");
sid.powerOff();
System.out.println(" SID: power is off");
}
}
| 8,902 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
M6526.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/M6526.java | /**
* @(#)M6526.java 1999/10/24
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.hardware.powered;
import sw_emulator.hardware.signaller;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.hardware.io.M6526IO;
import sw_emulator.math.Unsigned;
import sw_emulator.util.Monitor;
import sw_emulator.util.FlipFlop;
import sw_emulator.util.FlipFlopClock;
import sw_emulator.util.Counter;
import sw_emulator.util.FlipFlopDelayClock;
/**
* MOS 6526 cia chip implementation
*
* TOD emulation are based onto documentation of Commodore Book
* The other is based onto "A software Model of the CIA6526" by Wolfgang Lorenz
*
* @author Ice
* @version 1.00 23/10/1999
*/
public class M6526 extends Thread implements powered, signaller,
readableBus, writeableBus{
public static final int NTSC=0;
public static final int PAL=1;
/** The IRQ signal to use */
protected int sig_irq=signaller.S_IRQ;
/** The state of power */
protected boolean power=false;
/** The actual input FLAG signal */
protected int inputFLAG=1;
/** the actual input CNT signal */
protected int inputCNT=0;
/** The I/O of M6526 */
public M6526IO io;
/** The clock monitor */
protected Monitor monitor;
// states are n bits for better managing
/** State of CRA0 field (bit 0) START */
public int CRA0;
/** State of CRA1 field (bit 1) PBON */
public int CRA1;
/** State of CRA2 field (bit 2) OUTMODE */
public int CRA2;
/** State of CRA3 field (bit 3) RUNMODE */
public int CRA3;
/** State of CRA4 field (bit 4) LOAD */
public int CRA4;
/** State of CRA5 field (bit 5) INMODE */
public int CRA5;
/** State of CRA6 field (bit 6) SPMODE */
public int CRA6;
/** State of CRA7 field (bit 7) TODIN */
public int CRA7;
/** State of CRB0 field (bit 0) START */
public int CRB0;
/** State of CRB1 field (bit 1) PBON */
public int CRB1;
/** State of CRB2 field (bit 2) OUTMODE */
public int CRB2;
/** State of CRB3 field (bit 3) RUNMODE */
public int CRB3;
/** State of CRB4 field (bit 4) LOAD */
public int CRB4;
/** State of CRB56 filed (bits 5-6) INMODE*/
public int CRB56;
/** State of CRB7 field (bit 0) TOD/ALLARM */
public int CRB7;
// interrupt control register
/** Control: Interrupt register */
public int C_IR=0;
/** Control: Flag */
public int C_FLG=0;
/** Control: Serial Port */
public int C_SP=0;
/** Control: Alarm */
public int C_ALRM=0;
/** Control Timer B */
public int C_TB=0;
/** Control: Timer A */
public int C_TA=0;
/** Mask: Interrupt register */
public int M_SC=0;
/** Mask: Flag */
public int M_FLG=0;
/** Mask: Serial Port */
public int M_SP=0;
/** Mask: Alarm */
public int M_ALRM=0;
/** Mask Timer B */
public int M_TB=0;
/** Mask: Timer A */
public int M_TA=0;
/** Interrupt1 flip flop */
protected FlipFlopClock fInterrupt1=new FlipFlopClock();
/** CountA0 flip flop */
protected FlipFlop fCountA0=new FlipFlop();
/** CountA1 delay flip flop */
protected FlipFlopDelayClock fCountA1=new FlipFlopDelayClock();
/** LoadA0 flip flop */
protected FlipFlop fLoadA0=new FlipFlop();
/** LoadA1 delay flip flop */
protected FlipFlopDelayClock fLoadA1=new FlipFlopDelayClock();
/** OneShotA0 flip flop */
protected FlipFlopDelayClock fOneShotA0=new FlipFlopDelayClock();
/** CountA2 flip flop */
protected FlipFlopClock fCountA2=new FlipFlopClock();
/** CountA3 delay flip flop */
protected FlipFlopDelayClock fCountA3=new FlipFlopDelayClock();
/** TimerA flip flop */
protected FlipFlop fTimerA=new FlipFlop();
/** Timer A */
protected Counter timerA=new Counter();
/** CountB0 flip flop */
protected FlipFlop fCountB0=new FlipFlop();
/** CountB1 delay flip flop */
protected FlipFlopDelayClock fCountB1=new FlipFlopDelayClock();
/** LoadB0 flip flop */
protected FlipFlop fLoadB0=new FlipFlop();
/** LoadB1 delay flip flop */
protected FlipFlopDelayClock fLoadB1=new FlipFlopDelayClock();
/** OneShotB0 delay flip flop */
protected FlipFlopDelayClock fOneShotB0=new FlipFlopDelayClock();
/** CountB2 flip flop */
protected FlipFlopClock fCountB2=new FlipFlopClock();
/** CountB3 delay flip flop */
protected FlipFlopDelayClock fCountB3=new FlipFlopDelayClock();
/** TimerB flip flop */
protected FlipFlop fTimerB=new FlipFlop();
/** Timer B */
protected Counter timerB=new Counter();
/** Input Timer A value */
protected int inTimerA=0;
/** Input Timer B value */
protected int inTimerB=0;
/** Output Timer A value */
protected int outTimerA=0;
/** Output Timer B value */
protected int outTimerB=0;
/// TOD variables
/** Number of cycle for reacing a TOD signal of 1/10th sec. */
protected int MAX_TOD=5; // suppose PAL
/** The actual input TOD signal */
protected int inputTOD=0;
/**
* The counter of TOD signal. It is decremented, so we may change the PAL to
* NTSC pin without emulation problem.
*/
private int countTOD;
/** True if TOD is being writed */
private boolean isWritingTod=false;
/** True if tod is to increment */
private boolean isTodToIncrement=false;
/** Allarm value of Tod 10ths */
public int allarmTodThs;
/** Allarm value of Tod second */
public int allarmTodSec;
/** Allarm value of Tod minute */
public int allarmTodMin;
/** Allarm value of Tod hour */
public int allarmTodHr;
/** Latch value of Tod 10ths */
public int latchTodThs;
/** Latch value of Tod second */
public int latchTodSec;
/** Latch value of Tod minute */
public int latchTodMin;
/** Latch value of Tod hour */
public int latchTodHr;
/** Timer value of Tod 10ths */
public int timerTodThs;
/** Timer value of Tod second */
public int timerTodSec;
/** Timer value of Tod minute */
public int timerTodMin;
/** Timer value of Tod hour */
public int timerTodHr;
/**
* Construct the cia chip
*
* @param type the type of cia (NTSC, PAL)
* @param monitor the clock monitor at 1Mhz
* @param io the io of the chip
*/
public M6526(int type, Monitor monitor, M6526IO io) {
if (type==NTSC) MAX_TOD=6;
this.monitor=monitor;
this.io=io;
setName("CIA1"); // use this name for the thread
start();
}
/**
* Construct the cia chip with a special signal for the irq
*
* @param type the type of cia (NTSC, PAL)
* @param monitor the clock monitor at 1Mhz
* @param io the io of the chip
* @param sig_irq signal to use for irq
*/
public M6526(int type, Monitor monitor, M6526IO io, int sig_irq) {
this.sig_irq=sig_irq;
if (type==NTSC) MAX_TOD=6;
this.monitor=monitor;
this.io=io;
setName("CIA2"); // use this name for the thread
start();
}
/**
* Write a byte to the bus at specific address location.
*
* @param addr the address location
* @param value the byte value
*/
@Override
public void write(int addr, byte value) {
addr&=0x0F;
switch (addr) {
case 0x00: // Port A data
case 0x01: // Port B data
case 0x02: // Port A direction
case 0x03: // Port B direction
io.writeToPort(addr, value);
break;
case 0x04: // TA low
timerA.setLow(value);
break;
case 0x05: // TA high
timerA.setHigh(value);
break;
case 0x06: // TB low
timerB.setLow(value);
break;
case 0x07: // TB high
timerB.setHigh(value);
break;
case 0x08: // TOD 10TH
if (CRB7==0) { // TOD
timerTodThs=(value & 0x0F);
isWritingTod=false; // tod is not being writing
} else { // ALLARM
allarmTodThs=(value & 0x0F);
}
break;
case 0x09: // TOD sec
if (CRB7==0) { // TOD
timerTodSec=(value & 0x7F);
} else { // ALLARM
allarmTodSec=(value & 0x7F);
}
break;
case 0x0A: // TOD min
if (CRB7==0) { // TOD
timerTodMin=(value & 0x0F);
} else { // ALLARM
allarmTodMin=(value & 0x0F);
}
break;
case 0x0B: // TOD hr
if (CRB7==0) { // TOD
timerTodHr=(value & 0x9F);
isWritingTod=true; // tod is being writing
} else { // ALLARM
allarmTodHr=(value & 0x9F);
}
break;
case 0x0D: // ICR
M_TA=value & 0x01;
M_TB=(value>>=1)& 0x01;
M_ALRM=(value>>=1)& 0x01;
M_SP=(value>>=1)& 0x01;
M_FLG=(value>>=1)& 0x01;
M_SC=(value>>3)& 0x01;
break;
case 0x0E: // CRA
///dumpInternal("READ") ;
CRA0=value & 0x01;
CRA1=(value>>=1)& 0x01;
CRA2=(value>>=1)& 0x01;
CRA3=(value>>=1)& 0x01;
CRA4=(value>>=1)& 0x01;
CRA5=(value>>=1)& 0x01;
CRA6=(value>>=1)& 0x01;
CRA7=(value>>=1)& 0x01;
// START
if (CRA0==1) fTimerA.set();
// as reset in this flip flop can occurs in the phi phase,
// here we must update CountA2
fCountA2.set(CRA0==1 & inTimerA==1);
if (CRA4==1) fLoadA0.set(); // force loadA0
fOneShotA0.set(CRA3==1); // RUNMODE
///dumpInternal("AFTER");
break;
case 0x0F: // CRB
CRB0=value & 0x01;
CRB1=(value>>=1)& 0x01;
CRB2=(value>>=1)& 0x01;
CRB3=(value>>=1)& 0x01;
CRB4=(value>>=1)& 0x01;
CRB56=(value>>=1)& 0x03;
CRB7=(value>>=2)& 0x01; // TOD/ALLARM
// START
if (CRB0==1) fTimerB.set();
// as reset in this flip flop can occurs in the phi phase,
// here we must update CountA2
fCountB2.set(CRB0==1 && inTimerB==1);
if (CRB4==1) fLoadB0.set(); // force loadA0
fOneShotB0.set(CRB3==1); // RUNMODE
break;
}
}
/**
* Read a byte from the bus at specific address location.
*
* @param addr the address location
* @return the readed byte
*/
@Override
public byte read(int addr) {
addr&=0x0F;
switch (addr) {
case 0x00: // Port A data
case 0x01: // Port B data
case 0x02: // Port A direction
case 0x03: // Port B direction
return (byte)io.readFromPort(addr);
case 0x04: // TA low
return (byte)timerA.getLow();
case 0x05: // TA high
return (byte)timerA.getHigh();
case 0x06: // TB low
return (byte)timerB.getLow();
case 0x07: // TB high
return (byte)timerB.getHigh();
case 0x08: // TOD 10TH
return (byte)latchTodThs;
case 0x09: // TOD sec
return (byte)latchTodSec;
case 0x0A: // TOD min
return (byte)latchTodMin;
case 0x0B: // TOD hr
latchTodHr=timerTodHr; // actual values are latched
latchTodMin=timerTodMin;
latchTodSec=timerTodSec;
latchTodThs=timerTodThs;
return (byte)latchTodHr;
case 0x0D: // ICR
int res=(C_IR<<7)+
(C_FLG<<4)+
(C_SP<<3)+
(C_ALRM<<2)+
(C_TB<<1)+
(C_TA);
// clear according to figure 5
io.notifySignal(sig_irq, 1); // disable interrupt
// the flip flop reset signal is below
C_IR=0;
C_FLG=0;
C_SP=0;
C_ALRM=0;
C_TB=0;
C_TA=0;
return (byte)res;
case 0x0E: // CRA state
return (byte)(CRA0+
(CRA1<<1)+
(CRA2<<2)+
(CRA3<<3)+
///(CRA4<<4) Bit 4 is always 0 when read
(CRA5<<5)+
(CRA6<<6)+
(CRA7<<7));
case 0x0F: // CRB state
return (byte)((fTimerB.isSet() ? 1:0)+
(CRB1<<1)+
(CRB2<<2)+
(CRB3<<3)+
///(CRB4<<4)+ Bit 4 is always 0 when read
(CRB56<<5)+
(CRB7<<7));
}
fInterrupt1.reset(addr==0x0D);
return 0;
}
/**
* Notify a signal to the chip.
* Note: the signal that are level significative (like FLAG and TOD) may
* notify only when the level changes, else there will be timing error.
* E.g. a sequenxe of 1___0___1___0___1___0... is good, while a sequence of
* 1_1_0_0_1_1_0_0_1_1_0_0... is not good, even if the translaction in the
* same period are the same. This is done for speed up pourpuse. If we have
* that kind of sequence, we must use: <BR>
* <pre>
* case xx:
* if (inputxx!=value) {
* // same operactions as now
* }
* </pre>
*
* @param type the type of signal
* @param value the value of the signal (0/1)
*/
@Override
public void notifySignal(int type, int value) {
switch (type) {
case S_TOD:
inputTOD=value; // store in buffer the value
if (value==1) { // is there a level 0 to 1?
if (countTOD--==0) {
countTOD=MAX_TOD; // repristinate the counter
isTodToIncrement=true; // tod is to increment
}
}
break;
case S_FLAG:
inputFLAG=value; // store in buffer the value
if (value==0) { // is there a level 1 to 0?
}
break;
case S_CNT:
inputCNT=value;
if (value==1) { // is there a level 0 to 1?
fCountA0.set(); // set the CountA0 flipflop
fCountB0.set(); // set the CountB0 flipflop
}
break;
}
}
/**
* Set up the connection of IO with the external.
*
* @param io the external connection
*/
public void setIO(M6526IO io) {
this.io=io;
}
/**
* Execute the body of a cia clock (syncroned clocked part)
*/
protected void bodySync() {
// emulate all the state changed by clock ih flip flop
fCountA0.reset();
fCountA1.clock();
fLoadA0.reset();
fLoadA1.clock();
fOneShotA0.clock();
fCountA3.clock();
fCountA2.clock();
timerA.clock();
fCountB0.reset();
fCountB1.clock();
fLoadB0.reset();
fLoadB1.clock();
fOneShotB0.clock();
fCountB3.clock(); ///
fCountB2.clock(); ///
timerB.clock();
fInterrupt1.clock();
// check for interrupt
if (fInterrupt1.isSet()) {
C_IR=1;
io.notifySignal(sig_irq, 0); // notify an irq
}
}
/**
* Execute the body of async logic (not clocked) of cia
* Emulate all the login and connections between the flip flop
*/
protected void bodyAsync() {
boolean temp;
// tod testing
if (isTodToIncrement) {
isTodToIncrement=false;
// increment Tod 10 Ths
timerTodThs++;
if (timerTodThs==0x0A) {
timerTodThs=0;
//increment seconds
timerTodSec++;
if ((timerTodSec & 0x0F)==0x0A) {
timerTodSec+=6;
if (timerTodSec==0x60) {
timerTodSec=0;
// increment minutes
timerTodMin++;
if ((timerTodMin & 0x0F)==0x0A) {
timerTodMin+=6;
if (timerTodMin==0x60) {
timerTodMin=0;
// increment hours
timerTodHr++;
if ((timerTodHr & 0x1F)==0x0A) {
timerTodHr+=6;
} else {
// there is an AM/PM change
if ((timerTodHr & 0x1F)==0x13) {
timerTodHr &=0x8F;
timerTodHr ^=0x80;
}
}
}
}
}
}
}
// see if now there is an allarm to activate
if (allarmTodThs==timerTodThs &&
allarmTodSec==timerTodSec &&
allarmTodMin==timerTodMin &&
allarmTodHr==timerTodHr) {
// fire an irq
C_ALRM=1;
}
}
/// these are to be called before the clock for having the force load
fLoadA1.set(fLoadA0.isSet());
fLoadB1.set(fLoadB0.isSet());
// emulate as in figure 3
timerA.setDec(fCountA3.isSet());
timerB.setDec(fCountB3.isSet());
// emulate as in figure 3
// fCountA3.set(fCountA2.isSet());
fCountB3.set(fCountB2.isSet());
// calculate outTimerA output value
// emulate as in figure 3
outTimerA=((fCountA2.isSet() && timerA.isZero()) ? 1:0);
outTimerB=((fCountB2.isSet() && timerB.isZero()) ? 1:0);
temp=(outTimerA==1) || fLoadA1.isSet();
timerA.load(temp);
fCountA2.reset(temp);
timerA.setDec(fCountA3.isSet());
temp=(outTimerB==1) || fLoadB1.isSet();
timerB.load(temp);
fCountB2.reset(temp);
// emulate as in figure 1
fCountA1.set(fCountA0.isSet());
fCountB1.set(fCountB0.isSet());
// calculate inTimerA input value
// emulate as in figure 1
if (CRA5==1) inTimerA=fCountA1.toInt(); // cnt gives CountA1
else inTimerA=1; // phi2 alway gives 1
// calculate inTimerB input value (outTimerA value must be already done)
// emulate as in figure 2
switch (CRB56) {
case 0x00:
inTimerB=1; // phi2 alway gives 1
break;
case 0x01:
inTimerB=fCountB1.toInt(); // cnt gives CountB1
break;
case 0x02:
inTimerB=outTimerA; // same output as A
break;
case 0x03:
inTimerB=outTimerA & inputCNT; // and of cnt/intput A
break;
}
// emulate as in figure 3
if (((CRA3==1) || fOneShotA0.isSet()) && outTimerA==1) CRA0=0; //fTimerA.reset();
fCountA2.set((fTimerA.isSet() && inTimerA==1));
if (((CRB3==1) || fOneShotB0.isSet()) && outTimerB==1) CRB0=0; //fTimerB.reset();
fCountB2.set((fTimerB.isSet() && inTimerB==1));
// emulate as in figure 5
fInterrupt1.set((outTimerA==1 && M_TA==1) ||
(outTimerB==1 && M_TB==1) ||
(C_ALRM==1 && M_ALRM==1)
);
}
/**
* Performs the body of cia emulation.
* The emulation don't start if the io port is not set up with a correct
* handler.
*/
public void run() {
monitor.opNotify(); // notify that we will use it
while(io==null) {
this.yield();
}
while(true) {
while (!power) {
this.yield(); // give mutex to other threads
}
bodyAsync(); // execute tha async part of body
bodySync(); // execute the cia clock boby
monitor.opWait(); // attend clock signal
}
}
/**
* Power on the electronic component
*/
public void powerOn() {
power=true; // power is on
}
/**
* Power off the electronic component
*/
public void powerOff() {
power=false; // power is off
}
private void dumpInternal(String event) {
if (CRB0==0) return;
System.err.println(event);
System.err.println("A: ");
System.err.println(" CRA: "+CRA7+""+CRA6+""+CRA5+""+CRA4+" "+CRA3+""+CRA2+CRA1+""+CRA0);
System.err.println(" fCountA0= "+fCountA0.isSet());
System.err.println(" fCountA1= "+fCountA1.isSet());
System.err.println(" fCountA2= "+fCountA2.isSet());
System.err.println(" fCountA3= "+fCountA3.isSet());
System.err.println(" fLoadA0 = "+fLoadA0.isSet());
System.err.println(" fLoadA1 = "+fLoadA1.isSet());
System.err.println(" fOneShotA0= "+fOneShotA0.isSet());
System.err.println(" outTimerA= "+outTimerA);
System.err.println(" fTimerA= "+fTimerA.isSet());
System.err.println(" timerA= "+timerA.counter);
}
} | 23,427 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
PLA82S100.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/PLA82S100.java | /**
* @(#)PLA82S100.java 1999/10/15
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.hardware.cartridge.Cartridge;
import sw_emulator.hardware.powered;
import sw_emulator.hardware.signaller;
import sw_emulator.hardware.memory.Memory;
import sw_emulator.hardware.memory.ROM;
import sw_emulator.hardware.memory.ColorRAM;
import sw_emulator.hardware.bus.C64Bus;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.util.Monitor1;
/**
* Emulate the PLA 82S100 chip of a Commodore 64 computer.
* The emulation consists of calculating the rigth table for reading/writing
* bus operation of Cpu and Vic chips.
*
* For the VIC:
* it can access 16Kb, so the 64Kb of memory space addess are divide into four
* bank: 0, 1, 2, 3. The PLA set the correct bank using VA14 and VA15 signals.
*
* For the Cpu:
* it accesses 64Kb of memory in read and write operations.
* The available configurations are given by this signals value: LORAM, HIRAM,
* GAME, EXROM, CHAREN.
*
* The chips that may notify some changing signals may use
* <code>notifySignal</code> and then a <code>opSignal</code> to the available
* <code>monitor</code>.
*
* @author Ice
* @version 1.00 15/10/1999
*/
public class PLA82S100 extends Thread implements powered, signaller {
/** The state of power */
private boolean power=false;
/** True if it is a ultimax configuration */
private boolean ultimax=false;
/** The monitor where PLA attend a signal that changing value */
public Monitor1 monitor=new Monitor1("PLA 82S100");
/** A copy of actual C64 bus. */
protected C64Bus bus;
/** Cartridge expansion port */
protected Cartridge exp;
/** 8Kb of Ram memory address 0x0000 0x1FFF */
protected Memory ram0;
/** 8Kb of Ram memory address 0x2000 0x3FFF */
protected Memory ram1;
/** 8Kb of Ram memory address 0x4000 0x5FFF */
protected Memory ram2;
/** 8Kb of Ram memory address 0x6000 0x7FFF */
protected Memory ram3;
/** 8Kb of Ram memory address 0x8000 0x9FFF */
protected Memory ram4;
/** 8Kb of Ram mmemory address 0xA000 0xBFFF */
protected Memory ram5;
/** 8Kb of Ram memory address 0xC000 0xDFFF */
protected Memory ram6;
/** 8Kb of Ram memory address 0xE000 0xFFFF */
protected Memory ram7;
/** The 8Kb of Basic ROM */
protected ROM basic;
/** The 8Kb of Kernal ROM */
protected ROM kernal;
/** The 4Kb of Char ROM */
protected ROM chargen;
/** The 40h bytes of VIC I/O */
protected VicII vic;
/** The 20h bytes of SID I/O */
protected Sid sid;
/** The 1Kb of color RAM */
protected ColorRAM color;
/* The 10h bytes of Cia 1 */
protected M6526 cia1;
/** The 10h bytes of Cia2 */
protected M6526 cia2;
// external input signals
/** Loram signal from M6510 in the C64 */
protected int loram=1; // default is up
/** Hiram signal from M6510 cpu in the C64 */
protected int hiram=1; // default is up
/** Charen signal from M6510 in the C64 */
protected int charen=1; // default is up
/** Exrom signal from Cartridge in the C64 */
protected int exrom=1; // default is up
/** Game signal from Cartridge in the C64 */
protected int game=1; // default is up
/** Va14 signal from Cia2 (inverted) in the C64 */
protected int va14;
/** Va15 signal from Cia2 (inverted) in the C64 */
protected int va15;
/** Table for Vic in bank 0 (000h-3FFFh) with char ROM activated */
private readableBus[] vicT0R=new readableBus[0x4000>>8];
/** Table for Vic in bank 0 (0000h-3FFFh) without char ROM activated */
private readableBus[] vicT0=new readableBus[0x4000>>8];
/** Table for Vic in bank 1 (4000h-7FFFh) */
private readableBus[] vicT1=new readableBus[0x4000>>8];
/** Table for Vic in bank 2 (8000h-BFFFh) with char ROM activated */
private readableBus[] vicT2R=new readableBus[0x4000>>8];
/** Table for Vic in bank 2 (8000h-BFFFh) (without char ROM activated */
private readableBus[] vicT2=new readableBus[0x4000>>8];
/** Table for Vic in bank 3 (C000h-FFFFh) */
private readableBus[] vicT3=new readableBus[0x4000>>8];
/** Table for cpu read, configuration 11111. */
private readableBus[] cpuR11111=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 11110. */
private readableBus[] cpuR11110=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 101x1. */
private readableBus[] cpuR101x1=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 101x0. */
private readableBus[] cpuR101x0=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 10001. */
private readableBus[] cpuR10001=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 10000. */
private readableBus[] cpuR10000=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 011x1. */
private readableBus[] cpuR011x1=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 011x0. */
private readableBus[] cpuR011x0=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 001x-00x0. */
private readableBus[] cpuR001x_00x0=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 11101. */
private readableBus[] cpuR11101=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 11100. */
private readableBus[] cpuR11100=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 01001. */
private readableBus[] cpuR01001=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 01000. */
private readableBus[] cpuR01000=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 11001. */
private readableBus[] cpuR11001=new readableBus[0x10000>>8];
/** Table for cpu read, configuration 11000. */
private readableBus[] cpuR11000=new readableBus[0x10000>>8];
/** Table for cpu read, configuration xx01. */
private readableBus[] cpuRxx01=new readableBus[0x10000>>8];
/** Table for cpu write, configuration all to ram */
private writeableBus[] cpuWRam=new writeableBus[0x10000>>8];
/** Table for cpu write, configuration to ram and I/O */
private writeableBus[] cpuWIO=new writeableBus[0x10000>>8];
/** Table for cpu write, configuration ultimax */
private writeableBus[] cpuWUltimax=new writeableBus[0x10000>>8];
/**
* Construct a PLA82S100.
*
* @param bus the C64 bus where changing tables
* @param exp the cartridge expansion port.
* @param ram0 8Kb of Ram memory address 0x0000 0x1FFF
* @param ram1 8Kb of Ram memory address 0x2000 0x3FFF
* @param ram2 8Kb of Ram memory address 0x4000 0x5FFF
* @param ram3 8Kb of Ram memory address 0x6000 0x7FFF
* @param ram4 8Kb of Ram memory address 0x8000 0x9FFF
* @param ram5 8Kb of Ram memory address 0xA000 0xBFFF
* @param ram6 8Kb of Ram memory address 0xC000 0xDFFF
* @param ram7 8Kb of Ram memory address 0xE000 0xFFFF
* @param basic the 8Kb of Basic ROM
* @param kernal the 8Kb of kernal ROM
* @param chargen the 4Kb of char ROM
* @param vic the 40h bytes of VIC I/O
* @param sid the 20h bytes of SID I/O
* @param color the 1Kbyte of color ram
* @param cia1 the 10h bytes of CIA1
* @param cia2 the 10h bytes of CIA2
*/
public PLA82S100(C64Bus bus,
Cartridge exp,
Memory ram0, Memory ram1, Memory ram2, Memory ram3,
Memory ram4, Memory ram5, Memory ram6, Memory ram7,
ROM basic, ROM kernal, ROM chargen,
VicII vic, Sid sid, ColorRAM color,
M6526 cia1, M6526 cia2) {
// make copy of C64 bus.
this.bus=bus;
// make copy of Cartridge expansion port
this.exp=exp;
// make a copy of C64 RAM memory
this.ram0=ram0;
this.ram1=ram1;
this.ram2=ram2;
this.ram3=ram3;
this.ram4=ram4;
this.ram5=ram5;
this.ram6=ram6;
this.ram7=ram7;
// make a copy of ROMs
this.basic=basic;
this.kernal=kernal;
this.chargen=chargen;
// make a copy of I/O and Color
this.vic=vic;
this.sid=sid;
this.color=color;
this.cia1=cia1;
this.cia2=cia2;
buildCpuTables();
buildVicTables();
setName("PLA"); // use this name for the thread
start();
}
/**
* Build the table for Vic bus reading operation
* Remember that Vic always read the RAM, except for bank 0 and 2 where it
* see Char ROM in not Ultimax configutation.
*/
public void buildVicTables() {
int i;
// insert RAM to all tables
for (i=0; i<(0x2000>>8); i++) {
vicT0R[i]=ram0;
vicT0[i]=ram0;
vicT1[i]=ram2;
vicT2R[i]=ram4;
vicT2[i]=ram4;
vicT3[i]=ram6;
}
for (i=(0x2000>>8); i<(0x4000>>8); i++) {
vicT0R[i]=ram1;
vicT0[i]=ram1;
vicT1[i]=ram3;
vicT2R[i]=ram5;
vicT2[i]=ram5;
vicT3[i]=ram7;
}
// insert ROM
for (i=(0x1000>>8); i<(0x2000>>8); i++) {
vicT0R[i]=chargen; // address 1000h-1FFFh
vicT2R[i]=chargen; // address 9000h-9FFFh
}
}
/**
* Build the table for Cpu bus reading and writing operation.
* Remember that the available configuration come out from this signals:
* LORAM, HIRAM, GAME, EXROM, CHAREN.
*/
public void buildCpuTables() {
int i;
// insert value for address from 0000h to 1FFFh
for (i=0; i<(0x2000>>8); i++) {
cpuR11111[i]=ram0;
cpuR11110[i]=ram0;
cpuR101x1[i]=ram0;
cpuR101x0[i]=ram0;
cpuR10001[i]=ram0;
cpuR10000[i]=ram0;
cpuR011x1[i]=ram0;
cpuR011x0[i]=ram0;
cpuR001x_00x0[i]=ram0;
cpuR11101[i]=ram0;
cpuR11100[i]=ram0;
cpuR01001[i]=ram0;
cpuR01000[i]=ram0;
cpuR11001[i]=ram0;
cpuR11000[i]=ram0;
cpuWRam[i]=ram0;
cpuWIO[i]=ram0;
}
// insert value for address from 0000h to 0FFFh for Ultimax mode
for (i=0; i<(0x1000>>8); i++) {
cpuRxx01[i]=ram0;
cpuWUltimax[i]=ram0;
}
// insert value for address from 1000h to 1FFFh for Ultimax mode
for (i=0; i<(0x1000>>8); i++) {
// cpuRxx01[i]=open;
// cpuWUltiomax[i]=open;
}
// insert value for address from 2000h to 3FFFh
for (i=(0x2000>>8); i<(0x4000>>8); i++) {
cpuR11111[i]=ram1;
cpuR11110[i]=ram1;
cpuR101x1[i]=ram1;
cpuR101x0[i]=ram1;
cpuR10001[i]=ram1;
cpuR10000[i]=ram1;
cpuR011x1[i]=ram1;
cpuR011x0[i]=ram1;
cpuR001x_00x0[i]=ram1;
cpuR11101[i]=ram1;
cpuR11100[i]=ram1;
cpuR01001[i]=ram1;
cpuR01000[i]=ram1;
cpuR11001[i]=ram1;
cpuR11000[i]=ram1;
//cpuRxx01[i]=open;
cpuWRam[i]=ram1;
cpuWIO[i]=ram1;
//cpuUltimax[i]=open;
}
// insert value for address from 4000h to 5FFFh
for (i=(0x4000>>8); i<(0x6000>>8); i++) {
cpuR11111[i]=ram2;
cpuR11110[i]=ram2;
cpuR101x1[i]=ram2;
cpuR101x0[i]=ram2;
cpuR10001[i]=ram2;
cpuR10000[i]=ram2;
cpuR011x1[i]=ram2;
cpuR011x0[i]=ram2;
cpuR001x_00x0[i]=ram2;
cpuR11101[i]=ram2;
cpuR11100[i]=ram2;
cpuR01001[i]=ram2;
cpuR01000[i]=ram2;
cpuR11001[i]=ram2;
cpuR11000[i]=ram2;
//cpuRxx01[i]=open;
cpuWRam[i]=ram2;
cpuWIO[i]=ram2;
//cpuUltimax[i]=open;
}
// insert value for address from 6000h to 7FFFh
for (i=(0x6000>>8); i<(0x8000>>8); i++) {
cpuR11111[i]=ram3;
cpuR11110[i]=ram3;
cpuR101x1[i]=ram3;
cpuR101x0[i]=ram3;
cpuR10001[i]=ram3;
cpuR10000[i]=ram3;
cpuR011x1[i]=ram3;
cpuR011x0[i]=ram3;
cpuR001x_00x0[i]=ram3;
cpuR11101[i]=ram3;
cpuR11100[i]=ram3;
cpuR01001[i]=ram3;
cpuR01000[i]=ram3;
cpuR11001[i]=ram3;
cpuR11000[i]=ram3;
//cpuRxx01[i]=open;
cpuWRam[i]=ram3;
cpuWIO[i]=ram3;
//cpuWUltimax[i]=open;
}
// insert value for address from 8000h to 9FFFh
for (i=(0x8000>>8); i<(0xA000>>8); i++) {
cpuR11111[i]=ram4;
cpuR11110[i]=ram4;
cpuR101x1[i]=ram4;
cpuR101x0[i]=ram4;
cpuR10001[i]=ram4;
cpuR10000[i]=ram4;
cpuR011x1[i]=ram4;
cpuR011x0[i]=ram4;
cpuR001x_00x0[i]=ram4;
cpuR11101[i]=exp; // roml
cpuR11100[i]=exp; // roml
cpuR01001[i]=ram4;
cpuR01000[i]=ram4;
cpuR11001[i]=exp; // roml
cpuR11000[i]=exp; // roml
cpuRxx01[i]=exp; // roml
cpuWRam[i]=ram4;
cpuWIO[i]=ram4;
//cpuWUltimax[i]=ram4;
}
// insert value for address from A000h to BFFFh
for (i=(0xA000>>8); i<(0xC000>>8); i++) {
cpuR11111[i]=basic;
cpuR11110[i]=basic;
cpuR101x1[i]=ram5;
cpuR101x0[i]=ram5;
cpuR10001[i]=ram5;
cpuR10000[i]=ram5;
cpuR011x1[i]=ram5;
cpuR011x0[i]=ram5;
cpuR001x_00x0[i]=ram5;
cpuR11101[i]=basic;
cpuR11100[i]=basic;
cpuR01001[i]=exp; // romh
cpuR01000[i]=exp; // romh
cpuR11001[i]=exp; // romh
cpuR11000[i]=exp; // romh
//cpuRxx01[i]=open;
cpuWRam[i]=ram5;
cpuWIO[i]=ram5;
//cpuWUltimax[i]=open;
}
// insert value for address from C000h to CFFFh
for (i=(0xC000>>8); i<(0xD000>>8); i++) {
cpuR11111[i]=ram6;
cpuR11110[i]=ram6;
cpuR101x1[i]=ram6;
cpuR101x0[i]=ram6;
cpuR10001[i]=ram6;
cpuR10000[i]=ram6;
cpuR011x1[i]=ram6;
cpuR011x0[i]=ram6;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=ram6;
cpuR11100[i]=ram6;
cpuR01001[i]=ram6;
cpuR01000[i]=ram6;
cpuR11001[i]=ram6;
cpuR11000[i]=ram6;
//cpuRxx01[i]=open;
cpuWRam[i]=ram6;
cpuWIO[i]=ram6;
//cpuWUltimax[i]=ram6;
}
// insert value for address from D000h to D3FFh (VIC II)
for (i=(0xD000>>8); i<(0xD400>>8); i++) {
cpuR11111[i]=vic;
cpuR11110[i]=chargen;
cpuR101x1[i]=vic;
cpuR101x0[i]=chargen;
cpuR10001[i]=vic;
cpuR10000[i]=ram6;
cpuR011x1[i]=vic;
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=vic;
cpuR11100[i]=chargen;
cpuR01001[i]=vic;
cpuR01000[i]=chargen;
cpuR11001[i]=vic;
cpuR11000[i]=chargen;
cpuRxx01[i]=vic;
cpuWRam[i]=ram6;
cpuWIO[i]=vic;
cpuWUltimax[i]=vic;
}
// insert value for address from D400h to D7FFh (SID)
for (i=(0xD400>>8); i<(0xD800>>8); i++) {
cpuR11111[i]=sid;
cpuR11110[i]=chargen;
cpuR101x1[i]=sid;
cpuR101x0[i]=chargen;
cpuR10001[i]=sid;
cpuR10000[i]=ram6;
cpuR011x1[i]=sid;
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=sid;
cpuR11100[i]=chargen;
cpuR01001[i]=sid;
cpuR01000[i]=chargen;
cpuR11001[i]=sid;
cpuR11000[i]=chargen;
cpuRxx01[i]=sid;
cpuWRam[i]=ram6;
cpuWIO[i]=sid;
cpuWUltimax[i]=sid;
}
// insert value for address from D800h to DBFFh (Color)
for (i=(0xD800>>8); i<(0xDC00>>8); i++) {
cpuR11111[i]=color;
cpuR11110[i]=chargen;
cpuR101x1[i]=color;
cpuR101x0[i]=chargen;
cpuR10001[i]=color;
cpuR10000[i]=ram6;
cpuR011x1[i]=color;
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=color;
cpuR11100[i]=chargen;
cpuR01001[i]=color;
cpuR01000[i]=chargen;
cpuR11001[i]=color;
cpuR11000[i]=chargen;
cpuRxx01[i]=color;
cpuWRam[i]=ram6;
cpuWIO[i]=color;
cpuWUltimax[i]=color;
}
// insert value for address from DC00h to DCFFh (Color)
for (i=(0xDC00>>8); i<(0xDD00>>8); i++) {
cpuR11111[i]=cia1;
cpuR11110[i]=chargen;
cpuR101x1[i]=cia1;
cpuR101x0[i]=chargen;
cpuR10001[i]=cia1;
cpuR10000[i]=ram6;
cpuR011x1[i]=cia1;
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=cia1;
cpuR11100[i]=chargen;
cpuR01001[i]=cia1;
cpuR01000[i]=chargen;
cpuR11001[i]=cia1;
cpuR11000[i]=chargen;
cpuRxx01[i]=cia1;
cpuWRam[i]=ram6;
cpuWIO[i]=cia1;
cpuWUltimax[i]=cia1;
}
// insert value for address from DD00h to DDFFh (Color)
for (i=(0xDD00>>8); i<(0xDE00>>8); i++) {
cpuR11111[i]=cia2;
cpuR11110[i]=chargen;
cpuR101x1[i]=cia2;
cpuR101x0[i]=chargen;
cpuR10001[i]=cia2;
cpuR10000[i]=ram6;
cpuR011x1[i]=cia2;
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=cia2;
cpuR11100[i]=chargen;
cpuR01001[i]=cia2;
cpuR01000[i]=chargen;
cpuR11001[i]=cia2;
cpuR11000[i]=chargen;
cpuRxx01[i]=cia2;
cpuWRam[i]=ram6;
cpuWIO[i]=cia2;
cpuWUltimax[i]=cia2;
}
// insert value for address from DE00h to DEFFh (Color)
for (i=(0xDE00>>8); i<(0xDF00>>8); i++) {
cpuR11111[i]=exp; // exp1
cpuR11110[i]=chargen;
cpuR101x1[i]=exp; // exp1
cpuR101x0[i]=chargen;
cpuR10001[i]=exp; // exp1
cpuR10000[i]=ram6;
cpuR011x1[i]=exp; // exp1
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=exp; // exp1
cpuR11100[i]=chargen;
cpuR01001[i]=exp; // exp1
cpuR01000[i]=chargen;
cpuR11001[i]=exp; // exp1
cpuR11000[i]=chargen;
cpuRxx01[i]=exp; // exp1
cpuWRam[i]=ram6;
cpuWIO[i]=exp; // exp1
cpuWUltimax[i]=exp; // exp1
}
// insert value for address from DF00h to DFFFh (Color)
for (i=(0xDF00>>8); i<(0xE000>>8); i++) {
cpuR11111[i]=exp; // exp2
cpuR11110[i]=chargen;
cpuR101x1[i]=exp; // exp2
cpuR101x0[i]=chargen;
cpuR10001[i]=exp; // exp2
cpuR10000[i]=ram6;
cpuR011x1[i]=exp; // exp2
cpuR011x0[i]=chargen;
cpuR001x_00x0[i]=ram6;
cpuR11101[i]=exp; // exp2
cpuR11100[i]=chargen;
cpuR01001[i]=exp; // exp2
cpuR01000[i]=chargen;
cpuR11001[i]=exp; // exp2
cpuR11000[i]=chargen;
cpuRxx01[i]=exp; // exp2
cpuWRam[i]=ram6;
cpuWIO[i]=exp; // exp2
cpuWUltimax[i]=exp; // exp2
}
// insert value for address from E000h to fFFFh
for (i=(0xE000>>8); i<(0x10000>>8); i++) {
cpuR11111[i]=kernal;
cpuR11110[i]=kernal;
cpuR101x1[i]=ram7;
cpuR101x0[i]=ram7;
cpuR10001[i]=ram7;
cpuR10000[i]=ram7;
cpuR011x1[i]=kernal;
cpuR011x0[i]=kernal;
cpuR001x_00x0[i]=ram7;
cpuR11101[i]=kernal;
cpuR11100[i]=kernal;
cpuR01001[i]=kernal;
cpuR01000[i]=kernal;
cpuR11001[i]=kernal;
cpuR11000[i]=kernal;
cpuRxx01[i]=exp; // romh
cpuWRam[i]=ram7;
cpuWIO[i]=ram7;
//cpuWUltimax[i]=open;
}
}
/**
* Activate the right tables for the bus.
* It attends that a signal changes value, so calculate the tables (if power is
* on). Note that the first time the calculation is done even if signals are
* not changed, but this is right because this is the first.
*/
public void run() {
while (true) {
while (!power) { // is there power?
this.yield(); // no, attend power
}
chooseTables(); // calculate the right tables for bus
///monitor.opSignal2();
monitor.opWait(); // attend a signal changes value
}
}
/**
* Choose the right tables for the vic and cpu bus view.
* It reads the actual value of LORAM, HIRAM, EXROM, GAME and CHAREN signals
* for making the decision.
*/
public void chooseTables() {
// suppose not ultimax mode
ultimax=false;
// calculate current memory configuration
int config=(loram<<4)+(hiram<<3)+(exrom<<2)+(game<<1)+charen;
switch (config) {
case 0x1E: // 11110
bus.setTableCpu(cpuR11110, cpuWRam);
break;
case 0x1F: // 11111
bus.setTableCpu(cpuR11111, cpuWIO);
break;
case 0x14: // 10100
case 0x16: // 10110 = 101x0
bus.setTableCpu(cpuR101x0, cpuWRam);
break;
case 0x15: // 10101
case 0x17: // 10110 = 101x1
bus.setTableCpu(cpuR101x1, cpuWIO);
break;
case 0x10: // 10000
bus.setTableCpu(cpuR10000, cpuWRam);
break;
case 0x11: // 10001
bus.setTableCpu(cpuR10001, cpuWIO);
break;
case 0x0C: // 01100
case 0x0E: // 01110 = 011x0
bus.setTableCpu(cpuR011x0, cpuWRam);
break;
case 0x0D: // 01101
case 0x0F: // 01111 = 011x1
bus.setTableCpu(cpuR011x1, cpuWIO);
break;
case 0x04: // 00100
case 0x05: // 00101
case 0x06: // 00110
case 0x07: // 00111 = 001xx
case 0x00: // 00000
case 0x01: // 00001 = 00x0x
bus.setTableCpu(cpuR001x_00x0, cpuWRam);
break;
case 0x1C: // 11100
bus.setTableCpu(cpuR11100, cpuWRam);
break;
case 0x1D: // 11101
bus.setTableCpu(cpuR11101, cpuWIO);
break;
case 0x08: // 01000
bus.setTableCpu(cpuR01000, cpuWRam);
break;
case 0x09: // 01001
bus.setTableCpu(cpuR01001, cpuWIO);
break;
case 0x18: // 11000
bus.setTableCpu(cpuR11000, cpuWRam);
break;
case 0x19: // 11001
bus.setTableCpu(cpuR11001, cpuWIO);
break;
case 0x02: // 00010
case 0x03: // 00011
case 0x0A: // 01010
case 0x0B: // 01011
case 0x12: // 10010
case 0x1B: // 11011 = xx01x Ultimax
bus.setTableCpu(cpuRxx01, cpuWUltimax);
ultimax=true;
break;
}
config=(va15<<1)+va14; // bank selection
switch (config) {
case 0x00:
if (ultimax) bus.setTableVic(vicT0);
else bus.setTableVic(vicT0R);
break;
case 0x01:
bus.setTableVic(vicT1);
break;
case 0x02:
if (ultimax) bus.setTableVic(vicT2);
else bus.setTableVic(vicT2R);
break;
case 0x03:
bus.setTableVic(vicT3);
break;
}
}
/**
* Notify a signal to the chip
*
* @param type the type of signal
* @param value the value of the signal (0/1)
*/
public void notifySignal(int type, int value) {
switch (type) {
case S_LORAM:
loram=value;
break;
case S_HIRAM:
hiram=value;
break;
case S_CHAREN:
charen=value;
break;
case S_GAME:
game=value;
break;
case S_EXROM:
exrom=value;
break;
case S_VA14:
va14=1-value; // use the invert of the signal
break;
case S_VA15:
va15=1-value; // use the invert of the signal
break;
default:
System.err.println("ERROR: an invalid "+type+
" signal was notify to PLA82S100");
}
}
/**
* Set a new expansion cartridge
*
* @param exp the cartridge
*/
public void setExpansion(Cartridge exp) {
this.exp=exp;
buildCpuTables(); // rebuilt the cpu table
}
/**
* Power on the electronic component
*/
public void powerOn() {
power=true; // power is on
}
/**
* Power off the electronic component
*/
public void powerOff() {
power=false; // power is off
}
}
| 24,750 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
M6569.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/M6569.java | /**
* @(#)M6569.java 1999/12/06
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.hardware.bus.Bus;
import sw_emulator.hardware.io.VicII_IO;
import sw_emulator.hardware.memory.dinamic;
import sw_emulator.hardware.device.raster;
import sw_emulator.util.FlipFlop;
import sw_emulator.util.Monitor;
import sw_emulator.util.Monitor2;
/**
* Emulate the Vic 6569 chip.
* The Vic can access to 16Kbyte of memory at time, but his data bus is of 12
* bits; the up 4 bits is for color.
*
* M6569 features:
* <ul>
* <li>63 cycles for line</li>
* <li>312 lines</li>
* <li>284 visible lines</li>
* <li>403 visible pixels for line</li>
* <li>first vbank line: 300</li>
* <li>last vbank line: 15</li>
* <li>first X coo. of a line: 404</li>
* <li>first visible X coo.: 480</li>
* <li>last visible X coo.: 380</li>
* </ul>
*
* Note: the variables and methods naming is like that are used in Vic Article.
*
* Reference:
* Vic Article of Christian Bauer
*
* @author Ice
* @version 1.00 06/12/1999
*/
public class M6569 extends VicII {
/**
* Construct a VicII M6569 chip.
*
* @param extMonitor the external clock monitor
* @param bus the bus
* @param view the vic bus view
* @param io the vic io
* @param devicesToRefresh the devices to be refreshed
* @param tv the raster TV attached to the Vic output
*/
public M6569(Monitor extMonitor, Bus bus, int view, VicII_IO io,
dinamic[] devicesToRefresh, raster tv) {
super(extMonitor, bus, view, io, devicesToRefresh, tv);
// set specific Vic values
maxCycle=63;
firstVblankLine=300;
lastVblankLine=15;
firstVisXCoo=480;
lastVisXCoo=380;
firstXCoo=404;
lastXPos=0x1f7;
linesNumber=312;
raster=0; // initialize raster position
rasterX=firstXCoo; // at top of window
}
/**
* Execute VIC cycle operation when the clock signal is low (phase 1)
*/
public void fi0low() {
cycleRaster0(); // reset some values
cycleRaster30(); // bad line allowed?
cycleIsBadLine(); // is there a bad line?
switch (cycle) {
case 1:
cycleMob3Pointer(); // read mob 3 pointer
cycleRasterCompare(); // raster compare for IRQ
break;
case 2:
cycleMob3Middle(); // read mob 3 middle byte
break;
case 3:
cycleMob4Pointer(); // read mob 4 pointer
break;
case 4:
cycleMob4Middle(); // read mob 4 middle byte
break;
case 5:
cycleMob5Pointer(); // read mob 5 pointer
break;
case 6:
cycleMob5Middle(); // read mob 5 middle byte
break;
case 7:
cycleMob6Pointer(); // read mob 6 pointer
break;
case 8:
cycleMob6Middle(); // read mob 6 middle byte
break;
case 9:
cycleMob7Pointer(); // read mob 7 pointer
break;
case 10:
cycleMob7Middle(); // read mob 7 middle byte
break;
case 11:
cycleRefresh(); // refresh memory
setBA(1); // BA is now high
break;
case 12:
case 13:
case 14:
cycleRefresh(); // refresh memory
cycleSetVicCounter(); // set VC
cycleIsCAccess(); // is c-access ?
break;
case 15:
cycleRefresh(); // refresh memory
cycleMobCounterInc2(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 16:
cycleGAccess(); // performs g-access
cycleMobCounterInc1(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 17:
case 18:
case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleGAccess(); // performs g-access
cycleIsCAccess(); // is c-access ?
break;
case 55:
cycleGAccess(); // performs g-access
cycleInvertExp(); // invert exp. flip flop
cycleAllowDMA(); // allow DMA on
cycleMob0Allow(); // BA low if mob 0 allow
break;
case 56:
i_access(); // idle access
cycleAllowDMA(); // allow DMA on
break;
case 57:
cycleMob1Allow(); // BA low if mob 1 allow
i_access(); // idle access
break;
case 58:
cycleMob0Pointer(); // read sprite pointer 0
cycleMobDisplay(); // set display of mobs
cycleGotoIdle(); // try for going to idle
break;
case 59:
cycleMob0Middle(); // read mob 0 middle byte
break;
case 60:
cycleMob1Pointer(); // read mob 1 pointer
break;
case 61:
cycleMob1Middle(); // read mob 1 middle byte
break;
case 62:
cycleMob2Pointer(); // read mob 2 pointer
break;
case 63:
cycleMob2Middle(); // read mob 2 middle byte
cycleBorderComp(); // border comparison
break;
}
cycleAEC(); // search for AEC goes 0
}
/**
* Execute VIC cycle operation when the clock signal is high (phase 2)
*/
public void fi0high() {
switch (cycle) {
case 1:
cycleMob3Left(); // read mob 3 left byte
break;
case 2:
cycleMob3Right(); // read mob 3 right byte
break;
case 3:
cycleMob4Left(); // read mob 4 left byte
break;
case 4:
cycleMob4Right(); // read mob 4 right byte
break;
case 5:
cycleMob5Left(); // read mob 5 left byte
break;
case 6:
cycleMob5Right(); // read mob 5 right byte
break;
case 7:
cycleMob6Left(); // read mob 6 left byte
break;
case 8:
cycleMob6Right(); // read mob 6 right byte
break;
case 9:
cycleMob7Left(); // read mob 7 left byte
break;
case 10:
cycleMob7Right(); // read mob 7 right byte
break;
case 15: case 16: case 17: case 18: case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleCAccess(); // performs c-access
break;
case 58:
cycleMob0Left(); // read mob 0 left byte
break;
case 59:
cycleMob0Right(); // read mob 0 right byte
break;
case 60:
cycleMob1Left(); // read mob 1 left byte
break;
case 61:
cycleMob1Right(); // read mob 1 right byte
break;
case 62:
cycleMob2Left(); // read mob 2 left byte
break;
case 63:
cycleMob2Right(); // read mob 2 right byte
break;
}
}
} | 9,873 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
M6567R8.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/M6567R8.java | /**
* @(#)M6567R8.java 2000/04/15
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.hardware.bus.Bus;
import sw_emulator.hardware.io.VicII_IO;
import sw_emulator.hardware.memory.dinamic;
import sw_emulator.hardware.device.raster;
import sw_emulator.util.FlipFlop;
import sw_emulator.util.Monitor;
import sw_emulator.util.Monitor2;
/**
* Emulate the Vic 6567R8 chip.
* The Vic can access to 16Kbyte of memory at time, but his data bus is of 12
* bits; the up 4 bits is for color.
*
* M6567R8 features:
* <ul>
* <li>65 cycles for line</li>
* <li>263 lines</li>
* <li>235 visible lines</li>
* <li>418 visible pixels for line</li>
* <li>first vbank line: 13</li>
* <li>last vbank line: 40</li>
* <li>first X coo. of a line: 412</li>
* <li>first visible X coo.: 489</li>
* <li>last visible X coo.: 396</li>
* </ul>
*
* Note: the variables and methods naming is like that are used in Vic Article.
*
* Reference:
* Vic Article of Christian Bauer
*
* @author Ice
* @version 1.00 15/04/2000
*/
public class M6567R8 extends VicII {
/**
* Construct a VicII M6567R8 chip.
*
* @param extMonitor the external clock monitor
* @param bus the bus
* @param view the vic bus view
* @param io the vic io
* @param devicesToRefresh the devices to be refreshed
* @param tv the raster TV attached to the Vic output
*/
public M6567R8(Monitor extMonitor, Bus bus, int view, VicII_IO io,
dinamic[] devicesToRefresh, raster tv) {
super(extMonitor, bus, view, io, devicesToRefresh, tv);
// set specific Vic values
maxCycle=65;
firstVblankLine=13;
lastVblankLine=40;
firstVisXCoo=489;
lastVisXCoo=396;
lastXPos=0x207;
firstXCoo=412;
linesNumber=263;
raster=0; // initialize raster position
rasterX=firstXCoo; // at top of window
}
/**
* Execute VIC cycle operation when the clock signal is low (phase 1)
*/
public void fi0low() {
cycleRaster0(); // reset some values
cycleRaster30(); // bad line allowed?
cycleIsBadLine(); // is there a bad line?
switch (cycle) {
case 1:
cycleMob3Pointer(); // read mob 3 pointer
break;
case 2:
cycleMob3Middle(); // read mob 3 middle byte
break;
case 3:
cycleMob4Pointer(); // read mob 4 pointer
break;
case 4:
cycleMob4Middle(); // read mob 4 middle byte
break;
case 5:
cycleMob5Pointer(); // read mob 5 pointer
break;
case 6:
cycleMob5Middle(); // read mob 5 middle byte
break;
case 7:
cycleMob6Pointer(); // read mob 6 pointer
break;
case 8:
cycleMob6Middle(); // read mob 6 middle byte
break;
case 9:
cycleMob7Pointer(); // read mob 7 pointer
break;
case 10:
cycleMob7Middle(); // read mob 7 middle byte
break;
case 11:
cycleRefresh(); // refresh memory
setBA(1); // BA is now high
break;
case 12:
case 13:
case 14:
cycleRefresh(); // refresh memory
cycleSetVicCounter(); // set VC
cycleIsCAccess(); // is c-access ?
break;
case 15:
cycleRefresh(); // refresh memory
cycleMobCounterInc2(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 16:
cycleGAccess(); // performs g-access
cycleMobCounterInc1(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 17:
case 18:
case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleGAccess(); // performs g-access
cycleIsCAccess(); // is c-access ?
break;
case 55:
cycleGAccess(); // performs g-access
cycleInvertExp(); // invert exp. flip flop
cycleAllowDMA(); // allow DMA on
case 56:
i_access(); // idle access
cycleAllowDMA(); // allow DMA on
break;
case 57:
i_access(); // idle access
cycleMob0Allow(); // BA low if mob 0 allow
break;
case 58:
i_access(); // idle access
cycleMobDisplay(); // set display of mobs
cycleGotoIdle(); // try for going to idle
break;
case 59:
i_access(); // idle access
cycleMob1Allow(); // BA low if mob 1 allow
break;
case 60:
cycleMob0Pointer(); // read sprite pointer 0
break;
case 61:
cycleMob0Middle(); // read mob 0 middle byte
break;
case 62:
cycleMob1Pointer(); // read mob 1 pointer
break;
case 63:
cycleMob1Middle(); // read mob 1 middle byte
break;
case 64:
cycleMob2Pointer(); // read mob 2 pointer
break;
case 65:
cycleMob2Middle(); // read mob 2 middle byte
cycleBorderComp(); // border comparison (or 63?)
break;
}
cycleAEC(); // search for AEC goes 0
}
/**
* Execute VIC cycle operation when the clock signal is high (phase 2)
*/
public void fi0high() {
switch (cycle) {
case 1:
cycleMob3Left(); // read mob 3 left byte
break;
case 2:
cycleMob3Right(); // read mob 3 right byte
break;
case 3:
cycleMob4Left(); // read mob 4 left byte
break;
case 4:
cycleMob4Right(); // read mob 4 right byte
break;
case 5:
cycleMob5Left(); // read mob 5 left byte
break;
case 6:
cycleMob5Right(); // read mob 5 right byte
break;
case 7:
cycleMob6Left(); // read mob 6 left byte
break;
case 8:
cycleMob6Right(); // read mob 6 right byte
break;
case 9:
cycleMob7Left(); // read mob 7 left byte
break;
case 10:
cycleMob7Right(); // read mob 7 right byte
break;
case 15: case 16: case 17: case 18: case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleCAccess(); // performs c-access
break;
case 60:
cycleMob0Left(); // read mob 0 left byte
break;
case 61:
cycleMob0Right(); // read mob 0 right byte
break;
case 62:
cycleMob1Left(); // read mob 1 left byte
break;
case 63:
cycleMob1Right(); // read mob 1 right byte
break;
case 64:
cycleMob2Left(); // read mob 2 left byte
break;
case 65:
cycleMob2Right(); // read mob 2 right byte
break;
}
}
} | 9,998 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
M6567R56A.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/M6567R56A.java | /**
* @(#)M6567R56A.java 2000/04/15
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.hardware.bus.Bus;
import sw_emulator.hardware.io.VicII_IO;
import sw_emulator.hardware.memory.dinamic;
import sw_emulator.hardware.device.raster;
import sw_emulator.util.FlipFlop;
import sw_emulator.util.Monitor;
import sw_emulator.util.Monitor2;
/**
* Emulate the Vic 6567R56A chip.
* The Vic can access to 16Kbyte of memory at time, but his data bus is of 12
* bits; the up 4 bits is for color.
*
* M6569 features:
* <ul>
* <li>64 cycles for line</li>
* <li>262 lines</li>
* <li>234 visible lines</li>
* <li>411 visible pixels for line</li>
* <li>first vbank line: 13</li>
* <li>last vbank line: 40</li>
* <li>first X coo. of a line: 412</li>
* <li>first visible X coo.: 488</li>
* <li>last visible X coo.: 388</li>
* </ul>
*
* Note: the variables and methods naming is like that are used in Vic Article.
*
* Reference:
* Vic Article of Christian Bauer
*
* @author Ice
* @version 1.00 15/04/2000
*/
public class M6567R56A extends VicII {
/**
* Construct a VicII M6567R56A chip.
*
* @param extMonitor the external clock monitor
* @param bus the bus
* @param view the vic bus view
* @param io the vic io
* @param devicesToRefresh the devices to be refreshed
* @param tv the raster TV attached to the Vic output
*/
public M6567R56A(Monitor extMonitor, Bus bus, int view, VicII_IO io,
dinamic[] devicesToRefresh, raster tv) {
super(extMonitor, bus, view, io, devicesToRefresh, tv);
// set specific Vic values
maxCycle=64;
firstVblankLine=13;
lastVblankLine=40;
firstVisXCoo=488;
lastVisXCoo=388;
lastXPos=0x1ff;
firstXCoo=412;
linesNumber=262;
raster=0; // initialize raster position
rasterX=firstXCoo; // at top of window
}
/**
* Execute VIC cycle operation when the clock signal is low (phase 1)
*/
public void fi0low() {
cycleRaster0(); // reset some values
cycleRaster30(); // bad line allowed?
cycleIsBadLine(); // is there a bad line?
switch (cycle) {
case 1:
cycleMob3Pointer(); // read mob 3 pointer
break;
case 2:
cycleMob3Middle(); // read mob 3 middle byte
break;
case 3:
cycleMob4Pointer(); // read mob 4 pointer
break;
case 4:
cycleMob4Middle(); // read mob 4 middle byte
break;
case 5:
cycleMob5Pointer(); // read mob 5 pointer
break;
case 6:
cycleMob5Middle(); // read mob 5 middle byte
break;
case 7:
cycleMob6Pointer(); // read mob 6 pointer
break;
case 8:
cycleMob6Middle(); // read mob 6 middle byte
break;
case 9:
cycleMob7Pointer(); // read mob 7 pointer
break;
case 10:
cycleMob7Middle(); // read mob 7 middle byte
break;
case 11:
cycleRefresh(); // refresh memory
setBA(1); // BA is now high
break;
case 12:
case 13:
case 14:
cycleRefresh(); // refresh memory
cycleSetVicCounter(); // set VC
cycleIsCAccess(); // is c-access ?
break;
case 15:
cycleRefresh(); // refresh memory
cycleMobCounterInc2(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 16:
cycleGAccess(); // performs g-access
cycleMobCounterInc1(); // inc. mob counter base
cycleIsCAccess(); // is c-access ?
break;
case 17:
case 18:
case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleGAccess(); // performs g-access
cycleIsCAccess(); // is c-access ?
break;
case 55:
cycleGAccess(); // performs g-access
cycleInvertExp(); // invert exp. flip flop
cycleAllowDMA(); // allow DMA on
break;
case 56:
i_access(); // idle access
cycleAllowDMA(); // allow DMA on
cycleMob0Allow(); // BA low if mob 0 allow
break;
case 57:
i_access(); // idle access
break;
case 58:
i_access(); // idle access
cycleMob1Allow(); // BA low if mob 1 allow
cycleMobDisplay(); // set display of mobs
cycleGotoIdle(); // try for going to idle
break;
case 59:
cycleMob0Pointer(); // read sprite pointer 0
break;
case 60:
cycleMob0Middle(); // read mob 0 middle byte
break;
case 61:
cycleMob1Pointer(); // read mob 1 pointer
break;
case 62:
cycleMob1Middle(); // read mob 1 middle byte
break;
case 63:
cycleMob2Pointer(); // read mob 2 pointer
break;
case 64:
cycleMob2Middle(); // read mob 2 middle byte
cycleBorderComp(); // border comparison (or 63?)
break;
}
cycleAEC(); // search for AEC goes 0
}
/**
* Execute VIC cycle operation when the clock signal is high (phase 2)
*/
public void fi0high() {
switch (cycle) {
case 1:
cycleMob3Left(); // read mob 3 left byte
break;
case 2:
cycleMob3Right(); // read mob 3 right byte
break;
case 3:
cycleMob4Left(); // read mob 4 left byte
break;
case 4:
cycleMob4Right(); // read mob 4 right byte
break;
case 5:
cycleMob5Left(); // read mob 5 left byte
break;
case 6:
cycleMob5Right(); // read mob 5 right byte
break;
case 7:
cycleMob6Left(); // read mob 6 left byte
break;
case 8:
cycleMob6Right(); // read mob 6 right byte
break;
case 9:
cycleMob7Left(); // read mob 7 left byte
break;
case 10:
cycleMob7Right(); // read mob 7 right byte
break;
case 15: case 16: case 17: case 18: case 19:
case 20: case 21: case 22: case 23: case 24:
case 25: case 26: case 27: case 28: case 29:
case 30: case 31: case 32: case 33: case 34:
case 35: case 36: case 37: case 38: case 39:
case 40: case 41: case 42: case 43: case 44:
case 45: case 46: case 47: case 48: case 49:
case 50: case 51: case 52: case 53: case 54:
cycleCAccess(); // performs c-access
break;
case 58:
cycleMob0Left(); // read mob 0 left byte
break;
case 59:
cycleMob0Right(); // read mob 0 right byte
break;
case 60:
cycleMob1Left(); // read mob 1 left byte
break;
case 61:
cycleMob1Right(); // read mob 1 right byte
break;
case 62:
cycleMob2Left(); // read mob 2 left byte
break;
case 63:
cycleMob2Right(); // read mob 2 right byte
break;
}
}
} | 9,925 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
VicII.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/VicII.java | /**
* @(#)VicII.java 1999/10/16
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.util.Monitor;
import sw_emulator.hardware.powered;
import sw_emulator.hardware.signaller;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.hardware.bus.Bus;
import sw_emulator.hardware.memory.dinamic;
import sw_emulator.hardware.io.VicII_IO;
import sw_emulator.hardware.device.raster;
import sw_emulator.util.FlipFlop;
/**
* Emulate the Vic II chip.
* The Vic can access to 16Kbyte of memory at time, but his data bus is of 12
* bits; the up 4 bits is for color.
*
* Note: the variables and methods naming is like that are used in Vic Article,
* and the comment in sources between "..." are taken from Vic Article too.
*
* Features not implemented as in real VIC:
* <ul>
* <li>the value of AEC signal is equal to the expected only in fi2 of the
* cycle. This simplify the work of thread sinchronization, because if BA
* is high, AEC goes from low to high, but when it is low in this phase,
* no other chips are using (actively) the bus (in the source code a
* comment with AEC!! show this incompatibily).</li>
* </ul>
*
* Reference:
* Vic Article of Christian Bauer
* Pal Timing of Marko M"akel"a
* Missing Cycle of Pasi Ojala
*
* @author Ice
* @version 1.00 16/10/1999
*/
public abstract class VicII extends Thread implements powered,
readableBus, writeableBus{
// idle state if all value different from below
// note: for semplicity it's assumed that bit 3=1 means idle state
public static final int VIC_STANDARD_TEXT = 0x00; // standard text mode
public static final int VIC_MULTICOLOR_TEXT = 0x01; // multicolor text mode
public static final int VIC_STANDARD_BITMAP = 0x02; // standard bitmap mode
public static final int VIC_MULTICOLOR_BITMAP = 0x03; // multicolor bitmap
public static final int VIC_ECM_TEXT = 0x04; // ECM text mode
public static final int VIC_INVALID_TEXT = 0x05; // invalid text mode
public static final int VIC_INVALID_BITMAP1 = 0x06; // invalid bitmap mode 1
public static final int VIC_INVALID_BITMAP2 = 0x07; // invalid bitmap mode 2
public static final int RASTER_UP = 0x30; // begin of interval for bad line
public static final int RASTER_DW = 0xF7; // end of interval for bad line
public static final int LEFT0 = 0x1F; // left comparison for CSEL=0
public static final int LEFT1 = 0x18; // left comparison for CSEL=1
public static final int RIGHT0 = 0x14F; // right comparison for CSEL=0
public static final int RIGHT1 = 0x158; // right comparison for CSEL=1
public static final int TOP0 = 0x37; // top comparison for RSEL=0
public static final int TOP1 = 0x33; // top comparison for RSEL=1
public static final int BOTTOM0 = 0xF7; // bottom comparison for RSEL=0
public static final int BOTTOM1 = 0xFB; // bottom comparison for RSEL=1
public static final int[] LEFT = {LEFT0, LEFT1};
public static final int[] RIGHT = {RIGHT0, RIGHT1};
public static final int[] TOP = {TOP0, TOP1};
public static final int[] BOTTOM = {BOTTOM0, BOTTOM1};
public static final byte S_BA = signaller.S_BA;
public static final byte S_AEC = signaller.S_AEC;
public static final byte S_IRQ = signaller.S_IRQ;
public static final int BACKGR = 0; // background priority
public static final int FOREGR = 1; // foreground priority
/** First Vertical blanking line (line not visible) */
public int firstVblankLine;
/** Last Vertical blancking line (line not visible) */
public int lastVblankLine;
/** First Visible X Coordinate */
public int firstVisXCoo;
/** Last Visible X Coordinate */
public int lastVisXCoo;
/** First X coordinate */
public int maxCycle;
/** First X coordinate */
public int firstXCoo;
/** Last X position */
public int lastXPos;
/** Number of (raster) lines */
public int linesNumber;
/** External monitor of the dot clock */
public Monitor extMonitor;
/** Internal monitor for generate clock at 1/8 of dot clock */
public Monitor intMonitor=new Monitor("VIC II fi clock");
/** Actual VIC cycle */
protected int cycle;
/** State of bad line (true means this is a bad line) */
protected boolean badLine;
/** Allow the generation of bad line (if true) */
protected boolean allowBadLine;
/** Used for calculating <code>allowBadLine</code> */
private boolean den=false;
/** The state of power */
private boolean power=false;
/** The bus view of the Vic */
protected int view;
/** The bus where the Vic can read information (we not use write operation) */
protected Bus bus;
/** Vic IO signals */
protected VicII_IO io;
/** A sequence of dinamic devices that need refresh */
public dinamic[] devicesToRefresh;
/** The color number to display */
public int grColor;
/** The background/foreground priority of the pixel */
public int grPriority;
/** The TV where Vic send pixels output */
public raster tv;
// variables for sprites
/** Mobs X coordinate (bits 0 to 8) */
public int[] MxX=new int[8];
/** Mobs Y coordinate (bits 0 to 7) */
public int[] MxY=new int[8];
/** Memory pointer of srites */
public int[] MPx=new int[8];
/** MOB Data Counter (bit 0 to 5) */
public int[] MCx=new int[8];
/** MOB Data Counter Base (bit 0 to 5) */
public int[] MCBASEx=new int[8];
/** MOB Shift Register (bit 0 to 23) */
public int[] mobSequencer=new int[8];
/** Expansion Y flip flop */
public FlipFlop[] expansion=new FlipFlop[] {
new FlipFlop(), new FlipFlop(), new FlipFlop(), new FlipFlop(),
new FlipFlop(), new FlipFlop(), new FlipFlop(), new FlipFlop()
};
/** DMA state of a sprite (true means must read data) */
public boolean[] DMAx=new boolean[8];
/** Display of sprite (true means must be displayed) */
public boolean[] display=new boolean[8];
/**
* 24 Pixels of a sprite counter
* Note: this is used to display 24 pixels in sequence when rule 6 (of
* section 3.8.1) match. This must improve speed (but must be checked if
* it's 100 real Vic operation.
*/
public int[] pixels={-1,-1,-1,-1,-1,-1,-1,-1};
/** Sequencer counter for sprite x double features */
private int[] pixelsCount=new int[8];
/** Color sprite (bits 0 to 3) */
public byte[] MxC=new byte[8];
/** Sprite enabled (bit 0); */
public int[] MxE=new int[8];
/** Sprite X expansion (bit 0) */
public int[] MxXE=new int[8];
/** Sprite Y expansion (bit 0) */
public int[] MxYE=new int[8];
/** Sprite-sprite collision (bit 0) */
public int[] MxM=new int[8];
/** Sprite-data collision (bit 0) */
public int[] MxD=new int[8];
/** Sprite multicolor (bit 0) */
public int[] MxMC=new int[8];
/** Sprite-data priority (bit 0) */
public int[] MxDP=new int[8];
/** The color number to display of sprite */
public int[] spColor=new int[8];
/**
* The background/foreground priority of the sprite pixel
* Note: this (and related instructions) should be removed, because probably
* not actively used
*/
public int[] spPriority=new int[8];
/** Actual raster position (bits 0 to 8) */
public int raster;
/** Actual raster position to compare for making a interrupt (bits 0 to 8) */
public int rasterCompare=-1; // -1 not compare
/** X position of raster */
public int rasterX;
/** Light pen X latched value (bits 0 to 9) */
public int LPX=0;
/** Light oen Y latched value (bits 0 to 8) */
public int LPY=0;
/** Border color (bits 0 to 3) */
public byte EC;
/** Background color 0 (bits 0 to 3) */
public byte B0C;
/** Background color 1 (bits 0 to 3) */
public byte B1C;
/** Background color 2 (bits 0 to 3) */
public byte B2C;
/** Background color 3 (bits 0 to 3) */
public byte B3C;
/** Sprite multicolor 0 (bits 0 to 3) */
public byte MM0;
/** Sprite multicolor 1 (bits 0 to 3) */
public byte MM1;
/** Actual state of the vic (text, bitmap, idle ...) */
public int vicState;
/** State of ECM field (bit 0) */
public int ECM;
/** State of BMM field (bit 0) */
public int BMM;
/** State of MCM field (bit 0) */
public int MCM;
/** State of DEN field (bit 0) */
public int DEN;
/** State of RES field (bit 0) */
public int RES;
/** State of RSEL field (bit 0) */
public int RSEL;
/** State of CSEL field (bit 0) */
public int CSEL;
/** State of IRQ field (bit 0) */
public int IRQ;
/** State of Interrupt LightPen (bit 0) */
public int ILP;
/** State of Interrupt Mob Mob Collision (bit 0) */
public int IMMC;
/** State of Interrupt Mob Bitmap Collision (bit 0) */
public int IMBC;
/** State of Interrupt Raster (bit 0) */
public int IRST;
/** State of Interrupt Enable LightPen (bit 0) */
public int ELP;
/** State of Interrupt Enable Mob Mob Collision (bit 0) */
public int EMMC;
/** State of Interrupt Enable Mob Bitmap Collision (bit 0) */
public int EMBC;
/** State of Interrupt Enable Raster (bit 0) */
public int ERST;
/**
* Graphics Data Shift Register (bit 0 to 7)
* Note: because the register may be reload delayed by 0..7 pixel, 16 bits
* are used for making this delay with speed up porpoise.
*/
public int gdSequencer;
/** Scroll X register (bit 0 to 2) */
public int xScroll;
/** Scroll Y register (bit 0 to 2) */
public int yScroll;
/** Vic Counter (bits 0 to 9) */
public int VC;
/** Vic Counter Base (bits 0 to 9) */
public int VCBase;
/** Vic Memory pointer (bits 0 to 3) */
public int VM;
/** Video matrix line index */
public int VMLI;
/** Base Character pointer (bits 0 to 2) */
public int CB;
/** Row Conter (bits 0 to 2) */
public int RC;
/** Refresh lile counter (bits 0 to 7) */
public int REF;
/** Buffer for reading data of matrix and color line (bits 0 to 11) */
protected int[] videoMatrixColor=new int[40];
/** Internal buffer (for sequencer) of matrix and color line (12 bits) */
protected int videoBuffer;
/** Main Border flip flop */
protected FlipFlop mainBorder=new FlipFlop();
/** Vertical Border flip flop */
protected FlipFlop verticalBorder= new FlipFlop();
/** BA signal 0/1 */
public int BA;
/** Count the number of cycle with BA low */
public int countBA;
/** AEC signal 0/1 */
public int AEC;
/**
* Construct a VicII chip.
*
* @param extMonitor the external clock monitor
* @param bus the bus
* @param view the vic bus view
* @param io the vic io
* @param devicesToRefresh the devices to be refreshed
* @param tv the raster TV attached to the Vic output
*/
public VicII(Monitor extMonitor, Bus bus, int view, VicII_IO io,
dinamic[] devicesToRefresh, raster tv) {
this.extMonitor=extMonitor;
this.bus=bus;
this.view=view;
this.io=io;
this.devicesToRefresh=devicesToRefresh;
this.tv=tv;
setName("VicII"); // use this name for the thread
start();
}
/**
* Set up the connection of IO with the external.
* The vic emulation is not started if this value is null equal.
*
* @param io the external connection
*/
public void setIO(VicII_IO io) {
this.io=io;
}
/**
* Execute the cycles of VIC according to external dot clock.
* The power state is looked only 1 time over 8.
*/
public void run() {
int tick=0; // number of dot clock ticks
extMonitor.opNotify(); // notify that we will use it
cycle=1; // this is supposed
rasterX=firstXCoo+4; // +4 is the pixels needed
// for cycle=1
// do nothing until io connection are inserted
while (io==null) {
this.yield();
}
while (true) {
// do nothig until the power is arrived
while (!power) { // there's power ?
this.yield(); // no, attend power
}
// do nothing until the bus is available
while (!bus.isInitialized()) { // there's a bus?
this.yield(); // no, attend power
}
extMonitor.opWait(); // attend dot clock tick
dotClock(); // execute dot clock operat.
switch (++tick) {
case 1:
fi0low(); // execute oper. in 1° phase
break;
case 5:
fi0high(); // execute oper. in 2° phase
// attend that the connected circuits have finish
/// while (!intMonitor.isFinish()) {
/// yield();
///intMonitor.opWait2();
/// }
intMonitor.opSignal(); // clock tick at 1/8 of dot
break;
case 8:
cycle++; // increment cycle counter
if (cycle>maxCycle) // are at the last cycle
cycle=1; // reset cycle counter
tick=0; // reset tick counter
break;
}
///extMonitor.opSignal2();
}
}
/**
* Write a byte to the bus at specific address location.
*
* @param addr the address location
* @param value the byte value
*/
public void write(int addr, byte value) {
int i;
addr&=0x3f; // musk address
switch (addr) {
case 0x00: // X coord. sprite 0
case 0x02: // X coord. sprite 1
case 0x04: // X coord. sprite 2
case 0x06: // X coord. sprite 3
case 0x08: // X coord. sprite 4
case 0x0A: // X coord. sprite 5
case 0x0C: // X coord. sprite 6
case 0x0E: // X coord. sprite 7
MxX[addr>>1]=(MxX[addr>>1] & 0x100)+(value & 0xFF);
break;
case 0x01: // Y coord. sprite 0
case 0x03: // Y coord. sprite 1
case 0x05: // Y coord. sprite 2
case 0x07: // Y coord. sprite 3
case 0x09: // Y coord. sprite 4
case 0x0B: // Y coord. sprite 5
case 0x0D: // Y coord. sprite 6
case 0x0F: // Y coord. sprite 7
MxY[(addr-1)>>1]=(value & 0xFF);
break;
case 0x10: // MSBs of X coord.
MxX[0]=(MxX[0] & 0xFF)+(value & 0x100);
MxX[1]=(MxX[1] & 0xFF)+(value & 0x100);
MxX[2]=(MxX[2] & 0xFF)+(value & 0x100);
MxX[3]=(MxX[3] & 0xFF)+(value & 0x100);
MxX[4]=(MxX[4] & 0xFF)+(value & 0x100);
MxX[5]=(MxX[5] & 0xFF)+(value & 0x100);
MxX[6]=(MxX[6] & 0xFF)+(value & 0x100);
MxX[7]=(MxX[7] & 0xFF)+(value & 0x100);
break;
case 0x11: // Control register 1
rasterCompare=(rasterCompare & 0xFF)+((value<<1)& 0x100);
ECM=(value>>6)& 0x01;
BMM=(value>>5)& 0x01;
DEN=(value>>4)& 0x01;
RSEL=(value>>3)& 0x01;
yScroll=value & 0x07;
// calculates new vic state
vicState=(vicState & 0x09)+(ECM<<2)+(BMM<<1);
break;
case 0x12: // Raster counter
rasterCompare=(rasterCompare & 0x100)+(value & 0xFF);
break;
case 0x13: // Light pen X
case 0x14: // Light pen Y
break; // do nothing, write access ignored
case 0x15: // Sprite enabled
MxE[0]=value & 0x01;
MxE[1]=(value>>=1)& 0x01;
MxE[2]=(value>>=1)& 0x01;
MxE[3]=(value>>=1)& 0x01;
MxE[4]=(value>>=1)& 0x01;
MxE[5]=(value>>=1)& 0x01;
MxE[6]=(value>>=1)& 0x01;
MxE[7]=(value>>=1)& 0x01;
break;
case 0x16: // Control register 2
RES=(value & 0x20)>>5;
MCM=(value & 0x10)>>4;
CSEL=(value & 0x08)>>3;
xScroll=value & 0x07;
// calculates new vic state
vicState=(vicState & 0x0E)+MCM;
break;
case 0x17: // Sprite y expansion
for (i=0; i<8; i++) {
MxYE[i]=value & 0x01;
value>>=1;
// section 3.8.1. Memory access and display
// "1. The expansion flip flop is set as long as the bit in MxYE in
// register $d017 corresponding to the sprite is cleared".
if (MxYE[i]==0)
expansion[i].set(); // set exp. flip flop
}
break;
case 0x18: // Memory pointers
VM=(value & 0xF0)>>4;
CB=(value & 0x0E)>>1;
break;
case 0x19: // Interrupt register
if ((value & 0x01)==1) IRST=0; // ack. Raster Int.
if ((value & 0x02)==2) IMBC=0; // ack. Mob Bit. Int.
if ((value & 0x04)==4) IMMC=0; // ack. Mob Mob Int.
if ((value & 0x08)==8) ILP=0; // ack. LightPen Int.
if ((IRST+IMBC+IMMC+ILP==0) && (IRQ==1)) { // are there acks?
IRQ=0; // end of IRQ
io.notifySignal(S_IRQ, 1); // notify end of IRQ
}
break;
case 0x1A: // Interrupt enabled
ERST=value & 0x01; // Enable Raster Int.
EMBC=(value>>=1)& 0x01; // Enable Mob Bit. Int.
EMMC=(value>>=1)& 0x01; // Enable Mob Mob Int.
ELP=(value>>=1)& 0x01; // Enable LightPen Int.
if (((ERST==1) && (IRST==1)) ||
((EMBC==1) && (IMBC==1)) ||
((EMMC==1) && (IMBC==1)) ||
((ELP==1) && (ILP==1))) {
IRQ=1; // start of IRQ
io.notifySignal(S_IRQ, 0); // notify start of IRQ
}
break;
case 0x1B: // Sprite data priority
for (i=0; i<8; i++) {
MxDP[i]=value & 0x01;
value>>=1;
}
break;
case 0x1C: // Sprite multicolor
for (i=0; i<8; i++) {
MxMC[i]=value & 0x01;
value>>=1;
}
break;
case 0x1D: // Sprite x expansion
for (i=0; i<8; i++) {
MxXE[i]=value & 0x01;
value>>=1;
}
break;
case 0x1E: // Sprite-sprite collision
case 0x1F: // Sprite-data collision
// do nothing, write access ignored
break;
case 0x20: // Border color
EC=(byte)(value & 0x0F);
break;
case 0x21: // Background color 0
B0C=(byte)(value & 0x0F);
break;
case 0x22: // Background color 1
B1C=(byte)(value & 0x0F);
break;
case 0x23: // Background color 2
B2C=(byte)(value & 0x0F);
break;
case 0x24: // Background color 3
B3C=(byte)(value & 0x0F);
break;
case 0x25: // Sprite multicolor 0
MM0=(byte)(value & 0x0F);
break;
case 0x26: // Sprite multicolor 1
MM1=(byte)(value & 0x0F);
break;
case 0x27: // Color sprite 0
case 0x28: // Color sprite 1
case 0x29: // Color sprite 2
case 0x2A: // Color sprite 3
case 0x2B: // Color sprite 4
case 0x2C: // Color sprite 5
case 0x2D: // Color sprite 6
case 0x2E: // Color sprite 7
MxC[addr-0x27]=(byte)(value & 0x0F);
break;
default:
// do nothing, write ignored
}
}
/**
* Read a byte from the bus at specific address location.
*
* @param addr the address location
* @return the readed byte
*/
public byte read(int addr) {
int i; // local cycle
int tmp; // temp value
addr&=0x3f; // musk addr
switch (addr) {
case 0x00: // X coord. sprite 0
case 0x02: // X coord. sprite 1
case 0x04: // X coord. sprite 2
case 0x06: // X coord. sprite 3
case 0x08: // X coord. sprite 4
case 0x0A: // X coord. sprite 5
case 0x0C: // X coord. sprite 6
case 0x0E: // X coord. sprite 7
return (byte)MxX[addr>>1];
case 0x01: // Y coord. sprite 0
case 0x03: // Y coord. sprite 1
case 0x05: // Y coord. sprite 2
case 0x07: // Y coord. sprite 3
case 0x09: // Y coord. sprite 4
case 0x0B: // Y coord. sprite 5
case 0x0D: // Y coord. sprite 6
case 0x0F: // Y coord. sprite 7
return (byte)MxY[(addr-1)>>1];
case 0x10: // MSBs of X coord.
return (byte)(
(MxX[0]>>8)+
((MxX[1]>>7)& 0x02)+
((MxX[2]>>6)& 0x04)+
((MxX[3]>>5)& 0x08)+
((MxX[4]>>4)& 0x10)+
((MxX[5]>>3)& 0x20)+
((MxX[6]>>2)& 0x40)+
((MxX[7]>>1)& 0x80));
case 0x11: // Control register 1
return (byte)(
((raster>>1)& 0x80)+
(ECM<<6)+
(BMM<<5)+
(DEN<<4)+
(RSEL<<3)+
yScroll);
case 0x12: // Raster counter
return (byte)raster;
case 0x13: // Light pen X
return (byte)(LPX>>1); // Gives only 8 bits of 9
case 0x14: // Ligth pen Y
return (byte)LPY;
case 0x15: // Sprite enabled
return (byte)(
MxE[0]+
(MxE[1]<<1)+
(MxE[2]<<2)+
(MxE[3]<<3)+
(MxE[4]<<4)+
(MxE[5]<<5)+
(MxE[6]<<6)+
(MxE[7]<<7));
case 0x16: // Control register 2
return (byte)( // 2 bits not connected
0xC0+
(RES<<5)+
(MCM<<4)+
(CSEL<<3)+
xScroll);
case 0x17: // Sprite y expansion
return (byte)(
MxYE[0]+
(MxYE[1]<<1)+
(MxYE[2]<<2)+
(MxYE[3]<<3)+
(MxYE[4]<<4)+
(MxYE[5]<<5)+
(MxYE[6]<<6)+
(MxYE[7]<<7));
case 0x18: // Memory pointers
return (byte)(
(VM<<4)+
(CB<<1)+
1); // 1 bit not connected
case 0x19: // Interrupt register
return (byte) (
IRST+
(IMBC<<1)+
(IMMC<<2)+
(ILP<<3)+
(IRQ<<7));
case 0x1A: // Interrupt enabled
return (byte)(
ERST+
(EMBC<<1)+
(EMMC<<2)+
(ELP<<3));
case 0x1B: // Sprite data priority
return (byte)(
MxDP[0]+
(MxDP[1]<<1)+
(MxDP[2]<<2)+
(MxDP[3]<<3)+
(MxDP[4]<<4)+
(MxDP[5]<<5)+
(MxDP[6]<<6)+
(MxDP[7]<<7));
case 0x1C: // Sprite multicolor
return (byte)(
MxMC[0]+
(MxMC[1]<<1)+
(MxMC[2]<<2)+
(MxMC[3]<<3)+
(MxMC[4]<<4)+
(MxMC[5]<<5)+
(MxMC[6]<<6)+
(MxMC[7]<<7));
case 0x1D: // Sprite X expansion
return (byte)(
MxXE[0]+
(MxXE[1]<<1)+
(MxXE[2]<<2)+
(MxXE[3]<<3)+
(MxXE[4]<<4)+
(MxXE[5]<<5)+
(MxXE[6]<<6)+
(MxXE[7]<<7));
case 0x1E: // Sprite-sprite collision
tmp=0;
for (i=0; i<8; i++) {
tmp+=(MxM[i]<<i);
MxM[i]=0; // register is cleared
}
return (byte)tmp;
case 0x1F: // Sprite-data collision
tmp=0;
for (i=0; i<8; i++) {
tmp+=(MxD[i]<<i);
MxM[i]=0; // register is cleared
}
return (byte)tmp;
case 0x20: // Border color
return (byte)((EC & 0x0F)| 0xF0);
case 0x21: // Background color 0
return (byte)((B0C & 0x0F)| 0xF0);
case 0x22: // Background color 1
return (byte)((B1C & 0x0F)| 0xF0);
case 0x23: // Background color 2
return (byte)((B2C & 0x0F)| 0xF0);
case 0x24: // Background color 3
return (byte)((B3C & 0x0F)| 0xF0);
case 0x25: // Sprite multicolor 0
return (byte)((MM0 & 0x0F)| 0xF0);
case 0x26: // Sprite multicolor 1
return (byte)((MM1 & 0x0F)| 0xF0);
case 0x27: // Color sprite 0
case 0x28: // Color sprite 1
case 0x29: // Color sprite 2
case 0x2A: // Color sprite 3
case 0x2B: // Color sprite 4
case 0x2C: // Color sprite 5
case 0x2D: // Color sprite 6
case 0x2E: // Color sprite 7
return (byte)((MxC[addr-0x27] & 0x0F)| 0xF0);
default :
return (byte)0xFF; // not connected
}
}
/**
* Performs a c-accesses.
* It reads 12 bits: 8 for data, 4 for color. The address is the same for all
* the graphics mode:
* <ul>
* <li>VM13 VM12 VM11 VM10 VC9 VC8 VC7 VC6 VC5 VC4 VC3 VC2 VC1 VC0</li>
* </ul>
*
* @return 12 bits of readed data from bus
*/
protected int c_access() {
return bus.load((VM<<10)+VC, view, AEC);
}
/**
* Performs a g-accesses.
* It read 12 bits: 8 for data, 4 not used. The address depends by the
* mode graphics:
* <ul>
* <li>CB13 CB12 CB11 D7 D6 D5 D4 D3 D2 D1 D0 RC2 RC1 RC0 for standard and
* multicolor mode</li>
* <li>CB13 VC9 VC8 VC7 VC6 Vc5 VC4 VC3 VC2 VC1 VC0 RC2 RC1 RC0 for
* standard and multicolor bitmap</li>
* <li>CB13 CB12 CB11 0 0 D5 D4 D3 D2 D1 D0 RC2 RC1 RC0 for ECM and
* invalid text mode</li>
* <li>CB13 VC9 VC8 0 0 Vc5 VC4 VC3 VC2 VC1 VC0 RC2 RC1 RC0 for invalid
* bitmaps</li>
* </ul>
*
* @return 12 bits of readed data from bus
*/
protected int g_access() {
switch (vicState) {
case VIC_STANDARD_TEXT:
case VIC_MULTICOLOR_TEXT:
return bus.load((CB<<11)+
((videoBuffer & 0xFF)<<3)+
RC, view, 0); // AEC!!
case VIC_STANDARD_BITMAP:
case VIC_MULTICOLOR_BITMAP:
return bus.load( ((CB & 0x04)<<11)+
(VC<<3)+
RC, view, 0); // AEC!!
case VIC_ECM_TEXT:
case VIC_INVALID_TEXT:
return bus.load((CB<<11)+
((videoBuffer & 0x3F)<<3)+
RC, view, 0); // AEC!!
case VIC_INVALID_BITMAP1:
case VIC_INVALID_BITMAP2:
return bus.load( ((CB & 0x04)<<11)+
((VC & 0x19F)<<3)+
RC, view, 0); // AEC!!
default: // idle state
if (ECM==0) return bus.load(0x3FFF, view, 0); // AEC!!
else return bus.load(0x39FF, view, 0); // AEC!!
}
}
/**
* Performs a r-access.
* Referesh dinamic devices attached to the VIC at address:
* <ul>
* <li>1 1 1 1 1 1 REF7 REF6 REF5 REF4 REF3 REF2 REF1 REF0</li>
* </ul>
*/
protected void r_access() {
int i;
for (i=0; i<devicesToRefresh.length; i++)
devicesToRefresh[i].refreshLine(REF);
}
/**
* Performs a i-access.
* Read always from address 0x3FFF
*/
protected int i_access() {
return bus.load(0x3FFF, view, 0); // AEC!!
}
/**
* Performs a p-access.
* Read the sprite pointer at address:
* <ul>
* <li>VM13 VM12 VM11 VM10 1 1 1 1 1 1 1 number2 number1 number0</li>
* </ul>
*
* @param number the sprite number (must be 0 to 7)
*/
protected int p_access(int number) {
return bus.load( (VM<<10)+
0x3F8+
number, view, 0); // AEC!!
}
/**
* Performs a s-access.
* Read Mob data at address:
* <ul>
* <li>MP7 MP6 MP5 MP4 MP3 MP2 MP1 MP0 MC5 MC4 MC3 MC2 MC1 MC0</li>
* </ul>
*
* @param number the sprite number (must be 0 to 7)
*/
protected int s_access(int number) {
return (bus.load((MPx[number]<<6)+
MCx[number], view, 0)
)& 0xFF; // AEC!!
}
/**
* Cycle code for mob 0...
* BA is set low if mob 0 is allowed to be displayed
*/
protected void cycleMob0Allow() {
// set BA low for sprite 0 is necessary
if (DMAx[0]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 0...
* Read the sprite pointer of mob 0.
*/
protected void cycleMob0Pointer() {
MPx[0]=p_access(0); // read sprite pointer 0
}
/**
* Cycle code for mob 0...
* Read the mob 0 left byte if DMA of mob is on.
*/
protected void cycleMob0Left() {
if (DMAx[0]) { // is DMA of mob 0 on?
mobSequencer[0]=0;
mobSequencer[0]|=(s_access(0)<<16); // read left byte of mob
MCx[0]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 0...
* Read the mob 0 middle byte if the DMA of mob is on, then set BA low for
* sprite 2 if necessary.
*/
protected void cycleMob0Middle() {
// read data of sprite 0 if necessary
if (!DMAx[0]) { // is DMA of mob 0 off?
i_access(); // idle access
} else {
mobSequencer[0]|=(s_access(0)<<8); // read middle byte of mob
MCx[0]++; // inc Mob data counter
}
// set BA low for sprite 2 is necessary
if (DMAx[2]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 0...
* Read the mob 0 right byte if DMA of mob is on.
*/
protected void cycleMob0Right() {
if (DMAx[0]) { // is DMA of mob 0 on?
mobSequencer[0]|=s_access(0); // read right byte of mob
MCx[0]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 1...
* BA is set low if mob 0 is allowed to be displayed
*/
protected void cycleMob1Allow() {
// set BA low for sprite 1 is necessary
if (DMAx[1]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 1...
* Read the sprite pointer of mob 1 and set BA high if mob 1 and 2 off.
*/
protected void cycleMob1Pointer() {
MPx[1]=p_access(1); // read sprite pointer 1
// BA high if sprites 1 and 2 off
if (!DMAx[1] && !DMAx[2]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 1...
* Read the mob 1 left byte if DMA of mob is on.
*/
protected void cycleMob1Left() {
if (DMAx[1]) { // is DMA of mob 1 on?
mobSequencer[1]=0;
mobSequencer[1]|=(s_access(1)<<16); // read left byte of mob
MCx[1]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 1...
* Read the mob 1 middle byte if the DMA of mob is on, then set BA low for
* sprite 3 if necessary.
*/
protected void cycleMob1Middle() {
// read data of sprite 1 if necessary
if (!DMAx[1]) { // is DMA of mob 1 off?
i_access(); // idle access
} else {
mobSequencer[1]|=(s_access(1)<<8); // read middle byte of mob
MCx[1]++; // inc Mob data counter
}
// set BA low for sprite 3 is necessary
if (DMAx[3]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 1...
* Read the mob 1 right byte if DMA of mob is on.
*/
protected void cycleMob1Right() {
if (DMAx[1]) { // is DMA of mob 1 on?
mobSequencer[1]|=s_access(1); // read right byte of mob
MCx[1]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 2...
* Read the sprite pointer of mob 1 and set BA high if mob 2 and 3 off.
*/
protected void cycleMob2Pointer() {
MPx[2]=p_access(2); // read sprite pointer 2
// BA high if sprites 2 and 3 off
if (!DMAx[2] && !DMAx[3]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 2...
* Read the mob 2 left byte if DMA of mob is on.
*/
protected void cycleMob2Left() {
if (DMAx[2]) { // is DMA of mob 2 on?
mobSequencer[2]=0;
mobSequencer[2]|=(s_access(2)<<16); // read left byte of mob
MCx[2]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 2...
* Read the mob 2 middle byte if the DMA of mob is on, then set BA low for
* sprite 4 if necessary.
*/
protected void cycleMob2Middle() {
// read data of sprite 2 if necessary
if (!DMAx[2]) { // is DMA of mob 2 off?
i_access(); // idle access
} else {
mobSequencer[2]|=(s_access(2)<<8); // read middle byte of mob
MCx[2]++; // inc Mob data counter
}
// set BA low for sprite 4 is necessary
if (DMAx[4]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 2...
* Read the mob 2 right byte if DMA of mob is on.
*/
protected void cycleMob2Right() {
if (DMAx[2]) { // is DMA of mob 2 on?
mobSequencer[2]|=s_access(2); // read right byte of mob
MCx[2]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 3...
* Read the sprite pointer of mob 3 and set BA high if mob 3 and 4 off.
*/
protected void cycleMob3Pointer() {
MPx[3]=p_access(3); // read sprite pointer 3
// BA high if sprites 3 and 4 off
if (!DMAx[3] && !DMAx[4]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 3...
* Read the mob 3 left byte if DMA of mob is on.
*/
protected void cycleMob3Left() {
if (DMAx[3]) { // is DMA of mob 3 on?
mobSequencer[3]=0;
mobSequencer[3]|=(s_access(3)<<16); // read left byte of mob
MCx[3]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 3...
* Read the mob 3 middle byte if the DMA of mob is on, then set BA low for
* sprite 5 if necessary.
*/
protected void cycleMob3Middle() {
// read data of sprite 3 if necessary
if (!DMAx[3]) { // is DMA of mob 3 off?
i_access(); // idle access
} else {
mobSequencer[3]|=(s_access(3)<<8); // read middle byte of mob
MCx[3]++; // inc Mob data counter
}
// set BA low for sprite 5 is necessary
if (DMAx[5]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 3...
* Read the mob 3 right byte if DMA of mob is on.
*/
protected void cycleMob3Right() {
if (DMAx[3]) { // is DMA of mob 3 on?
mobSequencer[3]|=s_access(3); // read right byte of mob
MCx[3]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 4...
* Read the sprite pointer of mob 4 and set BA high if mob 4 and 5 off.
*/
protected void cycleMob4Pointer() {
MPx[4]=p_access(4); // read sprite pointer 4
// BA high if sprites 4 and 5 off
if (!DMAx[4] && !DMAx[5]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 4...
* Read the mob 4 left byte if DMA of mob is on.
*/
protected void cycleMob4Left() {
if (DMAx[4]) { // is DMA of mob 4 on?
mobSequencer[4]=0;
mobSequencer[4]|=(s_access(4)<<16); // read left byte of mob
MCx[4]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 4...
* Read the mob 4 middle byte if the DMA of mob is on, then set BA low for
* sprite 6 if necessary.
*/
protected void cycleMob4Middle() {
// read data of sprite 4 if necessary
if (!DMAx[4]) { // is DMA of mob 4 off?
i_access(); // idle access
} else {
mobSequencer[4]|=(s_access(4)<<8); // read middle byte of mob
MCx[4]++; // inc Mob data counter
}
// set BA low for sprite 6 is necessary
if (DMAx[6]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 4...
* Read the mob 4 right byte if DMA of mob is on.
*/
protected void cycleMob4Right() {
if (DMAx[4]) { // is DMA of mob 4 on?
mobSequencer[4]|=s_access(4); // read right byte of mob
MCx[4]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 5...
* Read the sprite pointer of mob 5 and set BA high if mob 5 and 6 off.
*/
protected void cycleMob5Pointer() {
MPx[5]=p_access(5); // read sprite pointer 5
// BA high if sprites 5 and 6 off
if (!DMAx[5] && !DMAx[6]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 5...
* Read the mob 3 left byte if DMA of mob is on.
*/
protected void cycleMob5Left() {
if (DMAx[5]) { // is DMA of mob 5 on?
mobSequencer[5]=0;
mobSequencer[5]|=(s_access(5)<<16); // read left byte of mob
MCx[5]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 5...
* Read the mob 5 middle byte if the DMA of mob is on, then set BA low for
* sprite 7 if necessary.
*/
protected void cycleMob5Middle() {
// read data of sprite 5 if necessary
if (!DMAx[5]) { // is DMA of mob 5 off?
i_access(); // idle access
} else {
mobSequencer[5]|=(s_access(5)<<8); // read middle byte of mob
MCx[5]++; // inc Mob data counter
}
// set BA low for sprite 7 is necessary
if (DMAx[7]) {
setBA(0); // BA is now low
}
}
/**
* Cycle code for mob 5...
* Read the mob 5 right byte if DMA of mob is on.
*/
protected void cycleMob5Right() {
if (DMAx[5]) { // is DMA of mob 5 on?
mobSequencer[5]|=s_access(5); // read right byte of mob
MCx[5]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 6...
* Read the sprite pointer of mob 6 and set BA high if mob 6 and 7 off.
*/
protected void cycleMob6Pointer() {
MPx[6]=p_access(6); // read sprite pointer 6
// BA high if sprites 6 and 7 off
if (!DMAx[6] && !DMAx[7]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 6...
* Read the mob 6 left byte if DMA of mob is on.
*/
protected void cycleMob6Left() {
if (DMAx[6]) { // is DMA of mob 6 on?
mobSequencer[6]=0;
mobSequencer[6]|=(s_access(6)<<16); // read left byte of mob
MCx[6]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 6...
* Read mob 6 middle byte if the DMA of mob is on.
*/
protected void cycleMob6Middle() {
if (!DMAx[6]) { // is DMA of mob 6 off?
i_access(); // idle access
} else {
mobSequencer[6]|=(s_access(6)<<8); // read middle byte of mob
MCx[6]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 6...
* Read the mob 6 right byte if DMA of mob is on.
*/
protected void cycleMob6Right() {
if (DMAx[6]) { // is DMA of mob 6 on?
mobSequencer[6]|=s_access(6); // read right byte of mob
MCx[6]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 7...
* Read the sprite pointer of mob 7 and set BA high if mob 7 off.
*/
protected void cycleMob7Pointer() {
MPx[7]=p_access(7); // read sprite pointer 7
// BA high if sprites 7 off
if (!DMAx[7]) {
setBA(1); // BA is now high
}
}
/**
* Cycle code for mob 7...
* Read the mob 7 left byte if DMA of mob is on.
*/
protected void cycleMob7Left() {
if (DMAx[7]) { // is DMA of mob 7 on?
mobSequencer[7]=0;
mobSequencer[7]|=(s_access(7)<<16); // read left byte of mob
MCx[7]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 7...
* Read mob 7 middle byte if the DMA of mob is on.
*/
protected void cycleMob7Middle() {
if (!DMAx[7]) { // is DMA of mob 7 off?
i_access(); // idle access
} else {
mobSequencer[7]|=(s_access(7)<<8); // read middle byte of mob
MCx[7]++; // inc Mob data counter
}
}
/**
* Cycle code for mob 7...
* Read the mob 7 right byte if DMA of mob is on.
*/
protected void cycleMob7Right() {
if (DMAx[7]) { // is DMA of mob 7 on?
mobSequencer[7]|=s_access(7); // read right byte of mob
MCx[7]++; // inc Mob data counter
}
}
/**
* Cycle code for mob counter...
* Increments mobs data counter base if expansion flip flops are set.
*/
protected void cycleMobCounterInc2() {
int i;
// section 3.8.1 Memory access and display
// "7. In the first phase of cycle 15, it is checked if the expansion
// flip flop is set. if so, MCBASE is incremented by 2."
for (i=0; i<8; i++) {
if (expansion[i].isSet()) // expansion flip-flop set?
MCBASEx[i]+=2; // increment mob data base
}
}
/**
* Cycle code for mob counter...
* Increments mobs data counter base if expansion flip flops are set and
* valutates if sprites are to be displayed.
*/
protected void cycleMobCounterInc1() {
int i;
// section 3.8.1 Memory access and display
// "8. In the first phase of cycle 16, it is checked if the expansion
// flip flop is set. If so, MCBASE is incremented by 1. After that, the
// VIC checks if MCBASE is equal to 63 and turns off the DMA and the
// display of a sprite if it is.
for (i=0; i<8; i++) {
if (expansion[i].isSet()) { // expansion flip-flop set?
MCBASEx[i]++; // increment mob data base
///? }
if (MCBASEx[i]==63) {
DMAx[i]=false; // turn off DMA of sprite
display[i]=false; // turn off sprite display
}
} ///?
}
}
/**
* Cycle code for expansion flip flop...
* Invert the expansion flip flop if MxYE is set.
*/
protected void cycleInvertExp() {
int i;
// section 3.8.1. Memory access and display
// "2. If the MxYE bit is set in the first phase of cycle 55, the expansion
// flip flop is inverted."
for (i=0; i<8; i++) {
if (MxYE[i]==1) // sprite Y expanded?
expansion[i].invert(); // invert the exp. flip flop
}
}
/**
* Cycle code for DMA of sprites...
* Allow DMA of sprite to be on if sprite is enabled and sprite position
* matchs the raster.
*/
protected void cycleAllowDMA() {
int i;
// section 3.8.1. Memory access and display
// "3. In the first phases of cycle 55 and 56, the VIC checks for every
// sprite if the corresponding MxE bit in register $d015 is set and the Y
// coordinate of the sprite match the lower 8 bits of RASTER. If this is
// the case and the DMA for the sprite is still off, the DMA is switched
// on, MCBASE is cleared, and if the MxYE bit is set the expansion flip
// flop is reset."
for (i=0; i<8; i++) {
if ((MxE[i]==1) && (MxY[i]==(raster & 0xFF))) {
if (!DMAx[i]) {
DMAx[i]=true; // turn DMA on
MCBASEx[i]=0; // clear MCBASE
if (MxYE[i]==1) // expansion set?
expansion[i].reset(); // reset flip flop
}
}
}
}
/**
* Cycle code for g-access...
* Execute a g-access and if in display state updates the counters
*/
protected void cycleGAccess() {
videoBuffer=videoMatrixColor[VMLI]; // update buffer
// section 3.7.3 Graphics modes
// "The heart of the sequencer is an 8 bit shift register that is shifted
// by 1 bit every pixel and reloaded with new graphics data after every
// g-access. With XSCROLL from register $d016 the reloading can be delayed
// by 0-7 pixels, thus shifting the display up to 7 pixels to the right."
//
// note: the following is a speed up emulation action that use the graphics
// data sequencer with 16 pixels instead of 8 (mappen in high of 32 bits).
// 16+8=24, but 4 is sub because the G-access is here emulated at start of
// the cycle.
gdSequencer+=((g_access()& 0xff)<<(20-xScroll)); // g-access
// section 3.7.2. VC and RC
// "4. VC and VMLI are incremented after each g-access in display
// state"
if (vicState<=0x07) { // dislay state?
VC++; // increment Vic Counter
VMLI++; // increment VMLI
}
}
/**
* Cycle code for refreshing...
* Refresh a line of memory.
*/
protected void cycleRefresh() {
r_access(); // refresh a line of memory
REF--; // dec refresh counter
}
/**
* Cycle code for border comparison...
* Set or reset the vertical border flip flop if raster reaches the bottom
* or the top border line.
*/
protected void cycleBorderComp() {
// 3.9. The border unit
// "2. If the Y coordinate reaches the bottom comparison value in cycle
// 63, the vertical border flip flop is set."
if (raster==BOTTOM[RSEL]) {
verticalBorder.set(); // set vertical border
}
// 3.9. The border unit
// "3. If the Y coordinate reaches the top comparison value in cycle 63
// and the DEN bit in register $d011 is set, the vertical border flip
// flop is reset."
// 3.10. Display Enable
// " - If the DEN bit is cleared, the reset input of the vertical border
// flip flop is deactivated."
if ((raster==TOP[RSEL]) && (DEN==1)) {
verticalBorder.reset(); // reset vertical border
}
}
/**
* Cycle code for c-access...
* Performs a c-access if there's a bad line condiction
* Note: in idle state there's no c-access and the data is assumend to be 0.
* This is included here for simplify the emulation.
*/
protected void cycleCAccess() {
// section 3.7.2. VC and RC
// "...Once started, one c-access is done in the second phase of every
// clock cycle in the range 15-54. The read data is stored in the
// video matrix/color line at the position specified by VMLI. ..."
// section 3.7.3:
// "...The idle state is a bit special in that no c-accesses occur in it
// and the sequencer uses "0" bits for the video matrix data."
if (badLine) {
if ((vicState & 0x08)!=0) // idle state?
videoMatrixColor[VMLI]=0; // no c-access in idle
else videoMatrixColor[VMLI]=c_access(); // c-access
}
}
/**
* Cycle for mobs display...
* Set the display of sprites if DMA is on and Y coordinate matchs raster.
*/
protected void cycleMobDisplay() {
int i;
// section 3.8.1. Memory access and display
// "4. In the first phase of cycle 58 [6569 timing], the MC of every
// sprite is loaded from it's belonging MCBASE and it is checked if
// the DMA for the sprite is turned on and the Y coordinate of the
// sprite matches the lower 8 bits of RASTER. If this is the case, the
// display of the sprite is turned on.
for (i=0; i<8; i++) {
MCx[i]=MCBASEx[i]; // load mob data counter
if (DMAx[i] && (MxY[i]==(raster & 0xFF)))
display[i]=true; // sprite display on
}
}
/**
* Cycle for going to idle state...
* Goes to idle state if there's not bad line condiction and RC reaches 7.
*/
protected void cycleGotoIdle() {
// section 3.7.1 Idle state/display state
// "The transition from display to idle state occurs in cycle 58 of a
// line if the RC contains the value 7 and there is no Bad Line
// Condition."
if ((RC==7) && !badLine) {
vicState|=0x08; // go to idle state
}
// section3.7.2 VC and RC
// "5. In the first phase of cycle 58, the VIC checks if RC=7. If so,
// the video logic goes to idle state an VCBASE is loaded from VC. If
// the video logic is in display state afterwards (this is always the
// case if there is a Bad Line Condiction), RC is incremented.
if (RC==7) {
vicState|=0x08; // go to idle state
VCBase=VC; // load VCbase from VC
}
if (vicState<=0x07) { // display state?
RC++; // increment row counter
}
}
/**
* Cycle code for Bad Line...
* Evaluates if there's a bad line condiction.
*/
protected void cycleIsBadLine() {
// section 3.5: bad line condiction:
// "A Bad Line Condiction is given at any arbitrary clock cycle,
// if at the negative edge of fi0 at the beginning of the cycle
// RASTER >= $30 and RASTER <= $F7 and the lower three bits of RASTER
// are equal to YSCROLL and if the DEN bit was set during an arbitrary
// cycle of raster line $30"
// section 3.7.1 Idle state/display state
// "The transition from idle to display state occurs as soon as there
// is a Bad Line Condiction"
if ((raster>=RASTER_UP) && // bad line condiction ?
(raster<=RASTER_DW) &&
((raster & 0x7)==yScroll) &&
allowBadLine) {
badLine=true; // this is a bad line
vicState&=0x7; // go to display state
} else badLine=false; // this is not a bad line
}
/**
* Cycle code for raster line 0 reached...
* If we reaches the raster line 0, performs some action.
*/
protected void cycleRaster0() {
// section 3.7.2. VC and RC
// "1. Once somewhere outside of the range of raster lines $30-$F7 (i.e.
// outside of the Bad Line range), VCBASE is reset to zero. This is
// presumably done in raster line 0, the exact moment cannot be determined
// and is irrelevant."
// section 3.13. DRAM refresh
// "... The counter is reset to $ff in raster line 0 ..."
if ((raster==0) && (cycle==1)) { // is raster line 0?
VCBase=0; // set VCBASE to 0
REF=0xFF; // init refresh address
}
}
/**
* Cycle code for raster $30 reached...
* If we reach raster $30, evaluate if bad line is allowed.
*/
protected void cycleRaster30() {
// section 3.5 bad line condiction:
// "... if the DEN bit was set during an arbitrary cycle of raster line $30"
if(raster==RASTER_UP) { // is raster line $30?
if (DEN==1) den=true; // is DEN=1 in one cycle?
if (cycle==maxCycle) {
allowBadLine=den; // allowBadline if DEN=1
den=false; // in one cycle
}
}
}
/**
* Cycle code for Vic Counter...
* Load the Vic counter from the base, and see for reset RC.
*/
protected void cycleSetVicCounter() {
// section 3.7.2. VC and RC
// "2. In the first phase of cycle 14 of each line, VC is loaded from
// VCBASE and VMLI is cleared. If there is a Bad Line Condiction in
// this phase, RC is also reset to zero."
VC=VCBase; // load VC with VCBASE
VMLI=0; // clear VMLI
if (badLine) { // bad line condiction ?
RC=0; // RC reset to zero
}
}
/**
* Cycle code for bad line...
* If there's a bad line condiction, allows c-access.
*/
protected void cycleIsCAccess() {
// section 3.7.2. VC and RC
// "3. If there is a Bad line condiction in cycles 12-54, BA is set low
// and the c-acesses are started..."
if (badLine) { // bad line condiction?
setBA(0); // BA is now low
}
}
/**
* Set the value of BA signal.
* Notify the signal to external chip and remember it for internal use.
*/
protected void setBA(int value) {
if (value==0) {
BA=0; // BA low
countBA=0; // first BA low
// notify to all the chip that BA is low
io.notifySignal(S_BA, value);
} else {
BA=1; // BA high
// notify to all the chip that BA is high
io.notifySignal(S_BA, value);
setAEC(1); // AEC goes high
}
}
/**
* Set and notify the new value of AEC
*
* @param value the 0/1 value of AEC
*/
public void setAEC(int value) {
// notify to all chip that AEC is changed
io.notifySignal(S_AEC, value);
}
/**
* Cycle code for AEC after 3 BA low...
* AEC must go low after 3 BA signal low
*/
protected void cycleAEC() {
if (BA==0) { // is BA low?
if (countBA==3) setAEC(0); // if 3 BA then AEC low
else countBA++; // else another BA low
}
}
/**
* Cycle code for raster compare for generating IRQ
*/
protected void cycleRasterCompare() {
if (raster==rasterCompare) {
IRST=1; // interrupt
rasterCompare=-1; /// (to verify)
if (ERST==1) { // is interrupt enabled?
IRQ=1; // start of IRQ
io.notifySignal(S_IRQ, 0); // notify start of IRQ
}
}
}
/**
* Execute VIC cycle operation when the clock signal is low (phase 1)
* This method is abstract because the cycle depends by the type of Vic
* (PAL, NTSC).
*/
public abstract void fi0low();
/**
* Execute VIC cycle operation when the clock signal is high (phase 2)
* This method is abstract because the cycle depends by the type of Vic
* (PAL, NTSC).
*/
public abstract void fi0high();
/**
* Vic dot clock execution
*/
public void dotClock() {
// are we not in vertical blancking interval ?
if (!((raster>=firstVblankLine) || (raster<=lastVblankLine))) {
// are we not in horizontal blancking interval ?
if (((rasterX<=lastVisXCoo) || (rasterX>=firstVisXCoo))) {
// 3.9. The border unit
// "1. If the X coordinate reaches the right comparison value, the main
// border flip flop is set."
if (rasterX==RIGHT[CSEL]) { // x reaches right comp.?
mainBorder.set(); // set main border f.f.
}
// 3.9. The border unit
// "4. If the X coordinate reaches the left comparison value and the Y
// coordinate reaches the bottom one, the vertical border flip flop is
// set."
// 3.9. The border unit
// "5. If the X coordinate reaches the left comparison value and the Y
// coordinate reaches the top one and the DEN bit in register $d011 is
// set, the vertical flip flop is reset."
// 3.10. Display Enable
// " - If the DEN bit is cleared, the reset input of the vertical border
// flip flop is deactivated."
// 3.9. The border unit
// "6. If the X coordinate reaches the left comparison value and the
// vertical border flip flop is not set, the main flip flop is reset."
if (rasterX==LEFT[CSEL]) { // x reaches left comp.?
if (raster==BOTTOM[RSEL]) {
verticalBorder.set(); // set vertical border
}
if ((raster==TOP[RSEL]) && (DEN==1)) {
verticalBorder.reset(); // reset vertical border
}
if (verticalBorder.isReset()) {
mainBorder.reset(); // reset main border
}
}
display();
}
}
//update raster positions
// Section 3.4. Display generation and display window dimensions
// "If you are wondering why the first visible X coordinates seems to come
// after the last visible ones: This is because for the reference point to
// mark the beginning of a raster line, the occurance of the raster IRQ has
// been chosen, witch doesn't coincide with X coordinate 0 but with the
// coordinate given as "First X coo. of a line". The x coordinates run up
// to $1ff (only $1f7 on the 6569) within a line, then comes X coordinate
// 0..."
rasterX++;
if (rasterX>lastXPos) { // is end of X position?
rasterX=0; // start of X position
}
if (rasterX==firstXCoo) { // is end of line
raster++; // next line
if (raster>linesNumber) { // if end of screen?
raster=0; // start of screen
tv.newFrame(); // start a new frame
}
}
}
/**
* Display unit of the Vic
* note: very experimental implementation: probably not the definitive.
*/
public void display() {
int color; // color to be send to raster TV
// this are calculated always
calculateSpritesInfo();
spritesCollision();
// section 3.9. The border unit
// "The main border flip flop controls the border display. If it is set,
// the VIC displays the color stored in register $d020, otherwise it
// displays the color that the priority multiplexer switches through from
// the graphics or sprite data sequencer. It has the highest display
// priority."
// "...the vertical border flip flop controls the output of the graphics
// data sequencer. The sequencer only outputs data if the flip flop is
// not set, otherwise it displays the background color. This was probably
// done to prevent sprite-graphics collisions in the border area."
if (verticalBorder.isSet()) {
tv.sendPixel(EC); // output border color
return;
} else {
calculateGraphicsInfo();
graphicsCollision();
}
if (mainBorder.isSet()) {
tv.sendPixel(EC); // output border color
} else {
tv.sendPixel(multiplexerOutput()); // output color
}
}
/**
* Calculate graphics information of the next pixel to show.
*/
public void calculateGraphicsInfo() {
switch (vicState) {
// section 3.7.3.1. Standard text mode (ECM/BMM/ECM=0/0/0)
// "In standard text mode, every bit in the character generator directly
// corresponds to one pixel on the screen. The foreground color is given
// by the color nibble from the video matrix for each character, the
// background color is set globaly with register $d021."
case VIC_STANDARD_TEXT:
if ((gdSequencer & 0x80000000)==0) {
grColor=(int)B0C; // background color 0
grPriority=BACKGR; // background priority
} else {
grColor=videoBuffer>>8; // 4 bit color
grPriority=FOREGR; // foreground priority
}
gdSequencer<<=1; // this pixel is now out
break;
// section 3.7.3.3 Standard bitmap mode (ECM/BMM/MCM=0/1/0)
// "In standard bitmap mode, every bit in the bitmap directly correponds
// to one pixel on the screen. Foreground and background color can be
// arbitrary set for every 8x8 block."
case VIC_STANDARD_BITMAP:
if ((gdSequencer & 0x80000000)==0) {
grColor=videoBuffer & 0x0f; // 4 bit color
grPriority=BACKGR; // background priority
} else {
grColor=(videoBuffer>>4) & 0x0f; // 4 bit color
grPriority=FOREGR; // foreground priority
}
gdSequencer<<=1; // this pixel is now out
break;
// section 3.7.3.7. Invalid bitmap mode 1 (ECM/BMM/MCM=1/1/0)
// "This mode also only display a black screen..."
// "The structure of the graphics is basically as in standard bitmap
// mode..."
case VIC_INVALID_BITMAP1:
if ((gdSequencer & 0x80000000)==0) {
grPriority=BACKGR; // background priority
} else {
grPriority=FOREGR; // foreground priority
}
grColor=0; // black color
gdSequencer<<=1; // this pixel is now out
break;
// section 3.7.3.2. Multicolor text mode (ECM/BMM/MCM=0/0/1)
// "...If bit 11 of the c-data is zero, the character is display as in
// standard text mode with only the color 0-7 available for the
// foreground. If the bit 11 is set, each two adjacement bits of the dot
// matrix form one pixel..."
case VIC_MULTICOLOR_TEXT:
if ((videoBuffer & 0x0800)==0) { // MC flag
if ((gdSequencer & 0x80000000)==0) {
grColor=B0C; // 4 bit color
grPriority=BACKGR; // background priority
} else {
grColor=(videoBuffer>>8)& 0x07; // 3 bit color
grPriority=FOREGR; // foreground priority
}
gdSequencer<<=1; // this pixel is now out
} else {
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC0000000) {
case 0x00:
grColor=B0C; // 4 bit color
grPriority=BACKGR; // background priority
break;
case 0x01:
grColor=B1C; // 4 bit color
grPriority=BACKGR; // background priority
break;
case 0x02:
grColor=B0C; // 4 bit color
grPriority=FOREGR; // foreground priority
break;
case 0x03:
grColor=(videoBuffer>>8) & 0x07; // 3 bit color
grPriority=FOREGR; // foreground priority
break;
}
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
}
break;
// section 3.7.3.4. multicolor bitmap mode (ECM/BMM/MCM=0/1/1)
// "Similar to the multicolor text mode, this mode also forms (twice
// as wide) pixels by combining two adjacement bits..."
case VIC_MULTICOLOR_BITMAP:
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC0000000) {
case 0x00:
grColor=B0C; // 4 bit color
grPriority=BACKGR; // background priority
break;
case 0x01:
grColor=(videoBuffer>>4)& 0x0f; // 4 bit color
grPriority=BACKGR; // background priority
break;
case 0x02:
grColor=videoBuffer & 0x0f; // 4 bit color
grPriority=FOREGR; // foreground priority
break;
case 0x03:
grColor=(videoBuffer>>8)& 0x0f; // 4 bit color
grPriority=FOREGR; // foreground priority
break;
}
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
break;
// section 3.7.3.5. ECM text mode (ECM/BMM/MCM/1/0/0)
// "This text mode is the same as the standard text mode, but it allows
// the selection of one of four background colors for every single
// character. The selection is done with upper two bits of the character
// pointer..."
case VIC_ECM_TEXT:
if ((gdSequencer & 0x80000000)==0) {
switch ((videoBuffer>>6)& 0x03) { // back. col. selection
case 0x00:
grColor=(int)B0C; // background color 0
grPriority=BACKGR; // background priority
break;
case 0x01:
grColor=(int)B1C; // background color 1
grPriority=BACKGR; // background priority
break;
case 0x02:
grColor=(int)B2C; // background color 2
grPriority=FOREGR; // foreground priority
break;
case 0x03:
grColor=(int)B3C; // background color 2
grPriority=FOREGR; // foreground priority
break;
}
} else {
grColor=videoBuffer>>8; // 4 bit color
grPriority=FOREGR; // foreground priority
}
gdSequencer<<=1; // this pixel is now out
break;
// section 3.7.3.6. Invalid text mode (ECM/BMM/MCM=1/0/1)
// "Setting the ECM and MCM bits simultaneously dosn't select one of the
// "official" graphics modes of the VIC but creates only black pixels.."
// "...The generated graphics is similar to that of the multicolor text
// mode, but the character set is limited to 64 characters as in ECM
// mode."
case VIC_INVALID_TEXT:
if ((videoBuffer & 0x0800)==0) { // MC flag
if ((gdSequencer & 0x80000000)==0) {
grPriority=BACKGR; // background priority
} else {
grPriority=FOREGR; // foreground priority
}
grColor=0; // black color
gdSequencer<<=1; // this pixel is now out
} else {
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC000) {
case 0x00:
case 0x01:
grPriority=BACKGR; // background priority
break;
case 0x02:
case 0x03:
grPriority=FOREGR; // foreground priority
}
grColor=0; // black color
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
}
break;
// section 3.7.3.8. Invalid bitmap mode 2 (ECM/BMM/MCM=1/1/1)
// "The last invalid mode also creates a black screen..."
// "...The structures of the graphics is basically as in multicolor
// bitmap mode, but the bits 9 and 10 of g-addresses are alwayszero
// due to the set ECM bit, with the same result as in the first invalid
// bitmap mode..."
case VIC_INVALID_BITMAP2:
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC0000000) {
case 0x00:
case 0x01:
grPriority=BACKGR; // background priority
break;
case 0x02:
case 0x03:
grPriority=FOREGR; // foreground priority
break;
}
grColor=B0C; // 4 bit color
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
break;
// section 3.7.3.9. Idle state
// "In idle state, the VIC reads the graphics data from address $3fff
// (resp. $39ff if the ECM bit is set) and displays it in the selected
// graphics mode, but with the video matrix (normally read in the
// c-accesses) being all "0" bits."
case (VIC_STANDARD_TEXT | 0x08): // in idle
case (VIC_MULTICOLOR_TEXT | 0x08): // in idle
case (VIC_ECM_TEXT | 0x08): // in idle
if ((gdSequencer & 0x80000000)==0) {
grColor=(int)B0C; // background color 0
grPriority=BACKGR; // background priority
} else {
grColor=0; // black color
grPriority=FOREGR; // foreground priority
}
gdSequencer<<=1; // this pixel is now out
break;
case (VIC_STANDARD_BITMAP | 0x08): // in idle
case (VIC_INVALID_TEXT | 0x08): // in idle
case (VIC_INVALID_BITMAP1 | 0x08): // in idle
if ((gdSequencer & 0x80000000)==0) {
grPriority=BACKGR; // background priority
} else {
grPriority=FOREGR; // foreground priority
}
grColor=0; // black color
gdSequencer<<=1; // this pixel is now out
break;
case (VIC_MULTICOLOR_BITMAP | 0x08): // in idle
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC0000000) {
case 0x00:
grColor=(int)B0C; // background color 0
grPriority=BACKGR; // background priority
break;
case 0x01:
grColor=0; // black color
grPriority=BACKGR; // background priority
break;
case 0x02:
case 0x03:
grColor=0; // black color
grPriority=FOREGR; // foreground priority
break;
}
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
break;
case (VIC_INVALID_BITMAP2 | 0x08): // in idle
if ((rasterX & 0x01)==0) { // twice indicator
switch (gdSequencer & 0xC0000000) {
case 0x00:
case 0x01:
grPriority=BACKGR; // background priority
break;
case 0x02:
case 0x03:
grPriority=FOREGR; // foreground priority
break;
}
grColor=(int)B0C; // 4 bit color
} else {
// previous information are still valid
gdSequencer<<=2; // these 2 pixels are out
}
break;
}
}
/**
* Calculate graphics sprites information of the next pixel to show.
*/
public void calculateSpritesInfo() {
int i; // cycle variable
for (i=0; i<8; i++) { // cycle to all the mobs
// section 3.8.1. Memory access and display
// "6. If the sprite display for a sprite is turned on, the shift
// register is shifted left by one bit with every pixel as soon as the
// current X coordinate of the raster beam matches the X coordinate of
// the sprite, and the bits that "fall off" are displayed. If the MxXE
// bit belonging to the sprite in register $d01d is set, the shift is
// done only every second pixel and the sprite appears twice as wide.
// If the sprite is in multicolor mode, every two adjacent bits form one
// pixel."
if (display[i]) { // display on ?
if ((rasterX==MxX[i]) && (pixels[i]==-1)) { // activate drawing ?
// note: when activated it display 24 pixel, even if MxX[i] changes
pixels[i]=24; // 24 pixels to draw
pixelsCount[i]=0; // reset count
}
if (pixels[i]!=-1) { // is drawing ?
switch (MxMC[i]) {
case 0x00: // normal
if (MxXE[i]==0) { // not double ?
if ((mobSequencer[i] & 0x800000)==0) { // 0 pixel
spColor[i]=-1; // trasparent
spPriority[i]=BACKGR; // background priority
} else { // 1 pixel
spColor[i]=MxC[i]; // sprite color
spPriority[i]=FOREGR; // foreground priority
}
mobSequencer[i]<<=1; // 1 pixel is out
mobSequencer[i]&=0xFFFFFF;
pixels[i]--;
} else { // double
if ((pixelsCount[i] % 2)==0) {
if ((mobSequencer[i] & 0x800000)==0) {
spColor[i]=-1; // trasparent
spPriority[i]=BACKGR; // background priority
} else { // 1 pixel
spColor[i]=MxC[i]; // sprite color
spPriority[i]=FOREGR; // foreground priority
}
pixelsCount[i]++; // inc pixel count
} else {
// previous information are still valid
mobSequencer[i]<<=1; // 1 pixel is out
mobSequencer[i]&=0xFFFFFF;
pixels[i]--;
pixelsCount[i]++; // inc pixel count
}
}
break;
case 0x01: // multicolor
if (MxXE[i]==0) { // not double ?
if ((pixelsCount[i] % 2)==0) {
switch (mobSequencer[i] & 0xC00000) {
case 0x000000:
spColor[i]=-1; // trasparent
spPriority[i]=BACKGR; // background priority
break;
case 0x400000:
spColor[i]=MM0; // multicolor 0
spPriority[i]=BACKGR; // background priority
break;
case 0x800000:
spColor[i]=MxC[i]; // sprite color
spPriority[i]=FOREGR; // foreground priority
break;
case 0xC00000:
spColor[i]=MM1; // multicolor 1
spPriority[i]=FOREGR; // foreground priority
break;
}
pixelsCount[i]++; // inc pixel count
} else {
// previous information are still valid
mobSequencer[i]<<=2; // 2 pixels are out
mobSequencer[i]&=0xFFFFFF;
pixels[i]-=2;
pixelsCount[i]++; // inc pixel count
}
} else { // double
if ((pixelsCount[i] % 4)==0) {
switch (mobSequencer[i] & 0xC00000) {
case 0x000000:
spColor[i]=-1; // trasparent
spPriority[i]=BACKGR; // background priority
break;
case 0x400000:
spColor[i]=MM0; // multicolor 0
spPriority[i]=BACKGR; // background priority
break;
case 0x800000:
spColor[i]=MxC[i]; // sprite color
spPriority[i]=FOREGR; // foreground priority
break;
case 0xC00000:
spColor[i]=MM1; // multicolor 1
spPriority[i]=FOREGR; // foreground priority
break;
}
}
if (((pixelsCount[i]+1) % 4)==0) { // last of 4 ?
mobSequencer[i]<<=2; // 2 pixels are out
mobSequencer[i]&=0xFFFFFF;
pixels[i]-=2;
}
// previous (or actual) information are still valid
pixelsCount[i]++; // inc pixel count
}
break;
default: // debug info
System.err.println("ERROR: MxMC of sprite "+i+" is invalid");
}
} else {
spColor[i]=-1; // no color
}
}
}
}
/**
* Claculate the output of Vic multiplexer.
* This multiplexer chooses the right color from graphics and sprite sequencer
* according to the priority.
*
* @return the color to display
*/
public int multiplexerOutput() {
int priority=BACKGR; // sprite priority
int color=-1; // sprite color: -1 = no sprite color or transparent
int i; // cycle variables
for (i=7; i>=0; i--) {
if (pixels[i]!=-1) { // are we drawing mob?
if (spPriority[i]==FOREGR) {
color=spColor[i]; // use color of this
priority=FOREGR; // max sprite priority
} else {
if ((priority==BACKGR) && (spColor[i]!=-1)) {
color=spColor[i]; // use color of this
}
}
if (pixels[i]<=0) pixels[i]=-1; // stop drawing mob
}
}
if (color==-1) // there's no sprite color?
return grColor; // graphics color
if (priority==FOREGR) // max priority
return color; // sprite color
if (grPriority==FOREGR) // max graphics priority
return grColor; // graphics color
return color; // sprite color
}
/**
* Check for sprite to sprite collision
*/
public void spritesCollision() {
int i; // cycle variables
int j; // cycle variables
// section 3.8.2. Priority and collision detection
// "A collision of sprites among themselvs is detected as soon as two or
// more sprite data sequencers output a non-transparent pixel in the course
// of display generation (this can also happen somewhere outside of the
// visible screen area). In this case, the MxM bits of all affected sprites
// are set in register $d01e and (if allowed ...), an interrupt is
// generated."
/// (not a speed up solution!)
for (i=7; i<1; i--) {
if (spColor[i]!=-1) { // not transparent ?
for (j=i-1; j<0; j--) {
if (spColor[i]!=-1) { // not transparent ?
MxM[i]|=1; // update collision flag
MxM[j]|=1; // update collision flag
}
}
}
}
}
/**
* Check for sprites to graphics collision
*/
public void graphicsCollision() {
int i; // cycle variables
// section 3.8.2. Priority and collision detection
// "A collision of sprites and other graphics data is detected as soon as
// one or more sprite data sequencers output a non-trasparent pixel in the
// course of display generation (this can also happen somewhere outside of
// the visible screen area). In this case, the MxM bits of all affected
// sprites are set in register $d01e (if allowed ...), an interrupt is
// generated."
for (i=0; i<8; i++) {
if ((spColor[i]!=-1) && (grPriority==FOREGR)) { // a collision
MxD[i]|=1; // update collision flag
}
}
}
/**
* Power on the electronic component
*/
public void powerOn() {
power=true; // power is on
}
/**
* Power off the electronic component
*/
public void powerOff() {
power=false; // power is off
}
}
| 88,882 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
Sid.java | /FileExtraction/Java_unseen/ice00_jc64/src/sw_emulator/hardware/chip/Sid.java | /**
* @(#)Sid.java 2000/04/15
*
* ICE Team Free Software Group
*
* This file is part of C64 Java Software Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*/
package sw_emulator.hardware.chip;
import sw_emulator.util.Monitor;
import sw_emulator.hardware.powered;
import sw_emulator.hardware.signaller;
import sw_emulator.hardware.bus.readableBus;
import sw_emulator.hardware.bus.writeableBus;
import sw_emulator.util.Monitor2;
/**
* Emulate the Sid chip.
*
* @author Ice
* @version 1.00 15/04/2000
*/
public /*abstract*/ class Sid extends Thread implements powered, signaller,
readableBus, writeableBus{
/**
* The state of power
*/
private boolean power=false;
/**
* The monitor where synchronization with a clock
*/
protected Monitor monitor;
/**
* Write a byte to the bus at specific address location.
*
* @param addr the address location
* @param value the byte value
*/
public void write(int addr, byte value) {
switch (addr) {
default:
// do nothing, write ignored
}
}
/**
* Read a byte from the bus at specific address location.
*
* @param addr the address location
* @return the readed byte
*/
public byte read(int addr) {
switch (addr) {
default :
return (byte)0xFF; // not connected
}
}
/**
* Execute the cycles of SID according to external clock.
*/
public void run() {
while (true) {
if (!power) // there's power ?
while (!power) { // no, attend power
this.yield(); // give mutex
}
///monitor.opSignal2();
monitor.opWait(); // attend synchronization
//....
}
}
/**
* Notify a signal to the chip
*
* @param type the type of signal
* @param value the value of the signal (0/1)
*/
public void notifySignal(int type, int value) {
switch (type) {
case S_RESET:
//....
break;
default:
System.err.println("ERROR: an invalid "+type+
" signal was notify to SID");
}
}
/**
* Power on the electronic component
*/
public void powerOn() {
power=true; // power is on
}
/**
* Power off the electronic component
*/
public void powerOff() {
power=false; // power is off
}
} | 3,218 | Java | .java | ice00/jc64 | 43 | 6 | 0 | 2019-11-30T14:02:48Z | 2024-05-05T18:41:15Z |
Stream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/Stream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
/**
* An interface that represents a Stream.
*/
public interface Stream {
/**
* Configures the stream. You need to call this before calling {@link #getSessionDescription()}
* to apply your configuration of the stream.
*/
public void configure() throws IllegalStateException, IOException;
/**
* Starts the stream.
* This method can only be called after {@link Stream#configure()}.
*/
public void start() throws IllegalStateException, IOException;
/**
* Stops the stream.
*/
public void stop();
/**
* Sets the Time To Live of packets sent over the network.
* @param ttl The time to live
* @throws IOException
*/
public void setTimeToLive(int ttl) throws IOException;
/**
* Sets the destination ip address of the stream.
* @param dest The destination address of the stream
*/
public void setDestinationAddress(InetAddress dest);
/**
* Sets the destination ports of the stream.
* If an odd number is supplied for the destination port then the next
* lower even number will be used for RTP and it will be used for RTCP.
* If an even number is supplied, it will be used for RTP and the next odd
* number will be used for RTCP.
* @param dport The destination port
*/
public void setDestinationPorts(int dport);
/**
* Sets the destination ports of the stream.
* @param rtpPort Destination port that will be used for RTP
* @param rtcpPort Destination port that will be used for RTCP
*/
public void setDestinationPorts(int rtpPort, int rtcpPort);
/**
* If a TCP is used as the transport protocol for the RTP session,
* the output stream to which RTP packets will be written to must
* be specified with this method.
*/
public void setOutputStream(OutputStream stream, byte channelIdentifier);
/**
* Returns a pair of source ports, the first one is the
* one used for RTP and the second one is used for RTCP.
**/
public int[] getLocalPorts();
/**
* Returns a pair of destination ports, the first one is the
* one used for RTP and the second one is used for RTCP.
**/
public int[] getDestinationPorts();
/**
* Returns the SSRC of the underlying {@link net.majorkernelpanic.streaming.rtp.RtpSocket}.
* @return the SSRC of the stream.
*/
public int getSSRC();
/**
* Returns an approximation of the bit rate consumed by the stream in bit per seconde.
*/
public long getBitrate();
/**
* Returns a description of the stream using SDP.
* This method can only be called after {@link Stream#configure()}.
* @throws IllegalStateException Thrown when {@link Stream#configure()} wa not called.
*/
public String getSessionDescription() throws IllegalStateException;
public boolean isStreaming();
}
| 3,733 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
SessionBuilder.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/SessionBuilder.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming;
import java.io.IOException;
import java.net.InetAddress;
import net.majorkernelpanic.streaming.audio.AACStream;
import net.majorkernelpanic.streaming.audio.AMRNBStream;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.audio.AudioStream;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.video.H263Stream;
import net.majorkernelpanic.streaming.video.H264Stream;
import net.majorkernelpanic.streaming.video.VideoQuality;
import net.majorkernelpanic.streaming.video.VideoStream;
import android.content.Context;
import android.hardware.Camera.CameraInfo;
import android.preference.PreferenceManager;
/**
* Call {@link #getInstance()} to get access to the SessionBuilder.
*/
public class SessionBuilder {
public final static String TAG = "SessionBuilder";
/** Can be used with {@link #setVideoEncoder}. */
public final static int VIDEO_NONE = 0;
/** Can be used with {@link #setVideoEncoder}. */
public final static int VIDEO_H264 = 1;
/** Can be used with {@link #setVideoEncoder}. */
public final static int VIDEO_H263 = 2;
/** Can be used with {@link #setAudioEncoder}. */
public final static int AUDIO_NONE = 0;
/** Can be used with {@link #setAudioEncoder}. */
public final static int AUDIO_AMRNB = 3;
/** Can be used with {@link #setAudioEncoder}. */
public final static int AUDIO_AAC = 5;
// Default configuration
private VideoQuality mVideoQuality = VideoQuality.DEFAULT_VIDEO_QUALITY;
private AudioQuality mAudioQuality = AudioQuality.DEFAULT_AUDIO_QUALITY;
private Context mContext;
private int mVideoEncoder = VIDEO_H263;
private int mAudioEncoder = AUDIO_AMRNB;
private int mCamera = CameraInfo.CAMERA_FACING_BACK;
private int mTimeToLive = 64;
private int mOrientation = 0;
private boolean mFlash = false;
private SurfaceView mSurfaceView = null;
private String mOrigin = null;
private String mDestination = null;
private Session.Callback mCallback = null;
// Removes the default public constructor
private SessionBuilder() {}
// The SessionManager implements the singleton pattern
private static volatile SessionBuilder sInstance = null;
/**
* Returns a reference to the {@link SessionBuilder}.
* @return The reference to the {@link SessionBuilder}
*/
public final static SessionBuilder getInstance() {
if (sInstance == null) {
synchronized (SessionBuilder.class) {
if (sInstance == null) {
SessionBuilder.sInstance = new SessionBuilder();
}
}
}
return sInstance;
}
/**
* Creates a new {@link Session}.
* @return The new Session
* @throws IOException
*/
public Session build() {
Session session;
session = new Session();
session.setOrigin(mOrigin);
session.setDestination(mDestination);
session.setTimeToLive(mTimeToLive);
session.setCallback(mCallback);
switch (mAudioEncoder) {
case AUDIO_AAC:
AACStream stream = new AACStream();
session.addAudioTrack(stream);
if (mContext!=null)
stream.setPreferences(PreferenceManager.getDefaultSharedPreferences(mContext));
break;
case AUDIO_AMRNB:
session.addAudioTrack(new AMRNBStream());
break;
}
switch (mVideoEncoder) {
case VIDEO_H263:
session.addVideoTrack(new H263Stream(mCamera));
break;
case VIDEO_H264:
H264Stream stream = new H264Stream(mCamera);
if (mContext!=null)
stream.setPreferences(PreferenceManager.getDefaultSharedPreferences(mContext));
session.addVideoTrack(stream);
break;
}
if (session.getVideoTrack()!=null) {
VideoStream video = session.getVideoTrack();
video.setFlashState(mFlash);
video.setVideoQuality(mVideoQuality);
video.setSurfaceView(mSurfaceView);
video.setPreviewOrientation(mOrientation);
video.setDestinationPorts(5006);
}
if (session.getAudioTrack()!=null) {
AudioStream audio = session.getAudioTrack();
audio.setAudioQuality(mAudioQuality);
audio.setDestinationPorts(5004);
}
return session;
}
/**
* Access to the context is needed for the H264Stream class to store some stuff in the SharedPreferences.
* Note that you should pass the Application context, not the context of an Activity.
**/
public SessionBuilder setContext(Context context) {
mContext = context;
return this;
}
/** Sets the destination of the session. */
public SessionBuilder setDestination(String destination) {
mDestination = destination;
return this;
}
/** Sets the origin of the session. It appears in the SDP of the session. */
public SessionBuilder setOrigin(String origin) {
mOrigin = origin;
return this;
}
/** Sets the video stream quality. */
public SessionBuilder setVideoQuality(VideoQuality quality) {
mVideoQuality = quality.clone();
return this;
}
/** Sets the audio encoder. */
public SessionBuilder setAudioEncoder(int encoder) {
mAudioEncoder = encoder;
return this;
}
/** Sets the audio quality. */
public SessionBuilder setAudioQuality(AudioQuality quality) {
mAudioQuality = quality.clone();
return this;
}
/** Sets the default video encoder. */
public SessionBuilder setVideoEncoder(int encoder) {
mVideoEncoder = encoder;
return this;
}
public SessionBuilder setFlashEnabled(boolean enabled) {
mFlash = enabled;
return this;
}
public SessionBuilder setCamera(int camera) {
mCamera = camera;
return this;
}
public SessionBuilder setTimeToLive(int ttl) {
mTimeToLive = ttl;
return this;
}
/**
* Sets the SurfaceView required to preview the video stream.
**/
public SessionBuilder setSurfaceView(SurfaceView surfaceView) {
mSurfaceView = surfaceView;
return this;
}
/**
* Sets the orientation of the preview.
* @param orientation The orientation of the preview
*/
public SessionBuilder setPreviewOrientation(int orientation) {
mOrientation = orientation;
return this;
}
public SessionBuilder setCallback(Session.Callback callback) {
mCallback = callback;
return this;
}
/** Returns the context set with {@link #setContext(Context)}*/
public Context getContext() {
return mContext;
}
/** Returns the destination ip address set with {@link #setDestination(String)}. */
public String getDestination() {
return mDestination;
}
/** Returns the origin ip address set with {@link #setOrigin(String)}. */
public String getOrigin() {
return mOrigin;
}
/** Returns the audio encoder set with {@link #setAudioEncoder(int)}. */
public int getAudioEncoder() {
return mAudioEncoder;
}
/** Returns the id of the {@link android.hardware.Camera} set with {@link #setCamera(int)}. */
public int getCamera() {
return mCamera;
}
/** Returns the video encoder set with {@link #setVideoEncoder(int)}. */
public int getVideoEncoder() {
return mVideoEncoder;
}
/** Returns the VideoQuality set with {@link #setVideoQuality(VideoQuality)}. */
public VideoQuality getVideoQuality() {
return mVideoQuality;
}
/** Returns the AudioQuality set with {@link #setAudioQuality(AudioQuality)}. */
public AudioQuality getAudioQuality() {
return mAudioQuality;
}
/** Returns the flash state set with {@link #setFlashEnabled(boolean)}. */
public boolean getFlashState() {
return mFlash;
}
/** Returns the SurfaceView set with {@link #setSurfaceView(SurfaceView)}. */
public SurfaceView getSurfaceView() {
return mSurfaceView;
}
/** Returns the time to live set with {@link #setTimeToLive(int)}. */
public int getTimeToLive() {
return mTimeToLive;
}
/** Returns a new {@link SessionBuilder} with the same configuration. */
public SessionBuilder clone() {
return new SessionBuilder()
.setDestination(mDestination)
.setOrigin(mOrigin)
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(mOrientation)
.setVideoQuality(mVideoQuality)
.setVideoEncoder(mVideoEncoder)
.setFlashEnabled(mFlash)
.setCamera(mCamera)
.setTimeToLive(mTimeToLive)
.setAudioEncoder(mAudioEncoder)
.setAudioQuality(mAudioQuality)
.setContext(mContext)
.setCallback(mCallback);
}
} | 8,939 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
MediaStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/MediaStream.java | /*
* Copyright (C) 2011-2015 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.Random;
import net.majorkernelpanic.streaming.audio.AudioStream;
import net.majorkernelpanic.streaming.rtp.AbstractPacketizer;
import net.majorkernelpanic.streaming.video.VideoStream;
import android.annotation.SuppressLint;
import android.media.MediaCodec;
import android.media.MediaRecorder;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
/**
* A MediaRecorder that streams what it records using a packetizer from the RTP package.
* You can't use this class directly !
*/
public abstract class MediaStream implements Stream {
protected static final String TAG = "MediaStream";
/** Raw audio/video will be encoded using the MediaRecorder API. */
public static final byte MODE_MEDIARECORDER_API = 0x01;
/** Raw audio/video will be encoded using the MediaCodec API with buffers. */
public static final byte MODE_MEDIACODEC_API = 0x02;
/** Raw audio/video will be encoded using the MediaCode API with a surface. */
public static final byte MODE_MEDIACODEC_API_2 = 0x05;
/** A LocalSocket will be used to feed the MediaRecorder object */
public static final byte PIPE_API_LS = 0x01;
/** A ParcelFileDescriptor will be used to feed the MediaRecorder object */
public static final byte PIPE_API_PFD = 0x02;
/** Prefix that will be used for all shared preferences saved by libstreaming */
protected static final String PREF_PREFIX = "libstreaming-";
/** The packetizer that will read the output of the camera and send RTP packets over the networked. */
protected AbstractPacketizer mPacketizer = null;
protected static byte sSuggestedMode = MODE_MEDIARECORDER_API;
protected byte mMode, mRequestedMode;
/**
* Starting lollipop the LocalSocket API cannot be used to feed a MediaRecorder object.
* You can force what API to use to create the pipe that feeds it with this constant
* by using {@link #PIPE_API_LS} and {@link #PIPE_API_PFD}.
*/
protected final static byte sPipeApi;
protected boolean mStreaming = false, mConfigured = false;
protected int mRtpPort = 0, mRtcpPort = 0;
protected byte mChannelIdentifier = 0;
protected OutputStream mOutputStream = null;
protected InetAddress mDestination;
protected ParcelFileDescriptor[] mParcelFileDescriptors;
protected ParcelFileDescriptor mParcelRead;
protected ParcelFileDescriptor mParcelWrite;
protected LocalSocket mReceiver, mSender = null;
private LocalServerSocket mLss = null;
private int mSocketId;
private int mTTL = 64;
protected MediaRecorder mMediaRecorder;
protected MediaCodec mMediaCodec;
static {
// We determine whether or not the MediaCodec API should be used
try {
Class.forName("android.media.MediaCodec");
// Will be set to MODE_MEDIACODEC_API at some point...
sSuggestedMode = MODE_MEDIACODEC_API;
Log.i(TAG,"Phone supports the MediaCoded API");
} catch (ClassNotFoundException e) {
sSuggestedMode = MODE_MEDIARECORDER_API;
Log.i(TAG,"Phone does not support the MediaCodec API");
}
// Starting lollipop, the LocalSocket API cannot be used anymore to feed
// a MediaRecorder object for security reasons
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
sPipeApi = PIPE_API_PFD;
} else {
sPipeApi = PIPE_API_LS;
}
}
public MediaStream() {
mRequestedMode = sSuggestedMode;
mMode = sSuggestedMode;
}
/**
* Sets the destination IP address of the stream.
* @param dest The destination address of the stream
*/
public void setDestinationAddress(InetAddress dest) {
mDestination = dest;
}
/**
* Sets the destination ports of the stream.
* If an odd number is supplied for the destination port then the next
* lower even number will be used for RTP and it will be used for RTCP.
* If an even number is supplied, it will be used for RTP and the next odd
* number will be used for RTCP.
* @param dport The destination port
*/
public void setDestinationPorts(int dport) {
if (dport % 2 == 1) {
mRtpPort = dport-1;
mRtcpPort = dport;
} else {
mRtpPort = dport;
mRtcpPort = dport+1;
}
}
/**
* Sets the destination ports of the stream.
* @param rtpPort Destination port that will be used for RTP
* @param rtcpPort Destination port that will be used for RTCP
*/
public void setDestinationPorts(int rtpPort, int rtcpPort) {
mRtpPort = rtpPort;
mRtcpPort = rtcpPort;
mOutputStream = null;
}
/**
* If a TCP is used as the transport protocol for the RTP session,
* the output stream to which RTP packets will be written to must
* be specified with this method.
*/
public void setOutputStream(OutputStream stream, byte channelIdentifier) {
mOutputStream = stream;
mChannelIdentifier = channelIdentifier;
}
/**
* Sets the Time To Live of packets sent over the network.
* @param ttl The time to live
* @throws IOException
*/
public void setTimeToLive(int ttl) throws IOException {
mTTL = ttl;
}
/**
* Returns a pair of destination ports, the first one is the
* one used for RTP and the second one is used for RTCP.
**/
public int[] getDestinationPorts() {
return new int[] {
mRtpPort,
mRtcpPort
};
}
/**
* Returns a pair of source ports, the first one is the
* one used for RTP and the second one is used for RTCP.
**/
public int[] getLocalPorts() {
return mPacketizer.getRtpSocket().getLocalPorts();
}
/**
* Sets the streaming method that will be used.
*
* If the mode is set to {@link #MODE_MEDIARECORDER_API}, raw audio/video will be encoded
* using the MediaRecorder API. <br />
*
* If the mode is set to {@link #MODE_MEDIACODEC_API} or to {@link #MODE_MEDIACODEC_API_2},
* audio/video will be encoded with using the MediaCodec. <br />
*
* The {@link #MODE_MEDIACODEC_API_2} mode only concerns {@link VideoStream}, it makes
* use of the createInputSurface() method of the MediaCodec API (Android 4.3 is needed there). <br />
*
* @param mode Can be {@link #MODE_MEDIARECORDER_API}, {@link #MODE_MEDIACODEC_API} or {@link #MODE_MEDIACODEC_API_2}
*/
public void setStreamingMethod(byte mode) {
mRequestedMode = mode;
}
/**
* Returns the streaming method in use, call this after
* {@link #configure()} to get an accurate response.
*/
public byte getStreamingMethod() {
return mMode;
}
/**
* Returns the packetizer associated with the {@link MediaStream}.
* @return The packetizer
*/
public AbstractPacketizer getPacketizer() {
return mPacketizer;
}
/**
* Returns an approximation of the bit rate consumed by the stream in bit per seconde.
*/
public long getBitrate() {
return !mStreaming ? 0 : mPacketizer.getRtpSocket().getBitrate();
}
/**
* Indicates if the {@link MediaStream} is streaming.
* @return A boolean indicating if the {@link MediaStream} is streaming
*/
public boolean isStreaming() {
return mStreaming;
}
/**
* Configures the stream with the settings supplied with
* {@link VideoStream#setVideoQuality(net.majorkernelpanic.streaming.video.VideoQuality)}
* for a {@link VideoStream} and {@link AudioStream#setAudioQuality(net.majorkernelpanic.streaming.audio.AudioQuality)}
* for a {@link AudioStream}.
*/
public synchronized void configure() throws IllegalStateException, IOException {
if (mStreaming) throw new IllegalStateException("Can't be called while streaming.");
if (mPacketizer != null) {
mPacketizer.setDestination(mDestination, mRtpPort, mRtcpPort);
mPacketizer.getRtpSocket().setOutputStream(mOutputStream, mChannelIdentifier);
}
mMode = mRequestedMode;
mConfigured = true;
}
/** Starts the stream. */
public synchronized void start() throws IllegalStateException, IOException {
if (mDestination==null)
throw new IllegalStateException("No destination ip address set for the stream !");
if (mRtpPort<=0 || mRtcpPort<=0)
throw new IllegalStateException("No destination ports set for the stream !");
mPacketizer.setTimeToLive(mTTL);
if (mMode != MODE_MEDIARECORDER_API) {
encodeWithMediaCodec();
} else {
encodeWithMediaRecorder();
}
}
/** Stops the stream. */
@SuppressLint("NewApi")
public synchronized void stop() {
if (mStreaming) {
try {
if (mMode==MODE_MEDIARECORDER_API) {
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
closeSockets();
mPacketizer.stop();
} else {
mPacketizer.stop();
mMediaCodec.stop();
mMediaCodec.release();
mMediaCodec = null;
}
} catch (Exception e) {
e.printStackTrace();
}
mStreaming = false;
}
}
protected abstract void encodeWithMediaRecorder() throws IOException;
protected abstract void encodeWithMediaCodec() throws IOException;
/**
* Returns a description of the stream using SDP.
* This method can only be called after {@link Stream#configure()}.
* @throws IllegalStateException Thrown when {@link Stream#configure()} was not called.
*/
public abstract String getSessionDescription();
/**
* Returns the SSRC of the underlying {@link net.majorkernelpanic.streaming.rtp.RtpSocket}.
* @return the SSRC of the stream
*/
public int getSSRC() {
return getPacketizer().getSSRC();
}
protected void createSockets() throws IOException {
if (sPipeApi == PIPE_API_LS) {
final String LOCAL_ADDR = "net.majorkernelpanic.streaming-";
for (int i=0;i<10;i++) {
try {
mSocketId = new Random().nextInt();
mLss = new LocalServerSocket(LOCAL_ADDR+mSocketId);
break;
} catch (IOException e1) {}
}
mReceiver = new LocalSocket();
mReceiver.connect( new LocalSocketAddress(LOCAL_ADDR+mSocketId));
mReceiver.setReceiveBufferSize(500000);
mReceiver.setSoTimeout(3000);
mSender = mLss.accept();
mSender.setSendBufferSize(500000);
} else {
Log.e(TAG, "parcelFileDescriptors createPipe version = Lollipop");
mParcelFileDescriptors = ParcelFileDescriptor.createPipe();
mParcelRead = new ParcelFileDescriptor(mParcelFileDescriptors[0]);
mParcelWrite = new ParcelFileDescriptor(mParcelFileDescriptors[1]);
}
}
protected void closeSockets() {
if (sPipeApi == PIPE_API_LS) {
try {
mReceiver.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
mSender.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
mLss.close();
} catch (Exception e) {
e.printStackTrace();
}
mLss = null;
mSender = null;
mReceiver = null;
} else {
try {
if (mParcelRead != null) {
mParcelRead.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (mParcelWrite != null) {
mParcelWrite.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 11,896 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
Session.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/Session.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.audio.AudioStream;
import net.majorkernelpanic.streaming.exceptions.CameraInUseException;
import net.majorkernelpanic.streaming.exceptions.ConfNotSupportedException;
import net.majorkernelpanic.streaming.exceptions.InvalidSurfaceException;
import net.majorkernelpanic.streaming.exceptions.StorageUnavailableException;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
import net.majorkernelpanic.streaming.video.VideoQuality;
import net.majorkernelpanic.streaming.video.VideoStream;
import android.hardware.Camera.CameraInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
/**
* You should instantiate this class with the {@link SessionBuilder}.<br />
* This is the class you will want to use to stream audio and or video to some peer using RTP.<br />
*
* It holds a {@link VideoStream} and a {@link AudioStream} together and provides
* synchronous and asynchronous functions to start and stop those steams.
* You should implement a callback interface {@link Callback} to receive notifications and error reports.<br />
*
* If you want to stream to a RTSP server, you will need an instance of this class and hand it to a {@link RtspClient}.
*
* If you don't use the RTSP protocol, you will still need to send a session description to the receiver
* for him to be able to decode your audio/video streams. You can obtain this session description by calling
* {@link #configure()} or {@link #syncConfigure()} to configure the session with its parameters
* (audio samplingrate, video resolution) and then {@link Session#getSessionDescription()}.<br />
*
* See the example 2 here: https://github.com/fyhertz/libstreaming-examples to
* see an example of how to get a SDP.<br />
*
* See the example 3 here: https://github.com/fyhertz/libstreaming-examples to
* see an example of how to stream to a RTSP server.<br />
*
*/
public class Session {
public final static String TAG = "Session";
public final static int STREAM_VIDEO = 0x01;
public final static int STREAM_AUDIO = 0x00;
/** Some app is already using a camera (Camera.open() has failed). */
public final static int ERROR_CAMERA_ALREADY_IN_USE = 0x00;
/** The phone may not support some streaming parameters that you are trying to use (bit rate, frame rate, resolution...). */
public final static int ERROR_CONFIGURATION_NOT_SUPPORTED = 0x01;
/**
* The internal storage of the phone is not ready.
* libstreaming tried to store a test file on the sdcard but couldn't.
* See H264Stream and AACStream to find out why libstreaming would want to something like that.
*/
public final static int ERROR_STORAGE_NOT_READY = 0x02;
/** The phone has no flash. */
public final static int ERROR_CAMERA_HAS_NO_FLASH = 0x03;
/** The supplied SurfaceView is not a valid surface, or has not been created yet. */
public final static int ERROR_INVALID_SURFACE = 0x04;
/**
* The destination set with {@link Session#setDestination(String)} could not be resolved.
* May mean that the phone has no access to the internet, or that the DNS server could not
* resolved the host name.
*/
public final static int ERROR_UNKNOWN_HOST = 0x05;
/**
* Some other error occurred !
*/
public final static int ERROR_OTHER = 0x06;
private String mOrigin;
private String mDestination;
private int mTimeToLive = 64;
private long mTimestamp;
private AudioStream mAudioStream = null;
private VideoStream mVideoStream = null;
private Callback mCallback;
private Handler mMainHandler;
private Handler mHandler;
/**
* Creates a streaming session that can be customized by adding tracks.
*/
public Session() {
long uptime = System.currentTimeMillis();
HandlerThread thread = new HandlerThread("net.majorkernelpanic.streaming.Session");
thread.start();
mHandler = new Handler(thread.getLooper());
mMainHandler = new Handler(Looper.getMainLooper());
mTimestamp = (uptime/1000)<<32 & (((uptime-((uptime/1000)*1000))>>32)/1000); // NTP timestamp
mOrigin = "127.0.0.1";
}
/**
* The callback interface you need to implement to get some feedback
* Those will be called from the UI thread.
*/
public interface Callback {
/**
* Called periodically to inform you on the bandwidth
* consumption of the streams when streaming.
*/
public void onBitrateUpdate(long bitrate);
/** Called when some error occurs. */
public void onSessionError(int reason, int streamType, Exception e);
/**
* Called when the previw of the {@link VideoStream}
* has correctly been started.
* If an error occurs while starting the preview,
* {@link Callback#onSessionError(int, int, Exception)} will be
* called instead of {@link Callback#onPreviewStarted()}.
*/
public void onPreviewStarted();
/**
* Called when the session has correctly been configured
* after calling {@link Session#configure()}.
* If an error occurs while configuring the {@link Session},
* {@link Callback#onSessionError(int, int, Exception)} will be
* called instead of {@link Callback#onSessionConfigured()}.
*/
public void onSessionConfigured();
/**
* Called when the streams of the session have correctly been started.
* If an error occurs while starting the {@link Session},
* {@link Callback#onSessionError(int, int, Exception)} will be
* called instead of {@link Callback#onSessionStarted()}.
*/
public void onSessionStarted();
/** Called when the stream of the session have been stopped. */
public void onSessionStopped();
}
/** You probably don't need to use that directly, use the {@link SessionBuilder}. */
void addAudioTrack(AudioStream track) {
removeAudioTrack();
mAudioStream = track;
}
/** You probably don't need to use that directly, use the {@link SessionBuilder}. */
void addVideoTrack(VideoStream track) {
removeVideoTrack();
mVideoStream = track;
}
/** You probably don't need to use that directly, use the {@link SessionBuilder}. */
void removeAudioTrack() {
if (mAudioStream != null) {
mAudioStream.stop();
mAudioStream = null;
}
}
/** You probably don't need to use that directly, use the {@link SessionBuilder}. */
void removeVideoTrack() {
if (mVideoStream != null) {
mVideoStream.stopPreview();
mVideoStream = null;
}
}
/** Returns the underlying {@link AudioStream} used by the {@link Session}. */
public AudioStream getAudioTrack() {
return mAudioStream;
}
/** Returns the underlying {@link VideoStream} used by the {@link Session}. */
public VideoStream getVideoTrack() {
return mVideoStream;
}
/**
* Sets the callback interface that will be called by the {@link Session}.
* @param callback The implementation of the {@link Callback} interface
*/
public void setCallback(Callback callback) {
mCallback = callback;
}
/**
* The origin address of the session.
* It appears in the session description.
* @param origin The origin address
*/
public void setOrigin(String origin) {
mOrigin = origin;
}
/**
* The destination address for all the streams of the session. <br />
* Changes will be taken into account the next time you start the session.
* @param destination The destination address
*/
public void setDestination(String destination) {
mDestination = destination;
}
/**
* Set the TTL of all packets sent during the session. <br />
* Changes will be taken into account the next time you start the session.
* @param ttl The Time To Live
*/
public void setTimeToLive(int ttl) {
mTimeToLive = ttl;
}
/**
* Sets the configuration of the stream. <br />
* You can call this method at any time and changes will take
* effect next time you call {@link #configure()}.
* @param quality Quality of the stream
*/
public void setVideoQuality(VideoQuality quality) {
if (mVideoStream != null) {
mVideoStream.setVideoQuality(quality);
}
}
/**
* Sets a Surface to show a preview of recorded media (video). <br />
* You can call this method at any time and changes will take
* effect next time you call {@link #start()} or {@link #startPreview()}.
*/
public void setSurfaceView(final SurfaceView view) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mVideoStream != null) {
mVideoStream.setSurfaceView(view);
}
}
});
}
/**
* Sets the orientation of the preview. <br />
* You can call this method at any time and changes will take
* effect next time you call {@link #configure()}.
* @param orientation The orientation of the preview
*/
public void setPreviewOrientation(int orientation) {
if (mVideoStream != null) {
mVideoStream.setPreviewOrientation(orientation);
}
}
/**
* Sets the configuration of the stream. <br />
* You can call this method at any time and changes will take
* effect next time you call {@link #configure()}.
* @param quality Quality of the stream
*/
public void setAudioQuality(AudioQuality quality) {
if (mAudioStream != null) {
mAudioStream.setAudioQuality(quality);
}
}
/**
* Returns the {@link Callback} interface that was set with
* {@link #setCallback(Callback)} or null if none was set.
*/
public Callback getCallback() {
return mCallback;
}
/**
* Returns a Session Description that can be stored in a file or sent to a client with RTSP.
* @return The Session Description.
* @throws IllegalStateException Thrown when {@link #setDestination(String)} has never been called.
*/
public String getSessionDescription() {
StringBuilder sessionDescription = new StringBuilder();
if (mDestination==null) {
throw new IllegalStateException("setDestination() has not been called !");
}
sessionDescription.append("v=0\r\n");
// TODO: Add IPV6 support
sessionDescription.append("o=- "+mTimestamp+" "+mTimestamp+" IN IP4 "+mOrigin+"\r\n");
sessionDescription.append("s=Unnamed\r\n");
sessionDescription.append("i=N/A\r\n");
sessionDescription.append("c=IN IP4 "+mDestination+"\r\n");
// t=0 0 means the session is permanent (we don't know when it will stop)
sessionDescription.append("t=0 0\r\n");
sessionDescription.append("a=recvonly\r\n");
// Prevents two different sessions from using the same peripheral at the same time
if (mAudioStream != null) {
sessionDescription.append(mAudioStream.getSessionDescription());
sessionDescription.append("a=control:trackID="+0+"\r\n");
}
if (mVideoStream != null) {
sessionDescription.append(mVideoStream.getSessionDescription());
sessionDescription.append("a=control:trackID="+1+"\r\n");
}
return sessionDescription.toString();
}
/** Returns the destination set with {@link #setDestination(String)}. */
public String getDestination() {
return mDestination;
}
/** Returns an approximation of the bandwidth consumed by the session in bit per second. */
public long getBitrate() {
long sum = 0;
if (mAudioStream != null) sum += mAudioStream.getBitrate();
if (mVideoStream != null) sum += mVideoStream.getBitrate();
return sum;
}
/** Indicates if a track is currently running. */
public boolean isStreaming() {
if ( (mAudioStream!=null && mAudioStream.isStreaming()) || (mVideoStream!=null && mVideoStream.isStreaming()) )
return true;
else
return false;
}
/**
* Configures all streams of the session.
**/
public void configure() {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
syncConfigure();
} catch (Exception e) {};
}
});
}
/**
* Does the same thing as {@link #configure()}, but in a synchronous manner. <br />
* Throws exceptions in addition to calling a callback
* {@link Callback#onSessionError(int, int, Exception)} when
* an error occurs.
**/
public void syncConfigure()
throws CameraInUseException,
StorageUnavailableException,
ConfNotSupportedException,
InvalidSurfaceException,
RuntimeException,
IOException {
for (int id=0;id<2;id++) {
Stream stream = id==0 ? mAudioStream : mVideoStream;
if (stream!=null && !stream.isStreaming()) {
try {
stream.configure();
} catch (CameraInUseException e) {
postError(ERROR_CAMERA_ALREADY_IN_USE , id, e);
throw e;
} catch (StorageUnavailableException e) {
postError(ERROR_STORAGE_NOT_READY , id, e);
throw e;
} catch (ConfNotSupportedException e) {
postError(ERROR_CONFIGURATION_NOT_SUPPORTED , id, e);
throw e;
} catch (InvalidSurfaceException e) {
postError(ERROR_INVALID_SURFACE , id, e);
throw e;
} catch (IOException e) {
postError(ERROR_OTHER, id, e);
throw e;
} catch (RuntimeException e) {
postError(ERROR_OTHER, id, e);
throw e;
}
}
}
postSessionConfigured();
}
/**
* Asynchronously starts all streams of the session.
**/
public void start() {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
syncStart();
} catch (Exception e) {}
}
});
}
/**
* Starts a stream in a synchronous manner. <br />
* Throws exceptions in addition to calling a callback.
* @param id The id of the stream to start
**/
public void syncStart(int id)
throws CameraInUseException,
StorageUnavailableException,
ConfNotSupportedException,
InvalidSurfaceException,
UnknownHostException,
IOException {
Stream stream = id==0 ? mAudioStream : mVideoStream;
if (stream!=null && !stream.isStreaming()) {
try {
InetAddress destination = InetAddress.getByName(mDestination);
stream.setTimeToLive(mTimeToLive);
stream.setDestinationAddress(destination);
stream.start();
if (getTrack(1-id) == null || getTrack(1-id).isStreaming()) {
postSessionStarted();
}
if (getTrack(1-id) == null || !getTrack(1-id).isStreaming()) {
mHandler.post(mUpdateBitrate);
}
} catch (UnknownHostException e) {
postError(ERROR_UNKNOWN_HOST, id, e);
throw e;
} catch (CameraInUseException e) {
postError(ERROR_CAMERA_ALREADY_IN_USE , id, e);
throw e;
} catch (StorageUnavailableException e) {
postError(ERROR_STORAGE_NOT_READY , id, e);
throw e;
} catch (ConfNotSupportedException e) {
postError(ERROR_CONFIGURATION_NOT_SUPPORTED , id, e);
throw e;
} catch (InvalidSurfaceException e) {
postError(ERROR_INVALID_SURFACE , id, e);
throw e;
} catch (IOException e) {
postError(ERROR_OTHER, id, e);
throw e;
} catch (RuntimeException e) {
postError(ERROR_OTHER, id, e);
throw e;
}
}
}
/**
* Does the same thing as {@link #start()}, but in a synchronous manner. <br />
* Throws exceptions in addition to calling a callback.
**/
public void syncStart()
throws CameraInUseException,
StorageUnavailableException,
ConfNotSupportedException,
InvalidSurfaceException,
UnknownHostException,
IOException {
syncStart(1);
try {
syncStart(0);
} catch (RuntimeException e) {
syncStop(1);
throw e;
} catch (IOException e) {
syncStop(1);
throw e;
}
}
/** Stops all existing streams. */
public void stop() {
mHandler.post(new Runnable() {
@Override
public void run() {
syncStop();
}
});
}
/**
* Stops one stream in a synchronous manner.
* @param id The id of the stream to stop
**/
private void syncStop(final int id) {
Stream stream = id==0 ? mAudioStream : mVideoStream;
if (stream!=null) {
stream.stop();
}
}
/** Stops all existing streams in a synchronous manner. */
public void syncStop() {
syncStop(0);
syncStop(1);
postSessionStopped();
}
/**
* Asynchronously starts the camera preview. <br />
* You should of course pass a {@link SurfaceView} to {@link #setSurfaceView(SurfaceView)}
* before calling this method. Otherwise, the {@link Callback#onSessionError(int, int, Exception)}
* callback will be called with {@link #ERROR_INVALID_SURFACE}.
*/
public void startPreview() {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mVideoStream != null) {
try {
mVideoStream.startPreview();
postPreviewStarted();
mVideoStream.configure();
} catch (CameraInUseException e) {
postError(ERROR_CAMERA_ALREADY_IN_USE , STREAM_VIDEO, e);
} catch (ConfNotSupportedException e) {
postError(ERROR_CONFIGURATION_NOT_SUPPORTED , STREAM_VIDEO, e);
} catch (InvalidSurfaceException e) {
postError(ERROR_INVALID_SURFACE , STREAM_VIDEO, e);
} catch (RuntimeException e) {
postError(ERROR_OTHER, STREAM_VIDEO, e);
} catch (StorageUnavailableException e) {
postError(ERROR_STORAGE_NOT_READY, STREAM_VIDEO, e);
} catch (IOException e) {
postError(ERROR_OTHER, STREAM_VIDEO, e);
}
}
}
});
}
/**
* Asynchronously stops the camera preview.
*/
public void stopPreview() {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mVideoStream != null) {
mVideoStream.stopPreview();
}
}
});
}
/** Switch between the front facing and the back facing camera of the phone. <br />
* If {@link #startPreview()} has been called, the preview will be briefly interrupted. <br />
* If {@link #start()} has been called, the stream will be briefly interrupted.<br />
* To find out which camera is currently selected, use {@link #getCamera()}
**/
public void switchCamera() {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mVideoStream != null) {
try {
mVideoStream.switchCamera();
postPreviewStarted();
} catch (CameraInUseException e) {
postError(ERROR_CAMERA_ALREADY_IN_USE , STREAM_VIDEO, e);
} catch (ConfNotSupportedException e) {
postError(ERROR_CONFIGURATION_NOT_SUPPORTED , STREAM_VIDEO, e);
} catch (InvalidSurfaceException e) {
postError(ERROR_INVALID_SURFACE , STREAM_VIDEO, e);
} catch (IOException e) {
postError(ERROR_OTHER, STREAM_VIDEO, e);
} catch (RuntimeException e) {
postError(ERROR_OTHER, STREAM_VIDEO, e);
}
}
}
});
}
/**
* Returns the id of the camera currently selected. <br />
* It can be either {@link CameraInfo#CAMERA_FACING_BACK} or
* {@link CameraInfo#CAMERA_FACING_FRONT}.
*/
public int getCamera() {
return mVideoStream != null ? mVideoStream.getCamera() : 0;
}
/**
* Toggles the LED of the phone if it has one.
* You can get the current state of the flash with
* {@link Session#getVideoTrack()} and {@link VideoStream#getFlashState()}.
**/
public void toggleFlash() {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mVideoStream != null) {
try {
mVideoStream.toggleFlash();
} catch (RuntimeException e) {
postError(ERROR_CAMERA_HAS_NO_FLASH, STREAM_VIDEO, e);
}
}
}
});
}
/** Deletes all existing tracks & release associated resources. */
public void release() {
removeAudioTrack();
removeVideoTrack();
mHandler.getLooper().quit();
}
private void postPreviewStarted() {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onPreviewStarted();
}
}
});
}
private void postSessionConfigured() {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onSessionConfigured();
}
}
});
}
private void postSessionStarted() {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onSessionStarted();
}
}
});
}
private void postSessionStopped() {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onSessionStopped();
}
}
});
}
private void postError(final int reason, final int streamType,final Exception e) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onSessionError(reason, streamType, e);
}
}
});
}
private void postBitRate(final long bitrate) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onBitrateUpdate(bitrate);
}
}
});
}
private Runnable mUpdateBitrate = new Runnable() {
@Override
public void run() {
if (isStreaming()) {
postBitRate(getBitrate());
mHandler.postDelayed(mUpdateBitrate, 500);
} else {
postBitRate(0);
}
}
};
public boolean trackExists(int id) {
if (id==0)
return mAudioStream!=null;
else
return mVideoStream!=null;
}
public Stream getTrack(int id) {
if (id==0)
return mAudioStream;
else
return mVideoStream;
}
}
| 21,985 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
InvalidSurfaceException.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/exceptions/InvalidSurfaceException.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.exceptions;
public class InvalidSurfaceException extends RuntimeException {
private static final long serialVersionUID = -7238661340093544496L;
public InvalidSurfaceException(String message) {
super(message);
}
}
| 1,134 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
StorageUnavailableException.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/exceptions/StorageUnavailableException.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.exceptions;
import java.io.IOException;
public class StorageUnavailableException extends IOException {
public StorageUnavailableException(String message) {
super(message);
}
private static final long serialVersionUID = -7537890350373995089L;
}
| 1,166 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
ConfNotSupportedException.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/exceptions/ConfNotSupportedException.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.exceptions;
public class ConfNotSupportedException extends RuntimeException {
public ConfNotSupportedException(String message) {
super(message);
}
private static final long serialVersionUID = 5876298277802827615L;
}
| 1,138 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
CameraInUseException.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/exceptions/CameraInUseException.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.exceptions;
public class CameraInUseException extends RuntimeException {
public CameraInUseException(String message) {
super(message);
}
private static final long serialVersionUID = -1866132102949435675L;
}
| 1,129 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
H263Stream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/video/H263Stream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.video;
import java.io.IOException;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.rtp.H263Packetizer;
import android.graphics.ImageFormat;
import android.hardware.Camera.CameraInfo;
import android.media.MediaRecorder;
import android.service.textservice.SpellCheckerService.Session;
/**
* A class for streaming H.263 from the camera of an android device using RTP.
* You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
* Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setVideoQuality(VideoQuality)}
* to configure the stream. You can then call {@link #start()} to start the RTP stream.
* Call {@link #stop()} to stop the stream.
*/
public class H263Stream extends VideoStream {
/**
* Constructs the H.263 stream.
* Uses CAMERA_FACING_BACK by default.
* @throws IOException
*/
public H263Stream() throws IOException {
this(CameraInfo.CAMERA_FACING_BACK);
}
/**
* Constructs the H.263 stream.
* @param cameraId Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
* @throws IOException
*/
public H263Stream(int cameraId) {
super(cameraId);
mCameraImageFormat = ImageFormat.NV21;
mVideoEncoder = MediaRecorder.VideoEncoder.H263;
mPacketizer = new H263Packetizer();
}
/**
* Starts the stream.
*/
public synchronized void start() throws IllegalStateException, IOException {
if (!mStreaming) {
configure();
super.start();
}
}
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mMode = MODE_MEDIARECORDER_API;
mQuality = mRequestedQuality.clone();
}
/**
* Returns a description of the stream using SDP. It can then be included in an SDP file.
*/
public String getSessionDescription() {
return "m=video "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 H263-1998/90000\r\n";
}
}
| 2,926 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
VideoQuality.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/video/VideoQuality.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.video;
import java.util.Iterator;
import java.util.List;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
/**
* A class that represents the quality of a video stream.
* It contains the resolution, the framerate (in fps) and the bitrate (in bps) of the stream.
*/
public class VideoQuality {
public final static String TAG = "VideoQuality";
/** Default video stream quality. */
public final static VideoQuality DEFAULT_VIDEO_QUALITY = new VideoQuality(176,144,20,500000);
/** Represents a quality for a video stream. */
public VideoQuality() {}
/**
* Represents a quality for a video stream.
* @param resX The horizontal resolution
* @param resY The vertical resolution
*/
public VideoQuality(int resX, int resY) {
this.resX = resX;
this.resY = resY;
}
/**
* Represents a quality for a video stream.
* @param resX The horizontal resolution
* @param resY The vertical resolution
* @param framerate The framerate in frame per seconds
* @param bitrate The bitrate in bit per seconds
*/
public VideoQuality(int resX, int resY, int framerate, int bitrate) {
this.framerate = framerate;
this.bitrate = bitrate;
this.resX = resX;
this.resY = resY;
}
public int framerate = 0;
public int bitrate = 0;
public int resX = 0;
public int resY = 0;
public boolean equals(VideoQuality quality) {
if (quality==null) return false;
return (quality.resX == this.resX &
quality.resY == this.resY &
quality.framerate == this.framerate &
quality.bitrate == this.bitrate);
}
public VideoQuality clone() {
return new VideoQuality(resX,resY,framerate,bitrate);
}
public static VideoQuality parseQuality(String str) {
VideoQuality quality = DEFAULT_VIDEO_QUALITY.clone();
if (str != null) {
String[] config = str.split("-");
try {
quality.bitrate = Integer.parseInt(config[0])*1000; // conversion to bit/s
quality.framerate = Integer.parseInt(config[1]);
quality.resX = Integer.parseInt(config[2]);
quality.resY = Integer.parseInt(config[3]);
}
catch (IndexOutOfBoundsException ignore) {}
}
return quality;
}
public String toString() {
return resX+"x"+resY+" px, "+framerate+" fps, "+bitrate/1000+" kbps";
}
/**
* Checks if the requested resolution is supported by the camera.
* If not, it modifies it by supported parameters.
**/
public static VideoQuality determineClosestSupportedResolution(Camera.Parameters parameters, VideoQuality quality) {
VideoQuality v = quality.clone();
int minDist = Integer.MAX_VALUE;
String supportedSizesStr = "Supported resolutions: ";
List<Size> supportedSizes = parameters.getSupportedPreviewSizes();
for (Iterator<Size> it = supportedSizes.iterator(); it.hasNext();) {
Size size = it.next();
supportedSizesStr += size.width+"x"+size.height+(it.hasNext()?", ":"");
int dist = Math.abs(quality.resX - size.width);
if (dist<minDist) {
minDist = dist;
v.resX = size.width;
v.resY = size.height;
}
}
Log.v(TAG, supportedSizesStr);
if (quality.resX != v.resX || quality.resY != v.resY) {
Log.v(TAG,"Resolution modified: "+quality.resX+"x"+quality.resY+"->"+v.resX+"x"+v.resY);
}
return v;
}
public static int[] determineMaximumSupportedFramerate(Camera.Parameters parameters) {
int[] maxFps = new int[]{0,0};
String supportedFpsRangesStr = "Supported frame rates: ";
List<int[]> supportedFpsRanges = parameters.getSupportedPreviewFpsRange();
for (Iterator<int[]> it = supportedFpsRanges.iterator(); it.hasNext();) {
int[] interval = it.next();
// Intervals are returned as integers, for example "29970" means "29.970" FPS.
supportedFpsRangesStr += interval[0]/1000+"-"+interval[1]/1000+"fps"+(it.hasNext()?", ":"");
if (interval[1]>maxFps[1] || (interval[0]>maxFps[0] && interval[1]==maxFps[1])) {
maxFps = interval;
}
}
Log.v(TAG,supportedFpsRangesStr);
return maxFps;
}
}
| 4,877 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
CodecManager.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/video/CodecManager.java | /*
* Copyright (C) 2011-2013 GUIGUI Simon, [email protected]
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.video;
import java.util.ArrayList;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.os.Build;
import android.util.Log;
import android.util.SparseArray;
@SuppressLint("InlinedApi")
public class CodecManager {
public final static String TAG = "CodecManager";
public static final int[] SUPPORTED_COLOR_FORMATS = {
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar
};
/**
* There currently is no way to know if an encoder is software or hardware from the MediaCodecInfo class,
* so we need to maintain a list of known software encoders.
*/
public static final String[] SOFTWARE_ENCODERS = {
"OMX.google.h264.encoder"
};
/**
* Contains a list of encoders and color formats that we may use with a {@link Translator}.
*/
static class Codecs {
/** A hardware encoder supporting a color format we can use. */
public String hardwareCodec;
public int hardwareColorFormat;
/** A software encoder supporting a color format we can use. */
public String softwareCodec;
public int softwareColorFormat;
}
/**
* Contains helper functions to choose an encoder and a color format.
*/
static class Selector {
private static HashMap<String,SparseArray<ArrayList<String>>> sHardwareCodecs = new HashMap<String, SparseArray<ArrayList<String>>>();
private static HashMap<String,SparseArray<ArrayList<String>>> sSoftwareCodecs = new HashMap<String, SparseArray<ArrayList<String>>>();
/**
* Determines the most appropriate encoder to compress the video from the Camera
*/
public static Codecs findCodecsFormMimeType(String mimeType, boolean tryColorFormatSurface) {
findSupportedColorFormats(mimeType);
SparseArray<ArrayList<String>> hardwareCodecs = sHardwareCodecs.get(mimeType);
SparseArray<ArrayList<String>> softwareCodecs = sSoftwareCodecs.get(mimeType);
Codecs list = new Codecs();
// On devices running 4.3, we need an encoder supporting the color format used to work with a Surface
if (Build.VERSION.SDK_INT>=18 && tryColorFormatSurface) {
int colorFormatSurface = MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface;
try {
// We want a hardware encoder
list.hardwareCodec = hardwareCodecs.get(colorFormatSurface).get(0);
list.hardwareColorFormat = colorFormatSurface;
} catch (Exception e) {}
try {
// We want a software encoder
list.softwareCodec = softwareCodecs.get(colorFormatSurface).get(0);
list.softwareColorFormat = colorFormatSurface;
} catch (Exception e) {}
if (list.hardwareCodec != null) {
Log.v(TAG,"Choosen primary codec: "+list.hardwareCodec+" with color format: "+list.hardwareColorFormat);
} else {
Log.e(TAG,"No supported hardware codec found !");
}
if (list.softwareCodec != null) {
Log.v(TAG,"Choosen secondary codec: "+list.hardwareCodec+" with color format: "+list.hardwareColorFormat);
} else {
Log.e(TAG,"No supported software codec found !");
}
return list;
}
for (int i=0;i<SUPPORTED_COLOR_FORMATS.length;i++) {
try {
list.hardwareCodec = hardwareCodecs.get(SUPPORTED_COLOR_FORMATS[i]).get(0);
list.hardwareColorFormat = SUPPORTED_COLOR_FORMATS[i];
break;
} catch (Exception e) {}
}
for (int i=0;i<SUPPORTED_COLOR_FORMATS.length;i++) {
try {
list.softwareCodec = softwareCodecs.get(SUPPORTED_COLOR_FORMATS[i]).get(0);
list.softwareColorFormat = SUPPORTED_COLOR_FORMATS[i];
break;
} catch (Exception e) {}
}
if (list.hardwareCodec != null) {
Log.v(TAG,"Choosen primary codec: "+list.hardwareCodec+" with color format: "+list.hardwareColorFormat);
} else {
Log.e(TAG,"No supported hardware codec found !");
}
if (list.softwareCodec != null) {
Log.v(TAG,"Choosen secondary codec: "+list.hardwareCodec+" with color format: "+list.softwareColorFormat);
} else {
Log.e(TAG,"No supported software codec found !");
}
return list;
}
/**
* Returns an associative array of the supported color formats and the names of the encoders for a given mime type
* This can take up to sec on certain phones the first time you run it...
**/
@SuppressLint("NewApi")
static private void findSupportedColorFormats(String mimeType) {
SparseArray<ArrayList<String>> softwareCodecs = new SparseArray<ArrayList<String>>();
SparseArray<ArrayList<String>> hardwareCodecs = new SparseArray<ArrayList<String>>();
if (sSoftwareCodecs.containsKey(mimeType)) {
return;
}
Log.v(TAG,"Searching supported color formats for mime type \""+mimeType+"\"...");
// We loop through the encoders, apparently this can take up to a sec (testes on a GS3)
for(int j = MediaCodecList.getCodecCount() - 1; j >= 0; j--){
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(j);
if (!codecInfo.isEncoder()) continue;
String[] types = codecInfo.getSupportedTypes();
for (int i = 0; i < types.length; i++) {
if (types[i].equalsIgnoreCase(mimeType)) {
MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
boolean software = false;
for (int k=0;k<SOFTWARE_ENCODERS.length;k++) {
if (codecInfo.getName().equalsIgnoreCase(SOFTWARE_ENCODERS[i])) {
software = true;
}
}
// And through the color formats supported
for (int k = 0; k < capabilities.colorFormats.length; k++) {
int format = capabilities.colorFormats[k];
if (software) {
if (softwareCodecs.get(format) == null) softwareCodecs.put(format, new ArrayList<String>());
softwareCodecs.get(format).add(codecInfo.getName());
} else {
if (hardwareCodecs.get(format) == null) hardwareCodecs.put(format, new ArrayList<String>());
hardwareCodecs.get(format).add(codecInfo.getName());
}
}
}
}
}
// Logs the supported color formats on the phone
StringBuilder e = new StringBuilder();
e.append("Supported color formats on this phone: ");
for (int i=0;i<softwareCodecs.size();i++) e.append(softwareCodecs.keyAt(i)+", ");
for (int i=0;i<hardwareCodecs.size();i++) e.append(hardwareCodecs.keyAt(i)+(i==hardwareCodecs.size()-1?".":", "));
Log.v(TAG, e.toString());
sSoftwareCodecs.put(mimeType, softwareCodecs);
sHardwareCodecs.put(mimeType, hardwareCodecs);
return;
}
}
static class Translator {
private int mOutputColorFormat;
private int mWidth;
private int mHeight;
private int mYStride;
private int mUVStride;
private int mYSize;
private int mUVSize;
private int bufferSize;
private int i;
private byte[] tmp;
public Translator(int outputColorFormat, int width, int height) {
mOutputColorFormat = outputColorFormat;
mWidth = width;
mHeight = height;
mYStride = (int) Math.ceil(mWidth / 16.0) * 16;
mUVStride = (int) Math.ceil( (mYStride / 2) / 16.0) * 16;
mYSize = mYStride * mHeight;
mUVSize = mUVStride * mHeight / 2;
bufferSize = mYSize + mUVSize * 2;
tmp = new byte[mUVSize*2];
}
public int getBufferSize() {
return bufferSize;
}
public int getUVStride() {
return mUVStride;
}
public int getYStride() {
return mYStride;
}
public byte[] translate(byte[] buffer) {
if (mOutputColorFormat == MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar) {
// FIXME: May be issues because of padding here :/
int wh4 = bufferSize/6; //wh4 = width*height/4
byte tmp;
for (i=wh4*4; i<wh4*5; i++) {
tmp = buffer[i];
buffer[i] = buffer[i+wh4];
buffer[i+wh4] = tmp;
}
}
else if (mOutputColorFormat == MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar) {
// We need to interleave the U and V channel
System.arraycopy(buffer, mYSize, tmp, 0, mUVSize*2); // Y
for (i = 0; i < mUVSize; i++) {
buffer[mYSize + i*2] = tmp[i + mUVSize]; // Cb (U)
buffer[mYSize + i*2+1] = tmp[i]; // Cr (V)
}
}
return buffer;
}
}
}
| 9,052 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
H264Stream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/video/H264Stream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.video;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.exceptions.ConfNotSupportedException;
import net.majorkernelpanic.streaming.exceptions.StorageUnavailableException;
import net.majorkernelpanic.streaming.hw.EncoderDebugger;
import net.majorkernelpanic.streaming.mp4.MP4Config;
import net.majorkernelpanic.streaming.rtp.H264Packetizer;
import android.annotation.SuppressLint;
import android.content.SharedPreferences.Editor;
import android.graphics.ImageFormat;
import android.hardware.Camera.CameraInfo;
import android.media.MediaRecorder;
import android.os.Environment;
import android.service.textservice.SpellCheckerService.Session;
import android.util.Base64;
import android.util.Log;
/**
* A class for streaming H.264 from the camera of an android device using RTP.
* You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
* Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setVideoQuality(VideoQuality)}
* to configure the stream. You can then call {@link #start()} to start the RTP stream.
* Call {@link #stop()} to stop the stream.
*/
public class H264Stream extends VideoStream {
public final static String TAG = "H264Stream";
private Semaphore mLock = new Semaphore(0);
private MP4Config mConfig;
/**
* Constructs the H.264 stream.
* Uses CAMERA_FACING_BACK by default.
*/
public H264Stream() {
this(CameraInfo.CAMERA_FACING_BACK);
}
/**
* Constructs the H.264 stream.
* @param cameraId Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
* @throws IOException
*/
public H264Stream(int cameraId) {
super(cameraId);
mMimeType = "video/avc";
mCameraImageFormat = ImageFormat.NV21;
mVideoEncoder = MediaRecorder.VideoEncoder.H264;
mPacketizer = new H264Packetizer();
}
/**
* Returns a description of the stream using SDP. It can then be included in an SDP file.
*/
public synchronized String getSessionDescription() throws IllegalStateException {
if (mConfig == null) throw new IllegalStateException("You need to call configure() first !");
return "m=video "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 H264/90000\r\n" +
"a=fmtp:96 packetization-mode=1;profile-level-id="+mConfig.getProfileLevel()+";sprop-parameter-sets="+mConfig.getB64SPS()+","+mConfig.getB64PPS()+";\r\n";
}
/**
* Starts the stream.
* This will also open the camera and display the preview if {@link #startPreview()} has not already been called.
*/
public synchronized void start() throws IllegalStateException, IOException {
if (!mStreaming) {
configure();
byte[] pps = Base64.decode(mConfig.getB64PPS(), Base64.NO_WRAP);
byte[] sps = Base64.decode(mConfig.getB64SPS(), Base64.NO_WRAP);
((H264Packetizer)mPacketizer).setStreamParameters(pps, sps);
super.start();
}
}
/**
* Configures the stream. You need to call this before calling {@link #getSessionDescription()} to apply
* your configuration of the stream.
*/
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mMode = mRequestedMode;
mQuality = mRequestedQuality.clone();
mConfig = testH264();
}
/**
* Tests if streaming with the given configuration (bit rate, frame rate, resolution) is possible
* and determines the pps and sps. Should not be called by the UI thread.
**/
private MP4Config testH264() throws IllegalStateException, IOException {
if (mMode != MODE_MEDIARECORDER_API) return testMediaCodecAPI();
else return testMediaRecorderAPI();
}
@SuppressLint("NewApi")
private MP4Config testMediaCodecAPI() throws RuntimeException, IOException {
createCamera();
updateCamera();
try {
if (mQuality.resX>=640) {
// Using the MediaCodec API with the buffer method for high resolutions is too slow
mMode = MODE_MEDIARECORDER_API;
}
EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY);
return new MP4Config(debugger.getB64SPS(), debugger.getB64PPS());
} catch (Exception e) {
// Fallback on the old streaming method using the MediaRecorder API
Log.e(TAG,"Resolution not supported with the MediaCodec API, we fallback on the old streamign method.");
mMode = MODE_MEDIARECORDER_API;
return testH264();
}
}
// Should not be called by the UI thread
private MP4Config testMediaRecorderAPI() throws RuntimeException, IOException {
String key = PREF_PREFIX+"h264-mr-"+mRequestedQuality.framerate+","+mRequestedQuality.resX+","+mRequestedQuality.resY;
if (mSettings != null) {
if (mSettings.contains(key)) {
String[] s = mSettings.getString(key, "").split(",");
return new MP4Config(s[0],s[1],s[2]);
}
}
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new StorageUnavailableException("No external storage or external storage not ready !");
}
final String TESTFILE = Environment.getExternalStorageDirectory().getPath()+"/spydroid-test.mp4";
Log.i(TAG,"Testing H264 support... Test file saved at: "+TESTFILE);
try {
File file = new File(TESTFILE);
file.createNewFile();
} catch (IOException e) {
throw new StorageUnavailableException(e.getMessage());
}
// Save flash state & set it to false so that led remains off while testing h264
boolean savedFlashState = mFlashEnabled;
mFlashEnabled = false;
boolean previewStarted = mPreviewStarted;
boolean cameraOpen = mCamera!=null;
createCamera();
// Stops the preview if needed
if (mPreviewStarted) {
lockCamera();
try {
mCamera.stopPreview();
} catch (Exception e) {}
mPreviewStarted = false;
}
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
unlockCamera();
try {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setVideoEncoder(mVideoEncoder);
mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface());
mMediaRecorder.setVideoSize(mRequestedQuality.resX,mRequestedQuality.resY);
mMediaRecorder.setVideoFrameRate(mRequestedQuality.framerate);
mMediaRecorder.setVideoEncodingBitRate((int)(mRequestedQuality.bitrate*0.8));
mMediaRecorder.setOutputFile(TESTFILE);
mMediaRecorder.setMaxDuration(3000);
// We wait a little and stop recording
mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.d(TAG,"MediaRecorder callback called !");
if (what==MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
Log.d(TAG,"MediaRecorder: MAX_DURATION_REACHED");
} else if (what==MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
Log.d(TAG,"MediaRecorder: MAX_FILESIZE_REACHED");
} else if (what==MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN) {
Log.d(TAG,"MediaRecorder: INFO_UNKNOWN");
} else {
Log.d(TAG,"WTF ?");
}
mLock.release();
}
});
// Start recording
mMediaRecorder.prepare();
mMediaRecorder.start();
if (mLock.tryAcquire(6,TimeUnit.SECONDS)) {
Log.d(TAG,"MediaRecorder callback was called :)");
Thread.sleep(400);
} else {
Log.d(TAG,"MediaRecorder callback was not called after 6 seconds... :(");
}
} catch (IOException e) {
throw new ConfNotSupportedException(e.getMessage());
} catch (RuntimeException e) {
throw new ConfNotSupportedException(e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
mMediaRecorder.stop();
} catch (Exception e) {}
mMediaRecorder.release();
mMediaRecorder = null;
lockCamera();
if (!cameraOpen) destroyCamera();
// Restore flash state
mFlashEnabled = savedFlashState;
if (previewStarted) {
// If the preview was started before the test, we try to restart it.
try {
startPreview();
} catch (Exception e) {}
}
}
// Retrieve SPS & PPS & ProfileId with MP4Config
MP4Config config = new MP4Config(TESTFILE);
// Delete dummy video
File file = new File(TESTFILE);
if (!file.delete()) Log.e(TAG,"Temp file could not be erased");
Log.i(TAG,"H264 Test succeded...");
// Save test result
if (mSettings != null) {
Editor editor = mSettings.edit();
editor.putString(key, config.getProfileLevel()+","+config.getB64SPS()+","+config.getB64PPS());
editor.commit();
}
return config;
}
}
| 9,777 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
VideoStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/video/VideoStream.java | /*
* Copyright (C) 2011-2015 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.video;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import net.majorkernelpanic.streaming.MediaStream;
import net.majorkernelpanic.streaming.Stream;
import net.majorkernelpanic.streaming.exceptions.CameraInUseException;
import net.majorkernelpanic.streaming.exceptions.ConfNotSupportedException;
import net.majorkernelpanic.streaming.exceptions.InvalidSurfaceException;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.hw.EncoderDebugger;
import net.majorkernelpanic.streaming.hw.NV21Convertor;
import net.majorkernelpanic.streaming.rtp.MediaCodecInputStream;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
/**
* Don't use this class directly.
*/
public abstract class VideoStream extends MediaStream {
protected final static String TAG = "VideoStream";
protected VideoQuality mRequestedQuality = VideoQuality.DEFAULT_VIDEO_QUALITY.clone();
protected VideoQuality mQuality = mRequestedQuality.clone();
protected Callback mSurfaceHolderCallback = null;
protected SurfaceView mSurfaceView = null;
protected SharedPreferences mSettings = null;
protected int mVideoEncoder, mCameraId = 0;
protected int mRequestedOrientation = 0, mOrientation = 0;
protected Camera mCamera;
protected Thread mCameraThread;
protected Looper mCameraLooper;
protected boolean mCameraOpenedManually = true;
protected boolean mFlashEnabled = false;
protected boolean mSurfaceReady = false;
protected boolean mUnlocked = false;
protected boolean mPreviewStarted = false;
protected boolean mUpdated = false;
protected String mMimeType;
protected String mEncoderName;
protected int mEncoderColorFormat;
protected int mCameraImageFormat;
protected int mMaxFps = 0;
/**
* Thread to draw on canvas
*/
private Thread canvasThread;
private Surface canvasSurface;
/**
* Don't use this class directly.
* Uses CAMERA_FACING_BACK by default.
*/
public VideoStream() {
this(CameraInfo.CAMERA_FACING_BACK);
}
/**
* Don't use this class directly
* @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
*/
@SuppressLint("InlinedApi")
public VideoStream(int camera) {
super();
setCamera(camera);
}
/**
* Sets the camera that will be used to capture video.
* You can call this method at any time and changes will take effect next time you start the stream.
* @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT
*/
public void setCamera(int camera) {
CameraInfo cameraInfo = new CameraInfo();
int numberOfCameras = Camera.getNumberOfCameras();
for (int i=0;i<numberOfCameras;i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == camera) {
mCameraId = i;
break;
}
}
}
/** Switch between the front facing and the back facing camera of the phone.
* If {@link #startPreview()} has been called, the preview will be briefly interrupted.
* If {@link #start()} has been called, the stream will be briefly interrupted.
* You should not call this method from the main thread if you are already streaming.
* @throws IOException
* @throws RuntimeException
**/
public void switchCamera() throws RuntimeException, IOException {
if (Camera.getNumberOfCameras() == 1) throw new IllegalStateException("Phone only has one camera !");
boolean streaming = mStreaming;
boolean previewing = mCamera!=null && mCameraOpenedManually;
mCameraId = (mCameraId == CameraInfo.CAMERA_FACING_BACK) ? CameraInfo.CAMERA_FACING_FRONT : CameraInfo.CAMERA_FACING_BACK;
setCamera(mCameraId);
stopPreview();
mFlashEnabled = false;
if (previewing) startPreview();
if (streaming) start();
}
/**
* Returns the id of the camera currently selected.
* Can be either {@link CameraInfo#CAMERA_FACING_BACK} or
* {@link CameraInfo#CAMERA_FACING_FRONT}.
*/
public int getCamera() {
return mCameraId;
}
/**
* Sets a Surface to show a preview of recorded media (video).
* You can call this method at any time and changes will take effect next time you call {@link #start()}.
*/
public synchronized void setSurfaceView(SurfaceView view) {
mSurfaceView = view;
if (mSurfaceHolderCallback != null && mSurfaceView != null && mSurfaceView.getHolder() != null) {
mSurfaceView.getHolder().removeCallback(mSurfaceHolderCallback);
}
if (mSurfaceView.getHolder() != null) {
mSurfaceHolderCallback = new Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceReady = false;
stopPreview();
Log.d(TAG,"Surface destroyed !");
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceReady = true;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.d(TAG,"Surface Changed !");
}
};
mSurfaceView.getHolder().addCallback(mSurfaceHolderCallback);
mSurfaceReady = true;
}
}
/** Turns the LED on or off if phone has one. */
public synchronized void setFlashState(boolean state) {
// If the camera has already been opened, we apply the change immediately
if (mCamera != null) {
if (mStreaming && mMode == MODE_MEDIARECORDER_API) {
lockCamera();
}
Parameters parameters = mCamera.getParameters();
// We test if the phone has a flash
if (parameters.getFlashMode()==null) {
// The phone has no flash or the choosen camera can not toggle the flash
throw new RuntimeException("Can't turn the flash on !");
} else {
parameters.setFlashMode(state?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF);
try {
mCamera.setParameters(parameters);
mFlashEnabled = state;
} catch (RuntimeException e) {
mFlashEnabled = false;
throw new RuntimeException("Can't turn the flash on !");
} finally {
if (mStreaming && mMode == MODE_MEDIARECORDER_API) {
unlockCamera();
}
}
}
} else {
mFlashEnabled = state;
}
}
/**
* Toggles the LED of the phone if it has one.
* You can get the current state of the flash with {@link VideoStream#getFlashState()}.
*/
public synchronized void toggleFlash() {
setFlashState(!mFlashEnabled);
}
/** Indicates whether or not the flash of the phone is on. */
public boolean getFlashState() {
return mFlashEnabled;
}
/**
* Sets the orientation of the preview.
* @param orientation The orientation of the preview
*/
public void setPreviewOrientation(int orientation) {
mRequestedOrientation = orientation;
mUpdated = false;
}
/**
* Sets the configuration of the stream. You can call this method at any time
* and changes will take effect next time you call {@link #configure()}.
* @param videoQuality Quality of the stream
*/
public void setVideoQuality(VideoQuality videoQuality) {
if (!mRequestedQuality.equals(videoQuality)) {
mRequestedQuality = videoQuality.clone();
mUpdated = false;
}
}
/**
* Returns the quality of the stream.
*/
public VideoQuality getVideoQuality() {
return mRequestedQuality;
}
/**
* Some data (SPS and PPS params) needs to be stored when {@link #getSessionDescription()} is called
* @param prefs The SharedPreferences that will be used to save SPS and PPS parameters
*/
public void setPreferences(SharedPreferences prefs) {
mSettings = prefs;
}
/**
* Configures the stream. You need to call this before calling {@link #getSessionDescription()}
* to apply your configuration of the stream.
*/
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mOrientation = mRequestedOrientation;
}
/**
* Starts the stream.
* This will also open the camera and display the preview
* if {@link #startPreview()} has not already been called.
*/
public synchronized void start() throws IllegalStateException, IOException {
if (!mPreviewStarted) mCameraOpenedManually = false;
super.start();
Log.d(TAG,"Stream configuration: FPS: "+mQuality.framerate+" Width: "+mQuality.resX+" Height: "+mQuality.resY);
}
/** Stops the stream. */
public synchronized void stop() {
if (mCamera != null) {
if (mMode == MODE_MEDIACODEC_API) {
mCamera.setPreviewCallbackWithBuffer(null);
}
if (mMode == MODE_MEDIACODEC_API_2) {
((SurfaceView)mSurfaceView).removeMediaCodecSurface();
}
super.stop();
// We need to restart the preview
if (!mCameraOpenedManually) {
destroyCamera();
} else {
try {
startPreview();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
public synchronized void startPreview()
throws CameraInUseException,
InvalidSurfaceException,
RuntimeException {
mCameraOpenedManually = true;
if (!mPreviewStarted) {
createCamera();
updateCamera();
}
}
/**
* Stops the preview.
*/
public synchronized void stopPreview() {
mCameraOpenedManually = false;
stop();
}
/**
* Video encoding is done by a MediaRecorder.
*/
protected void encodeWithMediaRecorder() throws IOException, ConfNotSupportedException {
Log.d(TAG,"Video encoded using the MediaRecorder API");
// We need a local socket to forward data output by the camera to the packetizer
createSockets();
// Reopens the camera if needed
destroyCamera();
createCamera();
// The camera must be unlocked before the MediaRecorder can use it
unlockCamera();
try {
mMediaRecorder = new MediaRecorder();
// mMediaRecorder.setCamera(mCamera);
// mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
Log.e(TAG, "HHQ use SURFACE");
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setVideoEncoder(mVideoEncoder);
mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface());
mMediaRecorder.setVideoSize(mRequestedQuality.resX, mRequestedQuality.resY);
mMediaRecorder.setVideoFrameRate(mRequestedQuality.framerate);
// The bandwidth actually consumed is often above what was requested
mMediaRecorder.setVideoEncodingBitRate((int) (mRequestedQuality.bitrate * 0.8));
// We write the output of the camera in a local socket instead of a file !
// This one little trick makes streaming feasible quiet simply: data from the camera
// can then be manipulated at the other end of the socket
FileDescriptor fd = null;
if (sPipeApi == PIPE_API_PFD) {
fd = mParcelWrite.getFileDescriptor();
} else {
fd = mSender.getFileDescriptor();
}
mMediaRecorder.setOutputFile(fd);
mMediaRecorder.prepare();
mMediaRecorder.start();
canvasSurface = mMediaRecorder.getSurface();
// canvasThread = new Thread(new MyTestThread(canvasSurface));
// canvasThread.start();
} catch (Exception e) {
throw new ConfNotSupportedException(e.getMessage());
}
InputStream is = null;
if (sPipeApi == PIPE_API_PFD) {
is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
} else {
is = mReceiver.getInputStream();
}
// This will skip the MPEG4 header if this step fails we can't stream anything :(
try {
byte buffer[] = new byte[4];
// Skip all atoms preceding mdat atom
while (!Thread.interrupted()) {
while (is.read() != 'm');
is.read(buffer,0,3);
if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't') break;
}
} catch (IOException e) {
Log.e(TAG,"Couldn't skip mp4 header :/");
stop();
throw e;
}
// The packetizer encapsulates the bit stream in an RTP stream and send it over the network
mPacketizer.setInputStream(is);
mPacketizer.start();
mStreaming = true;
}
/**
* Video encoding is done by a MediaCodec.
*/
protected void encodeWithMediaCodec() throws RuntimeException, IOException {
if (mMode == MODE_MEDIACODEC_API_2) {
// Uses the method MediaCodec.createInputSurface to feed the encoder
encodeWithMediaCodecMethod2();
} else {
// Uses dequeueInputBuffer to feed the encoder
encodeWithMediaCodecMethod1();
}
}
/**
* Video encoding is done by a MediaCodec.
*/
@SuppressLint("NewApi")
protected void encodeWithMediaCodecMethod1() throws RuntimeException, IOException {
Log.d(TAG,"Video encoded using the MediaCodec API with a buffer");
// Updates the parameters of the camera if needed
createCamera();
updateCamera();
// Estimates the frame rate of the camera
measureFramerate();
// Starts the preview if needed
if (!mPreviewStarted) {
try {
mCamera.startPreview();
mPreviewStarted = true;
} catch (RuntimeException e) {
destroyCamera();
throw e;
}
}
EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY);
final NV21Convertor convertor = debugger.getNV21Convertor();
mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName());
MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,debugger.getEncoderColorFormat());
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
Camera.PreviewCallback callback = new Camera.PreviewCallback() {
long now = System.nanoTime()/1000, oldnow = now, i=0;
ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
oldnow = now;
now = System.nanoTime()/1000;
if (i++>3) {
i = 0;
//Log.d(TAG,"Measured: "+1000000L/(now-oldnow)+" fps.");
}
try {
int bufferIndex = mMediaCodec.dequeueInputBuffer(500000);
if (bufferIndex>=0) {
inputBuffers[bufferIndex].clear();
if (data == null) Log.e(TAG,"Symptom of the \"Callback buffer was to small\" problem...");
else convertor.convert(data, inputBuffers[bufferIndex]);
mMediaCodec.queueInputBuffer(bufferIndex, 0, inputBuffers[bufferIndex].position(), now, 0);
} else {
Log.e(TAG,"No buffer available !");
}
} finally {
mCamera.addCallbackBuffer(data);
}
}
};
for (int i=0;i<10;i++) mCamera.addCallbackBuffer(new byte[convertor.getBufferSize()]);
mCamera.setPreviewCallbackWithBuffer(callback);
// The packetizer encapsulates the bit stream in an RTP stream and send it over the network
mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec));
mPacketizer.start();
mStreaming = true;
}
/**
* Video encoding is done by a MediaCodec.
* But here we will use the buffer-to-surface method
*/
@SuppressLint({ "InlinedApi", "NewApi" })
protected void encodeWithMediaCodecMethod2() throws RuntimeException, IOException {
Log.d(TAG,"Video encoded using the MediaCodec API with a surface");
// Updates the parameters of the camera if needed
createCamera();
updateCamera();
// Estimates the frame rate of the camera
measureFramerate();
EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY);
mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName());
MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
Surface surface = mMediaCodec.createInputSurface();
((SurfaceView)mSurfaceView).addMediaCodecSurface(surface);
mMediaCodec.start();
// The packetizer encapsulates the bit stream in an RTP stream and send it over the network
mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec));
mPacketizer.start();
mStreaming = true;
}
/**
* Returns a description of the stream using SDP.
* This method can only be called after {@link Stream#configure()}.
* @throws IllegalStateException Thrown when {@link Stream#configure()} wa not called.
*/
public abstract String getSessionDescription() throws IllegalStateException;
/**
* Opens the camera in a new Looper thread so that the preview callback is not called from the main thread
* If an exception is thrown in this Looper thread, we bring it back into the main thread.
* @throws RuntimeException Might happen if another app is already using the camera.
*/
private void openCamera() throws RuntimeException {
Log.e(TAG, "openCamera");
final Semaphore lock = new Semaphore(0);
final RuntimeException[] exception = new RuntimeException[1];
mCameraThread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
mCameraLooper = Looper.myLooper();
try {
mCamera = Camera.open(mCameraId);
} catch (RuntimeException e) {
exception[0] = e;
} finally {
lock.release();
Looper.loop();
}
}
});
mCameraThread.start();
lock.acquireUninterruptibly();
if (exception[0] != null) throw new CameraInUseException(exception[0].getMessage());
}
protected synchronized void createCamera() throws RuntimeException {
Log.e(TAG, "createCamera");
if (mSurfaceView == null)
throw new InvalidSurfaceException("Invalid surface !");
if (mSurfaceView.getHolder() == null || !mSurfaceReady)
throw new InvalidSurfaceException("Invalid surface !");
if (mCamera == null) {
openCamera();
mUpdated = false;
mUnlocked = false;
mCamera.setErrorCallback(new Camera.ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
// On some phones when trying to use the camera facing front the media server will die
// Whether or not this callback may be called really depends on the phone
if (error == Camera.CAMERA_ERROR_SERVER_DIED) {
// In this case the application must release the camera and instantiate a new one
Log.e(TAG,"Media server died !");
// We don't know in what thread we are so stop needs to be synchronized
mCameraOpenedManually = false;
stop();
} else {
Log.e(TAG,"Error unknown with the camera: "+error);
}
}
});
try {
// If the phone has a flash, we turn it on/off according to mFlashEnabled
// setRecordingHint(true) is a very nice optimization if you plane to only use the Camera for recording
Parameters parameters = mCamera.getParameters();
if (parameters.getFlashMode()!=null) {
parameters.setFlashMode(mFlashEnabled?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF);
}
parameters.setRecordingHint(true);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(mOrientation);
try {
if (mMode == MODE_MEDIACODEC_API_2) {
mSurfaceView.startGLThread();
mCamera.setPreviewTexture(mSurfaceView.getSurfaceTexture());
} else {
mCamera.setPreviewDisplay(mSurfaceView.getHolder());
}
} catch (IOException e) {
throw new InvalidSurfaceException("Invalid surface !");
}
} catch (RuntimeException e) {
destroyCamera();
throw e;
}
}
}
protected synchronized void destroyCamera() {
Log.e(TAG, "destroyCamera");
if (mCamera != null) {
if (mStreaming) super.stop();
lockCamera();
mCamera.stopPreview();
try {
mCamera.release();
} catch (Exception e) {
Log.e(TAG,e.getMessage()!=null?e.getMessage():"unknown error");
}
mCamera = null;
mCameraLooper.quit();
mUnlocked = false;
mPreviewStarted = false;
}
if(canvasThread != null && canvasThread.isAlive())
canvasThread.interrupt();
}
protected synchronized void updateCamera() throws RuntimeException {
Log.e(TAG, "updateCamera");
// The camera is already correctly configured
if (mUpdated) return;
if (mPreviewStarted) {
mPreviewStarted = false;
mCamera.stopPreview();
}
Parameters parameters = mCamera.getParameters();
mQuality = VideoQuality.determineClosestSupportedResolution(parameters, mQuality);
int[] max = VideoQuality.determineMaximumSupportedFramerate(parameters);
double ratio = (double)mQuality.resX/(double)mQuality.resY;
mSurfaceView.requestAspectRatio(ratio);
parameters.setPreviewFormat(mCameraImageFormat);
parameters.setPreviewSize(mQuality.resX, mQuality.resY);
parameters.setPreviewFpsRange(max[0], max[1]);
try {
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(mOrientation);
mCamera.startPreview();
mPreviewStarted = true;
mUpdated = true;
} catch (RuntimeException e) {
destroyCamera();
throw e;
}
}
protected void lockCamera() {
if (mUnlocked) {
Log.d(TAG,"Locking camera");
try {
mCamera.reconnect();
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
mUnlocked = false;
}
}
protected void unlockCamera() {
if (!mUnlocked) {
Log.d(TAG,"Unlocking camera");
try {
mCamera.unlock();
} catch (Exception e) {
Log.e(TAG,e.getMessage());
}
mUnlocked = true;
}
}
/**
* Computes the average frame rate at which the preview callback is called.
* We will then use this average frame rate with the MediaCodec.
* Blocks the thread in which this function is called.
*/
private void measureFramerate() {
final Semaphore lock = new Semaphore(0);
final Camera.PreviewCallback callback = new Camera.PreviewCallback() {
int i = 0, t = 0;
long now, oldnow, count = 0;
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
i++;
now = System.nanoTime()/1000;
if (i>3) {
t += now - oldnow;
count++;
}
if (i>20) {
mQuality.framerate = (int) (1000000/(t/count)+1);
lock.release();
}
oldnow = now;
}
};
mCamera.setPreviewCallback(callback);
try {
lock.tryAcquire(2,TimeUnit.SECONDS);
Log.d(TAG,"Actual framerate: "+mQuality.framerate);
if (mSettings != null) {
Editor editor = mSettings.edit();
editor.putInt(PREF_PREFIX+"fps"+mRequestedQuality.framerate+","+mCameraImageFormat+","+mRequestedQuality.resX+mRequestedQuality.resY, mQuality.framerate);
editor.commit();
}
} catch (InterruptedException e) {}
mCamera.setPreviewCallback(null);
}
public Surface getSurface(){
return canvasSurface;
}
public class MyTestThread implements Runnable{
private Surface surface;
public MyTestThread(Surface inputSurface){
surface = inputSurface;
}
@Override
public void run() {
Paint paint = new Paint();
paint.setTextSize(16);
paint.setColor(Color.RED);
int i;
/* Test: draw 10 frames at 30fps before start
* these should be dropped and not causing malformed stream.
*/
for(i = 0; i < 20000; i++) {
try{
if(!surface.isValid()) return;
Canvas canvas = surface.lockCanvas(null);
int background = (i * 255 / 99);
canvas.drawARGB(255, background, background, background);
canvas.drawRGB(125, 125, 125);
String text = "Frame #" + i;
canvas.drawText(text, 100, 100, paint);
Log.e(TAG, text);
surface.unlockCanvasAndPost(canvas);
}catch (Exception e){
e.printStackTrace();
return;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
| 25,329 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
RtcpDeinterleaver.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtsp/RtcpDeinterleaver.java | package net.majorkernelpanic.streaming.rtsp;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
class RtcpDeinterleaver extends InputStream implements Runnable {
public final static String TAG = "RtcpDeinterleaver";
private IOException mIOException;
private InputStream mInputStream;
private PipedInputStream mPipedInputStream;
private PipedOutputStream mPipedOutputStream;
private byte[] mBuffer;
public RtcpDeinterleaver(InputStream inputStream) {
mInputStream = inputStream;
mPipedInputStream = new PipedInputStream(4096);
try {
mPipedOutputStream = new PipedOutputStream(mPipedInputStream);
} catch (IOException e) {}
mBuffer = new byte[1024];
new Thread(this).start();
}
@Override
public void run() {
try {
while (true) {
int len = mInputStream.read(mBuffer, 0, 1024);
mPipedOutputStream.write(mBuffer, 0, len);
}
} catch (IOException e) {
try {
mPipedInputStream.close();
} catch (IOException ignore) {}
mIOException = e;
}
}
@Override
public int read(byte[] buffer) throws IOException {
if (mIOException != null) {
throw mIOException;
}
return mPipedInputStream.read(buffer);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (mIOException != null) {
throw mIOException;
}
return mPipedInputStream.read(buffer, offset, length);
}
@Override
public int read() throws IOException {
if (mIOException != null) {
throw mIOException;
}
return mPipedInputStream.read();
}
@Override
public void close() throws IOException {
mInputStream.close();
}
}
| 1,680 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
RtspServer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtsp/RtspServer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtsp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Implementation of a subset of the RTSP protocol (RFC 2326).
*
* It allows remote control of an android device cameras & microphone.
* For each connected client, a Session is instantiated.
* The Session will start or stop streams according to what the client wants.
*
*/
public class RtspServer extends Service {
public final static String TAG = "RtspServer";
/** The server name that will appear in responses. */
public static String SERVER_NAME = "MajorKernelPanic RTSP Server";
/** Port used by default. */
public static final int DEFAULT_RTSP_PORT = 8086;
/** Port already in use. */
public final static int ERROR_BIND_FAILED = 0x00;
/** A stream could not be started. */
public final static int ERROR_START_FAILED = 0x01;
/** Streaming started. */
public final static int MESSAGE_STREAMING_STARTED = 0X00;
/** Streaming stopped. */
public final static int MESSAGE_STREAMING_STOPPED = 0X01;
/** Key used in the SharedPreferences to store whether the RTSP server is enabled or not. */
public final static String KEY_ENABLED = "rtsp_enabled";
/** Key used in the SharedPreferences for the port used by the RTSP server. */
public final static String KEY_PORT = "rtsp_port";
protected SessionBuilder mSessionBuilder;
protected SharedPreferences mSharedPreferences;
protected boolean mEnabled = true;
protected int mPort = DEFAULT_RTSP_PORT;
protected WeakHashMap<Session,Object> mSessions = new WeakHashMap<Session,Object>(2);
private RequestListener mListenerThread;
private final IBinder mBinder = new LocalBinder();
private boolean mRestart = false;
private final LinkedList<CallbackListener> mListeners = new LinkedList<CallbackListener>();
public RtspServer() {
}
/** Be careful: those callbacks won't necessarily be called from the ui thread ! */
public interface CallbackListener {
/** Called when an error occurs. */
void onError(RtspServer server, Exception e, int error);
/** Called when streaming starts/stops. */
void onMessage(RtspServer server, int message);
}
/**
* See {@link CallbackListener} to check out what events will be fired once you set up a listener.
* @param listener The listener
*/
public void addCallbackListener(CallbackListener listener) {
synchronized (mListeners) {
if (mListeners.size() > 0) {
for (CallbackListener cl : mListeners) {
if (cl == listener) return;
}
}
mListeners.add(listener);
}
}
/**
* Removes the listener.
* @param listener The listener
*/
public void removeCallbackListener(CallbackListener listener) {
synchronized (mListeners) {
mListeners.remove(listener);
}
}
/** Returns the port used by the RTSP server. */
public int getPort() {
return mPort;
}
/**
* Sets the port for the RTSP server to use.
* @param port The port
*/
public void setPort(int port) {
Editor editor = mSharedPreferences.edit();
editor.putString(KEY_PORT, String.valueOf(port));
editor.commit();
}
/**
* Starts (or restart if needed, if for example the configuration
* of the server has been modified) the RTSP server.
*/
public void start() {
if (!mEnabled || mRestart) stop();
if (mEnabled && mListenerThread == null) {
try {
mListenerThread = new RequestListener();
} catch (Exception e) {
mListenerThread = null;
}
}
mRestart = false;
}
/**
* Stops the RTSP server but not the Android Service.
* To stop the Android Service you need to call {@link android.content.Context#stopService(Intent)};
*/
public void stop() {
if (mListenerThread != null) {
try {
mListenerThread.kill();
for ( Session session : mSessions.keySet() ) {
if ( session != null ) {
if (session.isStreaming()) session.stop();
}
}
} catch (Exception e) {
} finally {
mListenerThread = null;
}
}
}
/** Returns whether or not the RTSP server is streaming to some client(s). */
public boolean isStreaming() {
for ( Session session : mSessions.keySet() ) {
if ( session != null ) {
if (session.isStreaming()) return true;
}
}
return false;
}
public boolean isEnabled() {
return mEnabled;
}
/** Returns the bandwidth consumed by the RTSP server in bits per second. */
public long getBitrate() {
long bitrate = 0;
for ( Session session : mSessions.keySet() ) {
if ( session != null ) {
if (session.isStreaming()) bitrate += session.getBitrate();
}
}
return bitrate;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
// Let's restore the state of the service
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPort = Integer.parseInt(mSharedPreferences.getString(KEY_PORT, String.valueOf(mPort)));
mEnabled = mSharedPreferences.getBoolean(KEY_ENABLED, mEnabled);
// If the configuration is modified, the server will adjust
mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
start();
}
@Override
public void onDestroy() {
stop();
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
private OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PORT)) {
int port = Integer.parseInt(sharedPreferences.getString(KEY_PORT, String.valueOf(mPort)));
if (port != mPort) {
mPort = port;
mRestart = true;
start();
}
}
else if (key.equals(KEY_ENABLED)) {
mEnabled = sharedPreferences.getBoolean(KEY_ENABLED, mEnabled);
start();
}
}
};
/** The Binder you obtain when a connection with the Service is established. */
public class LocalBinder extends Binder {
public RtspServer getService() {
return RtspServer.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
protected void postMessage(int id) {
synchronized (mListeners) {
if (mListeners.size() > 0) {
for (CallbackListener cl : mListeners) {
cl.onMessage(this, id);
}
}
}
}
protected void postError(Exception exception, int id) {
synchronized (mListeners) {
if (mListeners.size() > 0) {
for (CallbackListener cl : mListeners) {
cl.onError(this, exception, id);
}
}
}
}
/**
* By default the RTSP uses {@link UriParser} to parse the URI requested by the client
* but you can change that behavior by override this method.
* @param uri The uri that the client has requested
* @param client The socket associated to the client
* @return A proper session
*/
protected Session handleRequest(String uri, Socket client) throws IllegalStateException, IOException {
Session session = UriParser.parse(uri);
session.setOrigin(client.getLocalAddress().getHostAddress());
if (session.getDestination()==null) {
session.setDestination(client.getInetAddress().getHostAddress());
}
return session;
}
class RequestListener extends Thread implements Runnable {
private final ServerSocket mServer;
public RequestListener() throws IOException {
try {
mServer = new ServerSocket(mPort);
start();
} catch (BindException e) {
Log.e(TAG,"Port already in use !");
postError(e, ERROR_BIND_FAILED);
throw e;
}
}
public void run() {
Log.i(TAG,"RTSP server listening on port "+mServer.getLocalPort());
while (!Thread.interrupted()) {
try {
new WorkerThread(mServer.accept()).start();
} catch (SocketException e) {
break;
} catch (IOException e) {
Log.e(TAG,e.getMessage());
continue;
}
}
Log.i(TAG,"RTSP server stopped !");
}
public void kill() {
try {
mServer.close();
} catch (IOException e) {}
try {
this.join();
} catch (InterruptedException ignore) {}
}
}
// One thread per client
class WorkerThread extends Thread implements Runnable {
private final Socket mClient;
private final OutputStream mOutput;
private final BufferedReader mInput;
// Each client has an associated session
private Session mSession;
public WorkerThread(final Socket client) throws IOException {
mInput = new BufferedReader(new InputStreamReader(client.getInputStream()));
mOutput = client.getOutputStream();
mClient = client;
mSession = new Session();
}
public void run() {
Request request;
Response response;
Log.i(TAG, "Connection from "+mClient.getInetAddress().getHostAddress());
while (!Thread.interrupted()) {
request = null;
response = null;
// Parse the request
try {
request = Request.parseRequest(mInput);
} catch (SocketException e) {
// Client has left
break;
} catch (Exception e) {
// We don't understand the request :/
response = new Response();
response.status = Response.STATUS_BAD_REQUEST;
}
// Do something accordingly like starting the streams, sending a session description
if (request != null) {
try {
response = processRequest(request);
}
catch (Exception e) {
// This alerts the main thread that something has gone wrong in this thread
postError(e, ERROR_START_FAILED);
Log.e(TAG,e.getMessage()!=null?e.getMessage():"An error occurred");
e.printStackTrace();
response = new Response(request);
}
}
// We always send a response
// The client will receive an "INTERNAL SERVER ERROR" if an exception has been thrown at some point
try {
response.send(mOutput);
} catch (IOException e) {
Log.e(TAG,"Response was not sent properly");
break;
}
}
// Streaming stops when client disconnects
boolean streaming = isStreaming();
mSession.syncStop();
if (streaming && !isStreaming()) {
postMessage(MESSAGE_STREAMING_STOPPED);
}
mSession.release();
try {
mClient.close();
} catch (IOException ignore) {}
Log.i(TAG, "Client disconnected");
}
public Response processRequest(Request request) throws IllegalStateException, IOException {
Response response = new Response(request);
/* ********************************************************************************** */
/* ********************************* Method DESCRIBE ******************************** */
/* ********************************************************************************** */
if (request.method.equalsIgnoreCase("DESCRIBE")) {
// Parse the requested URI and configure the session
mSession = handleRequest(request.uri, mClient);
mSessions.put(mSession, null);
mSession.syncConfigure();
String requestContent = mSession.getSessionDescription();
String requestAttributes =
"Content-Base: "+mClient.getLocalAddress().getHostAddress()+":"+mClient.getLocalPort()+"/\r\n" +
"Content-Type: application/sdp\r\n";
response.attributes = requestAttributes;
response.content = requestContent;
// If no exception has been thrown, we reply with OK
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************* Method OPTIONS ********************************* */
/* ********************************************************************************** */
else if (request.method.equalsIgnoreCase("OPTIONS")) {
response.status = Response.STATUS_OK;
response.attributes = "Public: DESCRIBE,SETUP,TEARDOWN,PLAY,PAUSE\r\n";
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************** Method SETUP ********************************** */
/* ********************************************************************************** */
else if (request.method.equalsIgnoreCase("SETUP")) {
Pattern p; Matcher m;
int p2, p1, ssrc, trackId, src[];
String destination;
p = Pattern.compile("trackID=(\\w+)",Pattern.CASE_INSENSITIVE);
m = p.matcher(request.uri);
if (!m.find()) {
response.status = Response.STATUS_BAD_REQUEST;
return response;
}
trackId = Integer.parseInt(m.group(1));
if (!mSession.trackExists(trackId)) {
response.status = Response.STATUS_NOT_FOUND;
return response;
}
p = Pattern.compile("client_port=(\\d+)-(\\d+)",Pattern.CASE_INSENSITIVE);
m = p.matcher(request.headers.get("transport"));
if (!m.find()) {
int[] ports = mSession.getTrack(trackId).getDestinationPorts();
p1 = ports[0];
p2 = ports[1];
}
else {
p1 = Integer.parseInt(m.group(1));
p2 = Integer.parseInt(m.group(2));
}
ssrc = mSession.getTrack(trackId).getSSRC();
src = mSession.getTrack(trackId).getLocalPorts();
destination = mSession.getDestination();
mSession.getTrack(trackId).setDestinationPorts(p1, p2);
boolean streaming = isStreaming();
mSession.syncStart(trackId);
if (!streaming && isStreaming()) {
postMessage(MESSAGE_STREAMING_STARTED);
}
response.attributes = "Transport: RTP/AVP/UDP;"+(InetAddress.getByName(destination).isMulticastAddress()?"multicast":"unicast")+
";destination="+mSession.getDestination()+
";client_port="+p1+"-"+p2+
";server_port="+src[0]+"-"+src[1]+
";ssrc="+Integer.toHexString(ssrc)+
";mode=play\r\n" +
"Session: "+ "1185d20035702ca" + "\r\n" +
"Cache-Control: no-cache\r\n";
response.status = Response.STATUS_OK;
// If no exception has been thrown, we reply with OK
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************** Method PLAY *********************************** */
/* ********************************************************************************** */
else if (request.method.equalsIgnoreCase("PLAY")) {
String requestAttributes = "RTP-Info: ";
if (mSession.trackExists(0)) requestAttributes += "url=rtsp://"+mClient.getLocalAddress().getHostAddress()+":"+mClient.getLocalPort()+"/trackID="+0+";seq=0,";
if (mSession.trackExists(1)) requestAttributes += "url=rtsp://"+mClient.getLocalAddress().getHostAddress()+":"+mClient.getLocalPort()+"/trackID="+1+";seq=0,";
requestAttributes = requestAttributes.substring(0, requestAttributes.length()-1) + "\r\nSession: 1185d20035702ca\r\n";
response.attributes = requestAttributes;
// If no exception has been thrown, we reply with OK
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************** Method PAUSE ********************************** */
/* ********************************************************************************** */
else if (request.method.equalsIgnoreCase("PAUSE")) {
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************* Method TEARDOWN ******************************** */
/* ********************************************************************************** */
else if (request.method.equalsIgnoreCase("TEARDOWN")) {
response.status = Response.STATUS_OK;
}
/* ********************************************************************************** */
/* ********************************* Unknown method ? ******************************* */
/* ********************************************************************************** */
else {
Log.e(TAG,"Command unknown: "+request);
response.status = Response.STATUS_BAD_REQUEST;
}
return response;
}
}
static class Request {
// Parse method & uri
public static final Pattern regexMethod = Pattern.compile("(\\w+) (\\S+) RTSP",Pattern.CASE_INSENSITIVE);
// Parse a request header
public static final Pattern rexegHeader = Pattern.compile("(\\S+):(.+)",Pattern.CASE_INSENSITIVE);
public String method;
public String uri;
public HashMap<String,String> headers = new HashMap<String,String>();
/** Parse the method, uri & headers of a RTSP request */
public static Request parseRequest(BufferedReader input) throws IOException, IllegalStateException, SocketException {
Request request = new Request();
String line;
Matcher matcher;
// Parsing request method & uri
if ((line = input.readLine())==null) throw new SocketException("Client disconnected");
matcher = regexMethod.matcher(line);
matcher.find();
request.method = matcher.group(1);
request.uri = matcher.group(2);
// Parsing headers of the request
while ( (line = input.readLine()) != null && line.length()>3 ) {
matcher = rexegHeader.matcher(line);
matcher.find();
request.headers.put(matcher.group(1).toLowerCase(Locale.US),matcher.group(2));
}
if (line==null) throw new SocketException("Client disconnected");
// It's not an error, it's just easier to follow what's happening in logcat with the request in red
Log.e(TAG,request.method+" "+request.uri);
return request;
}
}
static class Response {
// Status code definitions
public static final String STATUS_OK = "200 OK";
public static final String STATUS_BAD_REQUEST = "400 Bad Request";
public static final String STATUS_NOT_FOUND = "404 Not Found";
public static final String STATUS_INTERNAL_SERVER_ERROR = "500 Internal Server Error";
public String status = STATUS_INTERNAL_SERVER_ERROR;
public String content = "";
public String attributes = "";
private final Request mRequest;
public Response(Request request) {
this.mRequest = request;
}
public Response() {
// Be carefull if you modify the send() method because request might be null !
mRequest = null;
}
public void send(OutputStream output) throws IOException {
int seqid = -1;
try {
seqid = Integer.parseInt(mRequest.headers.get("cseq").replace(" ",""));
} catch (Exception e) {
Log.e(TAG,"Error parsing CSeq: "+(e.getMessage()!=null?e.getMessage():""));
}
String response = "RTSP/1.0 "+status+"\r\n" +
"Server: "+SERVER_NAME+"\r\n" +
(seqid>=0?("Cseq: " + seqid + "\r\n"):"") +
"Content-Length: " + content.length() + "\r\n" +
attributes +
"\r\n" +
content;
Log.d(TAG,response.replace("\r", ""));
output.write(response.getBytes());
}
}
}
| 20,510 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
UriParser.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtsp/UriParser.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtsp;
import static net.majorkernelpanic.streaming.SessionBuilder.AUDIO_AAC;
import static net.majorkernelpanic.streaming.SessionBuilder.AUDIO_AMRNB;
import static net.majorkernelpanic.streaming.SessionBuilder.AUDIO_NONE;
import static net.majorkernelpanic.streaming.SessionBuilder.VIDEO_H263;
import static net.majorkernelpanic.streaming.SessionBuilder.VIDEO_H264;
import static net.majorkernelpanic.streaming.SessionBuilder.VIDEO_NONE;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;
import net.majorkernelpanic.streaming.MediaStream;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.video.VideoQuality;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import android.hardware.Camera.CameraInfo;
/**
* This class parses URIs received by the RTSP server and configures a Session accordingly.
*/
public class UriParser {
public final static String TAG = "UriParser";
/**
* Configures a Session according to the given URI.
* Here are some examples of URIs that can be used to configure a Session:
* <ul><li>rtsp://xxx.xxx.xxx.xxx:8086?h264&flash=on</li>
* <li>rtsp://xxx.xxx.xxx.xxx:8086?h263&camera=front&flash=on</li>
* <li>rtsp://xxx.xxx.xxx.xxx:8086?h264=200-20-320-240</li>
* <li>rtsp://xxx.xxx.xxx.xxx:8086?aac</li></ul>
* @param uri The URI
* @throws IllegalStateException
* @throws IOException
* @return A Session configured according to the URI
*/
public static Session parse(String uri) throws IllegalStateException, IOException {
SessionBuilder builder = SessionBuilder.getInstance().clone();
byte audioApi = 0, videoApi = 0;
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri),"UTF-8");
if (params.size()>0) {
builder.setAudioEncoder(AUDIO_NONE).setVideoEncoder(VIDEO_NONE);
// Those parameters must be parsed first or else they won't necessarily be taken into account
for (Iterator<NameValuePair> it = params.iterator();it.hasNext();) {
NameValuePair param = it.next();
// FLASH ON/OFF
if (param.getName().equalsIgnoreCase("flash")) {
if (param.getValue().equalsIgnoreCase("on"))
builder.setFlashEnabled(true);
else
builder.setFlashEnabled(false);
}
// CAMERA -> the client can choose between the front facing camera and the back facing camera
else if (param.getName().equalsIgnoreCase("camera")) {
if (param.getValue().equalsIgnoreCase("back"))
builder.setCamera(CameraInfo.CAMERA_FACING_BACK);
else if (param.getValue().equalsIgnoreCase("front"))
builder.setCamera(CameraInfo.CAMERA_FACING_FRONT);
}
// MULTICAST -> the stream will be sent to a multicast group
// The default mutlicast address is 228.5.6.7, but the client can specify another
else if (param.getName().equalsIgnoreCase("multicast")) {
if (param.getValue()!=null) {
try {
InetAddress addr = InetAddress.getByName(param.getValue());
if (!addr.isMulticastAddress()) {
throw new IllegalStateException("Invalid multicast address !");
}
builder.setDestination(param.getValue());
} catch (UnknownHostException e) {
throw new IllegalStateException("Invalid multicast address !");
}
}
else {
// Default multicast address
builder.setDestination("228.5.6.7");
}
}
// UNICAST -> the client can use this to specify where he wants the stream to be sent
else if (param.getName().equalsIgnoreCase("unicast")) {
if (param.getValue()!=null) {
builder.setDestination(param.getValue());
}
}
// VIDEOAPI -> can be used to specify what api will be used to encode video (the MediaRecorder API or the MediaCodec API)
else if (param.getName().equalsIgnoreCase("videoapi")) {
if (param.getValue()!=null) {
if (param.getValue().equalsIgnoreCase("mr")) {
videoApi = MediaStream.MODE_MEDIARECORDER_API;
} else if (param.getValue().equalsIgnoreCase("mc")) {
videoApi = MediaStream.MODE_MEDIACODEC_API;
}
}
}
// AUDIOAPI -> can be used to specify what api will be used to encode audio (the MediaRecorder API or the MediaCodec API)
else if (param.getName().equalsIgnoreCase("audioapi")) {
if (param.getValue()!=null) {
if (param.getValue().equalsIgnoreCase("mr")) {
audioApi = MediaStream.MODE_MEDIARECORDER_API;
} else if (param.getValue().equalsIgnoreCase("mc")) {
audioApi = MediaStream.MODE_MEDIACODEC_API;
}
}
}
// TTL -> the client can modify the time to live of packets
// By default ttl=64
else if (param.getName().equalsIgnoreCase("ttl")) {
if (param.getValue()!=null) {
try {
int ttl = Integer.parseInt(param.getValue());
if (ttl<0) throw new IllegalStateException();
builder.setTimeToLive(ttl);
} catch (Exception e) {
throw new IllegalStateException("The TTL must be a positive integer !");
}
}
}
// H.264
else if (param.getName().equalsIgnoreCase("h264")) {
VideoQuality quality = VideoQuality.parseQuality(param.getValue());
builder.setVideoQuality(quality).setVideoEncoder(VIDEO_H264);
}
// H.263
else if (param.getName().equalsIgnoreCase("h263")) {
VideoQuality quality = VideoQuality.parseQuality(param.getValue());
builder.setVideoQuality(quality).setVideoEncoder(VIDEO_H263);
}
// AMR
else if (param.getName().equalsIgnoreCase("amrnb") || param.getName().equalsIgnoreCase("amr")) {
AudioQuality quality = AudioQuality.parseQuality(param.getValue());
builder.setAudioQuality(quality).setAudioEncoder(AUDIO_AMRNB);
}
// AAC
else if (param.getName().equalsIgnoreCase("aac")) {
AudioQuality quality = AudioQuality.parseQuality(param.getValue());
builder.setAudioQuality(quality).setAudioEncoder(AUDIO_AAC);
}
}
}
if (builder.getVideoEncoder()==VIDEO_NONE && builder.getAudioEncoder()==AUDIO_NONE) {
SessionBuilder b = SessionBuilder.getInstance();
builder.setVideoEncoder(b.getVideoEncoder());
builder.setAudioEncoder(b.getAudioEncoder());
}
Session session = builder.build();
if (videoApi>0 && session.getVideoTrack() != null) {
session.getVideoTrack().setStreamingMethod(videoApi);
}
if (audioApi>0 && session.getAudioTrack() != null) {
session.getAudioTrack().setStreamingMethod(audioApi);
}
return session;
}
}
| 7,640 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
RtspClient.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtsp/RtspClient.java | /*
* Copyright (C) 2011-2015 GUIGUI Simon, [email protected]
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtsp;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.Stream;
import net.majorkernelpanic.streaming.rtp.RtpSocket;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
/**
* RFC 2326.
* A basic and asynchronous RTSP client.
* The original purpose of this class was to implement a small RTSP client compatible with Wowza.
* It implements Digest Access Authentication according to RFC 2069.
*/
public class RtspClient {
public final static String TAG = "RtspClient";
/** Message sent when the connection to the RTSP server failed. */
public final static int ERROR_CONNECTION_FAILED = 0x01;
/** Message sent when the credentials are wrong. */
public final static int ERROR_WRONG_CREDENTIALS = 0x03;
/** Use this to use UDP for the transport protocol. */
public final static int TRANSPORT_UDP = RtpSocket.TRANSPORT_UDP;
/** Use this to use TCP for the transport protocol. */
public final static int TRANSPORT_TCP = RtpSocket.TRANSPORT_TCP;
/**
* Message sent when the connection with the RTSP server has been lost for
* some reason (for example, the user is going under a bridge).
* When the connection with the server is lost, the client will automatically try to
* reconnect as long as {@link #stopStream()} is not called.
**/
public final static int ERROR_CONNECTION_LOST = 0x04;
/**
* Message sent when the connection with the RTSP server has been reestablished.
* When the connection with the server is lost, the client will automatically try to
* reconnect as long as {@link #stopStream()} is not called.
*/
public final static int MESSAGE_CONNECTION_RECOVERED = 0x05;
private final static int STATE_STARTED = 0x00;
private final static int STATE_STARTING = 0x01;
private final static int STATE_STOPPING = 0x02;
private final static int STATE_STOPPED = 0x03;
private int mState = 0;
private class Parameters {
public String host;
public String username;
public String password;
public String path;
public Session session;
public int port;
public int transport;
public Parameters clone() {
Parameters params = new Parameters();
params.host = host;
params.username = username;
params.password = password;
params.path = path;
params.session = session;
params.port = port;
params.transport = transport;
return params;
}
}
private Parameters mTmpParameters;
private Parameters mParameters;
private int mCSeq;
private Socket mSocket;
private String mSessionID;
private String mAuthorization;
private BufferedReader mBufferedReader;
private OutputStream mOutputStream;
private Callback mCallback;
private Handler mMainHandler;
private Handler mHandler;
/**
* The callback interface you need to implement to know what's going on with the
* RTSP server (for example your Wowza Media Server).
*/
public interface Callback {
public void onRtspUpdate(int message, Exception exception);
}
public RtspClient() {
mCSeq = 0;
mTmpParameters = new Parameters();
mTmpParameters.port = 1935;
mTmpParameters.path = "/";
mTmpParameters.transport = TRANSPORT_UDP;
mAuthorization = null;
mCallback = null;
mMainHandler = new Handler(Looper.getMainLooper());
mState = STATE_STOPPED;
final Semaphore signal = new Semaphore(0);
new HandlerThread("net.majorkernelpanic.streaming.RtspClient"){
@Override
protected void onLooperPrepared() {
mHandler = new Handler();
signal.release();
}
}.start();
signal.acquireUninterruptibly();
}
/**
* Sets the callback interface that will be called on status updates of the connection
* with the RTSP server.
* @param cb The implementation of the {@link Callback} interface
*/
public void setCallback(Callback cb) {
mCallback = cb;
}
/**
* The {@link Session} that will be used to stream to the server.
* If not called before {@link #startStream()}, a it will be created.
*/
public void setSession(Session session) {
mTmpParameters.session = session;
}
public Session getSession() {
return mTmpParameters.session;
}
/**
* Sets the destination address of the RTSP server.
* @param host The destination address
* @param port The destination port
*/
public void setServerAddress(String host, int port) {
mTmpParameters.port = port;
mTmpParameters.host = host;
}
/**
* If authentication is enabled on the server, you need to call this with a valid login/password pair.
* Only implements Digest Access Authentication according to RFC 2069.
* @param username The login
* @param password The password
*/
public void setCredentials(String username, String password) {
mTmpParameters.username = username;
mTmpParameters.password = password;
}
/**
* The path to which the stream will be sent to.
* @param path The path
*/
public void setStreamPath(String path) {
mTmpParameters.path = path;
}
/**
* Call this with {@link #TRANSPORT_TCP} or {@value #TRANSPORT_UDP} to choose the
* transport protocol that will be used to send RTP/RTCP packets.
* Not ready yet !
*/
public void setTransportMode(int mode) {
mTmpParameters.transport = mode;
}
public boolean isStreaming() {
return mState==STATE_STARTED|mState==STATE_STARTING;
}
/**
* Connects to the RTSP server to publish the stream, and the effectively starts streaming.
* You need to call {@link #setServerAddress(String, int)} and optionally {@link #setSession(Session)}
* and {@link #setCredentials(String, String)} before calling this.
* Should be called of the main thread !
*/
public void startStream() {
if (mTmpParameters.host == null) throw new IllegalStateException("setServerAddress(String,int) has not been called !");
if (mTmpParameters.session == null) throw new IllegalStateException("setSession() has not been called !");
mHandler.post(new Runnable () {
@Override
public void run() {
if (mState != STATE_STOPPED) return;
mState = STATE_STARTING;
Log.d(TAG,"Connecting to RTSP server...");
// If the user calls some methods to configure the client, it won't modify its behavior until the stream is restarted
mParameters = mTmpParameters.clone();
mParameters.session.setDestination(mTmpParameters.host);
try {
mParameters.session.syncConfigure();
} catch (Exception e) {
mParameters.session = null;
mState = STATE_STOPPED;
return;
}
try {
tryConnection();
} catch (Exception e) {
postError(ERROR_CONNECTION_FAILED, e);
abort();
return;
}
try {
mParameters.session.syncStart();
mState = STATE_STARTED;
if (mParameters.transport == TRANSPORT_UDP) {
mHandler.post(mConnectionMonitor);
}
} catch (Exception e) {
abort();
}
}
});
}
/**
* Stops the stream, and informs the RTSP server.
*/
public void stopStream() {
mHandler.post(new Runnable () {
@Override
public void run() {
if (mParameters != null && mParameters.session != null) {
mParameters.session.stop();
}
if (mState != STATE_STOPPED) {
mState = STATE_STOPPING;
abort();
}
}
});
}
public void release() {
stopStream();
mHandler.getLooper().quit();
}
private void abort() {
try {
sendRequestTeardown();
} catch (Exception ignore) {}
try {
mSocket.close();
} catch (Exception ignore) {}
mHandler.removeCallbacks(mConnectionMonitor);
mHandler.removeCallbacks(mRetryConnection);
mState = STATE_STOPPED;
}
private void tryConnection() throws IOException {
mCSeq = 0;
mSocket = new Socket(mParameters.host, mParameters.port);
mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
mOutputStream = new BufferedOutputStream(mSocket.getOutputStream());
sendRequestAnnounce();
sendRequestSetup();
sendRequestRecord();
}
/**
* Forges and sends the ANNOUNCE request
*/
private void sendRequestAnnounce() throws IllegalStateException, SocketException, IOException {
String body = mParameters.session.getSessionDescription();
String request = "ANNOUNCE rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Content-Type: application/sdp\r\n\r\n" +
body;
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response response = Response.parseResponse(mBufferedReader);
if (response.headers.containsKey("server")) {
Log.v(TAG,"RTSP server name:" + response.headers.get("server"));
} else {
Log.v(TAG,"RTSP server name unknown");
}
if (response.headers.containsKey("session")) {
try {
Matcher m = Response.rexegSession.matcher(response.headers.get("session"));
m.find();
mSessionID = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server. Session id: "+mSessionID);
}
}
if (response.status == 401) {
String nonce, realm;
Matcher m;
if (mParameters.username == null || mParameters.password == null) throw new IllegalStateException("Authentication is enabled and setCredentials(String,String) was not called !");
try {
m = Response.rexegAuthenticate.matcher(response.headers.get("www-authenticate")); m.find();
nonce = m.group(2);
realm = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server");
}
String uri = "rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path;
String hash1 = computeMd5Hash(mParameters.username+":"+m.group(1)+":"+mParameters.password);
String hash2 = computeMd5Hash("ANNOUNCE"+":"+uri);
String hash3 = computeMd5Hash(hash1+":"+m.group(2)+":"+hash2);
mAuthorization = "Digest username=\""+mParameters.username+"\",realm=\""+realm+"\",nonce=\""+nonce+"\",uri=\""+uri+"\",response=\""+hash3+"\"";
request = "ANNOUNCE rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Authorization: " + mAuthorization + "\r\n" +
"Session: " + mSessionID + "\r\n" +
"Content-Type: application/sdp\r\n\r\n" +
body;
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
response = Response.parseResponse(mBufferedReader);
if (response.status == 401) throw new RuntimeException("Bad credentials !");
} else if (response.status == 403) {
throw new RuntimeException("Access forbidden !");
}
}
/**
* Forges and sends the SETUP request
*/
private void sendRequestSetup() throws IllegalStateException, SocketException, IOException {
for (int i=0;i<2;i++) {
Stream stream = mParameters.session.getTrack(i);
if (stream != null) {
String params = mParameters.transport==TRANSPORT_TCP ?
("TCP;interleaved="+2*i+"-"+(2*i+1)) : ("UDP;unicast;client_port="+(5000+2*i)+"-"+(5000+2*i+1)+";mode=receive");
String request = "SETUP rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+"/trackID="+i+" RTSP/1.0\r\n" +
"Transport: RTP/AVP/"+params+"\r\n" +
addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response response = Response.parseResponse(mBufferedReader);
Matcher m;
if (response.headers.containsKey("session")) {
try {
m = Response.rexegSession.matcher(response.headers.get("session"));
m.find();
mSessionID = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server. Session id: "+mSessionID);
}
}
if (mParameters.transport == TRANSPORT_UDP) {
try {
m = Response.rexegTransport.matcher(response.headers.get("transport")); m.find();
stream.setDestinationPorts(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)));
Log.d(TAG, "Setting destination ports: "+Integer.parseInt(m.group(3))+", "+Integer.parseInt(m.group(4)));
} catch (Exception e) {
e.printStackTrace();
int[] ports = stream.getDestinationPorts();
Log.d(TAG,"Server did not specify ports, using default ports: "+ports[0]+"-"+ports[1]);
}
} else {
stream.setOutputStream(mOutputStream, (byte)(2*i));
}
}
}
}
/**
* Forges and sends the RECORD request
*/
private void sendRequestRecord() throws IllegalStateException, SocketException, IOException {
String request = "RECORD rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"Range: npt=0.000-\r\n" +
addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response.parseResponse(mBufferedReader);
}
/**
* Forges and sends the TEARDOWN request
*/
private void sendRequestTeardown() throws IOException {
String request = "TEARDOWN rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" + addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
}
/**
* Forges and sends the OPTIONS request
*/
private void sendRequestOption() throws IOException {
String request = "OPTIONS rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" + addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response.parseResponse(mBufferedReader);
}
private String addHeaders() {
return "CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: 0\r\n" +
"Session: " + mSessionID + "\r\n" +
// For some reason you may have to remove last "\r\n" in the next line to make the RTSP client work with your wowza server :/
(mAuthorization != null ? "Authorization: " + mAuthorization + "\r\n":"") + "\r\n";
}
/**
* If the connection with the RTSP server is lost, we try to reconnect to it as
* long as {@link #stopStream()} is not called.
*/
private Runnable mConnectionMonitor = new Runnable() {
@Override
public void run() {
if (mState == STATE_STARTED) {
try {
// We poll the RTSP server with OPTION requests
sendRequestOption();
mHandler.postDelayed(mConnectionMonitor, 6000);
} catch (IOException e) {
// Happens if the OPTION request fails
postMessage(ERROR_CONNECTION_LOST);
Log.e(TAG, "Connection lost with the server...");
mParameters.session.stop();
mHandler.post(mRetryConnection);
}
}
}
};
/** Here, we try to reconnect to the RTSP. */
private Runnable mRetryConnection = new Runnable() {
@Override
public void run() {
if (mState == STATE_STARTED) {
try {
Log.e(TAG, "Trying to reconnect...");
tryConnection();
try {
mParameters.session.start();
mHandler.post(mConnectionMonitor);
postMessage(MESSAGE_CONNECTION_RECOVERED);
} catch (Exception e) {
abort();
}
} catch (IOException e) {
mHandler.postDelayed(mRetryConnection,1000);
}
}
}
};
final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
/** Needed for the Digest Access Authentication. */
private String computeMd5Hash(String buffer) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
return bytesToHex(md.digest(buffer.getBytes("UTF-8")));
} catch (NoSuchAlgorithmException ignore) {
} catch (UnsupportedEncodingException e) {}
return "";
}
private void postMessage(final int message) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onRtspUpdate(message, null);
}
}
});
}
private void postError(final int message, final Exception e) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onRtspUpdate(message, e);
}
}
});
}
static class Response {
// Parses method & uri
public static final Pattern regexStatus = Pattern.compile("RTSP/\\d.\\d (\\d+) (\\w+)",Pattern.CASE_INSENSITIVE);
// Parses a request header
public static final Pattern rexegHeader = Pattern.compile("(\\S+):(.+)",Pattern.CASE_INSENSITIVE);
// Parses a WWW-Authenticate header
public static final Pattern rexegAuthenticate = Pattern.compile("realm=\"(.+)\",\\s+nonce=\"(\\w+)\"",Pattern.CASE_INSENSITIVE);
// Parses a Session header
public static final Pattern rexegSession = Pattern.compile("(\\d+)",Pattern.CASE_INSENSITIVE);
// Parses a Transport header
public static final Pattern rexegTransport = Pattern.compile("client_port=(\\d+)-(\\d+).+server_port=(\\d+)-(\\d+)",Pattern.CASE_INSENSITIVE);
public int status;
public HashMap<String,String> headers = new HashMap<String,String>();
/** Parse the method, URI & headers of a RTSP request */
public static Response parseResponse(BufferedReader input) throws IOException, IllegalStateException, SocketException {
Response response = new Response();
String line;
Matcher matcher;
// Parsing request method & URI
if ((line = input.readLine())==null) throw new SocketException("Connection lost");
matcher = regexStatus.matcher(line);
matcher.find();
response.status = Integer.parseInt(matcher.group(1));
// Parsing headers of the request
while ( (line = input.readLine()) != null) {
//Log.e(TAG,"l: "+line.length()+", c: "+line);
if (line.length()>3) {
matcher = rexegHeader.matcher(line);
matcher.find();
response.headers.put(matcher.group(1).toLowerCase(Locale.US),matcher.group(2));
} else {
break;
}
}
if (line==null) throw new SocketException("Connection lost");
Log.d(TAG, "Response from server: "+response.status);
return response;
}
}
}
| 19,863 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
SurfaceView.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/gl/SurfaceView.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.gl;
import java.util.concurrent.Semaphore;
import net.majorkernelpanic.streaming.MediaStream;
import net.majorkernelpanic.streaming.video.VideoStream;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.graphics.SurfaceTexture.OnFrameAvailableListener;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
/**
* An enhanced SurfaceView in which the camera preview will be rendered.
* This class was needed for two reasons. <br />
*
* First, it allows to use to feed MediaCodec with the camera preview
* using the surface-to-buffer method while rendering it in a surface
* visible to the user. To force the surface-to-buffer method in
* libstreaming, call {@link MediaStream#setStreamingMethod(byte)}
* with {@link MediaStream#MODE_MEDIACODEC_API_2}. <br />
*
* Second, it allows to force the aspect ratio of the SurfaceView
* to match the aspect ratio of the camera preview, so that the
* preview do not appear distorted to the user of your app. To do
* that, call {@link SurfaceView#setAspectRatioMode(int)} with
* {@link SurfaceView#ASPECT_RATIO_PREVIEW} after creating your
* {@link SurfaceView}. <br />
*
*/
public class SurfaceView extends android.view.SurfaceView implements Runnable, OnFrameAvailableListener, SurfaceHolder.Callback {
public final static String TAG = "SurfaceView";
/**
* The aspect ratio of the surface view will be equal
* to the aspect ration of the camera preview.
**/
public static final int ASPECT_RATIO_PREVIEW = 0x01;
/** The surface view will fill completely fill its parent. */
public static final int ASPECT_RATIO_STRETCH = 0x00;
private Thread mThread = null;
private Handler mHandler = null;
private boolean mFrameAvailable = false;
private boolean mRunning = true;
private int mAspectRatioMode = ASPECT_RATIO_STRETCH;
// The surface in which the preview is rendered
private SurfaceManager mViewSurfaceManager = null;
// The input surface of the MediaCodec
private SurfaceManager mCodecSurfaceManager = null;
// Handles the rendering of the SurfaceTexture we got
// from the camera, onto a Surface
private TextureManager mTextureManager = null;
private final Semaphore mLock = new Semaphore(0);
private final Object mSyncObject = new Object();
// Allows to force the aspect ratio of the preview
private ViewAspectRatioMeasurer mVARM = new ViewAspectRatioMeasurer();
public SurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
mHandler = new Handler();
getHolder().addCallback(this);
}
public void setAspectRatioMode(int mode) {
mAspectRatioMode = mode;
}
public SurfaceTexture getSurfaceTexture() {
return mTextureManager.getSurfaceTexture();
}
public void addMediaCodecSurface(Surface surface) {
synchronized (mSyncObject) {
mCodecSurfaceManager = new SurfaceManager(surface,mViewSurfaceManager);
}
}
public void removeMediaCodecSurface() {
synchronized (mSyncObject) {
if (mCodecSurfaceManager != null) {
mCodecSurfaceManager.release();
mCodecSurfaceManager = null;
}
}
}
public void startGLThread() {
Log.d(TAG,"Thread started.");
if (mTextureManager == null) {
mTextureManager = new TextureManager();
}
if (mTextureManager.getSurfaceTexture() == null) {
mThread = new Thread(SurfaceView.this);
mRunning = true;
mThread.start();
mLock.acquireUninterruptibly();
}
}
@Override
public void run() {
mViewSurfaceManager = new SurfaceManager(getHolder().getSurface());
mViewSurfaceManager.makeCurrent();
mTextureManager.createTexture().setOnFrameAvailableListener(this);
mLock.release();
try {
long ts = 0, oldts = 0;
while (mRunning) {
synchronized (mSyncObject) {
mSyncObject.wait(2500);
if (mFrameAvailable) {
mFrameAvailable = false;
mViewSurfaceManager.makeCurrent();
mTextureManager.updateFrame();
mTextureManager.drawFrame();
mViewSurfaceManager.swapBuffer();
if (mCodecSurfaceManager != null) {
mCodecSurfaceManager.makeCurrent();
mTextureManager.drawFrame();
oldts = ts;
ts = mTextureManager.getSurfaceTexture().getTimestamp();
//Log.d(TAG,"FPS: "+(1000000000/(ts-oldts)));
mCodecSurfaceManager.setPresentationTime(ts);
mCodecSurfaceManager.swapBuffer();
}
} else {
Log.e(TAG,"No frame received !");
}
}
}
} catch (InterruptedException ignore) {
} finally {
mViewSurfaceManager.release();
mTextureManager.release();
}
}
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
synchronized (mSyncObject) {
mFrameAvailable = true;
mSyncObject.notifyAll();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mThread != null) {
mThread.interrupt();
}
mRunning = false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mVARM.getAspectRatio() > 0 && mAspectRatioMode == ASPECT_RATIO_PREVIEW) {
mVARM.measure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(mVARM.getMeasuredWidth(), mVARM.getMeasuredHeight());
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* Requests a certain aspect ratio for the preview. You don't have to call this yourself,
* the {@link VideoStream} will do it when it's needed.
*/
public void requestAspectRatio(double aspectRatio) {
if (mVARM.getAspectRatio() != aspectRatio) {
mVARM.setAspectRatio(aspectRatio);
mHandler.post(new Runnable() {
@Override
public void run() {
if (mAspectRatioMode == ASPECT_RATIO_PREVIEW) {
requestLayout();
}
}
});
}
}
/**
* This class is a helper to measure views that require a specific aspect ratio.
* @author Jesper Borgstrup
*/
public class ViewAspectRatioMeasurer {
private double aspectRatio;
public void setAspectRatio(double aspectRatio) {
this.aspectRatio = aspectRatio;
}
public double getAspectRatio() {
return this.aspectRatio;
}
/**
* Measure with the aspect ratio given at construction.<br />
* <br />
* After measuring, get the width and height with the {@link #getMeasuredWidth()}
* and {@link #getMeasuredHeight()} methods, respectively.
* @param widthMeasureSpec The width <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
* @param heightMeasureSpec The height <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
*/
public void measure(int widthMeasureSpec, int heightMeasureSpec) {
measure(widthMeasureSpec, heightMeasureSpec, this.aspectRatio);
}
/**
* Measure with a specific aspect ratio<br />
* <br />
* After measuring, get the width and height with the {@link #getMeasuredWidth()}
* and {@link #getMeasuredHeight()} methods, respectively.
* @param widthMeasureSpec The width <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
* @param heightMeasureSpec The height <tt>MeasureSpec</tt> passed in your <tt>View.onMeasure()</tt> method
* @param aspectRatio The aspect ratio to calculate measurements in respect to
*/
public void measure(int widthMeasureSpec, int heightMeasureSpec, double aspectRatio) {
int widthMode = MeasureSpec.getMode( widthMeasureSpec );
int widthSize = widthMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( widthMeasureSpec );
int heightMode = MeasureSpec.getMode( heightMeasureSpec );
int heightSize = heightMode == MeasureSpec.UNSPECIFIED ? Integer.MAX_VALUE : MeasureSpec.getSize( heightMeasureSpec );
if ( heightMode == MeasureSpec.EXACTLY && widthMode == MeasureSpec.EXACTLY ) {
/*
* Possibility 1: Both width and height fixed
*/
measuredWidth = widthSize;
measuredHeight = heightSize;
} else if ( heightMode == MeasureSpec.EXACTLY ) {
/*
* Possibility 2: Width dynamic, height fixed
*/
measuredWidth = (int) Math.min( widthSize, heightSize * aspectRatio );
measuredHeight = (int) (measuredWidth / aspectRatio);
} else if ( widthMode == MeasureSpec.EXACTLY ) {
/*
* Possibility 3: Width fixed, height dynamic
*/
measuredHeight = (int) Math.min( heightSize, widthSize / aspectRatio );
measuredWidth = (int) (measuredHeight * aspectRatio);
} else {
/*
* Possibility 4: Both width and height dynamic
*/
if ( widthSize > heightSize * aspectRatio ) {
measuredHeight = heightSize;
measuredWidth = (int)( measuredHeight * aspectRatio );
} else {
measuredWidth = widthSize;
measuredHeight = (int) (measuredWidth / aspectRatio);
}
}
}
private Integer measuredWidth = null;
/**
* Get the width measured in the latest call to <tt>measure()</tt>.
*/
public int getMeasuredWidth() {
if ( measuredWidth == null ) {
throw new IllegalStateException( "You need to run measure() before trying to get measured dimensions" );
}
return measuredWidth;
}
private Integer measuredHeight = null;
/**
* Get the height measured in the latest call to <tt>measure()</tt>.
*/
public int getMeasuredHeight() {
if ( measuredHeight == null ) {
throw new IllegalStateException( "You need to run measure() before trying to get measured dimensions" );
}
return measuredHeight;
}
}
}
| 10,550 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
SurfaceManager.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/gl/SurfaceManager.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Based on the work of fadden
*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.majorkernelpanic.streaming.gl;
import android.annotation.SuppressLint;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLExt;
import android.opengl.EGLSurface;
import android.opengl.GLES20;
import android.view.Surface;
@SuppressLint("NewApi")
public class SurfaceManager {
public final static String TAG = "TextureManager";
private static final int EGL_RECORDABLE_ANDROID = 0x3142;
private EGLContext mEGLContext = null;
private EGLContext mEGLSharedContext = null;
private EGLSurface mEGLSurface = null;
private EGLDisplay mEGLDisplay = null;
private Surface mSurface;
/**
* Creates an EGL context and an EGL surface.
*/
public SurfaceManager(Surface surface, SurfaceManager manager) {
mSurface = surface;
mEGLSharedContext = manager.mEGLContext;
eglSetup();
}
/**
* Creates an EGL context and an EGL surface.
*/
public SurfaceManager(Surface surface) {
mSurface = surface;
eglSetup();
}
public void makeCurrent() {
if (!EGL14.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext))
throw new RuntimeException("eglMakeCurrent failed");
}
public void swapBuffer() {
EGL14.eglSwapBuffers(mEGLDisplay, mEGLSurface);
}
/**
* Sends the presentation time stamp to EGL. Time is expressed in nanoseconds.
*/
public void setPresentationTime(long nsecs) {
EGLExt.eglPresentationTimeANDROID(mEGLDisplay, mEGLSurface, nsecs);
checkEglError("eglPresentationTimeANDROID");
}
/**
* Prepares EGL. We want a GLES 2.0 context and a surface that supports recording.
*/
private void eglSetup() {
mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if (mEGLDisplay == EGL14.EGL_NO_DISPLAY) {
throw new RuntimeException("unable to get EGL14 display");
}
int[] version = new int[2];
if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) {
throw new RuntimeException("unable to initialize EGL14");
}
// Configure EGL for recording and OpenGL ES 2.0.
int[] attribList;
if (mEGLSharedContext == null) {
attribList = new int[] {
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_NONE
};
} else {
attribList = new int[] {
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL_RECORDABLE_ANDROID, 1,
EGL14.EGL_NONE
};
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length,
numConfigs, 0);
checkEglError("eglCreateContext RGB888+recordable ES2");
// Configure context for OpenGL ES 2.0.
int[] attrib_list = {
EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
EGL14.EGL_NONE
};
if (mEGLSharedContext == null) {
mEGLContext = EGL14.eglCreateContext(mEGLDisplay, configs[0], EGL14.EGL_NO_CONTEXT, attrib_list, 0);
} else {
mEGLContext = EGL14.eglCreateContext(mEGLDisplay, configs[0], mEGLSharedContext, attrib_list, 0);
}
checkEglError("eglCreateContext");
// Create a window surface, and attach it to the Surface we received.
int[] surfaceAttribs = {
EGL14.EGL_NONE
};
mEGLSurface = EGL14.eglCreateWindowSurface(mEGLDisplay, configs[0], mSurface,
surfaceAttribs, 0);
checkEglError("eglCreateWindowSurface");
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDisable(GLES20.GL_CULL_FACE);
}
/**
* Discards all resources held by this class, notably the EGL context. Also releases the
* Surface that was passed to our constructor.
*/
public void release() {
if (mEGLDisplay != EGL14.EGL_NO_DISPLAY) {
EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_CONTEXT);
EGL14.eglDestroySurface(mEGLDisplay, mEGLSurface);
EGL14.eglDestroyContext(mEGLDisplay, mEGLContext);
EGL14.eglReleaseThread();
EGL14.eglTerminate(mEGLDisplay);
}
mEGLDisplay = EGL14.EGL_NO_DISPLAY;
mEGLContext = EGL14.EGL_NO_CONTEXT;
mEGLSurface = EGL14.EGL_NO_SURFACE;
mSurface.release();
}
/**
* Checks for EGL errors. Throws an exception if one is found.
*/
private void checkEglError(String msg) {
int error;
if ((error = EGL14.eglGetError()) != EGL14.EGL_SUCCESS) {
throw new RuntimeException(msg + ": EGL error: 0x" + Integer.toHexString(error));
}
}
}
| 6,060 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
TextureManager.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/gl/TextureManager.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Based on the work of fadden
*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.majorkernelpanic.streaming.gl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import android.annotation.SuppressLint;
import android.graphics.SurfaceTexture;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
/**
* Code for rendering a texture onto a surface using OpenGL ES 2.0.
*/
@SuppressLint("InlinedApi")
public class TextureManager {
public final static String TAG = "TextureManager";
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private final float[] mTriangleVerticesData = {
// X, Y, Z, U, V
-1.0f, -1.0f, 0, 0.f, 0.f,
1.0f, -1.0f, 0, 1.f, 0.f,
-1.0f, 1.0f, 0, 0.f, 1.f,
1.0f, 1.0f, 0, 1.f, 1.f,
};
private FloatBuffer mTriangleVertices;
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private static final String FRAGMENT_SHADER =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" + // highp here doesn't seem to matter
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
private float[] mMVPMatrix = new float[16];
private float[] mSTMatrix = new float[16];
private int mProgram;
private int mTextureID = -12345;
private int muMVPMatrixHandle;
private int muSTMatrixHandle;
private int maPositionHandle;
private int maTextureHandle;
private SurfaceTexture mSurfaceTexture;
public TextureManager() {
mTriangleVertices = ByteBuffer.allocateDirect(
mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mTriangleVertices.put(mTriangleVerticesData).position(0);
Matrix.setIdentityM(mSTMatrix, 0);
}
public int getTextureId() {
return mTextureID;
}
public SurfaceTexture getSurfaceTexture() {
return mSurfaceTexture;
}
public void updateFrame() {
mSurfaceTexture.updateTexImage();
}
public void drawFrame() {
checkGlError("onDrawFrame start");
mSurfaceTexture.getTransformMatrix(mSTMatrix);
//GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
//GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
checkGlError("glUseProgram");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID);
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maPosition");
GLES20.glEnableVertexAttribArray(maPositionHandle);
checkGlError("glEnableVertexAttribArray maPositionHandle");
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maTextureHandle");
GLES20.glEnableVertexAttribArray(maTextureHandle);
checkGlError("glEnableVertexAttribArray maTextureHandle");
Matrix.setIdentityM(mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawArrays");
GLES20.glFinish();
}
/**
* Initializes GL state. Call this after the EGL surface has been created and made current.
*/
public SurfaceTexture createTexture() {
mProgram = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
if (mProgram == 0) {
throw new RuntimeException("failed creating program");
}
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (maPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (maTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (muMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (muSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureID);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
checkGlError("glTexParameter");
mSurfaceTexture = new SurfaceTexture(mTextureID);
return mSurfaceTexture;
}
public void release() {
mSurfaceTexture = null;
}
/**
* Replaces the fragment shader. Pass in null to reset to default.
*/
public void changeFragmentShader(String fragmentShader) {
if (fragmentShader == null) {
fragmentShader = FRAGMENT_SHADER;
}
GLES20.glDeleteProgram(mProgram);
mProgram = createProgram(VERTEX_SHADER, fragmentShader);
if (mProgram == 0) {
throw new RuntimeException("failed creating program");
}
}
private int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
checkGlError("glCreateShader type=" + shaderType);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
Log.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
}
public void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
}
| 9,862 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AbstractPacketizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/AbstractPacketizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.Random;
import net.majorkernelpanic.streaming.rtcp.SenderReport;
/**
*
* Each packetizer inherits from this one and therefore uses RTP and UDP.
*
*/
abstract public class AbstractPacketizer {
protected static final int rtphl = RtpSocket.RTP_HEADER_LENGTH;
// Maximum size of RTP packets
protected final static int MAXPACKETSIZE = RtpSocket.MTU-28;
protected RtpSocket socket = null;
protected InputStream is = null;
protected byte[] buffer;
protected long ts = 0;
public AbstractPacketizer() {
int ssrc = new Random().nextInt();
ts = new Random().nextInt();
socket = new RtpSocket();
socket.setSSRC(ssrc);
}
public RtpSocket getRtpSocket() {
return socket;
}
public void setSSRC(int ssrc) {
socket.setSSRC(ssrc);
}
public int getSSRC() {
return socket.getSSRC();
}
public void setInputStream(InputStream is) {
this.is = is;
}
public void setTimeToLive(int ttl) throws IOException {
socket.setTimeToLive(ttl);
}
/**
* Sets the destination of the stream.
* @param dest The destination address of the stream
* @param rtpPort Destination port that will be used for RTP
* @param rtcpPort Destination port that will be used for RTCP
*/
public void setDestination(InetAddress dest, int rtpPort, int rtcpPort) {
socket.setDestination(dest, rtpPort, rtcpPort);
}
/** Starts the packetizer. */
public abstract void start();
/** Stops the packetizer. */
public abstract void stop();
/** Updates data for RTCP SR and sends the packet. */
protected void send(int length) throws IOException {
socket.commitBuffer(length);
}
/** For debugging purposes. */
protected static String printBuffer(byte[] buffer, int start,int end) {
String str = "";
for (int i=start;i<end;i++) str+=","+Integer.toHexString(buffer[i]&0xFF);
return str;
}
/** Used in packetizers to estimate timestamps in RTP packets. */
protected static class Statistics {
public final static String TAG = "Statistics";
private int count=700, c = 0;
private float m = 0, q = 0;
private long elapsed = 0;
private long start = 0;
private long duration = 0;
private long period = 10000000000L;
private boolean initoffset = false;
public Statistics() {}
public Statistics(int count, int period) {
this.count = count;
this.period = period;
}
public void reset() {
initoffset = false;
q = 0; m = 0; c = 0;
elapsed = 0;
start = 0;
duration = 0;
}
public void push(long value) {
elapsed += value;
if (elapsed>period) {
elapsed = 0;
long now = System.nanoTime();
if (!initoffset || (now - start < 0)) {
start = now;
duration = 0;
initoffset = true;
}
// Prevents drifting issues by comparing the real duration of the
// stream with the sum of all temporal lengths of RTP packets.
value += (now - start) - duration;
//Log.d(TAG, "sum1: "+duration/1000000+" sum2: "+(now-start)/1000000+" drift: "+((now-start)-duration)/1000000+" v: "+value/1000000);
}
if (c<5) {
// We ignore the first 20 measured values because they may not be accurate
c++;
m = value;
} else {
m = (m*q+value)/(q+1);
if (q<count) q++;
}
}
public long average() {
long l = (long)m;
duration += l;
return l;
}
}
}
| 4,341 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
MediaCodecInputStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/MediaCodecInputStream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import android.annotation.SuppressLint;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaFormat;
import android.util.Log;
/**
* An InputStream that uses data from a MediaCodec.
* The purpose of this class is to interface existing RTP packetizers of
* libstreaming with the new MediaCodec API. This class is not thread safe !
*/
@SuppressLint("NewApi")
public class MediaCodecInputStream extends InputStream {
public final String TAG = "MediaCodecInputStream";
private MediaCodec mMediaCodec = null;
private BufferInfo mBufferInfo = new BufferInfo();
private ByteBuffer[] mBuffers = null;
private ByteBuffer mBuffer = null;
private int mIndex = -1;
private boolean mClosed = false;
public MediaFormat mMediaFormat;
public MediaCodecInputStream(MediaCodec mediaCodec) {
mMediaCodec = mediaCodec;
mBuffers = mMediaCodec.getOutputBuffers();
}
@Override
public void close() {
mClosed = true;
}
@Override
public int read() throws IOException {
return 0;
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int min = 0;
try {
if (mBuffer==null) {
while (!Thread.interrupted() && !mClosed) {
mIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, 500000);
if (mIndex>=0 ){
//Log.d(TAG,"Index: "+mIndex+" Time: "+mBufferInfo.presentationTimeUs+" size: "+mBufferInfo.size);
mBuffer = mBuffers[mIndex];
mBuffer.position(0);
break;
} else if (mIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
mBuffers = mMediaCodec.getOutputBuffers();
} else if (mIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
mMediaFormat = mMediaCodec.getOutputFormat();
Log.i(TAG,mMediaFormat.toString());
} else if (mIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
Log.v(TAG,"No buffer available...");
//return 0;
} else {
Log.e(TAG,"Message: "+mIndex);
//return 0;
}
}
}
if (mClosed) throw new IOException("This InputStream was closed");
min = length < mBufferInfo.size - mBuffer.position() ? length : mBufferInfo.size - mBuffer.position();
mBuffer.get(buffer, offset, min);
if (mBuffer.position()>=mBufferInfo.size) {
mMediaCodec.releaseOutputBuffer(mIndex, false);
mBuffer = null;
}
} catch (RuntimeException e) {
e.printStackTrace();
}
return min;
}
public int available() {
if (mBuffer != null)
return mBufferInfo.size - mBuffer.position();
else
return 0;
}
public BufferInfo getLastBufferInfo() {
return mBufferInfo;
}
}
| 3,614 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AACLATMPacketizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/AACLATMPacketizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.media.MediaCodec.BufferInfo;
import android.os.SystemClock;
import android.util.Log;
/**
* RFC 3640.
*
* Encapsulates AAC Access Units in RTP packets as specified in the RFC 3640.
* This packetizer is used by the AACStream class in conjunction with the
* MediaCodec API introduced in Android 4.1 (API Level 16).
*
*/
@SuppressLint("NewApi")
public class AACLATMPacketizer extends AbstractPacketizer implements Runnable {
private final static String TAG = "AACLATMPacketizer";
private Thread t;
public AACLATMPacketizer() {
super();
socket.setCacheSize(0);
}
public void start() {
if (t==null) {
t = new Thread(this);
t.start();
}
}
public void stop() {
if (t != null) {
try {
is.close();
} catch (IOException ignore) {}
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {}
t = null;
}
}
public void setSamplingRate(int samplingRate) {
socket.setClockFrequency(samplingRate);
}
@SuppressLint("NewApi")
public void run() {
Log.d(TAG,"AAC LATM packetizer started !");
int length = 0;
long oldts;
BufferInfo bufferInfo;
try {
while (!Thread.interrupted()) {
buffer = socket.requestBuffer();
length = is.read(buffer, rtphl+4, MAXPACKETSIZE-(rtphl+4));
if (length>0) {
bufferInfo = ((MediaCodecInputStream)is).getLastBufferInfo();
//Log.d(TAG,"length: "+length+" ts: "+bufferInfo.presentationTimeUs);
oldts = ts;
ts = bufferInfo.presentationTimeUs*1000;
// Seems to happen sometimes
if (oldts>ts) {
socket.commitBuffer();
continue;
}
socket.markNextPacket();
socket.updateTimestamp(ts);
// AU-headers-length field: contains the size in bits of a AU-header
// 13+3 = 16 bits -> 13bits for AU-size and 3bits for AU-Index / AU-Index-delta
// 13 bits will be enough because ADTS uses 13 bits for frame length
buffer[rtphl] = 0;
buffer[rtphl+1] = 0x10;
// AU-size
buffer[rtphl+2] = (byte) (length>>5);
buffer[rtphl+3] = (byte) (length<<3);
// AU-Index
buffer[rtphl+3] &= 0xF8;
buffer[rtphl+3] |= 0x00;
send(rtphl+length+4);
} else {
socket.commitBuffer();
}
}
} catch (IOException e) {
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG,"ArrayIndexOutOfBoundsException: "+(e.getMessage()!=null?e.getMessage():"unknown error"));
e.printStackTrace();
} catch (InterruptedException ignore) {}
Log.d(TAG,"AAC LATM packetizer stopped !");
}
}
| 3,563 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
H263Packetizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/H263Packetizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import android.util.Log;
/**
* RFC 4629.
*
* H.263 Streaming over RTP.
*
* Must be fed with an InputStream containing H.263 frames.
* The stream must start with mpeg4 or 3gpp header, it will be skipped.
*
*/
public class H263Packetizer extends AbstractPacketizer implements Runnable {
public final static String TAG = "H263Packetizer";
private Statistics stats = new Statistics();
private Thread t;
public H263Packetizer() {
super();
socket.setClockFrequency(90000);
}
public void start() {
if (t==null) {
t = new Thread(this);
t.start();
}
}
public void stop() {
if (t != null) {
try {
is.close();
} catch (IOException ignore) {}
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {}
t = null;
}
}
public void run() {
long time, duration = 0;
int i = 0, j = 0, tr;
boolean firstFragment = true;
byte[] nextBuffer;
stats.reset();
try {
while (!Thread.interrupted()) {
if (j==0) buffer = socket.requestBuffer();
socket.updateTimestamp(ts);
// Each packet we send has a two byte long header (See section 5.1 of RFC 4629)
buffer[rtphl] = 0;
buffer[rtphl+1] = 0;
time = System.nanoTime();
if (fill(rtphl+j+2,MAXPACKETSIZE-rtphl-j-2)<0) return;
duration += System.nanoTime() - time;
j = 0;
// Each h263 frame starts with: 0000 0000 0000 0000 1000 00??
// Here we search where the next frame begins in the bit stream
for (i=rtphl+2;i<MAXPACKETSIZE-1;i++) {
if (buffer[i]==0 && buffer[i+1]==0 && (buffer[i+2]&0xFC)==0x80) {
j=i;
break;
}
}
// Parse temporal reference
tr = (buffer[i+2]&0x03)<<6 | (buffer[i+3]&0xFF)>>2;
//Log.d(TAG,"j: "+j+" buffer: "+printBuffer(rtphl, rtphl+5)+" tr: "+tr);
if (firstFragment) {
// This is the first fragment of the frame -> header is set to 0x0400
buffer[rtphl] = 4;
firstFragment = false;
} else {
buffer[rtphl] = 0;
}
if (j>0) {
// We have found the end of the frame
stats.push(duration);
ts+= stats.average(); duration = 0;
//Log.d(TAG,"End of frame ! duration: "+stats.average());
// The last fragment of a frame has to be marked
socket.markNextPacket();
send(j);
nextBuffer = socket.requestBuffer();
System.arraycopy(buffer,j+2,nextBuffer,rtphl+2,MAXPACKETSIZE-j-2);
buffer = nextBuffer;
j = MAXPACKETSIZE-j-2;
firstFragment = true;
} else {
// We have not found the beginning of another frame
// The whole packet is a fragment of a frame
send(MAXPACKETSIZE);
}
}
} catch (IOException e) {
} catch (InterruptedException e) {}
Log.d(TAG,"H263 Packetizer stopped !");
}
private int fill(int offset,int length) throws IOException {
int sum = 0, len;
while (sum<length) {
len = is.read(buffer, offset+sum, length-sum);
if (len<0) {
throw new IOException("End of stream");
}
else sum+=len;
}
return sum;
}
}
| 3,963 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
H264Packetizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/H264Packetizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.util.Log;
/**
*
* RFC 3984.
*
* H.264 streaming over RTP.
*
* Must be fed with an InputStream containing H.264 NAL units preceded by their length (4 bytes).
* The stream must start with mpeg4 or 3gpp header, it will be skipped.
*
*/
public class H264Packetizer extends AbstractPacketizer implements Runnable {
public final static String TAG = "H264Packetizer";
private Thread t = null;
private int naluLength = 0;
private long delay = 0, oldtime = 0;
private Statistics stats = new Statistics();
private byte[] sps = null, pps = null, stapa = null;
byte[] header = new byte[5];
private int count = 0;
private int streamType = 1;
public H264Packetizer() {
super();
socket.setClockFrequency(90000);
}
public void start() {
if (t == null) {
t = new Thread(this);
t.start();
}
}
public void stop() {
if (t != null) {
try {
is.close();
} catch (IOException e) {}
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {}
t = null;
}
}
public void setStreamParameters(byte[] pps, byte[] sps) {
this.pps = pps;
this.sps = sps;
// A STAP-A NAL (NAL type 24) containing the sps and pps of the stream
if (pps != null && sps != null) {
// STAP-A NAL header + NALU 1 (SPS) size + NALU 2 (PPS) size = 5 bytes
stapa = new byte[sps.length + pps.length + 5];
// STAP-A NAL header is 24
stapa[0] = 24;
// Write NALU 1 size into the array (NALU 1 is the SPS).
stapa[1] = (byte) (sps.length >> 8);
stapa[2] = (byte) (sps.length & 0xFF);
// Write NALU 2 size into the array (NALU 2 is the PPS).
stapa[sps.length + 3] = (byte) (pps.length >> 8);
stapa[sps.length + 4] = (byte) (pps.length & 0xFF);
// Write NALU 1 into the array, then write NALU 2 into the array.
System.arraycopy(sps, 0, stapa, 3, sps.length);
System.arraycopy(pps, 0, stapa, 5 + sps.length, pps.length);
}
}
public void run() {
long duration = 0;
Log.d(TAG,"H264 packetizer started !");
stats.reset();
count = 0;
if (is instanceof MediaCodecInputStream) {
streamType = 1;
socket.setCacheSize(0);
} else {
streamType = 0;
socket.setCacheSize(400);
}
try {
while (!Thread.interrupted()) {
oldtime = System.nanoTime();
// We read a NAL units from the input stream and we send them
send();
// We measure how long it took to receive NAL units from the phone
duration = System.nanoTime() - oldtime;
stats.push(duration);
// Computes the average duration of a NAL unit
delay = stats.average();
// Log.d(TAG,"duration: "+duration/1000000+" delay: "+delay/1000000);
}
} catch (IOException e) {
} catch (InterruptedException e) {}
Log.d(TAG,"H264 packetizer stopped !");
}
/**
* Reads a NAL unit in the FIFO and sends it.
* If it is too big, we split it in FU-A units (RFC 3984).
*/
@SuppressLint("NewApi")
private void send() throws IOException, InterruptedException {
int sum = 1, len = 0, type;
if (streamType == 0) {
// NAL units are preceeded by their length, we parse the length
fill(header,0,5);
ts += delay;
naluLength = header[3]&0xFF | (header[2]&0xFF)<<8 | (header[1]&0xFF)<<16 | (header[0]&0xFF)<<24;
if (naluLength>100000 || naluLength<0) resync();
// Log.e(TAG, "streamType: " + streamType + " nalulength: " + naluLength);
} else if (streamType == 1) {
// NAL units are preceeded with 0x00000001
fill(header,0,5);
ts = ((MediaCodecInputStream)is).getLastBufferInfo().presentationTimeUs*1000L;
//ts += delay;
naluLength = is.available()+1;
if (!(header[0]==0 && header[1]==0 && header[2]==0)) {
// Turns out, the NAL units are not preceeded with 0x00000001
Log.e(TAG, "NAL units are not preceeded by 0x00000001");
streamType = 2;
return;
}
} else {
// Nothing preceededs the NAL units
fill(header,0,1);
header[4] = header[0];
ts = ((MediaCodecInputStream)is).getLastBufferInfo().presentationTimeUs*1000L;
//ts += delay;
naluLength = is.available()+1;
}
// Parses the NAL unit type
type = header[4]&0x1F;
// The stream already contains NAL unit type 7 or 8, we don't need
// to add them to the stream ourselves
if (type == 7 || type == 8) {
Log.v(TAG,"SPS or PPS present in the stream.");
count++;
if (count>4) {
sps = null;
pps = null;
}
}
// We send two packets containing NALU type 7 (SPS) and 8 (PPS)
// Those should allow the H264 stream to be decoded even if no SDP was sent to the decoder.
if (type == 5 && sps != null && pps != null) {
buffer = socket.requestBuffer();
socket.markNextPacket();
socket.updateTimestamp(ts);
System.arraycopy(stapa, 0, buffer, rtphl, stapa.length);
super.send(rtphl+stapa.length);
}
//Log.d(TAG,"- Nal unit length: " + naluLength + " delay: "+delay/1000000+" type: "+type);
// Small NAL unit => Single NAL unit
if (naluLength<=MAXPACKETSIZE-rtphl-2) {
buffer = socket.requestBuffer();
buffer[rtphl] = header[4];
len = fill(buffer, rtphl+1, naluLength-1);
socket.updateTimestamp(ts);
socket.markNextPacket();
super.send(naluLength+rtphl);
//Log.d(TAG,"----- Single NAL unit - len:"+len+" delay: "+delay);
}
// Large NAL unit => Split nal unit
else {
// Set FU-A header
header[1] = (byte) (header[4] & 0x1F); // FU header type
header[1] += 0x80; // Start bit
// Set FU-A indicator
header[0] = (byte) ((header[4] & 0x60) & 0xFF); // FU indicator NRI
header[0] += 28;
while (sum < naluLength) {
buffer = socket.requestBuffer();
buffer[rtphl] = header[0];
buffer[rtphl+1] = header[1];
socket.updateTimestamp(ts);
if ((len = fill(buffer, rtphl+2, naluLength-sum > MAXPACKETSIZE-rtphl-2 ? MAXPACKETSIZE-rtphl-2 : naluLength-sum ))<0) return; sum += len;
// Last packet before next NAL
if (sum >= naluLength) {
// End bit on
buffer[rtphl+1] += 0x40;
socket.markNextPacket();
}
super.send(len+rtphl+2);
// Switch start bit
header[1] = (byte) (header[1] & 0x7F);
//Log.d(TAG,"----- FU-A unit, sum:"+sum);
}
}
}
private int fill(byte[] buffer, int offset,int length) throws IOException {
int sum = 0, len;
while (sum<length) {
len = is.read(buffer, offset+sum, length-sum);
if (len<0) {
throw new IOException("End of stream");
}
else sum+=len;
}
return sum;
}
private void resync() throws IOException {
int type;
Log.e(TAG,"Packetizer out of sync ! Let's try to fix that...(NAL length: "+naluLength+")");
while (true) {
header[0] = header[1];
header[1] = header[2];
header[2] = header[3];
header[3] = header[4];
header[4] = (byte) is.read();
type = header[4]&0x1F;
if (type == 5 || type == 1) {
naluLength = header[3]&0xFF | (header[2]&0xFF)<<8 | (header[1]&0xFF)<<16 | (header[0]&0xFF)<<24;
if (naluLength>0 && naluLength<100000) {
oldtime = System.nanoTime();
Log.e(TAG,"A NAL unit may have been found in the bit stream !");
break;
}
if (naluLength==0) {
Log.e(TAG,"NAL unit with NULL size found...");
} else if (header[3]==0xFF && header[2]==0xFF && header[1]==0xFF && header[0]==0xFF) {
Log.e(TAG,"NAL unit with 0xFFFFFFFF size found...");
}
}
}
}
} | 8,288 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AACADTSPacketizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/AACADTSPacketizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import net.majorkernelpanic.streaming.audio.AACStream;
import android.os.SystemClock;
import android.util.Log;
/**
*
* RFC 3640.
*
* This packetizer must be fed with an InputStream containing ADTS AAC.
* AAC will basically be rewrapped in an RTP stream and sent over the network.
* This packetizer only implements the aac-hbr mode (High Bit-rate AAC) and
* each packet only carry a single and complete AAC access unit.
*
*/
public class AACADTSPacketizer extends AbstractPacketizer implements Runnable {
private final static String TAG = "AACADTSPacketizer";
private Thread t;
private int samplingRate = 8000;
public AACADTSPacketizer() {
super();
}
public void start() {
if (t==null) {
t = new Thread(this);
t.start();
}
}
public void stop() {
if (t != null) {
try {
is.close();
} catch (IOException ignore) {}
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {}
t = null;
}
}
public void setSamplingRate(int samplingRate) {
this.samplingRate = samplingRate;
socket.setClockFrequency(samplingRate);
}
public void run() {
Log.d(TAG,"AAC ADTS packetizer started !");
// "A packet SHALL carry either one or more complete Access Units, or a
// single fragment of an Access Unit. Fragments of the same Access Unit
// have the same time stamp but different RTP sequence numbers. The
// marker bit in the RTP header is 1 on the last fragment of an Access
// Unit, and 0 on all other fragments." RFC 3640
// ADTS header fields that we need to parse
boolean protection;
int frameLength, sum, length, nbau, nbpk, samplingRateIndex, profile;
long oldtime = SystemClock.elapsedRealtime(), now = oldtime;
byte[] header = new byte[8];
try {
while (!Thread.interrupted()) {
// Synchronisation: ADTS packet starts with 12bits set to 1
while (true) {
if ( (is.read()&0xFF) == 0xFF ) {
header[1] = (byte) is.read();
if ( (header[1]&0xF0) == 0xF0) break;
}
}
// Parse adts header (ADTS packets start with a 7 or 9 byte long header)
fill(header, 2, 5);
// The protection bit indicates whether or not the header contains the two extra bytes
protection = (header[1]&0x01)>0 ? true : false;
frameLength = (header[3]&0x03) << 11 |
(header[4]&0xFF) << 3 |
(header[5]&0xFF) >> 5 ;
frameLength -= (protection ? 7 : 9);
// Number of AAC frames in the ADTS frame
nbau = (header[6]&0x03) + 1;
// The number of RTP packets that will be sent for this ADTS frame
nbpk = frameLength/MAXPACKETSIZE + 1;
// Read CRS if any
if (!protection) is.read(header,0,2);
samplingRate = AACStream.AUDIO_SAMPLING_RATES[(header[2]&0x3C) >> 2];
profile = ( (header[2]&0xC0) >> 6 ) + 1 ;
// We update the RTP timestamp
ts += 1024L*1000000000L/samplingRate; //stats.average();
//Log.d(TAG,"frameLength: "+frameLength+" protection: "+protection+" p: "+profile+" sr: "+samplingRate);
sum = 0;
while (sum<frameLength) {
buffer = socket.requestBuffer();
socket.updateTimestamp(ts);
// Read frame
if (frameLength-sum > MAXPACKETSIZE-rtphl-4) {
length = MAXPACKETSIZE-rtphl-4;
}
else {
length = frameLength-sum;
socket.markNextPacket();
}
sum += length;
fill(buffer, rtphl+4, length);
// AU-headers-length field: contains the size in bits of a AU-header
// 13+3 = 16 bits -> 13bits for AU-size and 3bits for AU-Index / AU-Index-delta
// 13 bits will be enough because ADTS uses 13 bits for frame length
buffer[rtphl] = 0;
buffer[rtphl+1] = 0x10;
// AU-size
buffer[rtphl+2] = (byte) (frameLength>>5);
buffer[rtphl+3] = (byte) (frameLength<<3);
// AU-Index
buffer[rtphl+3] &= 0xF8;
buffer[rtphl+3] |= 0x00;
send(rtphl+4+length);
}
}
} catch (IOException e) {
// Ignore
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG,"ArrayIndexOutOfBoundsException: "+(e.getMessage()!=null?e.getMessage():"unknown error"));
e.printStackTrace();
} catch (InterruptedException ignore) {}
Log.d(TAG,"AAC ADTS packetizer stopped !");
}
private int fill(byte[] buffer, int offset,int length) throws IOException {
int sum = 0, len;
while (sum<length) {
len = is.read(buffer, offset+sum, length-sum);
if (len<0) {
throw new IOException("End of stream");
}
else sum+=len;
}
return sum;
}
}
| 5,425 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
RtpSocket.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/RtpSocket.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import net.majorkernelpanic.streaming.rtcp.SenderReport;
import android.os.SystemClock;
import android.util.Log;
/**
* A basic implementation of an RTP socket.
* It implements a buffering mechanism, relying on a FIFO of buffers and a Thread.
* That way, if a packetizer tries to send many packets too quickly, the FIFO will
* grow and packets will be sent one by one smoothly.
*/
public class RtpSocket implements Runnable {
public static final String TAG = "RtpSocket";
/** Use this to use UDP for the transport protocol. */
public final static int TRANSPORT_UDP = 0x00;
/** Use this to use TCP for the transport protocol. */
public final static int TRANSPORT_TCP = 0x01;
public static final int RTP_HEADER_LENGTH = 12;
public static final int MTU = 1300;
private MulticastSocket mSocket;
private DatagramPacket[] mPackets;
private byte[][] mBuffers;
private long[] mTimestamps;
private SenderReport mReport;
private Semaphore mBufferRequested, mBufferCommitted;
private Thread mThread;
private int mTransport;
private long mCacheSize;
private long mClock = 0;
private long mOldTimestamp = 0;
private int mSsrc, mSeq = 0, mPort = -1;
private int mBufferCount, mBufferIn, mBufferOut;
private int mCount = 0;
private byte mTcpHeader[];
protected OutputStream mOutputStream = null;
private AverageBitrate mAverageBitrate;
/**
* This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread.
* @throws IOException
*/
public RtpSocket() {
mCacheSize = 0;
mBufferCount = 300; // TODO: readjust that when the FIFO is full
mBuffers = new byte[mBufferCount][];
mPackets = new DatagramPacket[mBufferCount];
mReport = new SenderReport();
mAverageBitrate = new AverageBitrate();
mTransport = TRANSPORT_UDP;
mTcpHeader = new byte[] {'$',0,0,0};
resetFifo();
for (int i=0; i<mBufferCount; i++) {
mBuffers[i] = new byte[MTU];
mPackets[i] = new DatagramPacket(mBuffers[i], 1);
/* Version(2) Padding(0) */
/* ^ ^ Extension(0) */
/* | | ^ */
/* | -------- | */
/* | |--------------------- */
/* | || -----------------------> Source Identifier(0) */
/* | || | */
mBuffers[i][0] = (byte) Integer.parseInt("10000000",2);
/* Payload Type */
mBuffers[i][1] = (byte) 96;
/* Byte 2,3 -> Sequence Number */
/* Byte 4,5,6,7 -> Timestamp */
/* Byte 8,9,10,11 -> Sync Source Identifier */
}
try {
mSocket = new MulticastSocket();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
private void resetFifo() {
mCount = 0;
mBufferIn = 0;
mBufferOut = 0;
mTimestamps = new long[mBufferCount];
mBufferRequested = new Semaphore(mBufferCount);
mBufferCommitted = new Semaphore(0);
mReport.reset();
mAverageBitrate.reset();
}
/** Closes the underlying socket. */
public void close() {
mSocket.close();
}
/** Sets the SSRC of the stream. */
public void setSSRC(int ssrc) {
this.mSsrc = ssrc;
for (int i=0;i<mBufferCount;i++) {
setLong(mBuffers[i], ssrc,8,12);
}
mReport.setSSRC(mSsrc);
}
/** Returns the SSRC of the stream. */
public int getSSRC() {
return mSsrc;
}
/** Sets the clock frequency of the stream in Hz. */
public void setClockFrequency(long clock) {
mClock = clock;
}
/** Sets the size of the FIFO in ms. */
public void setCacheSize(long cacheSize) {
mCacheSize = cacheSize;
}
/** Sets the Time To Live of the UDP packets. */
public void setTimeToLive(int ttl) throws IOException {
mSocket.setTimeToLive(ttl);
}
/** Sets the destination address and to which the packets will be sent. */
public void setDestination(InetAddress dest, int dport, int rtcpPort) {
if (dport != 0 && rtcpPort != 0) {
mTransport = TRANSPORT_UDP;
mPort = dport;
for (int i=0;i<mBufferCount;i++) {
mPackets[i].setPort(dport);
mPackets[i].setAddress(dest);
}
mReport.setDestination(dest, rtcpPort);
}
}
/**
* If a TCP is used as the transport protocol for the RTP session,
* the output stream to which RTP packets will be written to must
* be specified with this method.
*/
public void setOutputStream(OutputStream outputStream, byte channelIdentifier) {
if (outputStream != null) {
mTransport = TRANSPORT_TCP;
mOutputStream = outputStream;
mTcpHeader[1] = channelIdentifier;
mReport.setOutputStream(outputStream, (byte) (channelIdentifier+1));
}
}
public int getPort() {
return mPort;
}
public int[] getLocalPorts() {
return new int[] {
mSocket.getLocalPort(),
mReport.getLocalPort()
};
}
/**
* Returns an available buffer from the FIFO, it can then be modified.
* Call {@link #commitBuffer(int)} to send it over the network.
* @throws InterruptedException
**/
public byte[] requestBuffer() throws InterruptedException {
mBufferRequested.acquire();
mBuffers[mBufferIn][1] &= 0x7F;
return mBuffers[mBufferIn];
}
/** Puts the buffer back into the FIFO without sending the packet. */
public void commitBuffer() throws IOException {
if (mThread == null) {
mThread = new Thread(this);
mThread.start();
}
if (++mBufferIn>=mBufferCount) mBufferIn = 0;
mBufferCommitted.release();
}
/** Sends the RTP packet over the network. */
public void commitBuffer(int length) throws IOException {
updateSequence();
mPackets[mBufferIn].setLength(length);
mAverageBitrate.push(length);
if (++mBufferIn>=mBufferCount) mBufferIn = 0;
mBufferCommitted.release();
if (mThread == null) {
mThread = new Thread(this);
mThread.start();
}
}
/** Returns an approximation of the bitrate of the RTP stream in bits per second. */
public long getBitrate() {
return mAverageBitrate.average();
}
/** Increments the sequence number. */
private void updateSequence() {
setLong(mBuffers[mBufferIn], ++mSeq, 2, 4);
}
/**
* Overwrites the timestamp in the packet.
* @param timestamp The new timestamp in ns.
**/
public void updateTimestamp(long timestamp) {
mTimestamps[mBufferIn] = timestamp;
setLong(mBuffers[mBufferIn], (timestamp/100L)*(mClock/1000L)/10000L, 4, 8);
}
/** Sets the marker in the RTP packet. */
public void markNextPacket() {
mBuffers[mBufferIn][1] |= 0x80;
}
/** The Thread sends the packets in the FIFO one by one at a constant rate. */
@Override
public void run() {
Statistics stats = new Statistics(50,3000);
try {
// Caches mCacheSize milliseconds of the stream in the FIFO.
Thread.sleep(mCacheSize);
long delta = 0;
while (mBufferCommitted.tryAcquire(4,TimeUnit.SECONDS)) {
if (mOldTimestamp != 0) {
// We use our knowledge of the clock rate of the stream and the difference between two timestamps to
// compute the time lapse that the packet represents.
if ((mTimestamps[mBufferOut]-mOldTimestamp)>0) {
stats.push(mTimestamps[mBufferOut]-mOldTimestamp);
long d = stats.average()/1000000;
//Log.d(TAG,"delay: "+d+" d: "+(mTimestamps[mBufferOut]-mOldTimestamp)/1000000);
// We ensure that packets are sent at a constant and suitable rate no matter how the RtpSocket is used.
if (mCacheSize>0) Thread.sleep(d);
} else if ((mTimestamps[mBufferOut]-mOldTimestamp)<0) {
Log.e(TAG, "TS: "+mTimestamps[mBufferOut]+" OLD: "+mOldTimestamp);
}
delta += mTimestamps[mBufferOut]-mOldTimestamp;
if (delta>500000000 || delta<0) {
//Log.d(TAG,"permits: "+mBufferCommitted.availablePermits());
delta = 0;
}
}
mReport.update(mPackets[mBufferOut].getLength(), (mTimestamps[mBufferOut]/100L)*(mClock/1000L)/10000L);
mOldTimestamp = mTimestamps[mBufferOut];
if (mCount++>30) {
if (mTransport == TRANSPORT_UDP) {
mSocket.send(mPackets[mBufferOut]);
} else {
sendTCP();
}
}
if (++mBufferOut>=mBufferCount) mBufferOut = 0;
mBufferRequested.release();
}
} catch (Exception e) {
e.printStackTrace();
}
mThread = null;
resetFifo();
}
private void sendTCP() {
synchronized (mOutputStream) {
int len = mPackets[mBufferOut].getLength();
Log.d(TAG,"sent "+len);
mTcpHeader[2] = (byte) (len>>8);
mTcpHeader[3] = (byte) (len&0xFF);
try {
mOutputStream.write(mTcpHeader);
mOutputStream.write(mBuffers[mBufferOut], 0, len);
} catch (Exception e) {}
}
}
private void setLong(byte[] buffer, long n, int begin, int end) {
for (end--; end >= begin; end--) {
buffer[end] = (byte) (n % 256);
n >>= 8;
}
}
/**
* Computes an average bit rate.
**/
protected static class AverageBitrate {
private final static long RESOLUTION = 200;
private long mOldNow, mNow, mDelta;
private long[] mElapsed, mSum;
private int mCount, mIndex, mTotal;
private int mSize;
public AverageBitrate() {
mSize = 5000/((int)RESOLUTION);
reset();
}
public AverageBitrate(int delay) {
mSize = delay/((int)RESOLUTION);
reset();
}
public void reset() {
mSum = new long[mSize];
mElapsed = new long[mSize];
mNow = SystemClock.elapsedRealtime();
mOldNow = mNow;
mCount = 0;
mDelta = 0;
mTotal = 0;
mIndex = 0;
}
public void push(int length) {
mNow = SystemClock.elapsedRealtime();
if (mCount>0) {
mDelta += mNow - mOldNow;
mTotal += length;
if (mDelta>RESOLUTION) {
mSum[mIndex] = mTotal;
mTotal = 0;
mElapsed[mIndex] = mDelta;
mDelta = 0;
mIndex++;
if (mIndex>=mSize) mIndex = 0;
}
}
mOldNow = mNow;
mCount++;
}
public int average() {
long delta = 0, sum = 0;
for (int i=0;i<mSize;i++) {
sum += mSum[i];
delta += mElapsed[i];
}
//Log.d(TAG, "Time elapsed: "+delta);
return (int) (delta>0?8000*sum/delta:0);
}
}
/** Computes the proper rate at which packets are sent. */
protected static class Statistics {
public final static String TAG = "Statistics";
private int count=500, c = 0;
private float m = 0, q = 0;
private long elapsed = 0;
private long start = 0;
private long duration = 0;
private long period = 6000000000L;
private boolean initoffset = false;
public Statistics(int count, long period) {
this.count = count;
this.period = period*1000000L;
}
public void push(long value) {
duration += value;
elapsed += value;
if (elapsed>period) {
elapsed = 0;
long now = System.nanoTime();
if (!initoffset || (now - start < 0)) {
start = now;
duration = 0;
initoffset = true;
}
value -= (now - start) - duration;
//Log.d(TAG, "sum1: "+duration/1000000+" sum2: "+(now-start)/1000000+" drift: "+((now-start)-duration)/1000000+" v: "+value/1000000);
}
if (c<40) {
// We ignore the first 40 measured values because they may not be accurate
c++;
m = value;
} else {
m = (m*q+value)/(q+1);
if (q<count) q++;
}
}
public long average() {
long l = (long)m-2000000;
return l>0 ? l : 0;
}
}
}
| 12,293 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AMRNBPacketizer.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtp/AMRNBPacketizer.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtp;
import java.io.IOException;
import android.util.Log;
/**
*
* RFC 3267.
*
* AMR Streaming over RTP.
*
* Must be fed with an InputStream containing raw AMR NB
* Stream must begin with a 6 bytes long header: "#!AMR\n", it will be skipped
*
*/
public class AMRNBPacketizer extends AbstractPacketizer implements Runnable {
public final static String TAG = "AMRNBPacketizer";
private final int AMR_HEADER_LENGTH = 6; // "#!AMR\n"
private static final int AMR_FRAME_HEADER_LENGTH = 1; // Each frame has a short header
private static final int[] sFrameBits = {95, 103, 118, 134, 148, 159, 204, 244};
private int samplingRate = 8000;
private Thread t;
public AMRNBPacketizer() {
super();
socket.setClockFrequency(samplingRate);
}
public void start() {
if (t==null) {
t = new Thread(this);
t.start();
}
}
public void stop() {
if (t != null) {
try {
is.close();
} catch (IOException ignore) {}
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {}
t = null;
}
}
public void run() {
int frameLength, frameType;
long now = System.nanoTime(), oldtime = now;
byte[] header = new byte[AMR_HEADER_LENGTH];
try {
// Skip raw AMR header
fill(header,0,AMR_HEADER_LENGTH);
if (header[5] != '\n') {
Log.e(TAG,"Bad header ! AMR not correcty supported by the phone !");
return;
}
while (!Thread.interrupted()) {
buffer = socket.requestBuffer();
buffer[rtphl] = (byte) 0xF0;
// First we read the frame header
fill(buffer, rtphl+1,AMR_FRAME_HEADER_LENGTH);
// Then we calculate the frame payload length
frameType = (Math.abs(buffer[rtphl + 1]) >> 3) & 0x0f;
frameLength = (sFrameBits[frameType]+7)/8;
// And we read the payload
fill(buffer, rtphl+2,frameLength);
//Log.d(TAG,"Frame length: "+frameLength+" frameType: "+frameType);
// RFC 3267 Page 14: "For AMR, the sampling frequency is 8 kHz"
// FIXME: Is this really always the case ??
ts += 160L*1000000000L/samplingRate; //stats.average();
socket.updateTimestamp(ts);
socket.markNextPacket();
//Log.d(TAG,"expected: "+ expected + " measured: "+measured);
send(rtphl+1+AMR_FRAME_HEADER_LENGTH+frameLength);
}
} catch (IOException e) {
} catch (InterruptedException e) {}
Log.d(TAG,"AMR packetizer stopped !");
}
private int fill(byte[] buffer, int offset,int length) throws IOException {
int sum = 0, len;
while (sum<length) {
len = is.read(buffer, offset+sum, length-sum);
if (len<0) {
throw new IOException("End of stream");
}
else sum+=len;
}
return sum;
}
}
| 3,585 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AMRNBStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/audio/AMRNBStream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.audio;
import java.io.IOException;
import java.lang.reflect.Field;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.rtp.AMRNBPacketizer;
import android.media.MediaRecorder;
import android.service.textservice.SpellCheckerService.Session;
/**
* A class for streaming AAC from the camera of an android device using RTP.
* You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
* Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setAudioQuality(AudioQuality)}
* to configure the stream. You can then call {@link #start()} to start the RTP stream.
* Call {@link #stop()} to stop the stream.
*/
public class AMRNBStream extends AudioStream {
public AMRNBStream() {
super();
mPacketizer = new AMRNBPacketizer();
setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
try {
// RAW_AMR was deprecated in API level 16.
Field deprecatedName = MediaRecorder.OutputFormat.class.getField("RAW_AMR");
setOutputFormat(deprecatedName.getInt(null));
} catch (Exception e) {
setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
}
setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
/**
* Starts the stream.
*/
public synchronized void start() throws IllegalStateException, IOException {
if (!mStreaming) {
configure();
super.start();
}
}
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mMode = MODE_MEDIARECORDER_API;
mQuality = mRequestedQuality.clone();
}
/**
* Returns a description of the stream using SDP. It can then be included in an SDP file.
*/
public String getSessionDescription() {
return "m=audio "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 AMR/8000\r\n" +
"a=fmtp:96 octet-align=1;\r\n";
}
@Override
protected void encodeWithMediaCodec() throws IOException {
super.encodeWithMediaRecorder();
}
}
| 2,935 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AACStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/audio/AACStream.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.audio;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.rtp.AACADTSPacketizer;
import net.majorkernelpanic.streaming.rtp.AACLATMPacketizer;
import net.majorkernelpanic.streaming.rtp.MediaCodecInputStream;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.service.textservice.SpellCheckerService.Session;
import android.util.Log;
/**
* A class for streaming AAC from the camera of an android device using RTP.
* You should use a {@link Session} instantiated with {@link SessionBuilder} instead of using this class directly.
* Call {@link #setDestinationAddress(InetAddress)}, {@link #setDestinationPorts(int)} and {@link #setAudioQuality(AudioQuality)}
* to configure the stream. You can then call {@link #start()} to start the RTP stream.
* Call {@link #stop()} to stop the stream.
*/
public class AACStream extends AudioStream {
public final static String TAG = "AACStream";
/** MPEG-4 Audio Object Types supported by ADTS. **/
private static final String[] AUDIO_OBJECT_TYPES = {
"NULL", // 0
"AAC Main", // 1
"AAC LC (Low Complexity)", // 2
"AAC SSR (Scalable Sample Rate)", // 3
"AAC LTP (Long Term Prediction)" // 4
};
/** There are 13 supported frequencies by ADTS. **/
public static final int[] AUDIO_SAMPLING_RATES = {
96000, // 0
88200, // 1
64000, // 2
48000, // 3
44100, // 4
32000, // 5
24000, // 6
22050, // 7
16000, // 8
12000, // 9
11025, // 10
8000, // 11
7350, // 12
-1, // 13
-1, // 14
-1, // 15
};
private String mSessionDescription = null;
private int mProfile, mSamplingRateIndex, mChannel, mConfig;
private SharedPreferences mSettings = null;
private AudioRecord mAudioRecord = null;
private Thread mThread = null;
public AACStream() {
super();
if (!AACStreamingSupported()) {
Log.e(TAG,"AAC not supported on this phone");
throw new RuntimeException("AAC not supported by this phone !");
} else {
Log.d(TAG,"AAC supported on this phone");
}
}
private static boolean AACStreamingSupported() {
if (Build.VERSION.SDK_INT<14) return false;
try {
MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
return true;
} catch (Exception e) {
return false;
}
}
/**
* Some data (the actual sampling rate used by the phone and the AAC profile) needs to be stored once {@link #getSessionDescription()} is called.
* @param prefs The SharedPreferences that will be used to store the sampling rate
*/
public void setPreferences(SharedPreferences prefs) {
mSettings = prefs;
}
@Override
public synchronized void start() throws IllegalStateException, IOException {
if (!mStreaming) {
configure();
super.start();
}
}
public synchronized void configure() throws IllegalStateException, IOException {
super.configure();
mQuality = mRequestedQuality.clone();
// Checks if the user has supplied an exotic sampling rate
int i=0;
for (;i<AUDIO_SAMPLING_RATES.length;i++) {
if (AUDIO_SAMPLING_RATES[i] == mQuality.samplingRate) {
mSamplingRateIndex = i;
break;
}
}
// If he did, we force a reasonable one: 16 kHz
if (i>12) mQuality.samplingRate = 16000;
if (mMode != mRequestedMode || mPacketizer==null) {
mMode = mRequestedMode;
if (mMode == MODE_MEDIARECORDER_API) {
mPacketizer = new AACADTSPacketizer();
} else {
mPacketizer = new AACLATMPacketizer();
}
mPacketizer.setDestination(mDestination, mRtpPort, mRtcpPort);
mPacketizer.getRtpSocket().setOutputStream(mOutputStream, mChannelIdentifier);
}
if (mMode == MODE_MEDIARECORDER_API) {
testADTS();
// All the MIME types parameters used here are described in RFC 3640
// SizeLength: 13 bits will be enough because ADTS uses 13 bits for frame length
// config: contains the object type + the sampling rate + the channel number
// TODO: streamType always 5 ? profile-level-id always 15 ?
mSessionDescription = "m=audio "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 mpeg4-generic/"+mQuality.samplingRate+"\r\n"+
"a=fmtp:96 streamtype=5; profile-level-id=15; mode=AAC-hbr; config="+Integer.toHexString(mConfig)+"; SizeLength=13; IndexLength=3; IndexDeltaLength=3;\r\n";
} else {
mProfile = 2; // AAC LC
mChannel = 1;
mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;
mSessionDescription = "m=audio "+String.valueOf(getDestinationPorts()[0])+" RTP/AVP 96\r\n" +
"a=rtpmap:96 mpeg4-generic/"+mQuality.samplingRate+"\r\n"+
"a=fmtp:96 streamtype=5; profile-level-id=15; mode=AAC-hbr; config="+Integer.toHexString(mConfig)+"; SizeLength=13; IndexLength=3; IndexDeltaLength=3;\r\n";
}
}
@Override
protected void encodeWithMediaRecorder() throws IOException {
testADTS();
((AACADTSPacketizer)mPacketizer).setSamplingRate(mQuality.samplingRate);
super.encodeWithMediaRecorder();
}
@Override
@SuppressLint({ "InlinedApi", "NewApi" })
protected void encodeWithMediaCodec() throws IOException {
final int bufferSize = AudioRecord.getMinBufferSize(mQuality.samplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)*2;
((AACLATMPacketizer)mPacketizer).setSamplingRate(mQuality.samplingRate);
mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, mQuality.samplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
mMediaCodec = MediaCodec.createEncoderByType("audio/mp4a-latm");
MediaFormat format = new MediaFormat();
format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
format.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitRate);
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_SAMPLE_RATE, mQuality.samplingRate);
format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, bufferSize);
mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mAudioRecord.startRecording();
mMediaCodec.start();
final MediaCodecInputStream inputStream = new MediaCodecInputStream(mMediaCodec);
final ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers();
mThread = new Thread(new Runnable() {
@Override
public void run() {
int len = 0, bufferIndex = 0;
try {
while (!Thread.interrupted()) {
bufferIndex = mMediaCodec.dequeueInputBuffer(10000);
if (bufferIndex>=0) {
inputBuffers[bufferIndex].clear();
len = mAudioRecord.read(inputBuffers[bufferIndex], bufferSize);
if (len == AudioRecord.ERROR_INVALID_OPERATION || len == AudioRecord.ERROR_BAD_VALUE) {
Log.e(TAG,"An error occured with the AudioRecord API !");
} else {
//Log.v(TAG,"Pushing raw audio to the decoder: len="+len+" bs: "+inputBuffers[bufferIndex].capacity());
mMediaCodec.queueInputBuffer(bufferIndex, 0, len, System.nanoTime()/1000, 0);
}
}
}
} catch (RuntimeException e) {
e.printStackTrace();
}
}
});
mThread.start();
// The packetizer encapsulates this stream in an RTP stream and send it over the network
mPacketizer.setInputStream(inputStream);
mPacketizer.start();
mStreaming = true;
}
/** Stops the stream. */
public synchronized void stop() {
if (mStreaming) {
if (mMode==MODE_MEDIACODEC_API) {
Log.d(TAG, "Interrupting threads...");
mThread.interrupt();
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
}
super.stop();
}
}
/**
* Returns a description of the stream using SDP. It can then be included in an SDP file.
* Will fail if called when streaming.
*/
public String getSessionDescription() throws IllegalStateException {
if (mSessionDescription == null) throw new IllegalStateException("You need to call configure() first !");
return mSessionDescription;
}
/**
* Records a short sample of AAC ADTS from the microphone to find out what the sampling rate really is
* On some phone indeed, no error will be reported if the sampling rate used differs from the
* one selected with setAudioSamplingRate
* @throws IOException
* @throws IllegalStateException
*/
@SuppressLint("InlinedApi")
private void testADTS() throws IllegalStateException, IOException {
setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
Field name = MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
setOutputFormat(name.getInt(null));
}
catch (Exception ignore) {
setOutputFormat(6);
}
String key = PREF_PREFIX+"aac-"+mQuality.samplingRate;
if (mSettings!=null) {
if (mSettings.contains(key)) {
String[] s = mSettings.getString(key, "").split(",");
mQuality.samplingRate = Integer.valueOf(s[0]);
mConfig = Integer.valueOf(s[1]);
mChannel = Integer.valueOf(s[2]);
return;
}
}
final String TESTFILE = Environment.getExternalStorageDirectory().getPath()+"/spydroid-test.adts";
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new IllegalStateException("No external storage or external storage not ready !");
}
// The structure of an ADTS packet is described here: http://wiki.multimedia.cx/index.php?title=ADTS
// ADTS header is 7 or 9 bytes long
byte[] buffer = new byte[9];
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(mAudioSource);
mMediaRecorder.setOutputFormat(mOutputFormat);
mMediaRecorder.setAudioEncoder(mAudioEncoder);
mMediaRecorder.setAudioChannels(1);
mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
mMediaRecorder.setOutputFile(TESTFILE);
mMediaRecorder.setMaxDuration(1000);
mMediaRecorder.prepare();
mMediaRecorder.start();
// We record for 1 sec
// TODO: use the MediaRecorder.OnInfoListener
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
File file = new File(TESTFILE);
RandomAccessFile raf = new RandomAccessFile(file, "r");
// ADTS packets start with a sync word: 12bits set to 1
while (true) {
if ( (raf.readByte()&0xFF) == 0xFF ) {
buffer[0] = raf.readByte();
if ( (buffer[0]&0xF0) == 0xF0) break;
}
}
raf.read(buffer,1,5);
mSamplingRateIndex = (buffer[1]&0x3C)>>2 ;
mProfile = ( (buffer[1]&0xC0) >> 6 ) + 1 ;
mChannel = (buffer[1]&0x01) << 2 | (buffer[2]&0xC0) >> 6 ;
mQuality.samplingRate = AUDIO_SAMPLING_RATES[mSamplingRateIndex];
// 5 bits for the object type / 4 bits for the sampling rate / 4 bits for the channel / padding
mConfig = (mProfile & 0x1F) << 11 | (mSamplingRateIndex & 0x0F) << 7 | (mChannel & 0x0F) << 3;
Log.i(TAG,"MPEG VERSION: " + ( (buffer[0]&0x08) >> 3 ) );
Log.i(TAG,"PROTECTION: " + (buffer[0]&0x01) );
Log.i(TAG,"PROFILE: " + AUDIO_OBJECT_TYPES[ mProfile ] );
Log.i(TAG,"SAMPLING FREQUENCY: " + mQuality.samplingRate );
Log.i(TAG,"CHANNEL: " + mChannel );
raf.close();
if (mSettings!=null) {
Editor editor = mSettings.edit();
editor.putString(key, mQuality.samplingRate+","+mConfig+","+mChannel);
editor.commit();
}
if (!file.delete()) Log.e(TAG,"Temp file could not be erased");
}
}
| 12,763 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AudioQuality.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/audio/AudioQuality.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.audio;
/**
* A class that represents the quality of an audio stream.
*/
public class AudioQuality {
/** Default audio stream quality. */
public final static AudioQuality DEFAULT_AUDIO_QUALITY = new AudioQuality(8000,32000);
/** Represents a quality for a video stream. */
public AudioQuality() {}
/**
* Represents a quality for an audio stream.
* @param samplingRate The sampling rate
* @param bitRate The bitrate in bit per seconds
*/
public AudioQuality(int samplingRate, int bitRate) {
this.samplingRate = samplingRate;
this.bitRate = bitRate;
}
public int samplingRate = 0;
public int bitRate = 0;
public boolean equals(AudioQuality quality) {
if (quality==null) return false;
return (quality.samplingRate == this.samplingRate &
quality.bitRate == this.bitRate);
}
public AudioQuality clone() {
return new AudioQuality(samplingRate, bitRate);
}
public static AudioQuality parseQuality(String str) {
AudioQuality quality = DEFAULT_AUDIO_QUALITY.clone();
if (str != null) {
String[] config = str.split("-");
try {
quality.bitRate = Integer.parseInt(config[0])*1000; // conversion to bit/s
quality.samplingRate = Integer.parseInt(config[1]);
}
catch (IndexOutOfBoundsException ignore) {}
}
return quality;
}
}
| 2,205 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AudioStream.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/audio/AudioStream.java | /*
* Copyright (C) 2011-2015 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.audio;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import net.majorkernelpanic.streaming.MediaStream;
import android.media.MediaRecorder;
import android.os.ParcelFileDescriptor;
import android.util.Log;
/**
* Don't use this class directly.
*/
public abstract class AudioStream extends MediaStream {
protected int mAudioSource;
protected int mOutputFormat;
protected int mAudioEncoder;
protected AudioQuality mRequestedQuality = AudioQuality.DEFAULT_AUDIO_QUALITY.clone();
protected AudioQuality mQuality = mRequestedQuality.clone();
public AudioStream() {
setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
}
public void setAudioSource(int audioSource) {
mAudioSource = audioSource;
}
public void setAudioQuality(AudioQuality quality) {
mRequestedQuality = quality;
}
/**
* Returns the quality of the stream.
*/
public AudioQuality getAudioQuality() {
return mQuality;
}
protected void setAudioEncoder(int audioEncoder) {
mAudioEncoder = audioEncoder;
}
protected void setOutputFormat(int outputFormat) {
mOutputFormat = outputFormat;
}
@Override
protected void encodeWithMediaRecorder() throws IOException {
// We need a local socket to forward data output by the camera to the packetizer
createSockets();
Log.v(TAG,"Requested audio with "+mQuality.bitRate/1000+"kbps"+" at "+mQuality.samplingRate/1000+"kHz");
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(mAudioSource);
mMediaRecorder.setOutputFormat(mOutputFormat);
mMediaRecorder.setAudioEncoder(mAudioEncoder);
mMediaRecorder.setAudioChannels(1);
mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
// We write the output of the camera in a local socket instead of a file !
// This one little trick makes streaming feasible quiet simply: data from the camera
// can then be manipulated at the other end of the socket
FileDescriptor fd = null;
if (sPipeApi == PIPE_API_PFD) {
fd = mParcelWrite.getFileDescriptor();
} else {
fd = mSender.getFileDescriptor();
}
mMediaRecorder.setOutputFile(fd);
mMediaRecorder.setOutputFile(fd);
mMediaRecorder.prepare();
mMediaRecorder.start();
InputStream is = null;
if (sPipeApi == PIPE_API_PFD) {
is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
} else {
try {
// mReceiver.getInputStream contains the data from the camera
is = mReceiver.getInputStream();
} catch (IOException e) {
stop();
throw new IOException("Something happened with the local sockets :/ Start failed !");
}
}
// the mPacketizer encapsulates this stream in an RTP stream and send it over the network
mPacketizer.setInputStream(is);
mPacketizer.start();
mStreaming = true;
}
}
| 3,778 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
SenderReport.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/rtcp/SenderReport.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.rtcp;
import static net.majorkernelpanic.streaming.rtp.RtpSocket.TRANSPORT_TCP;
import static net.majorkernelpanic.streaming.rtp.RtpSocket.TRANSPORT_UDP;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.channels.IllegalSelectorException;
import android.os.SystemClock;
import android.util.Log;
/**
* Implementation of Sender Report RTCP packets.
*/
public class SenderReport {
public static final int MTU = 1500;
private static final int PACKET_LENGTH = 28;
private MulticastSocket usock;
private DatagramPacket upack;
private int mTransport;
private OutputStream mOutputStream = null;
private byte[] mBuffer = new byte[MTU];
private int mSSRC, mPort = -1;
private int mOctetCount = 0, mPacketCount = 0;
private long interval, delta, now, oldnow;
private byte mTcpHeader[];
public SenderReport(int ssrc) throws IOException {
super();
this.mSSRC = ssrc;
}
public SenderReport() {
mTransport = TRANSPORT_UDP;
mTcpHeader = new byte[] {'$',0,0,PACKET_LENGTH};
/* Version(2) Padding(0) */
/* ^ ^ PT = 0 */
/* | | ^ */
/* | -------- | */
/* | |--------------------- */
/* | || */
/* | || */
mBuffer[0] = (byte) Integer.parseInt("10000000",2);
/* Packet Type PT */
mBuffer[1] = (byte) 200;
/* Byte 2,3 -> Length */
setLong(PACKET_LENGTH/4-1, 2, 4);
/* Byte 4,5,6,7 -> SSRC */
/* Byte 8,9,10,11 -> NTP timestamp hb */
/* Byte 12,13,14,15 -> NTP timestamp lb */
/* Byte 16,17,18,19 -> RTP timestamp */
/* Byte 20,21,22,23 -> packet count */
/* Byte 24,25,26,27 -> octet count */
try {
usock = new MulticastSocket();
} catch (IOException e) {
// Very unlikely to happen. Means that all UDP ports are already being used
throw new RuntimeException(e.getMessage());
}
upack = new DatagramPacket(mBuffer, 1);
// By default we sent one report every 3 secconde
interval = 3000;
}
public void close() {
usock.close();
}
/**
* Sets the temporal interval between two RTCP Sender Reports.
* Default interval is set to 3 seconds.
* Set 0 to disable RTCP.
* @param interval The interval in milliseconds
*/
public void setInterval(long interval) {
this.interval = interval;
}
/**
* Updates the number of packets sent, and the total amount of data sent.
* @param length The length of the packet
* @param rtpts
* The RTP timestamp.
* @throws IOException
**/
public void update(int length, long rtpts) throws IOException {
mPacketCount += 1;
mOctetCount += length;
setLong(mPacketCount, 20, 24);
setLong(mOctetCount, 24, 28);
now = SystemClock.elapsedRealtime();
delta += oldnow != 0 ? now-oldnow : 0;
oldnow = now;
if (interval>0) {
if (delta>=interval) {
// We send a Sender Report
send(System.nanoTime(), rtpts);
delta = 0;
}
}
}
public void setSSRC(int ssrc) {
this.mSSRC = ssrc;
setLong(ssrc,4,8);
mPacketCount = 0;
mOctetCount = 0;
setLong(mPacketCount, 20, 24);
setLong(mOctetCount, 24, 28);
}
public void setDestination(InetAddress dest, int dport) {
mTransport = TRANSPORT_UDP;
mPort = dport;
upack.setPort(dport);
upack.setAddress(dest);
}
/**
* If a TCP is used as the transport protocol for the RTP session,
* the output stream to which RTP packets will be written to must
* be specified with this method.
*/
public void setOutputStream(OutputStream os, byte channelIdentifier) {
mTransport = TRANSPORT_TCP;
mOutputStream = os;
mTcpHeader[1] = channelIdentifier;
}
public int getPort() {
return mPort;
}
public int getLocalPort() {
return usock.getLocalPort();
}
public int getSSRC() {
return mSSRC;
}
/**
* Resets the reports (total number of bytes sent, number of packets sent, etc.)
*/
public void reset() {
mPacketCount = 0;
mOctetCount = 0;
setLong(mPacketCount, 20, 24);
setLong(mOctetCount, 24, 28);
delta = now = oldnow = 0;
}
private void setLong(long n, int begin, int end) {
for (end--; end >= begin; end--) {
mBuffer[end] = (byte) (n % 256);
n >>= 8;
}
}
/**
* Sends the RTCP packet over the network.
*
* @param ntpts
* the NTP timestamp.
* @param rtpts
* the RTP timestamp.
*/
private void send(long ntpts, long rtpts) throws IOException {
long hb = ntpts/1000000000;
long lb = ( ( ntpts - hb*1000000000 ) * 4294967296L )/1000000000;
setLong(hb, 8, 12);
setLong(lb, 12, 16);
setLong(rtpts, 16, 20);
if (mTransport == TRANSPORT_UDP) {
upack.setLength(PACKET_LENGTH);
usock.send(upack);
} else {
synchronized (mOutputStream) {
try {
mOutputStream.write(mTcpHeader);
mOutputStream.write(mBuffer, 0, PACKET_LENGTH);
} catch (Exception e) {}
}
}
}
}
| 6,024 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
EncoderDebugger.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/hw/EncoderDebugger.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.hw;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import net.majorkernelpanic.streaming.hw.CodecManager.Codec;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
/**
*
* The purpose of this class is to detect and by-pass some bugs (or underspecified configuration) that
* encoders available through the MediaCodec API may have. <br />
* Feeding the encoder with a surface is not tested here.
* Some bugs you may have encountered:<br />
* <ul>
* <li>U and V panes reversed</li>
* <li>Some padding is needed after the Y pane</li>
* <li>stride!=width or slice-height!=height</li>
* </ul>
*/
@SuppressLint("NewApi")
public class EncoderDebugger {
public final static String TAG = "EncoderDebugger";
/** Prefix that will be used for all shared preferences saved by libstreaming. */
private static final String PREF_PREFIX = "libstreaming-";
/**
* If this is set to false the test will be run only once and the result
* will be saved in the shared preferences.
*/
private static final boolean DEBUG = false;
/** Set this to true to see more logs. */
private static final boolean VERBOSE = false;
/** Will be incremented every time this test is modified. */
private static final int VERSION = 3;
/** Bit rate that will be used with the encoder. */
private final static int BITRATE = 1000000;
/** Frame rate that will be used to test the encoder. */
private final static int FRAMERATE = 20;
private final static String MIME_TYPE = "video/avc";
private final static int NB_DECODED = 34;
private final static int NB_ENCODED = 50;
private int mDecoderColorFormat, mEncoderColorFormat;
private String mDecoderName, mEncoderName, mErrorLog;
private MediaCodec mEncoder, mDecoder;
private int mWidth, mHeight, mSize;
private byte[] mSPS, mPPS;
private byte[] mData, mInitialImage;
private MediaFormat mDecOutputFormat;
private NV21Convertor mNV21;
private SharedPreferences mPreferences;
private byte[][] mVideo, mDecodedVideo;
private String mB64PPS, mB64SPS;
public synchronized static void asyncDebug(final Context context, final int width, final int height) {
new Thread(new Runnable() {
@Override
public void run() {
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
debug(prefs, width, height);
} catch (Exception e) {}
}
}).start();
}
public synchronized static EncoderDebugger debug(Context context, int width, int height) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return debug(prefs, width, height);
}
public synchronized static EncoderDebugger debug(SharedPreferences prefs, int width, int height) {
EncoderDebugger debugger = new EncoderDebugger(prefs, width, height);
debugger.debug();
return debugger;
}
public String getB64PPS() {
return mB64PPS;
}
public String getB64SPS() {
return mB64SPS;
}
public String getEncoderName() {
return mEncoderName;
}
public int getEncoderColorFormat() {
return mEncoderColorFormat;
}
/** This {@link NV21Convertor} will do the necessary work to feed properly the encoder. */
public NV21Convertor getNV21Convertor() {
return mNV21;
}
/** A log of all the errors that occurred during the test. */
public String getErrorLog() {
return mErrorLog;
}
private EncoderDebugger(SharedPreferences prefs, int width, int height) {
mPreferences = prefs;
mWidth = width;
mHeight = height;
mSize = width*height;
reset();
}
private void reset() {
mNV21 = new NV21Convertor();
mVideo = new byte[NB_ENCODED][];
mDecodedVideo = new byte[NB_DECODED][];
mErrorLog = "";
mPPS = null;
mSPS = null;
}
private void debug() {
// If testing the phone again is not needed,
// we just restore the result from the shared preferences
if (!checkTestNeeded()) {
String resolution = mWidth+"x"+mHeight+"-";
boolean success = mPreferences.getBoolean(PREF_PREFIX+resolution+"success",false);
if (!success) {
throw new RuntimeException("Phone not supported with this resolution ("+mWidth+"x"+mHeight+")");
}
mNV21.setSize(mWidth, mHeight);
mNV21.setSliceHeigth(mPreferences.getInt(PREF_PREFIX+resolution+"sliceHeight", 0));
mNV21.setStride(mPreferences.getInt(PREF_PREFIX+resolution+"stride", 0));
mNV21.setYPadding(mPreferences.getInt(PREF_PREFIX+resolution+"padding", 0));
mNV21.setPlanar(mPreferences.getBoolean(PREF_PREFIX+resolution+"planar", false));
mNV21.setColorPanesReversed(mPreferences.getBoolean(PREF_PREFIX+resolution+"reversed", false));
mEncoderName = mPreferences.getString(PREF_PREFIX+resolution+"encoderName", "");
mEncoderColorFormat = mPreferences.getInt(PREF_PREFIX+resolution+"colorFormat", 0);
mB64PPS = mPreferences.getString(PREF_PREFIX+resolution+"pps", "");
mB64SPS = mPreferences.getString(PREF_PREFIX+resolution+"sps", "");
return;
}
if (VERBOSE) Log.d(TAG, ">>>> Testing the phone for resolution "+mWidth+"x"+mHeight);
// Builds a list of available encoders and decoders we may be able to use
// because they support some nice color formats
Codec[] encoders = CodecManager.findEncodersForMimeType(MIME_TYPE);
Codec[] decoders = CodecManager.findDecodersForMimeType(MIME_TYPE);
int count = 0, n = 1;
for (int i=0;i<encoders.length;i++) {
count += encoders[i].formats.length;
}
// Tries available encoders
for (int i=0;i<encoders.length;i++) {
for (int j=0;j<encoders[i].formats.length;j++) {
reset();
mEncoderName = encoders[i].name;
mEncoderColorFormat = encoders[i].formats[j];
if (VERBOSE) Log.v(TAG, ">> Test "+(n++)+"/"+count+": "+mEncoderName+" with color format "+mEncoderColorFormat+" at "+mWidth+"x"+mHeight);
// Converts from NV21 to YUV420 with the specified parameters
mNV21.setSize(mWidth, mHeight);
mNV21.setSliceHeigth(mHeight);
mNV21.setStride(mWidth);
mNV21.setYPadding(0);
mNV21.setEncoderColorFormat(mEncoderColorFormat);
// /!\ NV21Convertor can directly modify the input
createTestImage();
mData = mNV21.convert(mInitialImage);
try {
// Starts the encoder
configureEncoder();
searchSPSandPPS();
if (VERBOSE) Log.v(TAG, "SPS and PPS in b64: SPS="+mB64SPS+", PPS="+mB64PPS);
// Feeds the encoder with an image repeatedly to produce some NAL units
encode();
// We now try to decode the NALs with decoders available on the phone
boolean decoded = false;
for (int k=0;k<decoders.length && !decoded;k++) {
for (int l=0;l<decoders[k].formats.length && !decoded;l++) {
mDecoderName = decoders[k].name;
mDecoderColorFormat = decoders[k].formats[l];
try {
configureDecoder();
} catch (Exception e) {
if (VERBOSE) Log.d(TAG, mDecoderName+" can't be used with "+mDecoderColorFormat+" at "+mWidth+"x"+mHeight);
releaseDecoder();
break;
}
try {
decode(true);
if (VERBOSE) Log.d(TAG, mDecoderName+" successfully decoded the NALs (color format "+mDecoderColorFormat+")");
decoded = true;
} catch (Exception e) {
if (VERBOSE) Log.e(TAG, mDecoderName+" failed to decode the NALs");
e.printStackTrace();
} finally {
releaseDecoder();
}
}
}
if (!decoded) throw new RuntimeException("Failed to decode NALs from the encoder.");
// Compares the image before and after
if (!compareLumaPanes()) {
// TODO: try again with a different stride
// TODO: try again with the "stride" param
throw new RuntimeException("It is likely that stride!=width");
}
int padding;
if ((padding = checkPaddingNeeded())>0) {
if (padding<4096) {
if (VERBOSE) Log.d(TAG, "Some padding is needed: "+padding);
mNV21.setYPadding(padding);
createTestImage();
mData = mNV21.convert(mInitialImage);
encodeDecode();
} else {
// TODO: try again with a different sliceHeight
// TODO: try again with the "slice-height" param
throw new RuntimeException("It is likely that sliceHeight!=height");
}
}
createTestImage();
if (!compareChromaPanes(false)) {
if (compareChromaPanes(true)) {
mNV21.setColorPanesReversed(true);
if (VERBOSE) Log.d(TAG, "U and V pane are reversed");
} else {
throw new RuntimeException("Incorrect U or V pane...");
}
}
saveTestResult(true);
Log.v(TAG, "The encoder "+mEncoderName+" is usable with resolution "+mWidth+"x"+mHeight);
return;
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw);
String stack = sw.toString();
String str = "Encoder "+mEncoderName+" cannot be used with color format "+mEncoderColorFormat;
if (VERBOSE) Log.e(TAG, str, e);
mErrorLog += str + "\n" + stack;
e.printStackTrace();
} finally {
releaseEncoder();
}
}
}
saveTestResult(false);
Log.e(TAG,"No usable encoder were found on the phone for resolution "+mWidth+"x"+mHeight);
throw new RuntimeException("No usable encoder were found on the phone for resolution "+mWidth+"x"+mHeight);
}
private boolean checkTestNeeded() {
String resolution = mWidth+"x"+mHeight+"-";
// Forces the test
if (DEBUG || mPreferences==null) return true;
// If the sdk has changed on the phone, or the version of the test
// it has to be run again
if (mPreferences.contains(PREF_PREFIX+resolution+"lastSdk")) {
int lastSdk = mPreferences.getInt(PREF_PREFIX+resolution+"lastSdk", 0);
int lastVersion = mPreferences.getInt(PREF_PREFIX+resolution+"lastVersion", 0);
if (Build.VERSION.SDK_INT>lastSdk || VERSION>lastVersion) {
return true;
}
} else {
return true;
}
return false;
}
/**
* Saves the result of the test in the shared preferences,
* we will run it again only if the SDK has changed on the phone,
* or if this test has been modified.
*/
private void saveTestResult(boolean success) {
String resolution = mWidth+"x"+mHeight+"-";
Editor editor = mPreferences.edit();
editor.putBoolean(PREF_PREFIX+resolution+"success", success);
if (success) {
editor.putInt(PREF_PREFIX+resolution+"lastSdk", Build.VERSION.SDK_INT);
editor.putInt(PREF_PREFIX+resolution+"lastVersion", VERSION);
editor.putInt(PREF_PREFIX+resolution+"sliceHeight", mNV21.getSliceHeigth());
editor.putInt(PREF_PREFIX+resolution+"stride", mNV21.getStride());
editor.putInt(PREF_PREFIX+resolution+"padding", mNV21.getYPadding());
editor.putBoolean(PREF_PREFIX+resolution+"planar", mNV21.getPlanar());
editor.putBoolean(PREF_PREFIX+resolution+"reversed", mNV21.getUVPanesReversed());
editor.putString(PREF_PREFIX+resolution+"encoderName", mEncoderName);
editor.putInt(PREF_PREFIX+resolution+"colorFormat", mEncoderColorFormat);
editor.putString(PREF_PREFIX+resolution+"encoderName", mEncoderName);
editor.putString(PREF_PREFIX+resolution+"pps", mB64PPS);
editor.putString(PREF_PREFIX+resolution+"sps", mB64SPS);
}
editor.commit();
}
/**
* Creates the test image that will be used to feed the encoder.
*/
private void createTestImage() {
mInitialImage = new byte[3*mSize/2];
for (int i=0;i<mSize;i++) {
mInitialImage[i] = (byte) (40+i%199);
}
for (int i=mSize;i<3*mSize/2;i+=2) {
mInitialImage[i] = (byte) (40+i%200);
mInitialImage[i+1] = (byte) (40+(i+99)%200);
}
}
/**
* Compares the Y pane of the initial image, and the Y pane
* after having encoded & decoded the image.
*/
private boolean compareLumaPanes() {
int d, e, f = 0;
for (int j=0;j<NB_DECODED;j++) {
for (int i=0;i<mSize;i+=10) {
d = (mInitialImage[i]&0xFF) - (mDecodedVideo[j][i]&0xFF);
e = (mInitialImage[i+1]&0xFF) - (mDecodedVideo[j][i+1]&0xFF);
d = d<0 ? -d : d;
e = e<0 ? -e : e;
if (d>50 && e>50) {
mDecodedVideo[j] = null;
f++;
break;
}
}
}
return f<=NB_DECODED/2;
}
private int checkPaddingNeeded() {
int i = 0, j = 3*mSize/2-1, max = 0;
int[] r = new int[NB_DECODED];
for (int k=0;k<NB_DECODED;k++) {
if (mDecodedVideo[k] != null) {
i = 0;
while (i<j && (mDecodedVideo[k][j-i]&0xFF)<50) i+=2;
if (i>0) {
r[k] = ((i>>6)<<6);
max = r[k]>max ? r[k] : max;
if (VERBOSE) Log.e(TAG,"Padding needed: "+r[k]);
} else {
if (VERBOSE) Log.v(TAG,"No padding needed.");
}
}
}
return ((max>>6)<<6);
}
/**
* Compares the U or V pane of the initial image, and the U or V pane
* after having encoded & decoded the image.
*/
private boolean compareChromaPanes(boolean crossed) {
int d, f = 0;
for (int j=0;j<NB_DECODED;j++) {
if (mDecodedVideo[j] != null) {
// We compare the U and V pane before and after
if (!crossed) {
for (int i=mSize;i<3*mSize/2;i+=1) {
d = (mInitialImage[i]&0xFF) - (mDecodedVideo[j][i]&0xFF);
d = d<0 ? -d : d;
if (d>50) {
//if (VERBOSE) Log.e(TAG,"BUG "+(i-mSize)+" d "+d);
f++;
break;
}
}
// We compare the V pane before with the U pane after
} else {
for (int i=mSize;i<3*mSize/2;i+=2) {
d = (mInitialImage[i]&0xFF) - (mDecodedVideo[j][i+1]&0xFF);
d = d<0 ? -d : d;
if (d>50) {
f++;
}
}
}
}
}
return f<=NB_DECODED/2;
}
/**
* Converts the image obtained from the decoder to NV21.
*/
private void convertToNV21(int k) {
byte[] buffer = new byte[3*mSize/2];
int stride = mWidth, sliceHeight = mHeight;
int colorFormat = mDecoderColorFormat;
boolean planar = false;
if (mDecOutputFormat != null) {
MediaFormat format = mDecOutputFormat;
if (format != null) {
if (format.containsKey("slice-height")) {
sliceHeight = format.getInteger("slice-height");
if (sliceHeight<mHeight) sliceHeight = mHeight;
}
if (format.containsKey("stride")) {
stride = format.getInteger("stride");
if (stride<mWidth) stride = mWidth;
}
if (format.containsKey(MediaFormat.KEY_COLOR_FORMAT)) {
if (format.getInteger(MediaFormat.KEY_COLOR_FORMAT)>0) {
colorFormat = format.getInteger(MediaFormat.KEY_COLOR_FORMAT);
}
}
}
}
switch (colorFormat) {
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
planar = false;
break;
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
planar = true;
break;
}
for (int i=0;i<mSize;i++) {
if (i%mWidth==0) i+=stride-mWidth;
buffer[i] = mDecodedVideo[k][i];
}
if (!planar) {
for (int i=0,j=0;j<mSize/4;i+=1,j+=1) {
if (i%mWidth/2==0) i+=(stride-mWidth)/2;
buffer[mSize+2*j+1] = mDecodedVideo[k][stride*sliceHeight+2*i];
buffer[mSize+2*j] = mDecodedVideo[k][stride*sliceHeight+2*i+1];
}
} else {
for (int i=0,j=0;j<mSize/4;i+=1,j+=1) {
if (i%mWidth/2==0) i+=(stride-mWidth)/2;
buffer[mSize+2*j+1] = mDecodedVideo[k][stride*sliceHeight+i];
buffer[mSize+2*j] = mDecodedVideo[k][stride*sliceHeight*5/4+i];
}
}
mDecodedVideo[k] = buffer;
}
/**
* Instantiates and starts the encoder.
* @throws IOException The encoder cannot be configured
*/
private void configureEncoder() throws IOException {
mEncoder = MediaCodec.createByCodecName(mEncoderName);
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BITRATE);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, FRAMERATE);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, mEncoderColorFormat);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mEncoder.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mEncoder.start();
}
private void releaseEncoder() {
if (mEncoder != null) {
try {
mEncoder.stop();
} catch (Exception ignore) {}
try {
mEncoder.release();
} catch (Exception ignore) {}
}
}
/**
* Instantiates and starts the decoder.
* @throws IOException The decoder cannot be configured
*/
private void configureDecoder() throws IOException {
byte[] prefix = new byte[] {0x00,0x00,0x00,0x01};
ByteBuffer csd0 = ByteBuffer.allocate(4+mSPS.length+4+mPPS.length);
csd0.put(new byte[] {0x00,0x00,0x00,0x01});
csd0.put(mSPS);
csd0.put(new byte[] {0x00,0x00,0x00,0x01});
csd0.put(mPPS);
mDecoder = MediaCodec.createByCodecName(mDecoderName);
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, mWidth, mHeight);
mediaFormat.setByteBuffer("csd-0", csd0);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, mDecoderColorFormat);
mDecoder.configure(mediaFormat, null, null, 0);
mDecoder.start();
ByteBuffer[] decInputBuffers = mDecoder.getInputBuffers();
int decInputIndex = mDecoder.dequeueInputBuffer(1000000/FRAMERATE);
if (decInputIndex>=0) {
decInputBuffers[decInputIndex].clear();
decInputBuffers[decInputIndex].put(prefix);
decInputBuffers[decInputIndex].put(mSPS);
mDecoder.queueInputBuffer(decInputIndex, 0, decInputBuffers[decInputIndex].position(), timestamp(), 0);
} else {
if (VERBOSE) Log.e(TAG,"No buffer available !");
}
decInputIndex = mDecoder.dequeueInputBuffer(1000000/FRAMERATE);
if (decInputIndex>=0) {
decInputBuffers[decInputIndex].clear();
decInputBuffers[decInputIndex].put(prefix);
decInputBuffers[decInputIndex].put(mPPS);
mDecoder.queueInputBuffer(decInputIndex, 0, decInputBuffers[decInputIndex].position(), timestamp(), 0);
} else {
if (VERBOSE) Log.e(TAG,"No buffer available !");
}
}
private void releaseDecoder() {
if (mDecoder != null) {
try {
mDecoder.stop();
} catch (Exception ignore) {}
try {
mDecoder.release();
} catch (Exception ignore) {}
}
}
/**
* Tries to obtain the SPS and the PPS for the encoder.
*/
private long searchSPSandPPS() {
ByteBuffer[] inputBuffers = mEncoder.getInputBuffers();
ByteBuffer[] outputBuffers = mEncoder.getOutputBuffers();
BufferInfo info = new BufferInfo();
byte[] csd = new byte[128];
int len = 0, p = 4, q = 4;
long elapsed = 0, now = timestamp();
while (elapsed<3000000 && (mSPS==null || mPPS==null)) {
// Some encoders won't give us the SPS and PPS unless they receive something to encode first...
int bufferIndex = mEncoder.dequeueInputBuffer(1000000/FRAMERATE);
if (bufferIndex>=0) {
check(inputBuffers[bufferIndex].capacity()>=mData.length, "The input buffer is not big enough.");
inputBuffers[bufferIndex].clear();
inputBuffers[bufferIndex].put(mData, 0, mData.length);
mEncoder.queueInputBuffer(bufferIndex, 0, mData.length, timestamp(), 0);
} else {
if (VERBOSE) Log.e(TAG,"No buffer available !");
}
// We are looking for the SPS and the PPS here. As always, Android is very inconsistent, I have observed that some
// encoders will give those parameters through the MediaFormat object (that is the normal behaviour).
// But some other will not, in that case we try to find a NAL unit of type 7 or 8 in the byte stream outputed by the encoder...
int index = mEncoder.dequeueOutputBuffer(info, 1000000/FRAMERATE);
if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// The PPS and PPS shoud be there
MediaFormat format = mEncoder.getOutputFormat();
ByteBuffer spsb = format.getByteBuffer("csd-0");
ByteBuffer ppsb = format.getByteBuffer("csd-1");
mSPS = new byte[spsb.capacity()-4];
spsb.position(4);
spsb.get(mSPS,0,mSPS.length);
mPPS = new byte[ppsb.capacity()-4];
ppsb.position(4);
ppsb.get(mPPS,0,mPPS.length);
break;
} else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
outputBuffers = mEncoder.getOutputBuffers();
} else if (index>=0) {
len = info.size;
if (len<128) {
outputBuffers[index].get(csd,0,len);
if (len>0 && csd[0]==0 && csd[1]==0 && csd[2]==0 && csd[3]==1) {
// Parses the SPS and PPS, they could be in two different packets and in a different order
//depending on the phone so we don't make any assumption about that
while (p<len) {
while (!(csd[p+0]==0 && csd[p+1]==0 && csd[p+2]==0 && csd[p+3]==1) && p+3<len) p++;
if (p+3>=len) p=len;
if ((csd[q]&0x1F)==7) {
mSPS = new byte[p-q];
System.arraycopy(csd, q, mSPS, 0, p-q);
} else {
mPPS = new byte[p-q];
System.arraycopy(csd, q, mPPS, 0, p-q);
}
p += 4;
q = p;
}
}
}
mEncoder.releaseOutputBuffer(index, false);
}
elapsed = timestamp() - now;
}
check(mPPS != null & mSPS != null, "Could not determine the SPS & PPS.");
mB64PPS = Base64.encodeToString(mPPS, 0, mPPS.length, Base64.NO_WRAP);
mB64SPS = Base64.encodeToString(mSPS, 0, mSPS.length, Base64.NO_WRAP);
return elapsed;
}
private long encode() {
int n = 0;
long elapsed = 0, now = timestamp();
int encOutputIndex = 0, encInputIndex = 0;
BufferInfo info = new BufferInfo();
ByteBuffer[] encInputBuffers = mEncoder.getInputBuffers();
ByteBuffer[] encOutputBuffers = mEncoder.getOutputBuffers();
while (elapsed<5000000) {
// Feeds the encoder with an image
encInputIndex = mEncoder.dequeueInputBuffer(1000000/FRAMERATE);
if (encInputIndex>=0) {
check(encInputBuffers[encInputIndex].capacity()>=mData.length, "The input buffer is not big enough.");
encInputBuffers[encInputIndex].clear();
encInputBuffers[encInputIndex].put(mData, 0, mData.length);
mEncoder.queueInputBuffer(encInputIndex, 0, mData.length, timestamp(), 0);
} else {
if (VERBOSE) Log.d(TAG,"No buffer available !");
}
// Tries to get a NAL unit
encOutputIndex = mEncoder.dequeueOutputBuffer(info, 1000000/FRAMERATE);
if (encOutputIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
encOutputBuffers = mEncoder.getOutputBuffers();
} else if (encOutputIndex>=0) {
mVideo[n] = new byte[info.size];
encOutputBuffers[encOutputIndex].clear();
encOutputBuffers[encOutputIndex].get(mVideo[n++], 0, info.size);
mEncoder.releaseOutputBuffer(encOutputIndex, false);
if (n>=NB_ENCODED) {
flushMediaCodec(mEncoder);
return elapsed;
}
}
elapsed = timestamp() - now;
}
throw new RuntimeException("The encoder is too slow.");
}
/**
* @param withPrefix If set to true, the decoder will be fed with NALs preceeded with 0x00000001.
* @return How long it took to decode all the NALs
*/
private long decode(boolean withPrefix) {
int n = 0, i = 0, j = 0;
long elapsed = 0, now = timestamp();
int decInputIndex = 0, decOutputIndex = 0;
ByteBuffer[] decInputBuffers = mDecoder.getInputBuffers();
ByteBuffer[] decOutputBuffers = mDecoder.getOutputBuffers();
BufferInfo info = new BufferInfo();
while (elapsed<3000000) {
// Feeds the decoder with a NAL unit
if (i<NB_ENCODED) {
decInputIndex = mDecoder.dequeueInputBuffer(1000000/FRAMERATE);
if (decInputIndex>=0) {
int l1 = decInputBuffers[decInputIndex].capacity();
int l2 = mVideo[i].length;
decInputBuffers[decInputIndex].clear();
if ((withPrefix && hasPrefix(mVideo[i])) || (!withPrefix && !hasPrefix(mVideo[i]))) {
check(l1>=l2, "The decoder input buffer is not big enough (nal="+l2+", capacity="+l1+").");
decInputBuffers[decInputIndex].put(mVideo[i],0,mVideo[i].length);
} else if (withPrefix && !hasPrefix(mVideo[i])) {
check(l1>=l2+4, "The decoder input buffer is not big enough (nal="+(l2+4)+", capacity="+l1+").");
decInputBuffers[decInputIndex].put(new byte[] {0,0,0,1});
decInputBuffers[decInputIndex].put(mVideo[i],0,mVideo[i].length);
} else if (!withPrefix && hasPrefix(mVideo[i])) {
check(l1>=l2-4, "The decoder input buffer is not big enough (nal="+(l2-4)+", capacity="+l1+").");
decInputBuffers[decInputIndex].put(mVideo[i],4,mVideo[i].length-4);
}
mDecoder.queueInputBuffer(decInputIndex, 0, l2, timestamp(), 0);
i++;
} else {
if (VERBOSE) Log.d(TAG,"No buffer available !");
}
}
// Tries to get a decoded image
decOutputIndex = mDecoder.dequeueOutputBuffer(info, 1000000/FRAMERATE);
if (decOutputIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
decOutputBuffers = mDecoder.getOutputBuffers();
} else if (decOutputIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
mDecOutputFormat = mDecoder.getOutputFormat();
} else if (decOutputIndex>=0) {
if (n>2) {
// We have successfully encoded and decoded an image !
int length = info.size;
mDecodedVideo[j] = new byte[length];
decOutputBuffers[decOutputIndex].clear();
decOutputBuffers[decOutputIndex].get(mDecodedVideo[j], 0, length);
// Converts the decoded frame to NV21
convertToNV21(j);
if (j>=NB_DECODED-1) {
flushMediaCodec(mDecoder);
if (VERBOSE) Log.v(TAG, "Decoding "+n+" frames took "+elapsed/1000+" ms");
return elapsed;
}
j++;
}
mDecoder.releaseOutputBuffer(decOutputIndex, false);
n++;
}
elapsed = timestamp() - now;
}
throw new RuntimeException("The decoder did not decode anything.");
}
/**
* Makes sure the NAL has a header or not.
* @param withPrefix If set to true, the NAL will be preceded with 0x00000001.
*/
private boolean hasPrefix(byte[] nal) {
if (nal[0] == 0 && nal[1] == 0 && nal[2] == 0 && nal[3] == 0x01)
return true;
else
return false;
}
/**
* @throws IOException The decoder cannot be configured.
*/
private void encodeDecode() throws IOException {
encode();
try {
configureDecoder();
decode(true);
} finally {
releaseDecoder();
}
}
private void flushMediaCodec(MediaCodec mc) {
int index = 0;
BufferInfo info = new BufferInfo();
while (index != MediaCodec.INFO_TRY_AGAIN_LATER) {
index = mc.dequeueOutputBuffer(info, 1000000/FRAMERATE);
if (index>=0) {
mc.releaseOutputBuffer(index, false);
}
}
}
private void check(boolean cond, String message) {
if (!cond) {
if (VERBOSE) Log.e(TAG,message);
throw new IllegalStateException(message);
}
}
private long timestamp() {
return System.nanoTime()/1000;
}
}
| 27,823 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
CodecManager.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/hw/CodecManager.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.hw;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.annotation.SuppressLint;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.util.Log;
@SuppressLint("InlinedApi")
public class CodecManager {
public final static String TAG = "CodecManager";
public static final int[] SUPPORTED_COLOR_FORMATS = {
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar,
MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar,
MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar
};
private static Codec[] sEncoders = null;
private static Codec[] sDecoders = null;
static class Codec {
public Codec(String name, Integer[] formats) {
this.name = name;
this.formats = formats;
}
public String name;
public Integer[] formats;
}
/**
* Lists all encoders that claim to support a color format that we know how to use.
* @return A list of those encoders
*/
@SuppressLint("NewApi")
public synchronized static Codec[] findEncodersForMimeType(String mimeType) {
if (sEncoders != null) return sEncoders;
ArrayList<Codec> encoders = new ArrayList<Codec>();
// We loop through the encoders, apparently this can take up to a sec (testes on a GS3)
for(int j = MediaCodecList.getCodecCount() - 1; j >= 0; j--){
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(j);
if (!codecInfo.isEncoder()) continue;
String[] types = codecInfo.getSupportedTypes();
for (int i = 0; i < types.length; i++) {
if (types[i].equalsIgnoreCase(mimeType)) {
try {
MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
Set<Integer> formats = new HashSet<Integer>();
// And through the color formats supported
for (int k = 0; k < capabilities.colorFormats.length; k++) {
int format = capabilities.colorFormats[k];
for (int l=0;l<SUPPORTED_COLOR_FORMATS.length;l++) {
if (format == SUPPORTED_COLOR_FORMATS[l]) {
formats.add(format);
}
}
}
Codec codec = new Codec(codecInfo.getName(), (Integer[]) formats.toArray(new Integer[formats.size()]));
encoders.add(codec);
} catch (Exception e) {
Log.wtf(TAG,e);
}
}
}
}
sEncoders = (Codec[]) encoders.toArray(new Codec[encoders.size()]);
return sEncoders;
}
/**
* Lists all decoders that claim to support a color format that we know how to use.
* @return A list of those decoders
*/
@SuppressLint("NewApi")
public synchronized static Codec[] findDecodersForMimeType(String mimeType) {
if (sDecoders != null) return sDecoders;
ArrayList<Codec> decoders = new ArrayList<Codec>();
// We loop through the decoders, apparently this can take up to a sec (testes on a GS3)
for(int j = MediaCodecList.getCodecCount() - 1; j >= 0; j--){
MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(j);
if (codecInfo.isEncoder()) continue;
String[] types = codecInfo.getSupportedTypes();
for (int i = 0; i < types.length; i++) {
if (types[i].equalsIgnoreCase(mimeType)) {
try {
MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
Set<Integer> formats = new HashSet<Integer>();
// And through the color formats supported
for (int k = 0; k < capabilities.colorFormats.length; k++) {
int format = capabilities.colorFormats[k];
for (int l=0;l<SUPPORTED_COLOR_FORMATS.length;l++) {
if (format == SUPPORTED_COLOR_FORMATS[l]) {
formats.add(format);
}
}
}
Codec codec = new Codec(codecInfo.getName(), (Integer[]) formats.toArray(new Integer[formats.size()]));
decoders.add(codec);
} catch (Exception e) {
Log.wtf(TAG,e);
}
}
}
}
sDecoders = (Codec[]) decoders.toArray(new Codec[decoders.size()]);
// We will use the decoder from google first, it seems to work properly on many phones
for (int i=0;i<sDecoders.length;i++) {
if (sDecoders[i].name.equalsIgnoreCase("omx.google.h264.decoder")) {
Codec codec = sDecoders[0];
sDecoders[0] = sDecoders[i];
sDecoders[i] = codec;
}
}
return sDecoders;
}
}
| 5,300 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
NV21Convertor.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/hw/NV21Convertor.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.hw;
import java.nio.ByteBuffer;
import android.media.MediaCodecInfo;
import android.util.Log;
/**
* Converts from NV21 to YUV420 semi planar or planar.
*/
public class NV21Convertor {
private int mSliceHeight, mHeight;
private int mStride, mWidth;
private int mSize;
private boolean mPlanar, mPanesReversed = false;
private int mYPadding;
private byte[] mBuffer;
ByteBuffer mCopy;
public void setSize(int width, int height) {
mHeight = height;
mWidth = width;
mSliceHeight = height;
mStride = width;
mSize = mWidth*mHeight;
}
public void setStride(int width) {
mStride = width;
}
public void setSliceHeigth(int height) {
mSliceHeight = height;
}
public void setPlanar(boolean planar) {
mPlanar = planar;
}
public void setYPadding(int padding) {
mYPadding = padding;
}
public int getBufferSize() {
return 3*mSize/2;
}
public void setEncoderColorFormat(int colorFormat) {
switch (colorFormat) {
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
setPlanar(false);
break;
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
setPlanar(true);
break;
}
}
public void setColorPanesReversed(boolean b) {
mPanesReversed = b;
}
public int getStride() {
return mStride;
}
public int getSliceHeigth() {
return mSliceHeight;
}
public int getYPadding() {
return mYPadding;
}
public boolean getPlanar() {
return mPlanar;
}
public boolean getUVPanesReversed() {
return mPanesReversed;
}
public void convert(byte[] data, ByteBuffer buffer) {
byte[] result = convert(data);
int min = buffer.capacity() < data.length?buffer.capacity() : data.length;
buffer.put(result, 0, min);
}
public byte[] convert(byte[] data) {
// A buffer large enough for every case
if (mBuffer==null || mBuffer.length != 3*mSliceHeight*mStride/2+mYPadding) {
mBuffer = new byte[3*mSliceHeight*mStride/2+mYPadding];
}
if (!mPlanar) {
if (mSliceHeight==mHeight && mStride==mWidth) {
// Swaps U and V
if (!mPanesReversed) {
for (int i = mSize; i < mSize+mSize/2; i += 2) {
mBuffer[0] = data[i+1];
data[i+1] = data[i];
data[i] = mBuffer[0];
}
}
if (mYPadding>0) {
System.arraycopy(data, 0, mBuffer, 0, mSize);
System.arraycopy(data, mSize, mBuffer, mSize+mYPadding, mSize/2);
return mBuffer;
}
return data;
}
} else {
if (mSliceHeight==mHeight && mStride==mWidth) {
// De-interleave U and V
if (!mPanesReversed) {
for (int i = 0; i < mSize/4; i+=1) {
mBuffer[i] = data[mSize+2*i+1];
mBuffer[mSize/4+i] = data[mSize+2*i];
}
} else {
for (int i = 0; i < mSize/4; i+=1) {
mBuffer[i] = data[mSize+2*i];
mBuffer[mSize/4+i] = data[mSize+2*i+1];
}
}
if (mYPadding == 0) {
System.arraycopy(mBuffer, 0, data, mSize, mSize/2);
} else {
System.arraycopy(data, 0, mBuffer, 0, mSize);
System.arraycopy(mBuffer, 0, mBuffer, mSize+mYPadding, mSize/2);
return mBuffer;
}
return data;
}
}
return data;
}
}
| 4,247 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
MP4Parser.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/mp4/MP4Parser.java | package net.majorkernelpanic.streaming.mp4;
/*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.HashMap;
import android.util.Base64;
import android.util.Log;
/**
* Parse an mp4 file.
* An mp4 file contains a tree where each node has a name and a size.
* This class is used by H264Stream.java to determine the SPS and PPS parameters of a short video recorded by the phone.
*/
public class MP4Parser {
private static final String TAG = "MP4Parser";
private HashMap<String, Long> mBoxes = new HashMap<String, Long>();
private final RandomAccessFile mFile;
private long mPos = 0;
/** Parses the mp4 file. **/
public static MP4Parser parse(String path) throws IOException {
return new MP4Parser(path);
}
private MP4Parser(final String path) throws IOException, FileNotFoundException {
mFile = new RandomAccessFile(new File(path), "r");
try {
parse("",mFile.length());
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Parse error: malformed mp4 file");
}
}
public void close() {
try {
mFile.close();
} catch (Exception e) {};
}
public long getBoxPos(String box) throws IOException {
Long r = mBoxes.get(box);
if (r==null) throw new IOException("Box not found: "+box);
return mBoxes.get(box);
}
public StsdBox getStsdBox() throws IOException {
try {
return new StsdBox(mFile,getBoxPos("/moov/trak/mdia/minf/stbl/stsd"));
} catch (IOException e) {
throw new IOException("stsd box could not be found");
}
}
private void parse(String path, long len) throws IOException {
ByteBuffer byteBuffer;
long sum = 0, newlen = 0;
byte[] buffer = new byte[8];
String name = "";
if(!path.equals("")) mBoxes.put(path, mPos-8);
while (sum<len) {
mFile.read(buffer,0,8);
mPos += 8; sum += 8;
if (validBoxName(buffer)) {
name = new String(buffer,4,4);
if (buffer[3] == 1) {
// 64 bits atom size
mFile.read(buffer,0,8);
mPos += 8; sum += 8;
byteBuffer = ByteBuffer.wrap(buffer,0,8);
newlen = byteBuffer.getLong()-16;
} else {
// 32 bits atom size
byteBuffer = ByteBuffer.wrap(buffer,0,4);
newlen = byteBuffer.getInt()-8;
}
// 1061109559+8 correspond to "????" in ASCII the HTC Desire S seems to write that sometimes, maybe other phones do
// "wide" atom would produce a newlen == 0, and we shouldn't throw an exception because of that
if (newlen < 0 || newlen == 1061109559) throw new IOException();
Log.d(TAG, "Atom -> name: "+name+" position: "+mPos+", length: "+newlen);
sum += newlen;
parse(path+'/'+name,newlen);
}
else {
if( len < 8){
mFile.seek(mFile.getFilePointer() - 8 + len);
sum += len-8;
} else {
int skipped = mFile.skipBytes((int)(len-8));
if (skipped < ((int)(len-8))) {
throw new IOException();
}
mPos += len-8;
sum += len-8;
}
}
}
}
private boolean validBoxName(byte[] buffer) {
for (int i=0;i<4;i++) {
// If the next 4 bytes are neither lowercase letters nor numbers
if ((buffer[i+4]< 'a' || buffer[i+4]>'z') && (buffer[i+4]<'0'|| buffer[i+4]>'9') ) return false;
}
return true;
}
static String toHexString(byte[] buffer,int start, int len) {
String c;
StringBuilder s = new StringBuilder();
for (int i=start;i<start+len;i++) {
c = Integer.toHexString(buffer[i]&0xFF);
s.append( c.length()<2 ? "0"+c : c );
}
return s.toString();
}
}
class StsdBox {
private RandomAccessFile fis;
private byte[] buffer = new byte[4];
private long pos = 0;
private byte[] pps;
private byte[] sps;
private int spsLength, ppsLength;
/** Parse the sdsd box in an mp4 file
* fis: proper mp4 file
* pos: stsd box's position in the file
*/
public StsdBox (RandomAccessFile fis, long pos) {
this.fis = fis;
this.pos = pos;
findBoxAvcc();
findSPSandPPS();
}
public String getProfileLevel() {
return MP4Parser.toHexString(sps,1,3);
}
public String getB64PPS() {
return Base64.encodeToString(pps, 0, ppsLength, Base64.NO_WRAP);
}
public String getB64SPS() {
return Base64.encodeToString(sps, 0, spsLength, Base64.NO_WRAP);
}
private boolean findSPSandPPS() {
/*
* SPS and PPS parameters are stored in the avcC box
* You may find really useful information about this box
* in the document ISO-IEC 14496-15, part 5.2.4.1.1
* The box's structure is described there
* <pre>
* aligned(8) class AVCDecoderConfigurationRecord {
* unsigned int(8) configurationVersion = 1;
* unsigned int(8) AVCProfileIndication;
* unsigned int(8) profile_compatibility;
* unsigned int(8) AVCLevelIndication;
* bit(6) reserved = ‘111111’b;
* unsigned int(2) lengthSizeMinusOne;
* bit(3) reserved = ‘111’b;
* unsigned int(5) numOfSequenceParameterSets;
* for (i=0; i< numOfSequenceParameterSets; i++) {
* unsigned int(16) sequenceParameterSetLength ;
* bit(8*sequenceParameterSetLength) sequenceParameterSetNALUnit;
* }
* unsigned int(8) numOfPictureParameterSets;
* for (i=0; i< numOfPictureParameterSets; i++) {
* unsigned int(16) pictureParameterSetLength;
* bit(8*pictureParameterSetLength) pictureParameterSetNALUnit;
* }
* }
* </pre>
*/
try {
// TODO: Here we assume that numOfSequenceParameterSets = 1, numOfPictureParameterSets = 1 !
// Here we extract the SPS parameter
fis.skipBytes(7);
spsLength = 0xFF&fis.readByte();
sps = new byte[spsLength];
fis.read(sps,0,spsLength);
// Here we extract the PPS parameter
fis.skipBytes(2);
ppsLength = 0xFF&fis.readByte();
pps = new byte[ppsLength];
fis.read(pps,0,ppsLength);
} catch (IOException e) {
return false;
}
return true;
}
private boolean findBoxAvcc() {
try {
fis.seek(pos+8);
while (true) {
while (fis.read() != 'a');
fis.read(buffer,0,3);
if (buffer[0] == 'v' && buffer[1] == 'c' && buffer[2] == 'C') break;
}
} catch (IOException e) {
return false;
}
return true;
}
}
| 7,022 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
MP4Config.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/main/java/net/majorkernelpanic/streaming/mp4/MP4Config.java | /*
* Copyright (C) 2011-2014 GUIGUI Simon, [email protected]
*
* This file is part of libstreaming (https://github.com/fyhertz/libstreaming)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.majorkernelpanic.streaming.mp4;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.util.Base64;
import android.util.Log;
/**
* Finds SPS & PPS parameters in mp4 file.
*/
public class MP4Config {
public final static String TAG = "MP4Config";
private MP4Parser mp4Parser;
private String mProfilLevel, mPPS, mSPS;
public MP4Config(String profil, String sps, String pps) {
mProfilLevel = profil;
mPPS = pps;
mSPS = sps;
}
public MP4Config(String sps, String pps) {
mPPS = pps;
mSPS = sps;
mProfilLevel = MP4Parser.toHexString(Base64.decode(sps, Base64.NO_WRAP),1,3);
}
public MP4Config(byte[] sps, byte[] pps) {
mPPS = Base64.encodeToString(pps, 0, pps.length, Base64.NO_WRAP);
mSPS = Base64.encodeToString(sps, 0, sps.length, Base64.NO_WRAP);
mProfilLevel = MP4Parser.toHexString(sps,1,3);
}
/**
* Finds SPS & PPS parameters inside a .mp4.
* @param path Path to the file to analyze
* @throws IOException
* @throws FileNotFoundException
*/
public MP4Config (String path) throws IOException, FileNotFoundException {
StsdBox stsdBox;
// We open the mp4 file and parse it
try {
mp4Parser = MP4Parser.parse(path);
} catch (IOException ignore) {
// Maybe enough of the file has been parsed and we can get the stsd box
}
// We find the stsdBox
stsdBox = mp4Parser.getStsdBox();
mPPS = stsdBox.getB64PPS();
mSPS = stsdBox.getB64SPS();
mProfilLevel = stsdBox.getProfileLevel();
mp4Parser.close();
}
public String getProfileLevel() {
return mProfilLevel;
}
public String getB64PPS() {
Log.d(TAG, "PPS: "+mPPS);
return mPPS;
}
public String getB64SPS() {
Log.d(TAG, "SPS: "+mSPS);
return mSPS;
}
} | 2,612 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
ApplicationTest.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streaming/src/androidTest/java/net/majorkernelpanic/streaming/ApplicationTest.java | package net.majorkernelpanic.streaming;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 361 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AppConfig.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamandroidphone/src/main/java/com/quan404/streamandroidphone/AppConfig.java | package com.quan404.streamandroidphone;
/**
* Created by quanhua on 01/10/2015.
*/
public class AppConfig {
public static final String STREAM_URL = "rtsp://192.168.1.108:1935/live/test";
public static final String PUBLISHER_USERNAME = "quan";
public static final String PUBLISHER_PASSWORD = "quan12345";
}
| 321 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
StreamAndroidPhone.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamandroidphone/src/main/java/com/quan404/streamandroidphone/StreamAndroidPhone.java | package com.quan404.streamandroidphone;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
import net.majorkernelpanic.streaming.video.VideoQuality;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StreamAndroidPhone extends Activity implements RtspClient.Callback,
Session.Callback, SurfaceHolder.Callback {
// log tag
public final static String TAG = StreamAndroidPhone.class.getSimpleName();
// surfaceview
private static SurfaceView mSurfaceView;
// Rtsp session
private Session mSession;
private static RtspClient mClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_stream_android_phone);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
// Initialize RTSP client
initRtspClient();
}
@Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
@Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onBitrateUpdate(long bitrate) {
// Log.d(TAG, "Bitrate: " + bitrate);
}
@Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
alertError(e.getMessage());
e.printStackTrace();
}
}
@Override
public void onPreviewStarted() {
}
@Override
public void onSessionConfigured() {
}
@Override
public void onSessionStarted() {
}
@Override
public void onSessionStopped() {
}
private void alertError(final String msg) {
final String error = (msg == null) ? "Unknown error: " : msg;
AlertDialog.Builder builder = new AlertDialog.Builder(StreamAndroidPhone.this);
builder.setMessage(error).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
alertError(exception.getMessage());
exception.printStackTrace();
break;
}
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoQuality(new VideoQuality(640, 480, 15, 200000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(90)
.setCallback(this).build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
@Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
}
| 6,051 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
ApplicationTest.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamandroidphone/src/androidTest/java/com/quan404/streamandroidphone/ApplicationTest.java | package com.quan404.streamandroidphone;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 361 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
CheckableLinearLayout.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/main/java/com/serenegiant/widget/CheckableLinearLayout.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: CheckableLinearLayout.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.LinearLayout;
public final class CheckableLinearLayout extends LinearLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckableLinearLayout(final Context context) {
this(context, null);
}
public CheckableLinearLayout(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(final boolean checked) {
if (mChecked != checked) {
mChecked = checked;
final int n = this.getChildCount();
View v;
for (int i = 0; i < n; i++) {
v = this.getChildAt(i);
if (v instanceof Checkable)
((Checkable)v).setChecked(checked);
}
refreshDrawableState();
}
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
}
| 2,395 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AspectRatioViewInterface.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/main/java/com/serenegiant/widget/AspectRatioViewInterface.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: AspectRatioViewInterface.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
public interface AspectRatioViewInterface {
public void setAspectRatio(double aspectRatio);
public void onPause();
public void onResume();
}
| 1,157 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
UVCCameraTextureView.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/main/java/com/serenegiant/widget/UVCCameraTextureView.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: CheckableLinearLayout.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;
/**
* change the view size with keeping the specified aspect ratio.
* if you set this view with in a FrameLayout and set property "android:layout_gravity="center",
* you can show this view in the center of screen and keep the aspect ratio of content
* XXX it is better that can set the aspect raton a a xml property
*/
public class UVCCameraTextureView extends TextureView // API >= 14
implements AspectRatioViewInterface {
private double mRequestedAspect = -1.0;
public UVCCameraTextureView(final Context context) {
this(context, null, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void setAspectRatio(final double aspectRatio) {
if (aspectRatio < 0) {
throw new IllegalArgumentException();
}
if (mRequestedAspect != aspectRatio) {
mRequestedAspect = aspectRatio;
requestLayout();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mRequestedAspect > 0) {
int initialWidth = MeasureSpec.getSize(widthMeasureSpec);
int initialHeight = MeasureSpec.getSize(heightMeasureSpec);
final int horizPadding = getPaddingLeft() + getPaddingRight();
final int vertPadding = getPaddingTop() + getPaddingBottom();
initialWidth -= horizPadding;
initialHeight -= vertPadding;
final double viewAspectRatio = (double)initialWidth / initialHeight;
final double aspectDiff = mRequestedAspect / viewAspectRatio - 1;
if (Math.abs(aspectDiff) > 0.01) {
if (aspectDiff > 0) {
// width priority decision
initialHeight = (int) (initialWidth / mRequestedAspect);
} else {
// height priority decison
initialWidth = (int) (initialHeight * mRequestedAspect);
}
initialWidth += horizPadding;
initialHeight += vertPadding;
widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| 3,472 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AppConfig.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/main/java/com/quan404/streamusbcamera/AppConfig.java | package com.quan404.streamusbcamera;
/**
* Created by quanhua on 01/10/2015.
*/
public class AppConfig {
public static final String STREAM_URL = "rtsp://192.168.1.108:1935/live/test";
public static final String PUBLISHER_USERNAME = "quan";
public static final String PUBLISHER_PASSWORD = "quan12345";
}
| 318 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
StreamUsbCamera.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/main/java/com/quan404/streamusbcamera/StreamUsbCamera.java | package com.quan404.streamusbcamera;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Toast;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.IFrameCallback;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.widget.UVCCameraTextureView;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
import net.majorkernelpanic.streaming.video.VideoQuality;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StreamUsbCamera extends Activity implements CameraDialog.CameraDialogParent, RtspClient.Callback,
Session.Callback, SurfaceHolder.Callback{
// for debugging
private static String TAG = "StreamUsbCamera";
private static boolean DEBUG = true;
// for thread pool
private static final int CORE_POOL_SIZE = 1; // initial/minimum threads
private static final int MAX_POOL_SIZE = 4; // maximum threads
private static final int KEEP_ALIVE_TIME = 10; // time periods while keep the idle thread
protected static final ThreadPoolExecutor EXECUTER
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
// for accessing USB and USB camera
private USBMonitor mUSBMonitor;
private UVCCamera mCamera = null;
private UVCCameraTextureView mUVCCameraView;
private Surface mPreviewSurface;
// Rtsp session
private boolean READY_FOR_STREAM = false;
private Session mSession;
private static RtspClient mClient;
private static SurfaceView mSurfaceView;
private Surface canvasSurface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_usb_camera);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
mUVCCameraView = (UVCCameraTextureView) findViewById(R.id.UVCCameraTextureView);
mUVCCameraView.setAspectRatio(UVCCamera.DEFAULT_PREVIEW_WIDTH * 1.0f / UVCCamera.DEFAULT_PREVIEW_HEIGHT);
mUVCCameraView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCamera == null) {
CameraDialog.showDialog(StreamUsbCamera.this);
} else {
releaseUVCCamera();
}
}
});
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
// Initialize RTSP client
initRtspClient();
}
public void testBitmap(View view){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.raw.image, opts);
if(!READY_FOR_STREAM){
READY_FOR_STREAM = true;
toggleStreaming();
}
new Thread(new MyTestBitmapThread(bitmap)).start();
}
public class MyTestBitmapThread implements Runnable{
private Bitmap bitmap;
public MyTestBitmapThread(Bitmap bm){
bitmap = bm;
}
@Override
public void run() {
for(int i = 0 ; i < 1000 ; i++){
drawOnCanvas(bitmap, "#Frame " + i);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
@Override
protected void onResume() {
super.onResume();
mUSBMonitor.register();
if (mCamera != null)
mCamera.startPreview();
toggleStreaming();
}
@Override
protected void onPause() {
mUSBMonitor.unregister();
if (mCamera != null)
mCamera.stopPreview();
toggleStreaming();
super.onPause();
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onBitrateUpdate(long bitrate) {
// Log.d(TAG, "Bitrate: " + bitrate);
}
@Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
alertError(e.getMessage());
e.printStackTrace();
}
}
@Override
public void onPreviewStarted() {
}
@Override
public void onSessionConfigured() {
}
@Override
public void onSessionStarted() {
}
@Override
public void onSessionStopped() {
}
private void alertError(final String msg) {
final String error = (msg == null) ? "Unknown error: " : msg;
AlertDialog.Builder builder = new AlertDialog.Builder(StreamUsbCamera.this);
builder.setMessage(error).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
alertError(exception.getMessage());
exception.printStackTrace();
break;
}
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoQuality(new VideoQuality(640, 480, 15, 200000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setPreviewOrientation(90)
.setSurfaceView(mSurfaceView)
.setCallback(this).build();
// Get Surface
canvasSurface = mSession.getVideoTrack().getSurface();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
Log.e(TAG, "done initRtsp");
}
private void toggleStreaming() {
if(!READY_FOR_STREAM) return;
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
@Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
if(mUSBMonitor != null){
mUSBMonitor.destroy();
}
if (mCamera != null)
mCamera.destroy();
super.onDestroy();
}
private USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
@Override
public void onAttach(UsbDevice device) {
if (DEBUG) Log.v(TAG, "onAttach:" + device);
Toast.makeText(StreamUsbCamera.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
}
@Override
public void onDettach(UsbDevice device) {
if (DEBUG) Log.v(TAG, "onDetach:" + device);
Toast.makeText(StreamUsbCamera.this, "USB_DEVICE_DETACHED", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnect(UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
if(mCamera != null) return;
if (DEBUG) Log.v(TAG, "onConnect: " + device);
final UVCCamera camera = new UVCCamera();
EXECUTER.execute(new Runnable() {
@Override
public void run() {
// Open Camera
camera.open(ctrlBlock);
// Set Preview Mode
try {
if (DEBUG) Log.v(TAG, "MJPEG MODE");
camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.FRAME_FORMAT_MJPEG, 0.5f);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
if (DEBUG) Log.v(TAG, "PREVIEW MODE");
try {
camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.DEFAULT_PREVIEW_MODE, 0.5f);
} catch (IllegalArgumentException e2) {
if (DEBUG) Log.v(TAG, "CAN NOT ENTER PREVIEW MODE");
// camera.destroy();
releaseUVCCamera();
e2.printStackTrace();
}
}
// Start Preview
if (mCamera == null) {
mCamera = camera;
if (mPreviewSurface != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface.release()");
mPreviewSurface.release();
mPreviewSurface = null;
}
final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
if (st != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface = new Surface(st);");
mPreviewSurface = new Surface(st);
}
camera.setPreviewDisplay(mPreviewSurface);
camera.setFrameCallback(mIFrameCallback, UVCCamera.PIXEL_FORMAT_RGB565);
camera.startPreview();
}
}
});
}
@Override
public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {
if(DEBUG) Log.v(TAG, "onDisconnect" + device);
if(mCamera != null && device.equals(mCamera.getDevice())){
releaseUVCCamera();
}
}
@Override
public void onCancel() {
}
};
private void releaseUVCCamera(){
if(DEBUG) Log.v(TAG, "releaseUVCCamera");
mCamera.close();
if (mPreviewSurface != null){
mPreviewSurface.release();
mPreviewSurface = null;
}
mCamera.destroy();
mCamera = null;
}
@Override
public USBMonitor getUSBMonitor() {
return mUSBMonitor;
}
android.os.Handler handlr = new android.os.Handler();
final Bitmap bitmap = Bitmap.createBitmap(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, Bitmap.Config.RGB_565);
private final IFrameCallback mIFrameCallback = new IFrameCallback() {
@Override
public void onFrame(final ByteBuffer frame) {
frame.clear();
synchronized (bitmap) {
bitmap.copyPixelsFromBuffer(frame.asReadOnlyBuffer());
if(!READY_FOR_STREAM){
READY_FOR_STREAM = true;
toggleStreaming();
}
drawOnCanvas(bitmap, "");
}
}
};
private void drawOnCanvas(Bitmap bitmap, String text){
Paint paint = new Paint();
/* Test: draw 10 frames at 30fps before start
* these should be dropped and not causing malformed stream.
*/
try{
if(canvasSurface == null || !canvasSurface.isValid()) {
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid())");
canvasSurface = mSession.getVideoTrack().getSurface();
if(canvasSurface == null || !canvasSurface.isValid()) {
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid()) READ OK");
}else{
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid()) READ FAIL");
}
return;
}
Canvas canvas = canvasSurface.lockCanvas(null);
Log.d(TAG, "drawOnCanvas locked");
canvas.drawBitmap(bitmap, 0, 0, paint);
paint.setTextSize(20);
canvas.drawText(text, 100, 100, paint);
canvasSurface.unlockCanvasAndPost(canvas);
}catch (Exception e) {
e.printStackTrace();
return;
}
}
}
| 14,932 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
ApplicationTest.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamusbcamera/src/androidTest/java/com/quan404/streamusbcamera/ApplicationTest.java | package com.quan404.streamusbcamera;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 358 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
CheckableLinearLayout.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/main/java/com/serenegiant/widget/CheckableLinearLayout.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: CheckableLinearLayout.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.LinearLayout;
public final class CheckableLinearLayout extends LinearLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckableLinearLayout(final Context context) {
this(context, null);
}
public CheckableLinearLayout(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(final boolean checked) {
if (mChecked != checked) {
mChecked = checked;
final int n = this.getChildCount();
View v;
for (int i = 0; i < n; i++) {
v = this.getChildAt(i);
if (v instanceof Checkable)
((Checkable)v).setChecked(checked);
}
refreshDrawableState();
}
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
}
| 2,395 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AspectRatioViewInterface.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/main/java/com/serenegiant/widget/AspectRatioViewInterface.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: AspectRatioViewInterface.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
public interface AspectRatioViewInterface {
public void setAspectRatio(double aspectRatio);
public void onPause();
public void onResume();
}
| 1,157 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
UVCCameraTextureView.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/main/java/com/serenegiant/widget/UVCCameraTextureView.java | package com.serenegiant.widget;
/*
* UVCCamera
* library and sample to access to UVC web camera on non-rooted Android device
*
* Copyright (c) 2014-2015 saki [email protected]
*
* File name: CheckableLinearLayout.java
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All files in the folder are under this Apache License, Version 2.0.
* Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;
/**
* change the view size with keeping the specified aspect ratio.
* if you set this view with in a FrameLayout and set property "android:layout_gravity="center",
* you can show this view in the center of screen and keep the aspect ratio of content
* XXX it is better that can set the aspect raton a a xml property
*/
public class UVCCameraTextureView extends TextureView // API >= 14
implements AspectRatioViewInterface {
private double mRequestedAspect = -1.0;
public UVCCameraTextureView(final Context context) {
this(context, null, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public UVCCameraTextureView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void setAspectRatio(final double aspectRatio) {
if (aspectRatio < 0) {
throw new IllegalArgumentException();
}
if (mRequestedAspect != aspectRatio) {
mRequestedAspect = aspectRatio;
requestLayout();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mRequestedAspect > 0) {
int initialWidth = MeasureSpec.getSize(widthMeasureSpec);
int initialHeight = MeasureSpec.getSize(heightMeasureSpec);
final int horizPadding = getPaddingLeft() + getPaddingRight();
final int vertPadding = getPaddingTop() + getPaddingBottom();
initialWidth -= horizPadding;
initialHeight -= vertPadding;
final double viewAspectRatio = (double)initialWidth / initialHeight;
final double aspectDiff = mRequestedAspect / viewAspectRatio - 1;
if (Math.abs(aspectDiff) > 0.01) {
if (aspectDiff > 0) {
// width priority decision
initialHeight = (int) (initialWidth / mRequestedAspect);
} else {
// height priority decison
initialWidth = (int) (initialHeight * mRequestedAspect);
}
initialWidth += horizPadding;
initialHeight += vertPadding;
widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| 3,472 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
AppConfig.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/main/java/com/quan404/streamdualusbcamera/AppConfig.java | package com.quan404.streamdualusbcamera;
/**
* Created by quanhua on 01/10/2015.
*/
public class AppConfig {
public static final String STREAM_URL = "rtsp://192.168.1.108:1935/live/test";
public static final String PUBLISHER_USERNAME = "quan";
public static final String PUBLISHER_PASSWORD = "quan12345";
}
| 322 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
StreamDualUsbCamera.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/main/java/com/quan404/streamdualusbcamera/StreamDualUsbCamera.java | package com.quan404.streamdualusbcamera;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Toast;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.IFrameCallback;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;
import com.serenegiant.widget.UVCCameraTextureView;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
import net.majorkernelpanic.streaming.video.VideoQuality;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StreamDualUsbCamera extends Activity implements CameraDialog.CameraDialogParent, RtspClient.Callback,
Session.Callback, SurfaceHolder.Callback{
// for debugging
private static String TAG = "StreamDualUsbCamera";
private static boolean DEBUG = true;
// for thread pool
private static final int CORE_POOL_SIZE = 1; // initial/minimum threads
private static final int MAX_POOL_SIZE = 4; // maximum threads
private static final int KEEP_ALIVE_TIME = 10; // time periods while keep the idle thread
protected static final ThreadPoolExecutor EXECUTER
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
// for accessing USB and USB camera
private USBMonitor mUSBMonitor;
private UVCCamera mCameraLeft = null;
private UVCCameraTextureView mUVCCameraViewLeft;
private Surface mPreviewSurfaceLeft;
private UVCCamera mCameraRight = null;
private UVCCameraTextureView mUVCCameraViewRight;
private Surface mPreviewSurfaceRight;
private int SELECTED_ID = -1;
private int SELECTED_FPS = 24;
private long SELECTED_FRAME_TIME = 0;
// Rtsp session
private boolean READY_FOR_STREAM = false;
private Session mSession;
private static RtspClient mClient;
private static SurfaceView mSurfaceView;
private Surface canvasSurface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_dual_usb_camera);
hideNavigationBar();
SELECTED_FRAME_TIME = 1000L / SELECTED_FPS;
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
mUVCCameraViewLeft = (UVCCameraTextureView) findViewById(R.id.cameraView01);
mUVCCameraViewLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCameraLeft == null) {
CameraDialog.showDialog(StreamDualUsbCamera.this);
SELECTED_ID = 0;
} else {
releaseUVCCamera(0);
}
}
});
mUVCCameraViewRight = (UVCCameraTextureView) findViewById(R.id.cameraView02);
mUVCCameraViewRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCameraRight == null) {
CameraDialog.showDialog(StreamDualUsbCamera.this);
SELECTED_ID = 1;
} else {
releaseUVCCamera(1);
}
}
});
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
new Thread(new MyStreamThread()).start();
// Initialize RTSP client
initRtspClient();
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoQuality(new VideoQuality(UVCCamera.DEFAULT_PREVIEW_WIDTH * 2, UVCCamera.DEFAULT_PREVIEW_HEIGHT, SELECTED_FPS, 400000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setPreviewOrientation(90)
.setSurfaceView(mSurfaceView)
.setCallback(this).build();
// Get Surface
canvasSurface = mSession.getVideoTrack().getSurface();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
Log.e(TAG, "done initRtsp");
}
private void toggleStreaming() {
if(!READY_FOR_STREAM) return;
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
@Override
protected void onResume() {
super.onResume();
mUSBMonitor.register();
if (mCameraLeft != null)
mCameraLeft.startPreview();
if (mCameraRight != null)
mCameraRight.startPreview();
}
@Override
protected void onPause() {
mUSBMonitor.unregister();
if (mCameraLeft != null)
mCameraLeft.stopPreview();
if (mCameraRight != null)
mCameraRight.stopPreview();
super.onPause();
}
@Override
protected void onDestroy() {
if(mUSBMonitor != null){
mUSBMonitor.destroy();
}
if (mCameraLeft != null)
mCameraLeft.destroy();
if (mCameraRight != null)
mCameraRight.destroy();
releaseUVCCamera(2);
super.onDestroy();
}
private USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
@Override
public void onAttach(UsbDevice device) {
if (DEBUG) Log.v(TAG, "onAttach:" + device);
Toast.makeText(StreamDualUsbCamera.this, "USB_DEVICE_ATTACHED", Toast.LENGTH_SHORT).show();
}
@Override
public void onDettach(UsbDevice device) {
if (DEBUG) Log.v(TAG, "onDetach:" + device);
Toast.makeText(StreamDualUsbCamera.this, "USB_DEVICE_DETACHED", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnect(UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
if(mCameraLeft != null && mCameraRight != null) return;
if (DEBUG) Log.v(TAG, "onConnect: " + device);
final UVCCamera camera = new UVCCamera();
final int current_id = SELECTED_ID;
SELECTED_ID = -1;
EXECUTER.execute(new Runnable() {
@Override
public void run() {
// Open Camera
camera.open(ctrlBlock);
// Set Preview Mode
try {
if (DEBUG) Log.v(TAG, "MJPEG MODE");
camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.FRAME_FORMAT_MJPEG, 0.5f);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
if (DEBUG) Log.v(TAG, "PREVIEW MODE");
try {
camera.setPreviewSize(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, UVCCamera.DEFAULT_PREVIEW_MODE, 0.5f);
} catch (IllegalArgumentException e2) {
if (DEBUG) Log.v(TAG, "CAN NOT ENTER PREVIEW MODE");
camera.destroy();
e2.printStackTrace();
}
}
// Start Preview
if (mCameraLeft == null && current_id == 0) {
mCameraLeft = camera;
if (mPreviewSurfaceLeft != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface.release()");
mPreviewSurfaceLeft.release();
mPreviewSurfaceLeft = null;
}
final SurfaceTexture st = mUVCCameraViewLeft.getSurfaceTexture();
if (st != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface = new Surface(st);");
mPreviewSurfaceLeft = new Surface(st);
}
camera.setPreviewDisplay(mPreviewSurfaceLeft);
camera.setFrameCallback(mIFrameCallbackLeft, UVCCamera.PIXEL_FORMAT_RGB565);
camera.startPreview();
}
if (mCameraRight == null && current_id == 1) {
mCameraRight = camera;
if (mPreviewSurfaceRight != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface.release()");
mPreviewSurfaceRight.release();
mPreviewSurfaceRight = null;
}
final SurfaceTexture st = mUVCCameraViewRight.getSurfaceTexture();
if (st != null) {
if (DEBUG) Log.v(TAG, "mPreviewSurface = new Surface(st);");
mPreviewSurfaceRight = new Surface(st);
}
camera.setPreviewDisplay(mPreviewSurfaceRight);
camera.setFrameCallback(mIFrameCallbackRight, UVCCamera.PIXEL_FORMAT_RGB565);
camera.startPreview();
}
}
});
}
@Override
public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {
if(DEBUG) Log.v(TAG, "onDisconnect" + device);
if(mCameraLeft != null && device.equals(mCameraLeft.getDevice())){
releaseUVCCamera(0);
}
if(mCameraRight != null && device.equals(mCameraRight.getDevice())){
releaseUVCCamera(1);
}
}
@Override
public void onCancel() {
}
};
private static final int MAX_FRAME_AVAILABLE = 1;
private Semaphore flagLeft = new Semaphore(MAX_FRAME_AVAILABLE);
private final Bitmap bitmapLeft = Bitmap.createBitmap(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, Bitmap.Config.RGB_565);
private final IFrameCallback mIFrameCallbackLeft = new IFrameCallback() {
@Override
public void onFrame(final ByteBuffer frame) {
frame.clear();
Log.d(TAG, "hasFrame");
synchronized (bitmapLeft) {
bitmapLeft.copyPixelsFromBuffer(frame.asReadOnlyBuffer());
flagLeft.release(); //++
}
}
};
private Semaphore flagRight = new Semaphore(MAX_FRAME_AVAILABLE);
final Bitmap bitmapRight = Bitmap.createBitmap(UVCCamera.DEFAULT_PREVIEW_WIDTH, UVCCamera.DEFAULT_PREVIEW_HEIGHT, Bitmap.Config.RGB_565);
private final IFrameCallback mIFrameCallbackRight = new IFrameCallback() {
@Override
public void onFrame(final ByteBuffer frame) {
frame.clear();
synchronized (bitmapRight) {
bitmapRight.copyPixelsFromBuffer(frame.asReadOnlyBuffer());
flagRight.release(); //++
}
}
};
@Override
public void onBitrateUpdate(long bitrate) {
}
@Override
public void onSessionError(int reason, int streamType, Exception e) {
}
@Override
public void onPreviewStarted() {
}
@Override
public void onSessionConfigured() {
}
@Override
public void onSessionStarted() {
}
@Override
public void onSessionStopped() {
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
@Override
public void onRtspUpdate(int message, Exception exception) {
}
private class MyStreamThread implements Runnable{
@Override
public void run() {
flagLeft.drainPermits();
flagRight.drainPermits();
while(true){
try {
flagLeft.acquire();//--
flagRight.acquire();
Bitmap left = bitmapLeft;
Bitmap right = bitmapRight;
if(!READY_FOR_STREAM){
READY_FOR_STREAM = true;
toggleStreaming();
}
Bitmap merge = Bitmap.createBitmap(UVCCamera.DEFAULT_PREVIEW_WIDTH * 2, UVCCamera.DEFAULT_PREVIEW_HEIGHT, Bitmap.Config.RGB_565 ); // merge left , right
Canvas canvas = new Canvas(merge);
canvas.drawBitmap(left, 0, 0, null);
canvas.drawBitmap(right, left.getWidth(), 0, null);
drawOnCanvas(merge);
Thread.sleep(SELECTED_FRAME_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void drawOnCanvas(Bitmap bitmap){
Paint paint = new Paint();
/* Test: draw 10 frames at 30fps before start
* these should be dropped and not causing malformed stream.
*/
try{
if(canvasSurface == null || !canvasSurface.isValid()) {
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid())");
canvasSurface = mSession.getVideoTrack().getSurface();
if(canvasSurface == null || !canvasSurface.isValid()) {
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid()) READ OK");
}else{
Log.d(TAG, "if(canvasSurface == null || !canvasSurface.isValid()) READ FAIL");
}
return;
}
Canvas canvas = canvasSurface.lockCanvas(null);
Log.d(TAG, "drawOnCanvas locked");
canvas.drawBitmap(bitmap, 0, 0, paint);
canvasSurface.unlockCanvasAndPost(canvas);
}catch (Exception e) {
e.printStackTrace();
return;
}
}
private void releaseUVCCamera(int id){
if(DEBUG) Log.v(TAG, "releaseUVCCamera");
if(id == 0 || id == 2){
mCameraLeft.close();
if (mPreviewSurfaceLeft != null){
mPreviewSurfaceLeft.release();
mPreviewSurfaceLeft = null;
}
mCameraLeft.destroy();
mCameraLeft = null;
}
if(id == 1 || id == 2){
mCameraRight.close();
if (mPreviewSurfaceRight != null){
mPreviewSurfaceRight.release();
mPreviewSurfaceRight = null;
}
mCameraRight.destroy();
mCameraRight = null;
}
SELECTED_ID = -1;
}
@Override
public USBMonitor getUSBMonitor() {
return mUSBMonitor;
}
// for UI fullscreen
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus)
hideNavigationBar();
}
private void hideNavigationBar() {
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
} | 17,778 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
ApplicationTest.java | /FileExtraction/Java_unseen/quanhua92_libstreaming_android_studio/streamdualusbcamera/src/androidTest/java/com/quan404/streamdualusbcamera/ApplicationTest.java | package com.quan404.streamdualusbcamera;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 362 | Java | .java | quanhua92/libstreaming_android_studio | 13 | 7 | 0 | 2015-10-01T03:19:52Z | 2015-10-06T09:32:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/package-info.java | /**
* package-info: ssms 测试
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
package com.chengjs.cjsssmsweb; | 171 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/common/package-info.java | /**
* package-info:
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/10
*/
package com.chengjs.cjsssmsweb.common; | 167 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
MapperTest.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/common/mapper/MapperTest.java | package com.chengjs.cjsssmsweb.common.mapper;
import com.chengjs.cjsssmsweb.common.util.codec.MD5Util;
import com.chengjs.cjsssmsweb.common.util.math.MathUtil;
import com.chengjs.cjsssmsweb.mybatis.MybatisHelper;
import com.chengjs.cjsssmsweb.mybatis.mapper.master.UUserMapper;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import java.io.IOException;
import java.util.Date;
/**
* MapperTest:
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
public class MapperTest {
private static final String NUM = MathUtil.genRandNum(4);
public static void main(String[] args) throws IOException {
SqlSession session = null;
try {
session = MybatisHelper.getSqlSession();
UUserMapper mapper = session.getMapper(UUserMapper.class);
UUser user = new UUser();
// user.setId(UUIDUtil.uuid());
user.setUsername("mapperTestUser" + NUM);
user.setPassword(MD5Util.md5("1"));
user.setDescription("MapperTest创建的User");
// user.setDiscard("1");
user.setCreatetime(new Date());
user.setModifytime(new Date());
//新增一条数据
Assert.assertEquals(1, mapper.insert(user));
// mapper.insert(user);
/*Mapper null属性不使用数据库默认值 用selective方法即可,为null,不参与sql,数据库使用默认值*/
// mapper.insertSelective(user);
System.out.println("回调 user id :" + user.getId());
/* //查询数据 等号查询
List<UUser> users = mapper.select(user);
//ID回写,不为空
System.out.printf(user.getId());
Assert.assertNotNull(user.getId());
//通过主键删除新增的数据
Assert.assertEquals("1", mapper.deleteByPrimaryKey(user));*/
// session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
}
| 1,978 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
PageMapperTest.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/common/pagehelper/PageMapperTest.java | package com.chengjs.cjsssmsweb.common.pagehelper;
import com.chengjs.cjsssmsweb.mybatis.MybatisHelper;
import com.chengjs.cjsssmsweb.mybatis.mapper.master.CountryMapper;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.Country;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* PageMapperTest:
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/10
*/
public class PageMapperTest {
@Test
public void test(){
SqlSession sqlSession = MybatisHelper.getSqlSession();
CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
Example example = new Example(Country.class);
example.createCriteria().andGreaterThan("id",100);
PageHelper.startPage(2,10);
/*SELECT Id,countryname,countrycode FROM country WHERE ( Id > ? )*/
List<Country> countries = countryMapper.selectByExample(example);
PageInfo<Country> pageInfo = new PageInfo<Country>(countries);
System.out.println(pageInfo.getTotal());
countries = countryMapper.selectByExample(example);
pageInfo = new PageInfo<Country>(countries);
System.out.println(pageInfo.getTotal());
}
}
| 1,326 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/components/package-info.java | /**
* package-info: 组件包
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
package com.chengjs.cjsssmsweb.components; | 180 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
LuceneTest.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/test/java/com/chengjs/cjsssmsweb/components/lucene/LuceneTest.java | package com.chengjs.cjsssmsweb.components.lucene;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* LuceneTest:
* author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/8/29
*/
public class LuceneTest {
private static final Logger log = LoggerFactory.getLogger(LuceneTest.class);
@Test
public void luceneTest() throws Exception {
// Store the index in memory:
Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
// Directory directory = FSDirectory.open("/tmp/testindex");
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
try {
IndexWriter iwriter = new IndexWriter(directory, config);
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
iwriter.addDocument(doc);
iwriter.close();
// Now search the index:
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, 1000, new Sort()).scoreDocs;
assertEquals(1, hits.length);
// Iterate through the results:
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
}
ireader.close();
directory.close();
log.debug("LuceneTest Passed");
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 2,710 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/package-info.java | /**
* package-info: 通用模块,与单独项目解耦部分放到此包
* author: Chengjs, version:1.0.0, 2017-09-08
*/
package com.chengjs.cjsssmsweb.common; | 162 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/mapper/package-info.java | /**
* package-info: Mapper 实践经验和细节 https://github.com/abel533/Mapper
*
* 1.回写的UUID http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/10.Mapper-UUID.md
* Oracle: <property name="ORDER" value="BEFORE"/> 配置如此先取到值否则报错
* @Id
* @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "select uuid()")
* private String id;
*
* @Id
* @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "select SEQ_ID.nextval from dual")
* private Integer id;
*
*
*
*
*
*
*
*
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/10
*/
package com.chengjs.cjsssmsweb.common.mapper; | 702 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
MyMapper.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/mapper/MyMapper.java | package com.chengjs.cjsssmsweb.common.mapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* MyMapper: 其他接口继承 Mapper即可, 见com.chengjs.cjsssmsweb.mybatis.mapper.master下Mapper-generate生成的接口
*
* http://git.oschina.net/free/Mapper/blob/master/wiki/mapper3/3.Use.md
*
* 1.泛型T必须被指定为具体的类型
* 1)驼峰 UserInfo => user_info
* 2)@Table(name = "tableName")
* 3)@Column(name = "fieldName")
* 4)@Transient 字段不作为表字段使用
* 5)@id
* 6)实体类可以继承使用
* 7)实体类不建议使用基本类型 如int
* 8)@NameStype 配置pojo和表名映射
* normal,camelhump,uppercase,lowercase
*
* 2.主键策略(insert): 序列(支持Oracle)、UUID(任意数据库,字段长度32)、主键自增(类似Mysql,Hsqldb)
* 序列和UUID可以配置多个,主键自增只能配置一个
*
* @GeneratedValue(generator = "JDBC")
* @GeneratedValue(strategy = GenerationType.IDENTITY)
* @GeneratedValue(generator = "UUID")
*
*
* @author: <a href="mailto:[email protected]">chengjs</a>, version:1.0.0, 21:12
*/
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
| 1,221 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
MapperGenerate.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/mapper/MapperGenerate.java | package com.chengjs.cjsssmsweb.common.mapper;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.util.ArrayList;
import java.util.List;
/**
* MapperGenerate:
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
public class MapperGenerate {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<>();
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(
MapperGenerate.class.getResourceAsStream("/database/mybatis-generator-mapper-config.xml"));
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
| 1,008 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
UnicodeReader.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/UnicodeReader.java | package com.chengjs.cjsssmsweb.common.miniui;
/**
version: 1.1 / 2007-01-25
- changed BOM recognition ordering (longer boms first)
Original pseudocode : Thomas Weidenfeller
Implementation tweaked: Aki Nieminen
http://www.unicode.org/unicode/faq/utf_bom.html
BOMs:
00 00 FE FF = UTF-32, big-endian
FF FE 00 00 = UTF-32, little-endian
EF BB BF = UTF-8,
FE FF = UTF-16, big-endian
FF FE = UTF-16, little-endian
Win2k Notepad:
Unicode format = UTF-16LE
***/
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.Reader;
/**
* Generic unicode textreader, which will use BOM mark
* to identify the encoding to be used. If BOM is not found
* then use a given default or system encoding.
*/
public class UnicodeReader extends Reader {
PushbackInputStream internalIn;
InputStreamReader internalIn2 = null;
String defaultEnc;
private static final int BOM_SIZE = 4;
/**
*
* @param in inputstream to be read
* @param defaultEnc default encoding if stream does not have
* BOM marker. Give NULL to use system-level default.
*/
public UnicodeReader(InputStream in, String defaultEnc) {
internalIn = new PushbackInputStream(in, BOM_SIZE);
this.defaultEnc = defaultEnc;
}
public String getDefaultEncoding() {
return defaultEnc;
}
/**
* Get stream encoding or NULL if stream is uninitialized.
* Call init() or read() method to initialize it.
*/
public String getEncoding() {
if (internalIn2 == null) return null;
return internalIn2.getEncoding();
}
/**
* Read-ahead four bytes and check for BOM marks. Extra bytes are
* unread back to the stream, only BOM bytes are skipped.
*/
protected void init() throws IOException {
if (internalIn2 != null) return;
String encoding;
byte bom[] = new byte[BOM_SIZE];
int n, unread;
n = internalIn.read(bom, 0, bom.length);
if ( (bom[0] == (byte)0x00) && (bom[1] == (byte)0x00) &&
(bom[2] == (byte)0xFE) && (bom[3] == (byte)0xFF) ) {
encoding = "UTF-32BE";
unread = n - 4;
} else if ( (bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) &&
(bom[2] == (byte)0x00) && (bom[3] == (byte)0x00) ) {
encoding = "UTF-32LE";
unread = n - 4;
} else if ( (bom[0] == (byte)0xEF) && (bom[1] == (byte)0xBB) &&
(bom[2] == (byte)0xBF) ) {
encoding = "UTF-8";
unread = n - 3;
} else if ( (bom[0] == (byte)0xFE) && (bom[1] == (byte)0xFF) ) {
encoding = "UTF-16BE";
unread = n - 2;
} else if ( (bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) ) {
encoding = "UTF-16LE";
unread = n - 2;
} else {
// Unicode BOM mark not found, unread all bytes
encoding = defaultEnc;
unread = n;
}
//System.out.println("read=" + n + ", unread=" + unread);
if (unread > 0) internalIn.unread(bom, (n - unread), unread);
// Use given encoding
if (encoding == null) {
internalIn2 = new InputStreamReader(internalIn);
} else {
internalIn2 = new InputStreamReader(internalIn, encoding);
}
}
public void close() throws IOException {
init();
internalIn2.close();
}
public int read(char[] cbuf, int off, int len) throws IOException {
init();
return internalIn2.read(cbuf, off, len);
}
} | 3,606 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/package-info.java | /**
* package-info: miniui框架后台一些通用工具类
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/24
*/
package com.chengjs.cjsssmsweb.common.miniui; | 214 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
TestDB.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/TestDB.java | package com.chengjs.cjsssmsweb.common.miniui;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class TestDB {
//mysql
public static String driver = "com.mysql.jdbc.Driver";
public static String url = "jdbc:mysql://localhost/plusoft_test?useUnicode=true&characterEncoding=GBK";
public static String user = "root";
public static String pwd = "";
//sqlserver
// public static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// public static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=plusoft_test;";
// public static String user = "";
// public static String pwd = "";
////////////////////////////////////////////////////
public String InsertNode(HashMap n) throws Exception {
String sql = "insert into plus_file (id, name, type, size, url, pid, createdate, updatedate, folder, num)"
+ " values(?,?,?,?,?,?,?,?,?,?)";
DBInsert(sql, n);
return n.get("id").toString();
}
public void RemoveNode(HashMap n) throws Exception {
String id = n.get("id").toString();
Connection conn = getConn();
Statement stmt = conn.createStatement();
String sql = "delete from plus_file where id = \"" + id + "\"";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
public void UpdateTreeNode(HashMap n) throws Exception {
String sql =
"UPDATE plus_file "
+ " SET "
+ " name = ?,"
+ " pid = ?,"
+ " num = ?"
+ " WHERE id = ?";
Connection conn = getConn();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(n.get("name")));
stmt.setString(2, ToString(n.get("pid")));
stmt.setInt(3, ToInt(n.get("num")));
stmt.setString(4, ToString(n.get("id")));
stmt.executeUpdate();
stmt.close();
conn.close();
}
public ArrayList GetDepartments() throws Exception {
String sql = "select *"
+ " from t_department";
ArrayList data = DBSelect(sql);
return data;
}
public HashMap GetDepartment(String id) throws Exception {
String sql = "select * from t_department where id = '" + id + "'";
ArrayList data = DBSelect(sql);
return data.size() > 0 ? (HashMap) data.get(0) : null;
}
public ArrayList GetPositions() throws Exception {
String sql = "select * from t_position";
ArrayList data = DBSelect(sql);
return data;
}
public ArrayList GetEducationals() throws Exception {
String sql = "select * from t_educational";
ArrayList data = DBSelect(sql);
return data;
}
public ArrayList GetPositionsByDepartmenId(String departmentId) throws Exception {
String sql = "select * from t_position where dept_id = '" + departmentId + "'";
ArrayList dataAll = DBSelect(sql);
return dataAll;
}
public HashMap GetDepartmentEmployees(String departmentId, int index, int size) throws Exception {
String sql = "select * from t_employee where dept_id = '" + departmentId + "'";
ArrayList dataAll = DBSelect(sql);
ArrayList data = new ArrayList();
int start = index * size, end = start + size;
for (int i = 0, l = dataAll.size(); i < l; i++) {
HashMap record = (HashMap) dataAll.get(i);
if (record == null) continue;
if (start <= i && i < end) {
data.add(record);
}
}
HashMap result = new HashMap();
result.put("data", data);
result.put("total", dataAll.size());
return result;
}
public HashMap SearchEmployees(String key, int index, int size, String sortField, String sortOrder) throws Exception {
//System.Threading.Thread.Sleep(300);
if (key == null) key = "";
String sql =
"select a.*, b.name dept_name, c.name position_name, d.name educational_name \n"
+ "from t_employee a \n"
+ "left join t_department b \n"
+ "on a.dept_id = b.id \n"
+ "left join t_position c \n"
+ "on a.position = c.id \n"
+ "left join t_educational d \n"
+ "on a.educational = d.id \n"
+ "where a.name like '%" + key + "%' \n";
if (StringUtil.isNullOrEmpty(sortField) == false) {
if ("desc".equals(sortOrder) == false) sortOrder = "asc";
sql += " order by " + sortField + " " + sortOrder;
} else {
sql += " order by createtime desc";
}
ArrayList dataAll = DBSelect(sql);
ArrayList data = new ArrayList();
int start = index * size, end = start + size;
for (int i = 0, l = dataAll.size(); i < l; i++) {
HashMap record = (HashMap) dataAll.get(i);
if (record == null) continue;
if (start <= i && i < end) {
data.add(record);
}
//record.put("createtime", new Timestamp(100,10,10,1,1,1,1));
}
HashMap result = new HashMap();
result.put("data", data);
result.put("total", dataAll.size());
//minAge, maxAge, avgAge
ArrayList ages = DBSelect("select min(age) as minAge, max(age) as maxAge, avg(age) as avgAge from t_employee");
HashMap ageInfo = (HashMap) ages.get(0);
result.put("minAge", ageInfo.get("minAge"));
result.put("maxAge", ageInfo.get("maxAge"));
result.put("avgAge", ageInfo.get("avgAge"));
return result;
}
public HashMap GetEmployee(String id) throws Exception {
String sql = "select * from t_employee where id = '" + id + "'";
ArrayList data = DBSelect(sql);
return data.size() > 0 ? (HashMap) data.get(0) : null;
}
public String InsertEmployee(HashMap user) throws Exception {
String id = (user.get("id") == null || user.get("id").toString().equals("")) ? UUID.randomUUID().toString() : user.get("id").toString();
user.put("id", id);
if (user.get("name") == null) user.put("name", "");
if (StringUtil.isNullOrEmpty(user.get("gender"))) user.put("gender", 0);
Connection conn = getConn();
String sql = "INSERT INTO t_employee (id, loginname, name, age, married, gender, birthday, country, city, dept_id, position, createtime, salary, educational, school, email, remarks)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(user.get("id")));
stmt.setString(2, ToString(user.get("loginname")));
stmt.setString(3, ToString(user.get("name")));
stmt.setInt(4, ToInt(user.get("age")));
stmt.setInt(5, ToInt(user.get("married")));
stmt.setInt(6, ToInt(user.get("gender")));
stmt.setTimestamp(7, ToDate(user.get("birthday")));
stmt.setString(8, ToString(user.get("country")));
stmt.setString(9, ToString(user.get("city")));
stmt.setString(10, ToString(user.get("dept_id")));
stmt.setString(11, ToString(user.get("position")));
stmt.setTimestamp(12, ToDate(user.get("createtime")));
stmt.setString(13, ToString(user.get("salary")));
stmt.setString(14, ToString(user.get("educational")));
stmt.setString(15, ToString(user.get("school")));
stmt.setString(16, ToString(user.get("email")));
stmt.setString(17, ToString(user.get("remarks")));
stmt.executeUpdate();
stmt.close();
conn.close();
return id;
}
public void DeleteEmployee(String userId) throws Exception {
Connection conn = getConn();
Statement stmt = conn.createStatement();
String sql = "delete from t_employee where id = \"" + userId + "\"";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
public void UpdateEmployee(HashMap user) throws Exception {
HashMap db_user = GetEmployee(user.get("id").toString());
Iterator iter = user.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
db_user.put(key, val);
}
DeleteEmployee(user.get("id").toString());
InsertEmployee(db_user);
}
public void UpdateDepartment(HashMap d) throws Exception {
HashMap db_d = GetDepartment(d.get("id").toString());
Iterator iter = d.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
db_d.put(key, val);
}
String sql =
"UPDATE t_department "
+ " SET "
+ " name = ?, "
+ " manager = ?, "
+ " manager_name = ? "
+ " WHERE id = ?";
Connection conn = getConn();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(db_d.get("name")));
stmt.setString(2, ToString(db_d.get("manager")));
stmt.setString(3, ToString(db_d.get("manager_name")));
stmt.setString(4, ToString(db_d.get("id")));
stmt.executeUpdate();
stmt.close();
conn.close();
}
public HashMap SearchEmployeesByMultiSort(String key, int index, int size, ArrayList sortFields) throws Exception {
//System.Threading.Thread.Sleep(300);
if (key == null) key = "";
String sql =
"select a.*, b.name dept_name, c.name position_name, d.name educational_name \n"
+ "from t_employee a \n"
+ "left join t_department b \n"
+ "on a.dept_id = b.id \n"
+ "left join t_position c \n"
+ "on a.position = c.id \n"
+ "left join t_educational d \n"
+ "on a.educational = d.id \n"
+ "where a.name like '%" + key + "%' \n";
int length = sortFields.size();
if (length > 0) {
for (int i = 0; i < length; i++) {
HashMap record = (HashMap) sortFields.get(i);
String sortField = (String) record.get("field");
String sortOrder = (String) record.get("dir");
if (i == 0) {
sql += " order by " + sortField + " " + sortOrder;
} else {
sql += "," + sortField + " " + sortOrder;
}
}
} else {
sql += " order by createtime desc";
}
ArrayList dataAll = DBSelect(sql);
ArrayList data = new ArrayList();
int start = index * size, end = start + size;
for (int i = 0, l = dataAll.size(); i < l; i++) {
HashMap record = (HashMap) dataAll.get(i);
if (record == null) continue;
if (start <= i && i < end) {
data.add(record);
}
}
System.out.println();
HashMap result = new HashMap();
result.put("data", data);
result.put("total", dataAll.size());
return result;
}
/////////////////////////////////////////////////////////////////
private Connection getConn() throws Exception {
Class.forName(driver).newInstance();
Connection conn = null;
if (user == null || user.equals("")) {
conn = java.sql.DriverManager.getConnection(url);
} else {
conn = java.sql.DriverManager.getConnection(url, user, pwd);
}
return conn;
}
public ArrayList DBSelect(String sql) throws Exception {
Connection conn = getConn();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery(sql);
ArrayList list = ResultSetToList(rst);
rst.close();
stmt.close();
conn.close();
return list;
}
public void DBDelete(String sql) throws Exception {
Connection conn = getConn();
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
public void DBInsert(String sql, HashMap node) throws Exception {
Connection conn = getConn();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(node.get("id")));
stmt.setString(2, ToString(node.get("name")));
stmt.setString(3, ToString(node.get("type")));
stmt.setString(4, ToString(node.get("size")));
stmt.setString(5, ToString(node.get("url")));
stmt.setString(6, ToString(node.get("pid")));
stmt.setTimestamp(7, ToDate(node.get("createdate")));
stmt.setTimestamp(8, ToDate(node.get("updatedate")));
stmt.setInt(9, ToInt(node.get("folder")));
stmt.setInt(10, ToInt(node.get("num")));
stmt.executeUpdate();
stmt.close();
conn.close();
}
private static ArrayList ResultSetToList(ResultSet rs) throws Exception {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
ArrayList list = new ArrayList();
Map rowData;
while (rs.next()) {
rowData = new HashMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
Object v = rs.getObject(i);
if (v != null && (v.getClass() == Date.class || v.getClass() == java.sql.Date.class)) {
Timestamp ts = rs.getTimestamp(i);
v = new Date(ts.getTime());
//v = ts;
} else if (v != null && v.getClass() == Clob.class) {
v = clob2String((Clob) v);
}
rowData.put(md.getColumnName(i), v);
}
list.add(rowData);
}
return list;
}
private static String clob2String(Clob clob) throws Exception {
return (clob != null ? clob.getSubString(1, (int) clob.length()) : null);
}
private int ToInt(Object o) {
if (o == null) return 0;
double d = Double.parseDouble(o.toString());
int i = 0;
i -= d;
return -i;
}
private String ToString(Object o) {
if (o == null) return "";
return o.toString();
}
private Timestamp ToDate(Object o) {
try {
if (o.getClass() == String.class) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
o = format.parse(o.toString());
return new Timestamp(((Date) o).getTime());
}
return o != null ? new Timestamp(((Date) o).getTime()) : null;
} catch (Exception ex) {
return null;
}
}
}
| 14,034 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
File.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/File.java | package com.chengjs.cjsssmsweb.common.miniui;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class File {
public static String encoding = "UTF-8";
public static String read(String path){
StringBuffer buf = new StringBuffer();
try {
FileInputStream in = new FileInputStream(path);
// 指定读取文件时以UTF-8的格式读取
BufferedReader br = new BufferedReader(new UnicodeReader(in, encoding));
String line = br.readLine();
while (line != null) {
buf.append(line);
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
return buf.toString();
}
public static void write(String path, String content){
try
{
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(path),"UTF-8");
//out.write("\n"+content);
out.write(content);
out.flush();
out.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static String getFileName(String fileName){
String[] ss = fileName.split(".");
fileName = ss[0];
String[] ss2 = fileName.split("/");
fileName = ss[ss.length-1];
return fileName;
}
}
| 1,368 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
JSON.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/JSON.java | package com.chengjs.cjsssmsweb.common.miniui;
import net.sf.json.JSONSerializer;
import java.sql.Timestamp;
import java.util.Date;
public class JSON {
/*
public static String Encode(Object obj) {
if(obj == null || obj.toString().equals("null")) return null;
if(obj != null && obj.getClass() == String.class){
return obj.toString();
}
JSONSerializer serializer = new JSONSerializer();
serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Date.class);
serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Timestamp.class);
return serializer.deepSerialize(obj);
}
*/
/*
public static Object Decode(String json) {
if (StringUtil.isNullOrEmpty(json)) return "";
JSONDeserializer deserializer = new JSONDeserializer();
deserializer.use(String.class, new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"));
Object obj = deserializer.deserialize(json);
if(obj != null && obj.getClass() == String.class){
return Decode(obj.toString());
}
return obj;
}
*/
}
| 1,014 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
StringUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/StringUtil.java | package com.chengjs.cjsssmsweb.common.miniui;
import java.util.Collection;
import java.util.Iterator;
public class StringUtil {
public static boolean isNullOrEmpty(Object obj) {
return obj == null || "".equals(obj.toString());
}
public static String toString(Object obj){
if(obj == null) return "null";
return obj.toString();
}
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
}
| 705 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
TreeUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/miniui/TreeUtil.java | package com.chengjs.cjsssmsweb.common.miniui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TreeUtil {
public static ArrayList ToTree(List table, String childrenField, String idField, String parentIdField)
{
ArrayList tree = new ArrayList();
Map hash = new HashMap();
for (int i = 0, l = table.size(); i < l; i++)
{
Map t = (Map)table.get(i);
hash.put(t.get(idField), t);
}
for (int i = 0, l = table.size(); i < l; i++)
{
Map t = (Map)table.get(i);
Object parentID = t.get(parentIdField);
if (parentID == null || parentID.toString().equals("-1"))
{
tree.add(t);
continue;
}
Map parent = (Map)hash.get(parentID);
if (parent == null)
{
tree.add(t);
continue;
}
List children = (List)parent.get(childrenField);
if (children == null)
{
children = new ArrayList();
parent.put(childrenField, children);
}
children.add(t);
}
SyncTreeNodes(tree, 1, "", childrenField);
return tree;
}
private static void SyncTreeNodes(ArrayList nodes, int outlineLevel, String outlineNumber, String childrenField)
{
for (int i = 0, l = nodes.size(); i < l; i++)
{
HashMap node = (HashMap)nodes.get(i);
node.put("OutlineLevel", outlineLevel);
node.put("OutlineNumber", outlineNumber + (i + 1));
ArrayList childNodes = (ArrayList)node.get(childrenField);
if (childNodes != null && childNodes.size() > 0)
{
SyncTreeNodes(childNodes, outlineLevel + 1, node.get("OutlineNumber").toString() + ".", childrenField);
}
}
}
public static ArrayList ToList(List tree, String parentId, String childrenField, String idField, String parentIdField)
{
ArrayList list = new ArrayList();
for (int i = 0, len = tree.size(); i < len; i++)
{
Map task = (Map)tree.get(i);
task.put(parentIdField, parentId);
list.add(task);
List children = (List)task.get(childrenField);
if (children != null && children.size() > 0)
{
String id = task.get(idField) == null ?"" : task.get(idField).toString();
List list2 = ToList(children, id, childrenField, idField, parentIdField);
list.addAll(list2);
}
//task.remove(childrenField);
}
return list;
}
}
| 2,826 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
StatusEnum.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/enums/StatusEnum.java | package com.chengjs.cjsssmsweb.common.enums;
import java.util.ArrayList;
import java.util.List;
/**
* 返回结果状态。
*
*/
public enum StatusEnum {
/** 成功 */
SUCCESS("9000", "成功"),
/** 失败 */
FAIL("4000", "失败"),
/** 重复请求 */
REPEAT_REQUEST("5000", "重复请求"),
/**操作成功*/
HANDLE_SUCCESS("1","操作成功"),
/**操作失败*/
HANDLE_FAIL("2","操作异常"),
;
/** 枚举值码 */
private final String code;
/** 枚举描述 */
private final String message;
/**
* 构建一个 StatusEnum 。
* @param code 枚举值码。
* @param message 枚举描述。
*/
private StatusEnum(String code, String message) {
this.code = code;
this.message = message;
}
/**
* 得到枚举值码。
* @return 枚举值码。
*/
public String getCode() {
return code;
}
/**
* 得到枚举描述。
* @return 枚举描述。
*/
public String getMessage() {
return message;
}
/**
* 得到枚举值码。
* @return 枚举值码。
*/
public String code() {
return code;
}
/**
* 得到枚举描述。
* @return 枚举描述。
*/
public String message() {
return message;
}
/**
* 通过枚举值码查找枚举值。
* @param code 查找枚举值的枚举值码。
* @return 枚举值码对应的枚举值。
* @throws IllegalArgumentException 如果 code 没有对应的 StatusEnum 。
*/
public static StatusEnum findStatus(String code) {
for (StatusEnum status : values()) {
if (status.getCode().equals(code)) {
return status;
}
}
throw new IllegalArgumentException("ResultInfo StatusEnum not legal:" + code);
}
/**
* 获取全部枚举值。
*
* @return 全部枚举值。
*/
public static List<StatusEnum> getAllStatus() {
List<StatusEnum> list = new ArrayList<StatusEnum>();
for (StatusEnum status : values()) {
list.add(status);
}
return list;
}
/**
* 获取全部枚举值码。
*
* @return 全部枚举值码。
*/
public static List<String> getAllStatusCode() {
List<String> list = new ArrayList<String>();
for (StatusEnum status : values()) {
list.add(status.code());
}
return list;
}
}
| 2,194 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/pagehelper/package-info.java | /**
* package-info: PageHelper 实践经验和细节
* https://github.com/pagehelper/Mybatis-PageHelper
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/10
*/
package com.chengjs.cjsssmsweb.common.pagehelper; | 305 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
GridMiniHelper.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/pagehelper/GridMiniHelper.java | package com.chengjs.cjsssmsweb.common.pagehelper;
import com.chengjs.cjsssmsweb.mybatis.MybatisHelper;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import com.github.pagehelper.PageRowBounds;
import org.apache.ibatis.session.SqlSession;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* GridMiniHelper: Miniui grid 查询帮助工具类
* author: Chengjs, version:1.0.0, 2017-09-30
*/
public class GridMiniHelper {
/*mapper*/
public static Mapper getSample(Class<UUser> aClass) {
SqlSession sqlSession = MybatisHelper.getSqlSession(); /*2.sqlSession*/
return (Mapper) sqlSession.getMapper(aClass);
}
/*criteria*/
public static Example.Criteria getCriteria(Class<UUser> aClass, Example example) {
Example.Criteria criteria = example.createCriteria();
return criteria;
}
}
| 882 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
PageHelperTest.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/pagehelper/PageHelperTest.java | package com.chengjs.cjsssmsweb.common.pagehelper;
import com.chengjs.cjsssmsweb.mybatis.MybatisHelper;
import com.chengjs.cjsssmsweb.mybatis.mapper.master.CountryMapper;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.Country;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.mybatis.mapper.entity.Example;
import java.io.IOException;
import java.util.List;
/**
* PageHelperTest:
*
* https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/en/HowToUse.md
*
* Criteria: http://www.cnblogs.com/kangping/p/6001519.html
*
*
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
public class PageHelperTest {
private static final Logger log = LoggerFactory.getLogger(PageHelperTest.class);
public static void main(String[] args) throws IOException {
SqlSession sqlSession = MybatisHelper.getSqlSession();
CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
/*rowBounds*/
RowBounds rowBounds = new RowBounds(2, 5);
/*Example*/
Example example = new Example(Country.class);
Example.Criteria criteria = example.createCriteria();
// criteria.andCountrycodeBetween("0", "ZZZZZZZZZZ");
// criteria.andIdBetween(0, 20);
List<Country> countries1 = countryMapper.selectByExample(example);
log.debug("countries1" + countries1.size());
List<Country> countries2 = countryMapper.selectByExampleAndRowBounds(example, rowBounds);
log.debug("countries2" + countries2.size());
PageInfo<Country> pageInfo = new PageInfo<>(countries1);
System.out.println("PageHelperTest.main() pageInfo :" + pageInfo.getSize());
}
/*3.Example*/
// Example example = new Example(pojo_clz);
/*3.params附着条件, Criteria之间是AND关系, oredCriteria中的Criteria是OR关系*/
// Example.Criteria criteria1 = example.createCriteria();
// criteria.andCountrycodeBetween("0", "ZZZZZZZZZZ");
// criteria.andIdBetween(0, 20);
// Object obj = mapper_clz.newInstance();
// Method m = obj.getClass().getDeclaredMethod(strs[1], String.class);
// String result = (String) m.invoke(obj, "aaaaa");
// Method m = mapper.getClass().getMethod(method, new Class[]{Map.class});
// Object result = m.invoke(mapper, params);
}
| 2,430 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
UUIDUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/UUIDUtil.java | package com.chengjs.cjsssmsweb.common.util;
import java.util.UUID;
/**
* UUIDUtil:
* author: Chengjs, version:1.0.0, 2017-08-06
*/
public class UUIDUtil {
public static String uuid(){
UUID uuid=UUID.randomUUID();
String str = uuid.toString();
String uuidStr=str.replace("-", "");
return uuidStr;
}
}
| 325 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
DateUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/DateUtil.java | package com.chengjs.cjsssmsweb.common.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期工具类
*/
public class DateUtil {
public static final String PATTERN = "yyyy-MM-dd HH:mm:dd";
/**
* 日期对象转字符串
* @param date
* @param format
* @return
*/
public static String formatDate(Date date,String format){
String result="";
SimpleDateFormat sdf=new SimpleDateFormat(format);
if(date!=null){
result=sdf.format(date);
}
return result;
}
/**
* 字符串转日期对象
* @param str
* @param format
* @return
* @throws Exception
*/
public static Date formatString(String str,String format) throws Exception{
if(StringUtil.isEmpty(str)){
return null;
}
SimpleDateFormat sdf=new SimpleDateFormat(format);
return sdf.parse(str);
}
public static String getCurrentDateStr(){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat(PATTERN);
return sdf.format(date);
}
}
| 977 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
StringUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/StringUtil.java | package com.chengjs.cjsssmsweb.common.util;
import java.util.Collection;
import java.util.Iterator;
/**
* 字符串工具类
*
* @author
*/
public class StringUtil {
/**
* 字符串是否为空,包括blank
*
* @param str
* @return
*/
public static boolean isNullOrEmpty(String str) {
return null != str && 0 != str.trim().length() ? false : true;
}
/**
* 返回"null" 或者 toString
*
* @param obj
* @return
*/
public static boolean reNullOrEmpty(Object obj) {
return obj == null || "".equals(obj.toString());
}
/**
* 判断是否是空
*
* @param str
* @return
*/
public static boolean isEmpty(String str) {
if (str == null || "".equals(str.trim())) {
return true;
} else {
return false;
}
}
/**
* 判断是否不是空
*
* @param str
* @return
*/
public static boolean isNotEmpty(String str) {
if ((str != null) && !"".equals(str.trim())) {
return true;
} else {
return false;
}
}
/**
* 格式化模糊查询
*
* @param str
* @return
*/
public static String formatLike(String str) {
if (isNotEmpty(str)) {
return "%" + str + "%";
} else {
return null;
}
}
/**
* 返回"null"或者toString
*
* @param obj
* @return
*/
public static String toString(Object obj) {
if (obj == null) return "null";
return obj.toString();
}
/**
* 用标签来连接string
*
* @param s
* @param delimiter
* @return
*/
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
/**
* 首字母变大写
* @param name
* @return
*/
public static String captureName(String name) {
/*效率低的方法*/
/* name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;*/
/*高效率方法*/
char[] cs = name.toCharArray();
cs[0] -= 32;
return String.valueOf(cs);
}
/**
* 去除%
* @param str
* @return
*/
public static String reSqlLikeStr(String str) {
return str.replace("%", "");
}
}
| 2,353 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
MD5Util.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/codec/MD5Util.java | package com.chengjs.cjsssmsweb.common.util.codec;
import com.chengjs.cjsssmsweb.common.util.StringUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
/**
* MD5Util: 基于shiro的MD5加密
* author: <a href="mailto:[email protected]">chengjs</a>, version:1.0.0, 2017/8/25
*/
public class MD5Util {
public static final String DEFAULT_SALT = "minipa_chengjs";
/**
* 指定加密盐
* @param str
* @param salt
* @return
*/
public static String md5(String str, String salt){
if (StringUtil.isNullOrEmpty(salt)) {
salt = DEFAULT_SALT;
}
return new Md5Hash(str,salt).toString() ;
}
/**
* 采用默认加密盐
* @param str
* @return
*/
public static String md5(String str){
return new Md5Hash(str,DEFAULT_SALT).toString() ;
}
public static void main(String[] args) {
String md5 = md5("123456", DEFAULT_SALT) ;
System.out.println(md5); // 119d3a4d2dfbca3d23bd1c52a1d6a6e6
}
}
| 962 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
CacheMap.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/memory/CacheMap.java | package com.chengjs.cjsssmsweb.common.util.memory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* CacheMap: 存储短暂对象的缓存类,实现Map接口,内部有一个定时器用来清除过期(DEFAULT_TIMEOUT秒)的对象
* 为避免创建过多线程,没有特殊要求请使用getDefault()方法来获取本类的实例。
*
* issue1: 由于线程获取cpu的资源问题,清除时间太短,则不能够准确的在规定时间内将数据清楚 请务必注意;
* issue2: 另外这个缓存能够承受多大的并行压力 也没有进行测试 还需要研究下
*
* @author: <a href="mailto:[email protected]">chengjs</a>
* @version: 1.0.0, 2017-09-08
*
* @param <K>
* @param <V>
*
* ALL RIGHTS RESERVED,COPYRIGHT(C) FCH LIMITED Shanghai Servyou Ltd 2017
**/
public class CacheMap<K, V> extends AbstractMap<K, V> {
private static final Log logger = LogFactory.getFactory().getLog(CacheMap.class);
/**
* 默认缓存超时清除时间 单位"ms毫秒"
*/
private static final long DEFAULT_TIMEOUT = 180000;
private static CacheMap<Object, Object> defaultInstance;
public static synchronized final CacheMap<Object, Object> getDefault() {
if (defaultInstance == null) {
defaultInstance = new CacheMap<Object, Object>(DEFAULT_TIMEOUT);
}
return defaultInstance;
}
private class CacheEntry implements Entry<K, V> {
long time;
V value;
K key;
CacheEntry(K key, V value) {
super();
this.value = value;
this.key = key;
this.time = System.currentTimeMillis();
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
return this.value = value;
}
}
private class ClearThread extends Thread {
ClearThread() {
setName("clear cache thread");
}
public void run() {
while (true) {
try {
long now = System.currentTimeMillis();
Object[] keys = map.keySet().toArray();
for (Object key : keys) {
CacheEntry entry = map.get(key);
if (now - entry.time >= cacheTimeout) {
synchronized (map) {
map.remove(key);
if (logger.isDebugEnabled()) {
logger.debug("清除对象 key "+key+" 时间:"+now);
}
}
}
}
Thread.sleep(cacheTimeout);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private long cacheTimeout;
private Map<K, CacheEntry> map = new HashMap<K, CacheEntry>();
public CacheMap(long timeout) {
this.cacheTimeout = timeout;
new ClearThread().start();
}
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>();
Set<Entry<K, CacheEntry>> wrapEntrySet = map.entrySet();
for (Entry<K, CacheEntry> entry : wrapEntrySet) {
entrySet.add(entry.getValue());
}
return entrySet;
}
@Override
public V get(Object key) {
CacheEntry entry = map.get(key);
return entry == null ? null : entry.value;
}
@Override
public V put(K key, V value) {
CacheEntry entry = new CacheEntry(key, value);
synchronized (map) {
map.put(key, entry);
if (logger.isDebugEnabled()) {
logger.debug("缓存中放入对象 key: "+key+" 时间:"+ System.currentTimeMillis());
}
}
return value;
}
} | 4,201 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
MathUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/math/MathUtil.java | package com.chengjs.cjsssmsweb.common.util.math;
import java.security.SecureRandom;
/**
* MathUtil: 数字相关工具类
* author: Chengjs, version:1.0.0, 2017-09-08
*/
public class MathUtil {
/**
* 生成随机数字
*
* @param iLength 随机数位数
* @return 生成的随机数
*/
public static String genRandNum(int iLength) {
StringBuffer result = new StringBuffer();
SecureRandom tRandom = new SecureRandom();
long tLong = getAbsRandom(tRandom);
result.append(tLong);
// aString = (String.valueOf(tLong)).trim();
while (result.length() < iLength) {
tLong = getAbsRandom(tRandom);
result.append(tLong);
// aString += (String.valueOf(tLong)).trim();
}
// result = result.substring(0,aLength);
return result.substring(0, iLength);
}
/**
* 生成正数随机数
* @param tRandom
* @return
*/
private static long getAbsRandom(SecureRandom tRandom) {
long l = tRandom.nextLong();
if (l == Long.MIN_VALUE) {
l = Long.MAX_VALUE;
} else {
l = Math.abs(l);
}
return l;
}
}
| 1,104 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
CashUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/math/CashUtil.java | package com.chengjs.cjsssmsweb.common.util.math;
import com.chengjs.cjsssmsweb.common.util.StringUtil;
import java.math.BigDecimal;
import java.text.DecimalFormat;
/**
* CashUtil: 涉及金额的计算,以及double类型的计算
* author: Chengjs, version:1.0.0, 2017-09-08
*/
public class CashUtil {
/*格式化2位小数*/
private static java.text.DecimalFormat df2 = new java.text.DecimalFormat("############0.00");
/*格式化4位小数*/
private static java.text.DecimalFormat df4 = new java.text.DecimalFormat("############0.0000");
/*格式化6位小数*/
private static java.text.DecimalFormat df6 = new java.text.DecimalFormat("############0.000000");
/*如果有4位小数格式化4位小数,否则格式化成2位小数*/
private static java.text.DecimalFormat df2or4 = new java.text.DecimalFormat("############0.00##");
/**
* @param d d
* @param v v
* @return boolean
*/
public static boolean isDoubleEquals(double d, double v) {
return Math.abs(d - v) < 0.0000001;
}
/**
* 转换null为0.0d,主要用于从map中get数据时,避免空指针异常
*
* @param o 对象
* @return double
*/
public static double nvlDouble(Object o) {
double d = 0d;
if (!StringUtil.isNullOrEmpty(nvl(o))) {
d = Double.parseDouble(o.toString());
}
return d;
}
/**
* 转化null为空字串,主要用于从map中get数据时,避免空指针异常
* 公司架构提供的StringUtil.nvl(String)只针对String参数,而多数情况我们传入的是Object,因此需要新写一个
*
* @param o object
* @return 字符串
*/
public static String nvl(Object o) {
return (null != o) ? o.toString() : "";
}
/**
* 数字金额转化成中文大写的金额
*
* @param value value
* @return String
*/
public static String changeToBig(double value) {
boolean fsFlag = false;
if (value < 0) {
fsFlag = true;
value = value * (-1.0);
}
char[] hunit = {'拾', '佰', '仟'}; // 段内位置表示
char[] vunit = {'万', '亿'}; // 段名表示
char[] digit = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'}; // 数字表示
DecimalFormat df = new DecimalFormat("##0");
String valStr = df.format(value * 100); // 转化成字符串
if (valStr.length() == 1)
valStr = "0" + valStr;
String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
String rail = valStr.substring(valStr.length() - 2); // 取小数部分
// String prefix = ""; // 整数部分转化的结果
StringBuffer sb = new StringBuffer();
String suffix = ""; // 小数部分转化的结果
// 处理小数点后面的数
if (rail.equals("00")) { // 如果小数部分为0
suffix = "整";
} else {
// 否则把角分转化出来
if (rail.charAt(0) == '0') {
if ("0".equals(head) || "".equals(head)) {
suffix = digit[rail.charAt(1) - '0'] + "分";
} else {
suffix = "零" + digit[rail.charAt(1) - '0'] + "分"; //
}
} else if (rail.charAt(1) == '0') {
suffix = digit[rail.charAt(0) - '0'] + "角整"; //
} else
suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
}
// 处理小数点前面的数
if ("0".equals(head) || "".equals(head)) {
if (fsFlag) {
return "負" + suffix;
}
return suffix;
}
char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
char zero = '0'; // 标志'0'表示出现过0
byte zeroSerNum = 0; // 连续出现0的次数
for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
int idx = (chDig.length - i - 1) % 4; // 取段内位置
int vidx = (chDig.length - i - 1) / 4; // 取段位置
if (chDig[i] == '0') { // 如果当前字符是0
zeroSerNum++; // 连续0次数递增
if (zero == '0') { // 标志
zero = digit[0];
}
if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
// prefix += vunit[vidx - 1];
sb.append(vunit[vidx - 1]);
zero = '0';
}
continue;
}
zeroSerNum = 0; // 连续0次数清零
if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
// prefix += zero;
sb.append(zero);
zero = '0';
}
// prefix += digit[chDig[i] - '0']; // 转化该数字表示
sb.append(digit[chDig[i] - '0']);
if (idx > 0)
sb.append(hunit[idx - 1]);
// prefix += hunit[idx - 1];
if (idx == 0 && vidx > 0) {
// prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
sb.append(vunit[vidx - 1]);
}
}
if (sb.toString().length() > 0)
sb.append("圆");
// prefix += '圆'; // 如果整数部分存在,则有圆的字样
if (StringUtil.isNullOrEmpty(sb.toString()))
sb = new StringBuffer(digit[0] + "圆");
if (fsFlag) {
return "負" + sb.toString() + suffix;
} else {
return sb.toString() + suffix; // 返回正确表示
}
}
/**
* 判断传入的double是不是整数,如果是整数,就不要显示.0,返回int模样的字符串
*
* @param number number
* @return String
*/
public static String getNumberSring(double number) {
String tempString = String.valueOf(double2String(number));
if (tempString.indexOf(".") == -1) {
return tempString;
} else {
String[] numbers = tempString.split("\\.");
if (Integer.parseInt(numbers[1]) == 0) {
return numbers[0];
} else if (numbers[1].endsWith("0")) {
return tempString.substring(0, tempString.length() - 1);
} else {
return tempString;
}
}
}
/**
* 将传入的金额格式化,防止在使用String.valueOf(je)时得到科学计数法格式的字符串
*
* @param je double
* @return String 格式化后的金额,保留2位小数
*/
public static String double2String(double je) {
return df2.format(je);
}
/**
* 将传入的金额格式化,防止在使用String.valueOf(je)时得到科学计数法格式的字符串
*
* @param je 金额
* @return String
*/
public static String doubledj2String(double je) {
return df2or4.format(je);
}
/**
* 将传入的金额格式化,防止在使用String.valueOf(je)时得到科学计数法格式的字符串
*
* @param je double
* @return String 格式化后的金额,保留4位小数
*/
public static String double2String4(double je) {
return df4.format(je);
}
/**
* 将传入的金额格式化,防止在使用String.valueOf(je)时得到科学计数法格式的字符串
*
* @param je double
* @return String 格式化后的金额,保留6位小数
*/
public static String double2String6(double je) {
return df6.format(je);
}
/**
* 四舍五入
* @param v v
* @param scale scale
* @return double
*/
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 两个double数相加
*
* @param v v
* @param d d
* @return double
*/
public static double add(double v, double d) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
double d2 = b1.add(b2).doubleValue();
return b1.add(b2).doubleValue();
}
/**
* 两个double数相加(适合商业运算)
*
* @param s s
* @param str str
* @return 结果值
*/
public static double addString(String s, String str) {
BigDecimal b1 = new BigDecimal(s);
BigDecimal b2 = new BigDecimal(str);
return b1.add(b2).doubleValue();
}
/**
* double + double,并保留scale位小数
*
* @param v v
* @param d d
* @param scale scale
* @return double
*/
public static double add(double v, double d, int scale) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return CashUtil.round(b1.add(b2).doubleValue(), scale);
}
/**
* double - double
*
* @param v v
* @param d d
* @return double
*/
public static double sub(double v, double d) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return b1.subtract(b2).doubleValue();
}
/**
* 两个double数相减(适合商业运算)
*
* @param v1 v1
* @param v2 v2
* @return double
*/
public static double subString(String v1, String v2) {
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.subtract(b2).doubleValue();
}
/**
* 两个double数相减,并保留scale位小数
*
* @param v v
* @param d d
* @param scale scale
* @return double
*/
public static double sub(double v, double d, int scale) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return CashUtil.round(b1.subtract(b2).doubleValue(), scale);
}
/**
* 两个double数相乘
*
* @param v v
* @param d d
* @return Double
*/
public static double mul(double v, double d) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return b1.multiply(b2).doubleValue();
}
/**
* 两个double数相乘
*
* @param v v
* @param d d
* @param scale scale
* @return Double
*/
public static double mul(double v, double d, int scale) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return CashUtil.round(b1.multiply(b2).doubleValue(), scale);
}
/**
* 两个double类型相乘,用String类型构造(适合商业运算)
*
* @param s s
* @param str str
* @return double
*/
public static double mulString(String s, String str) {
BigDecimal b1 = new BigDecimal(s);
BigDecimal b2 = new BigDecimal(str);
return b1.multiply(b2).doubleValue();
}
/**
* 两个double类型相乘,用String类型构造,用String类型构造(适合商业运算)
*
* @param s s
* @param str s2
* @param scale scale
* @return double
*/
public static double mulString(String s, String str, int scale) {
BigDecimal b1 = new BigDecimal(s);
BigDecimal b2 = new BigDecimal(str);
return round(b1.multiply(b2).doubleValue(), scale);
}
/**
* 两个double数相除
*
* @param v v
* @param d d
* @return double
*/
public static double div(double v, double d) {
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return b1.divide(b2, 10, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 两个double数相除,并保留scale位小数
*
* @param v v
* @param d d
* @param scale scale
* @return double
*/
public static double div(double v, double d, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v);
BigDecimal b2 = new BigDecimal(d);
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
| 11,455 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
PropertiesUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/resources/PropertiesUtil.java | package com.chengjs.cjsssmsweb.common.util.resources;
import com.chengjs.cjsssmsweb.enums.EnvEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* PropertiesUtil:
* author: Chengjs, version:1.0.0, 2017-08-05
*/
public class PropertiesUtil {
private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties prop = new Properties();
private Long lastModified = 0l;// TODO 热加载
static {
try {
prop.load(PropertiesUtil.class.getResourceAsStream(EnvEnum.CJS_SSMS_PROP_PATH.val()));
//转码处理
Set<Object> keyset = prop.keySet();
Iterator<Object> iter = keyset.iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
String newValue = null;
try {
//属性配置文件自身的编码
String propertiesFileEncode = "utf-8";
newValue = new String(prop.getProperty(key).getBytes("ISO-8859-1"), propertiesFileEncode);
} catch (UnsupportedEncodingException e) {
newValue = prop.getProperty(key);
}
prop.setProperty(key, newValue);
}
} catch (Exception e) {
log.error("读取"+EnvEnum.CJS_SSMS_PROP_PATH.val()+"出错!", e);
}
}
private static Properties getProp() {
return prop;
}
public static void main(String[] args) {
log.debug(String.valueOf(getProp()));
}
public static String getValue(String param){
return getProp().getProperty(param);
};
}
| 1,629 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
ReflectUtil.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/common/util/reflect/ReflectUtil.java | package com.chengjs.cjsssmsweb.common.util.reflect;
import org.apache.log4j.Logger;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ReflectUtil: 反射工具类
*
* @author: <a href="mailto:[email protected]">chengjs</a>
* @version: 1.0.0, 2017-09-08
*
* ALL RIGHTS RESERVED,COPYRIGHT(C) FCH LIMITED Shanghai Servyou Ltd 2017
**/
public class ReflectUtil {
private static Logger log = Logger.getLogger(ReflectUtil.class);
private final static String[] PROTOTYPE_CLASS_NAMES = new String[] { "java.lang.String",
"java.lang.Character","java.lang.Integer",
"java.lang.Object", "java.lang.Short",
"java.lang.Boolean", "java.lang.Byte",
"java.lang.Long","java.lang.Double",
"java.lang.Float", "int", "short", "char",
"boolean", "byte", "long", "double", "float" };
/**
*
* @Title: loadClass
* @Description: 加载类
* @param className
* @return Class
* @throws
*/
@SuppressWarnings("unchecked")
public static Class loadClass(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
clazz.newInstance();
} catch (ClassNotFoundException e) {
log.error(e);
} catch (InstantiationException e) {
log.error(e);
} catch (IllegalAccessException e) {
log.error(e);
}
return clazz;
}
/**
*
* @Title: newInstance
* @Description: 创建类实例
* @param clazz Class
* @return Object
* @throws
*/
@SuppressWarnings("unchecked")
public static Object newInstance(Class clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
log.error(e);
} catch (IllegalAccessException e) {
log.error(e);
}
return null;
}
/**
*
* @Title: newInstance
* @Description: 根据ClassName创建类实例
* @param className String
* @return Object
* @throws
*/
@SuppressWarnings("unchecked")
public static Object newInstance(String className) {
Class clazz = loadClass(className);
return newInstance(clazz);
}
/**
*
* @Title: gainField
* @Description: 获取clazz对象的名为propertyName的字段
* @param clazz Class
* @param propertyName 属性名
* @return Field
* @throws
*/
@SuppressWarnings("unchecked")
public static Field gainField(Class clazz, String propertyName) {
Field field = null;
try {
field = clazz.getDeclaredField(propertyName);
} catch (SecurityException e) {
log.error(e);
} catch (NoSuchFieldException e) {
log.error(e);
}
return field;
}
/**
*
* @Title: gainFieldWithParent
* @Description: 递归获取父类的名为propertyName字段
* @param clazz
* @param propertyName
* @return Field
* @throws
*/
@SuppressWarnings("unchecked")
public static Field gainFieldWithParent(Class clazz, String propertyName) {
Field field = null;
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(propertyName);
if (field != null)
return field;
} catch (Exception e) {
// 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
// 如果这里的异常打印或者往外抛,则就不会执行clazz =
// clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return field;
}
/**
*
* @Title: printObject
* @Description: 打印对象
* @param entity void
* @throws
*/
public static void printObject(Object entity) {
if (null == entity)
return;
}
/**
* 根据属性名获取属性值
*
* @param obj
* @param property
* @return Object
*/
@SuppressWarnings("unchecked")
public static Object getProperty(Object obj, String property) {
Class clazz = obj.getClass();
String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
Method method = null;
Object rstObj = null;
try {
method = clazz.getDeclaredMethod(methodName, new Class[]{});
} catch (SecurityException e1) {
log.error(e1);
} catch (NoSuchMethodException e1) {
log.error(e1);
}
if (null == method)
return null;
try {
rstObj = method.invoke(obj, new Object[]{});
} catch (IllegalArgumentException e) {
log.error(e);
} catch (IllegalAccessException e) {
log.error(e);
} catch (InvocationTargetException e) {
log.error(e);
}
return rstObj;
}
/**
*
* @Title: gainPropertyMap
* @Description: 获取属性,值 Map(传入任意对象,得到其属性名,值Map)
* @param object
* @return Map
* @throws
*/
@SuppressWarnings("unchecked")
public static Map gainPropertyMap(Object object) {
Field[] fields = listField(object);
Map propertyMap = new HashMap();
for (int i = 0; null != fields && i < fields.length; i++) {
Field field = fields[i];
Object value = null;
String propertyName = field.getName();
try {
value = getProperty(object, propertyName);
} catch (IllegalArgumentException e) {
log.error(e);
}
propertyMap.put(propertyName, value);
}
return propertyMap;
}
/**
*
* @Title: listField
* @Description: 罗列出对象的所有字段
* @param object object
* @return Field[]
* @throws
*/
@SuppressWarnings("unchecked")
public static Field[] listField(Object object) {
return listField(object.getClass());
}
/**
*
* @Title: listField
* @Description: 罗列出对象的所有字段
* @param clazz clazz
* @return Field[]
* @throws
*/
@SuppressWarnings("unchecked")
public static Field[] listField(Class clazz) {
Field[] fields = clazz.getDeclaredFields();
List fieldList = new ArrayList();
for(int i = 0 ; null != fields && fields.length > 0 && i < fields.length; i ++){
if(!"serialVersionUID".equalsIgnoreCase(fields[i].getName())){
fieldList.add(fields[i]);
}
}
return (Field[]) fieldList.toArray(new Field[0]);
}
/**
* 是否为ArrayList类型
*
* @param obj Object
* @return boolean 是ArrayList类型返回true,否则返回false
*/
@SuppressWarnings("unchecked")
public static boolean isArrayListType(Object obj) {
Class clazz = obj.getClass();
return "java.lang.ArrayList".equals(clazz.getName());
}
/**
*
* @Title: isBusinessElementType
* @Description: isBusinessElementType
* @param obj Object
* @return boolean 是BusinessElement类型返回true,不是返回false
* @throws
*/
@SuppressWarnings("unchecked")
public static boolean isBusinessElementType(Object obj) {
Class clazz = obj.getClass();
return "cn.com.servyou.wlfp.base.xml.entity.BusinessElement".equals(clazz.getName());
}
/**
*
* @Title: isPrototype
* @Description: 是否为基本类型
* @param className
* @return boolean
* @throws
*/
private static boolean isPrototype(String className) {
for (int i = 0; i < PROTOTYPE_CLASS_NAMES.length; i++) {
if (PROTOTYPE_CLASS_NAMES[i].equals(className)) {
return true;
}
}
return false;
}
/**
* @Title: isListNotNull
* @Description: 列表是否为空
* @param list
* @return boolean
* @throws
*/
@SuppressWarnings({ "unchecked", "unused" })
private static boolean isListNotNull(List list) {
return null != list && !list.isEmpty();
}
}
| 8,552 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
UserFrontController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/UserFrontController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.enums.EnvEnum;
import com.chengjs.cjsssmsweb.common.enums.StatusEnum;
import com.chengjs.cjsssmsweb.enums.TestEnv;
import com.chengjs.cjsssmsweb.components.lucene.IndexerTest;
import com.chengjs.cjsssmsweb.components.lucene.SearcherTest;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import com.chengjs.cjsssmsweb.service.master.IUserFrontService;
import com.chengjs.cjsssmsweb.service.master.IUserManagerService;
import com.chengjs.cjsssmsweb.util.ExceptionUtil;
import com.chengjs.cjsssmsweb.util.HttpRespUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 前台用户Controller
*/
@Controller
@RequestMapping("/user")
public class UserFrontController {
private Logger log = LoggerFactory.getLogger(UserFrontController.class);
@Autowired
private IUserFrontService userFService;
@Autowired
private IUserManagerService userMService;
/**
* @param userid
* @param model
* @return
*/
@RequestMapping("/frontUserSet/{userid}")
public String frontUserSet(@PathVariable String userid, Model model) {
UUser user = userFService.getUserById(userid);
model.addAttribute("currentUser", user);
/*TODO 给用户添加头像属性*/
/* String img_id = user.getImg_id();
if (img_id != null) {
String path = imgService.selectByPrimaryKey(Integer.parseInt(img_id)).getPath();
model.addAttribute("headimg", path);
}*/
return "front/user/userSet";
}
/**
* 当前用户信息展示
*
* @param request
* @param model
* @return
*/
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request, Model model) {
String userid = request.getParameter("userid");
UUser user = this.userFService.getUserById(userid);
model.addAttribute("user", user);
return "showUser";
}
/**
* 查询用户信息
*
* @param userid
* @param request
* @return
*/
@RequestMapping("/queryUser/{userid}")
public String queryUser(@PathVariable String userid, HttpServletRequest request) {
UUser user = userFService.getUserById(userid);
request.setAttribute("user", user);
return "showUser";
}
@RequestMapping("/turnToIndex")
public String turnToIndex() {
return "index";
}
@RequestMapping("/turnToUserList")
public String turnToUserList() {
return "user/userList";
}
@RequestMapping("/queryUser")
public String queryUser(String querykey) throws Exception {
querykey = new String(querykey.getBytes("ISO-8859-1"), "UTF-8");
UUser u = new UUser();
List<UUser> users = userFService.findAllByQuery(u);
List<String> usernames = new ArrayList<>();
List<String> cities = new ArrayList<String>();
List<String> descriptions = new ArrayList<String>();
for (UUser user : users) {
usernames.add(user.getUsername());
descriptions.add(user.getDescription());
}
IndexerTest indexer = new IndexerTest();
String[] usernames2 = (String[]) usernames.toArray(new String[usernames.size()]);
String[] descriptions2 = (String[]) descriptions.toArray(new String[descriptions.size()]);
indexer.setUsernames(usernames2);
indexer.setDescriptions(descriptions2);
indexer.index(EnvEnum.LUCENE_INDEX_PATH.val());
try {
SearcherTest.search(EnvEnum.LUCENE_INDEX_PATH.val(), querykey);
} catch (Exception e) {
log.error("系统异常", e);
}
return null;
}
@RequestMapping("/createUser")
public void createUser(UUser user, HttpServletResponse response) throws IOException {
try {
userFService.createUser(user);
response.getWriter().print("true");
} catch (Exception e) {
log.error("系统异常", e);
response.getWriter().print("false");
}
}
@RequestMapping("/deleteUser")
public void deleteUser(String userids, HttpServletResponse response) throws IOException {
String[] str_ids = userids.split(",");
for (String id : str_ids) {
userFService.deleteByPrimaryKey(id);
response.getWriter().print("true");
}
}
@RequestMapping("/edit")
public void edit(UUser user, HttpServletResponse response) {
try {
userFService.updateByPrimaryKeySelective(user);
response.getWriter().print("true");
} catch (Exception e) {
log.error("系统异常", e);
}
}
/**
* 登录,(不跳转页面,ajax请求)
* <p>
* 测试环境中,这里的User登录其实也是使用User来登录的
* <p>
* EAO issue: 此处的login仍然使用UserRealm 如何切分,或者从设计上来说,管理平台和App应当分开为2套
*
* @param username
* @param password
* @param response
* @return
*/
@RequestMapping("/loginUser")
public void login(String username, String password, HttpServletResponse response) {
/*===== tpja ajax请求mvc响应 =====*/
Map<String, Object> remap = new HashedMap();
UUser user = new UUser();
user.setUsername(username);
user.setPassword(password);
//用户视图相关操作尽在Subject
Subject subject = SecurityUtils.getSubject();
StatusEnum re_status = StatusEnum.FAIL; // 请求操作状态
if (subject.isAuthenticated()) {
remap.put("msg", "已经登录");
HttpRespUtil.respJson(StatusEnum.SUCCESS, remap, response);
} else {
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
token.setRememberMe(TestEnv.onTFalse);//default rememberMe true
try {
subject.login(token);
String principal_username = subject.getPrincipal().toString();
log.info("User [" + principal_username + "] 普通用户 登录成功.");
//1.进行session相关事项,可为webSession也可为其他session
Session session = subject.getSession();
session.setAttribute("userName", user.getUsername());
re_status = StatusEnum.SUCCESS;
HttpRespUtil.buildRespStatus("恭喜" + user.getUsername() + "登录成功", remap, re_status);
} catch (UnknownAccountException e) {
ExceptionUtil.controllerEHJson("用户名不存在", e, log, remap, re_status);
} catch (IncorrectCredentialsException e) {
ExceptionUtil.controllerEHJson("密码错误请重试", e, log, remap, re_status);
} catch (LockedAccountException e) {
ExceptionUtil.controllerEHJson("账号已被锁定", e, log, remap, re_status);
} catch (AuthenticationException e) {
ExceptionUtil.controllerEHJson("用户或密码错误", e, log, remap, re_status);
} catch (Exception e) {
ExceptionUtil.controllerEHJson("未知错误", e, log, remap, re_status);
} finally {
HttpRespUtil.respJson(re_status, remap, response);
}
}
}
/**
* 注册
* JavaBean: User这种的bean会自动返回给前端
*
* @param user
* @param model
* @param response
*/
@RequestMapping("/register")
public void register(UUser user, Model model, HttpServletResponse response) {
Map<String, Object> remap = new HashedMap();
try {
boolean b = userFService.registerUser(user);
if (b) {
log.info("注册普通用户" + user.getUsername() + "成功。");
remap.put("msg", "恭喜您," + user.getUsername() + "注册成功。");
HttpRespUtil.respJson(StatusEnum.SUCCESS, remap, response);
} else {
remap.put("msg", "用户名已存在。");
HttpRespUtil.respJson(StatusEnum.SUCCESS, remap, response);
}
} catch (Exception e) {
log.debug("注册普通用户" + user.getUsername() + "异常");
remap.put("msg","注册普通用户异常");
HttpRespUtil.respJson(StatusEnum.FAIL, remap, response);
e.printStackTrace();
}
}
@RequestMapping("/logoutUser")
public String logout(UUser user, Model model) throws IOException {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
//session.removeAttribute("userName");
session.removeAttribute("sysbUserName");
return "redirect:/index.jsp";
}
}
| 9,052 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/package-info.java | /**
* package-info: Controller
* commonSelect 通用select查询, text='text' value='value'
* 适用于miniui-combobox
*
* ############################### 1.controller绑定参数方式 ###############################
* http://www.cnblogs.com/HD/p/4107674.html
* http://www.cnblogs.com/xiepeixing/p/4243288.html
*
* 1. @RequestMapping(value = "/showUser/{userId}", method = RequestMethod.GET)
* public String showUser( @PathVariable("userId") Integer userId, ModelMap modelMap ){
* 2.primary value: 表单中变量name要和controller参数名一致,或@RequestParam来绑定
*
* 3.object value: 于基本类型不同,表单中无此变量,或变量为"",则参数值为null
* 4.自定义对象: 表单各name和对象参数名一致, public void test(User user)
* 5.自定义复合对象:表单中用"field.field"方式来命名inputName,对象中有对象
* 6.List:要浆List<User>绑定在对象里如 ListForm里有属性List<User> users
*
* 表单里用 users[0].name来绑定,----不好使
* spring会以最大下标创建List对象,在页面动态变动后,会导致下标不一致
* 7.Set类似List,需先行add对应数量的模型----不好使
* 8.Map:需绑定在对象中,相对灵活 绑定方式users['x'].firstName ---- 可用
*
* ############################### 2.controller注解参数 ###############################
* ModelAndView modelAndView = new ModelAndView(); return modelAndView;
*
* 1.ModelMap model 页面${attributeName}
*
* 2.HttpServletRequest request, HttpServletResponse response
* 3.@RequestParam(value = "method") String method
* @RequestParam(required=false) String name, //从HttpServletRequest中绑定name参数
* @RequestParam ( "age" ) int age
* 4.@PathVariable String name
*
* 5.@CookieValue 绑定cookie值到Controller
* testCookieValue( @CookieValue ( "hello" ) String cookieValue, @CookieValue String hello) {
* 6.testRequestHeader( @RequestHeader ( "Host" ) String hostAddr, @RequestHeader String Host, @RequestHeader String host )
* 绑定HttpServletRequest头信息到Controller方法参数 --大小写不敏感,其他绑定都是敏感的
*
* 7.URI模板
* Controller上的:@RequestMapping ( "/test/{variable1}" )
* Method上的:@RequestMapping ( "/showView/{variable2}" )
* Method里取参数:showView( @PathVariable String variable1, @PathVariable ( "variable2" ) int variable2)
* 两种参数方式 前者只能在debug模式使用, 后者固定按照名称去绑定url中的变量,
* 支持通配符"*"
*
* ############################### 3.创建json数据 ###############################
* public @ResponseBody User getUser(@PathVariable String name)
* retrun user;
*
* ############################### 4.controller映射处理 ###############################
* ControllerClassNameHandlerMapping
* 1./helloWorld.html或 /hello{任何字母}.html,DispatcherServlet将请求转发到HelloController
* SimpleUrlHandlerMapping
* 2.可显示的匹配转发请求 http://www.yiibai.com/spring_mvc/springmvc_simpleurlhandlermapping.html
* ############################### mvc视图解析器 ###############################
* 1.InternalResourceViewResolver
* 2.XmlViewResolver http://www.yiibai.com/spring_mvc/springmvc_xmlviewresolver.html
* 3.ResourceBundleViewResolver
* 4.可配置多视图解析器并定义顺序
*
* ############################### 5.@RequestMapping高级应用 ###############################
* 1.@RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })
* 满足 param1=value1 且 param2存在 且 param3不存在 则能进入请求
* 2.@RequestMapping (value= "testMethod" , method={RequestMethod. GET , RequestMethod. DELETE })
* 只有 GET/DELETE 方法能够访问此方法
* 3.RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept" })
* 只有请求头包含 Accept 信息 且 host为localhost 才能正确访问此方法
*
* ############################### 6.@标记的处理器方法支持的 方法参数 和 返回值类型 ###############################
* ############ 参数类型:
* 1.HttpServlet对象: HttpServletRequest 、HttpServletResponse 和HttpSession
* 2.WebRequest(spring的对象):可访问HttpServletRequest 和HttpSession的属性值
* 3.InputStream 、OutputStream 、Reader 和Writer
* 4.@PathVariable 、@RequestParam 、@CookieValue 和@RequestHeader 标记的参数
* 5.@ModelAttribute
* 6.java.util.Map 、Spring 封装的Model 和ModelMap 。 这些都可以用来封装模型数据,用来给视图做展示
* 7.实体类 接收上传的参数
* 8.Spring 封装的MultipartFile, 用来接收上传文件的
* 9.Spring 封装的Errors 和BindingResult 对象。 这两个对象参数必须紧接在需要验证的实体对象参数之后,它里面包含了实体对象的验证结果。
* ############ 返回值类型:
* 1.ModelAndView
* 2.模型对象:包括Spring 封装好的Model 和ModelMap ,以及java.util.Map ,
* 当没有视图返回的时候视图名称将由RequestToViewNameTranslator 来决定
* 3.视图对象:在渲染视图的过程中模型的话就可以给处理器方法定义一个模型参数,然后在方法体里面往模型中添加值
* 4.String:往往是一个视图的名称
* 5.void:此情况一般直接把结果写到HttpServeletRequest中,
* 若没写,spring将会利用RequestToViewNameTranslator来返回一个视图的名称
* 6.@ResponseBody:任何返回值类型将经过HttpMessageConverters转换之后再写到HttpServletResponse中
* 7.其他任何返回值类型都会被当做模型中的一个属性来处理,返回的视图还是由RequestToViewNameTranslator来决定
* 添加属性到模型可在方法上,@ModelAttribute(“attributeName”),否则使用返回值类名称首字母小写形式表示
*
* ############################### 7.传递保存数据 ###############################
* 1.@ModelAttribute 和 @SessionAttributes 在不同模型和控制器间共享数据
* 1.1@ModelAttribute: 在方法上,该方法将在处理器方法执行前执行,并将结果放在session或model属性中
*
* @return
*/
package com.chengjs.cjsssmsweb.controller; | 6,229 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
UserManagerController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/UserManagerController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.common.enums.StatusEnum;
import com.chengjs.cjsssmsweb.enums.TestEnv;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import com.chengjs.cjsssmsweb.service.master.IUserManagerService;
import com.chengjs.cjsssmsweb.util.ExceptionUtil;
import com.chengjs.cjsssmsweb.util.HttpRespUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* UserController 管理台权限管理模块
*
* @author: <a href="mailto:[email protected]">chengjs</a>
*/
@Controller
@RequestMapping("/muser")
public class UserManagerController {
private static final Logger log = LoggerFactory.getLogger(UserManagerController.class);
@Autowired
private IUserManagerService userMService;
/**
* 注册
* JavaBean: User这种的bean会自动返回给前端
*
* @param user
* @param model
* @param response
* @return
*/
@RequestMapping("/muser/register")
public void register(UUser user, Model model, HttpServletResponse response) {
try {
userMService.registerUser(user);
log.info("用户:" + user.getUsername() + "注册管理台成功。");
HttpRespUtil.respJson(StatusEnum.SUCCESS, response);
} catch (Exception e) {
log.debug("注册管理台用户异常");
e.printStackTrace();
}
}
/**
* 登录
* <p>
* 非JavaBean: 要和前端传递的参数对象的参数名,保持一致 var params = {param1:v1},这里的参数 (String param1)
* 其不会自动返回给前端,用response或model增加属性方式返回给前端
*
* @param model
* @return
*/
@RequestMapping("/mloginUser")
public String login(UUser user, Model model) {
//用户视图相关操作尽在Subject
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
token.setRememberMe(TestEnv.onTFalse);//default rememberMe true
String out = "../../login";
try {
subject.login(token);
String principal_username = subject.getPrincipal().toString();
log.info("User [" + principal_username + "] 后台用户 登录成功.");
model.addAttribute("success", "恭喜" + principal_username + "登录成功");
//1.进行session相关事项,可为webSession也可为其他session
Session session = subject.getSession();
session.setAttribute("UserName", user.getUsername());
//2.一个(非常强大)的实例级别的权限
if (subject.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
model.addAttribute("User", user);
out = "admin";
} catch (UnknownAccountException e) {
ExceptionUtil.controllerEH(model, "用户名不存在", e, log, StatusEnum.FAIL);
} catch (IncorrectCredentialsException e) {
ExceptionUtil.controllerEH(model, "密码错误请重试", e, log, StatusEnum.FAIL);
} catch (LockedAccountException e) {
ExceptionUtil.controllerEH(model, "账号已被锁定", e, log, StatusEnum.FAIL);
} catch (AuthenticationException e) {
ExceptionUtil.controllerEH(model, "用户或密码错误", e, log, StatusEnum.FAIL);
} catch (Exception e) {
ExceptionUtil.controllerEH(model, "未知错误", e, log, StatusEnum.FAIL);
} finally {
return out;
}
} else {
model.addAttribute("success", "已登录");
return "admin";
}
}
@RequestMapping("/mlogoutUser")
public String logout(UUser user, Model model) throws IOException {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.removeAttribute("UserName");
return "redirect:../login.jsp";
}
}
| 4,729 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
SelectController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/SelectController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.mybatis.MybatisHelper;
import com.chengjs.cjsssmsweb.mybatis.mapper.master.UUserMapper;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import com.chengjs.cjsssmsweb.service.common.ISelectService;
import com.chengjs.cjsssmsweb.util.page.HttpReqsUtil;
import com.github.pagehelper.PageRowBounds;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* GridController: miniui类表单 后端请求类
* <p>
* 需实现的功能:
* 1.通用grid表格查询,导出: IN(taskName,params), 匹配参数信息,页面信息,排序信息, 映射mybatis_sqlxml, OUT(grid json)
* 2.通用select下拉查询: IN(taskName),匹配组织sql,查询结果
* <p>
* 功能现状:
* 一、原公司框架逻辑:配置logic + task,在所有logic和task中去匹配然后组织参数,执行sql获取返回值.
* 优势: 简洁好扩展,参数为空控制在logic中,logic,task分离可重用,直接关联数据源,清楚明了
* 借助2者分离,实现一些通用查询(比如说此处grid,select的通用查询).
* 缺憾: logic task实际业务中重用率非常低,要分开写多一套手续
* 二、现mybatis设计:接口+xml,
* 1)目标页面传入taskName("WebUserRolePermissionDao_WebUserGrid"),解析到interface("WebUserRolePermissionDao")--"WebUserGrid方法"
* 根据spring来获取接口实现对象,调用对应方法来获取结果--反射
* 2)
* 三、开源通用查询:
* 1.单表 多表
* 2.grid select
* <p>
* 四、思路
* 1.Mapper框架的
* <p>
* <p>
* <p>
* 四、参考文章
* http://www.cnblogs.com/svili/p/6057452.html
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/3
*/
@Controller
@RequestMapping("/select")
public class SelectController {
private static final Logger log = LoggerFactory.getLogger(SelectController.class);
@Autowired
private ISelectService selectService;
/**
* 通用selected查询
*
* @param method 查询方法名和ISelectDao中配置的一样
* @param request
* @return
* @throws UnsupportedEncodingException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
@RequestMapping("/comSelect")
public @ResponseBody
List<Map<String, String>> commonSelect(@RequestParam(value = "method") String method, HttpServletRequest request)
throws UnsupportedEncodingException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
HashMap<String, String> params = HttpReqsUtil.getRequestVals(request);
List<Map<String, String>> list = selectService.commonSelect(method, params);
return list;
}
/**
* commonGridQuery 通用grid数据查询
* key:查询条件书写规范: "UUserMapper_gridUsers"(Dao接口名_方法名)
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "/comGridQuery", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> commonGridQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {
HashMap<String, String> params = HttpReqsUtil.getRequestVals(request);
log.debug("grid通用查询参数:==>" + String.valueOf(params));
String data = params.get("data");
JSONObject obj = JSONObject.fromObject(data);//查询条件
HashMap<String, String> paramsMap = (HashMap<String, String>) JSONObject.toBean(JSONObject.fromObject(obj), HashMap.class);
Map<String, Object> resultMap = null;
/*分页*/
int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
/*字段排序*/
String sortField = request.getParameter("sortField");
String sortOrder = request.getParameter("sortOrder");
resultMap = selectService.queryGridKey(pageIndex,pageSize,sortField,sortOrder,paramsMap);
return resultMap;
}
/**
* users gird表查询
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "/userGridQuery", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> usersGridQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {
HashMap<String, String> params = HttpReqsUtil.getRequestVals(request);
log.debug("grid通用查询参数:==>" + String.valueOf(params));
String data = params.get("data");
JSONObject obj = JSONObject.fromObject(data);//查询条件
HashMap<String, String> paramsMap = (HashMap<String, String>) JSONObject.toBean(JSONObject.fromObject(obj), HashMap.class);
Map<String, Object> resultMap = null;
/*分页*/
int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
/*字段排序*/
String sortField = request.getParameter("sortField");
String sortOrder = request.getParameter("sortOrder");
return getGrids(pageIndex, pageSize, paramsMap);
}
/**
* 数据表grid查询 It's not good enough
* @param pageIndex
* @param pageSize
* @param paramsMap 给criteria添加参数使用
* @return
*/
private Map<String, Object> getGrids(int pageIndex, int pageSize, HashMap<String, String> paramsMap) {
PageRowBounds rowBounds = new PageRowBounds(pageIndex+1, pageSize);
SqlSession sqlSession = MybatisHelper.getSqlSession();
Mapper mapper = (Mapper) sqlSession.getMapper(UUserMapper.class);
Example example = new Example(UUser.class);
Example.Criteria criteria = example.createCriteria();
/*criteria增加条件...*/
List<UUser> users = (List<UUser>) mapper.selectByExampleAndRowBounds(example, rowBounds);
/*4.构造适合miniui_grid展示的map*/
Map<String, Object> map_grid = new HashedMap();
map_grid.put("total", users.size());
map_grid.put("data", users);
return map_grid;
}
/*========================== url ==========================*/
/**
* @return 普通方式实现grid表单的查询
*/
@RequestMapping("/usergrid")
public String usergrid() {
log.debug("user/usergrid");
return "user/usergrid";
}
} | 7,111 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
WebSocketController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/WebSocketController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.SocketContent;
import com.chengjs.cjsssmsweb.service.master.ISocketContentService;
import com.chengjs.cjsssmsweb.common.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.security.Principal;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* WebSocketController:
*
* 类似Servlet的注解mapping。无需在web.xml中配置。
* configurator = SpringConfigurator.class是为了使该类可以通过Spring注入。
*
* 该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。
*
* @author: <a href="mailto:[email protected]">chengjs</a>, version:1.0.0, 16:58
*/
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
public class WebSocketController {
private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);
/**
* TODO 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
* 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
*/
private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<WebSocketController>();
/**
* 与客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
@Autowired
private ISocketContentService contentService;
public WebSocketController() {
}
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.debug("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.debug("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
log.debug("来自客户端的消息:" + message);
/*群发消息*/
for (WebSocketController item : webSocketSet) {
try {
Principal principal = session.getUserPrincipal();
if (null == principal) {
log.debug("群发消息,未获取到当前用户认证信息。");
continue;
}
item.serializeMessage(message,principal);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.debug("发生错误");
error.printStackTrace();
}
/**
* 自定义方法: 聊天内容保存到数据库
*
* @param message
* @param username
* @throws IOException
*/
public void serializeMessage(String message, Principal username) throws IOException {
SocketContent content = new SocketContent();
content.setId(UUIDUtil.uuid());
content.setContentsender(username.getName());
content.setContent(message);
content.setCreatetime(new Date());
contentService.insertSelective(content);
if (log.isDebugEnabled()) {
log.debug("聊天内容入库:\"" + content.toString() + "\"");
}
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketController.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketController.onlineCount--;
}
}
| 4,668 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
ErrorController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/ErrorController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.common.enums.StatusEnum;
import com.chengjs.cjsssmsweb.req.BaseResponse;
import com.chengjs.cjsssmsweb.vo.NULLBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
/**
* ClassName: ErrorController <br/>
* Function: 错误异常统一处理. <br/>
*
* @author chengjs
* @since JDK 1.7
*/
@ControllerAdvice
public class ErrorController {
private static final Logger log = LoggerFactory.getLogger(ErrorController.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object processUnauthenticatedException(NativeWebRequest request, Exception e) {
log.error("请求出现异常:", e);
BaseResponse<NULLBody> response = new BaseResponse<NULLBody>();
response.setCode(StatusEnum.FAIL.getCode());
if (e instanceof RuntimeException) {
response.setMessage(e.getMessage());
} else {
response.setMessage(StatusEnum.FAIL.getMessage());
}
return response;
}
}
| 1,397 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
IndexController.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/controller/IndexController.java | package com.chengjs.cjsssmsweb.controller;
import com.chengjs.cjsssmsweb.common.enums.StatusEnum;
import com.chengjs.cjsssmsweb.common.util.StringUtil;
import com.chengjs.cjsssmsweb.components.lucene.LuceneIndex;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.SocketContent;
import com.chengjs.cjsssmsweb.mybatis.pojo.master.UUser;
import com.chengjs.cjsssmsweb.service.master.ISocketContentService;
import com.chengjs.cjsssmsweb.service.master.IUserFrontService;
import com.chengjs.cjsssmsweb.util.HttpRespUtil;
import com.chengjs.cjsssmsweb.util.page.PageEntity;
import com.chengjs.cjsssmsweb.util.page.PageUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* IndexController:
* author: <a href="mailto:[email protected]">chengjs</a>, version:1.0.0, 2017/8/24
*/
@Controller
@RequestMapping("/")
public class IndexController {
private static final Logger log = LoggerFactory.getLogger(IndexController.class);
@Autowired
private IUserFrontService userFService;
@Autowired
private ISocketContentService socketContentService;
/**
* model.addAttribute(attr1) ---- jsp ${attr1}
*
* @param page 直接取和页面上参数名相同的参数 @RequestParam
* @param request
* @param model
* @return 重定向的方式 return "redirect:index"
* @throws Exception
*/
@RequestMapping("/index")
public String index(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
HttpServletRequest request, Model model) throws Exception {
PageEntity pageEntity = new PageEntity(page, 10);
Map<String, Object> map = new HashMap<String, Object>();
map.put("start", pageEntity.getStart());
map.put("size", pageEntity.getPageSize());
List<UUser> users = userFService.list(map);
Long total = userFService.getTotal(map);
model.addAttribute("webusers", users);
StringBuffer param = new StringBuffer();
String pageHtml = PageUtil.genPagination(request.getContextPath() + "/index", total, page, 10, param.toString());
model.addAttribute("pageHtml", pageHtml);
return "index";
}
@RequestMapping("/index/turnToWebSocketIndex")
public String turnToWebSocketIndex() {
return "websocket";
}
/**
* 加载聊天记录
*
* @param response
*/
@RequestMapping("/content_load")
public void content_load(HttpServletResponse response) {
JSONObject jsonObject = new JSONObject();
try {
JSONObject jo = new JSONObject();
List<SocketContent> list = socketContentService.findSocketContentList();
jo.put("contents", list);
jsonObject = HttpRespUtil.parseJson(StatusEnum.HANDLE_SUCCESS, jo);
HttpRespUtil.responseBuildJson(response, jsonObject);
} catch (Exception e) {
log.error("操作异常", e);
HttpRespUtil.respJson(StatusEnum.HANDLE_FAIL, response);
}
}
/**
* 查询lucene索引下的blog Html
*
* @param query_key
* @param page
* @param model
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/queryLuceneByKey")
public String search(@RequestParam(value = "query_key", required = false, defaultValue = "") String query_key,
@RequestParam(value = "page", required = false, defaultValue = "1") String page,
Model model,
HttpServletRequest request) throws Exception {
List<UUser> userList = new ArrayList<>();
if (StringUtil.isNullOrEmpty(query_key)) { //关键词为空
//TODO 无关键词时如何处理
model.addAttribute("userList", userList);
} else {
LuceneIndex luceneIndex = new LuceneIndex();
userList = luceneIndex.searchBlog(query_key);
if (log.isDebugEnabled()) {
log.debug(String.format("关键字%s查询结果为:%s", query_key, String.valueOf(userList)));
}
/**
* 此处查询后分页,采用空间换时间,查出所有,截取分页
*/
Integer toIndex = userList.size() >= Integer.parseInt(page) * 5 ? Integer.parseInt(page) * 5 : userList.size();
List<UUser> newList = userList.subList((Integer.parseInt(page) - 1) * 5, toIndex);
model.addAttribute("userList", newList);
}
String pageHtml = this.genUpAndDownPageCode(Integer.parseInt(page), userList.size(), query_key, 5, "");
model.addAttribute("pageHtml", pageHtml);
model.addAttribute("resultTotal", userList.size());
model.addAttribute("query_key", query_key);
model.addAttribute("pageTitle", "搜索关键字'" + query_key + "'结果页面");
log.debug("query_key:" + query_key + ",共查询到" + userList.size() + "条。");
return "queryResult";
}
@RequestMapping(value = "/jsonpInfo", method = {RequestMethod.GET})
@ResponseBody
public Object jsonpInfo(String callback, String userId) throws IOException {
UUser user = userFService.getUserById(userId);
JSONPObject jsonpObject = new JSONPObject(callback, user);
return jsonpObject;
}
@RequestMapping("/createAllIndex")
public void createAllIndex(HttpServletResponse response) throws Exception {
Map<String, Object> remap = new HashedMap();
JSONObject jsonObject = new JSONObject();
try {
Map<String, Object> map = new HashMap<String, Object>();
List<UUser> users = userFService.list(map);
/*先删除原有的索引再创建新的*/
for (UUser user : users) {
LuceneIndex luceneIndex = new LuceneIndex();
luceneIndex.deleteIndex(user.getId() + "");
}
for (UUser user : users) {
LuceneIndex luceneIndex = new LuceneIndex();
luceneIndex.addIndex(user);
}
remap.put("msg", "重新生成索引成功");
log.debug("重新生成索引成功");
HttpRespUtil.respJson(StatusEnum.HANDLE_SUCCESS, remap, response);
} catch (Exception e) {
log.error("操作异常", e);
remap.put("msg", "重新生成索引失败");
HttpRespUtil.respJson(StatusEnum.HANDLE_FAIL, remap, response);
}
}
/**
* 查询之后的分页
*
* @param page
* @param totalNum
* @param q
* @param pageSize
* @param projectContext
* @return
*/
private String genUpAndDownPageCode(int page, Integer totalNum, String q, Integer pageSize, String projectContext) {
long totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
StringBuffer pageCode = new StringBuffer();
if (totalPage == 0) {
return "";
} else {
pageCode.append("<nav>");
pageCode.append("<ul class='pager' >");
if (page > 1) {
pageCode.append("<li><a href='" + projectContext + "/queryLuceneByKey?page=" + (page - 1) + "&q=" + q + "'>上一页</a></li>");
} else {
pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
}
if (page < totalPage) {
pageCode.append("<li><a href='" + projectContext + "/queryLuceneByKey?page=" + (page + 1) + "&q=" + q + "'>下一页</a></li>");
} else {
pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
}
pageCode.append("</ul>");
pageCode.append("</nav>");
}
return pageCode.toString();
}
}
| 7,989 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
package-info.java | /FileExtraction/Java_unseen/MiniPa_cjs_ssms/cjs_ssms_web/src/main/java/com/chengjs/cjsssmsweb/mybatis/package-info.java | /**
* package-info: mybatis mapper,pojo,xml
*
* @author: <a href="mailto:[email protected]">chengjs_minipa</a>, version:1.0.0, 2017/9/9
*/
package com.chengjs.cjsssmsweb.mybatis; | 191 | Java | .java | MiniPa/cjs_ssms | 11 | 11 | 1 | 2017-08-20T09:31:28Z | 2018-10-11T06:27:09Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.