proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/Avc1ToAvc3TrackImpl.java
|
ReplaceSyncSamplesList
|
get
|
class ReplaceSyncSamplesList extends AbstractList<Sample> {
List<Sample> parentSamples;
public ReplaceSyncSamplesList(List<Sample> parentSamples) {
this.parentSamples = parentSamples;
}
@Override
public Sample get(final int index) {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return parentSamples.size();
}
}
|
final Sample orignalSample = parentSamples.get(index);
if (orignalSample.getSampleEntry().getType().equals("avc1") && Arrays.binarySearch(Avc1ToAvc3TrackImpl.this.getSyncSamples(), index + 1) >= 0) {
final AvcConfigurationBox avcC = orignalSample.getSampleEntry().getBoxes(AvcConfigurationBox.class).get(0);
final int len = avcC.getLengthSizeMinusOne() + 1;
final ByteBuffer buf = ByteBuffer.allocate(len);
final SampleEntry se = avc1toavc3.get(orignalSample.getSampleEntry());
return new Sample() {
public SampleEntry getSampleEntry() {
return se;
}
public void writeTo(WritableByteChannel channel) throws IOException {
for (ByteBuffer bytes : avcC.getSequenceParameterSets()) {
IsoTypeWriterVariable.write(bytes.limit(), (ByteBuffer) ((Buffer)buf).rewind(), len);
channel.write((ByteBuffer) ((Buffer)buf).rewind());
channel.write(bytes);
}
for (ByteBuffer bytes : avcC.getSequenceParameterSetExts()) {
IsoTypeWriterVariable.write(bytes.limit(), (ByteBuffer) ((Buffer)buf).rewind(), len);
channel.write((ByteBuffer) ((Buffer)buf).rewind());
channel.write((bytes));
}
for (ByteBuffer bytes : avcC.getPictureParameterSets()) {
IsoTypeWriterVariable.write(bytes.limit(), (ByteBuffer) ((Buffer)buf).rewind(), len);
channel.write((ByteBuffer) ((Buffer)buf).rewind());
channel.write((bytes));
}
orignalSample.writeTo(channel);
}
public long getSize() {
int spsPpsSize = 0;
for (ByteBuffer bytes : avcC.getSequenceParameterSets()) {
spsPpsSize += len + bytes.limit();
}
for (ByteBuffer bytes : avcC.getSequenceParameterSetExts()) {
spsPpsSize += len + bytes.limit();
}
for (ByteBuffer bytes : avcC.getPictureParameterSets()) {
spsPpsSize += len + bytes.limit();
}
return orignalSample.getSize() + spsPpsSize;
}
public ByteBuffer asByteBuffer() {
int spsPpsSize = 0;
for (ByteBuffer bytes : avcC.getSequenceParameterSets()) {
spsPpsSize += len + bytes.limit();
}
for (ByteBuffer bytes : avcC.getSequenceParameterSetExts()) {
spsPpsSize += len + bytes.limit();
}
for (ByteBuffer bytes : avcC.getPictureParameterSets()) {
spsPpsSize += len + bytes.limit();
}
ByteBuffer data = ByteBuffer.allocate(l2i(orignalSample.getSize()) + spsPpsSize);
for (ByteBuffer bytes : avcC.getSequenceParameterSets()) {
IsoTypeWriterVariable.write(bytes.limit(), data, len);
data.put(bytes);
}
for (ByteBuffer bytes : avcC.getSequenceParameterSetExts()) {
IsoTypeWriterVariable.write(bytes.limit(), data, len);
data.put(bytes);
}
for (ByteBuffer bytes : avcC.getPictureParameterSets()) {
IsoTypeWriterVariable.write(bytes.limit(), data, len);
data.put(bytes);
}
data.put(orignalSample.asByteBuffer());
return (ByteBuffer) ((Buffer)data).rewind();
}
};
} else {
return orignalSample;
}
| 117
| 979
| 1,096
|
<methods>public void <init>(org.mp4parser.muxer.Track) ,public void close() throws java.io.IOException,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getHandler() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public long[] getSampleDurations() ,public List<org.mp4parser.boxes.sampleentry.SampleEntry> getSampleEntries() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public List<org.mp4parser.muxer.Sample> getSamples() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() ,public org.mp4parser.muxer.TrackMetaData getTrackMetaData() <variables>private org.mp4parser.muxer.Track parent
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/ChangeTimeScaleTrack.java
|
ChangeTimeScaleTrack
|
adjustCtts
|
class ChangeTimeScaleTrack implements Track {
private static Logger LOG = LoggerFactory.getLogger(ChangeTimeScaleTrack.class.getName());
Track source;
List<CompositionTimeToSample.Entry> ctts;
long[] decodingTimes;
long timeScale;
/**
* Changes the time scale of the source track to the target time scale and makes sure
* that any rounding errors that may have summed are corrected exactly before the syncSamples.
*
* @param source the source track
* @param targetTimeScale the resulting time scale of this track.
* @param syncSamples at these sync points where rounding error are corrected.
*/
public ChangeTimeScaleTrack(Track source, long targetTimeScale, long[] syncSamples) {
this.source = source;
this.timeScale = targetTimeScale;
double timeScaleFactor = (double) targetTimeScale / source.getTrackMetaData().getTimescale();
ctts = adjustCtts(source.getCompositionTimeEntries(), timeScaleFactor);
decodingTimes = adjustTts(source.getSampleDurations(), timeScaleFactor, syncSamples, getTimes(source, syncSamples, targetTimeScale));
}
private static long[] getTimes(Track track, long[] syncSamples, long targetTimeScale) {
long[] syncSampleTimes = new long[syncSamples.length];
int currentSample = 1; // first syncsample is 1
long currentDuration = 0;
int currentSyncSampleIndex = 0;
while (currentSample <= syncSamples[syncSamples.length - 1]) {
if (currentSample == syncSamples[currentSyncSampleIndex]) {
syncSampleTimes[currentSyncSampleIndex++] = (currentDuration * targetTimeScale) / track.getTrackMetaData().getTimescale();
}
currentDuration += track.getSampleDurations()[currentSample - 1];
currentSample++;
}
return syncSampleTimes;
}
/**
* Adjusting the composition times is easy. Just scale it by the factor - that's it. There is no rounding
* error summing up.
*
* @param source
* @param timeScaleFactor
* @return
*/
static List<CompositionTimeToSample.Entry> adjustCtts(List<CompositionTimeToSample.Entry> source, double timeScaleFactor) {<FILL_FUNCTION_BODY>}
static long[] adjustTts(long[] sourceArray, double timeScaleFactor, long[] syncSample, long[] syncSampleTimes) {
long summedDurations = 0;
long[] scaledArray = new long[sourceArray.length];
for (int i = 1; i <= sourceArray.length; i++) {
long duration = sourceArray[i - 1];
long x = Math.round(timeScaleFactor * duration);
int ssIndex;
if ((ssIndex = Arrays.binarySearch(syncSample, i + 1)) >= 0) {
// we are at the sample before sync point
if (syncSampleTimes[ssIndex] != summedDurations) {
long correction = syncSampleTimes[ssIndex] - (summedDurations + x);
LOG.debug(String.format("Sample %d %d / %d - correct by %d", i, summedDurations, syncSampleTimes[ssIndex], correction));
x += correction;
}
}
summedDurations += x;
scaledArray[i - 1] = x;
}
return scaledArray;
}
public void close() throws IOException {
source.close();
}
public List<SampleEntry> getSampleEntries() {
return source.getSampleEntries();
}
public long[] getSampleDurations() {
return decodingTimes;
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return ctts;
}
public long[] getSyncSamples() {
return source.getSyncSamples();
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return source.getSampleDependencies();
}
public TrackMetaData getTrackMetaData() {
TrackMetaData trackMetaData = (TrackMetaData) source.getTrackMetaData().clone();
trackMetaData.setTimescale(timeScale);
return trackMetaData;
}
public String getHandler() {
return source.getHandler();
}
public List<Sample> getSamples() {
return source.getSamples();
}
public SubSampleInformationBox getSubsampleInformationBox() {
return source.getSubsampleInformationBox();
}
public long getDuration() {
long duration = 0;
for (long delta : decodingTimes) {
duration += delta;
}
return duration;
}
@Override
public String toString() {
return "ChangeTimeScaleTrack{" +
"source=" + source +
'}';
}
public String getName() {
return "timeScale(" + source.getName() + ")";
}
public List<Edit> getEdits() {
return source.getEdits();
}
public Map<GroupEntry, long[]> getSampleGroups() {
return source.getSampleGroups();
}
}
|
if (source != null) {
List<CompositionTimeToSample.Entry> entries2 = new ArrayList<CompositionTimeToSample.Entry>(source.size());
for (CompositionTimeToSample.Entry entry : source) {
entries2.add(new CompositionTimeToSample.Entry(entry.getCount(), (int) Math.round(timeScaleFactor * entry.getOffset())));
}
return entries2;
} else {
return null;
}
| 1,357
| 121
| 1,478
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/CleanInputStream.java
|
CleanInputStream
|
read
|
class CleanInputStream extends FilterInputStream {
int prevprev = -1;
int prev = -1;
public CleanInputStream(InputStream in) {
super(in);
}
public boolean markSupported() {
return false;
}
public int read() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Copy of InputStream.read(b, off, len)
*
* @see java.io.InputStream#read()
*/
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte) c;
int i = 1;
try {
for (; i < len; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte) c;
}
} catch (IOException ee) {
}
return i;
}
}
|
int c = super.read();
if (c == 3 && prevprev == 0 && prev == 0) {
// discard this character
prevprev = -1;
prev = -1;
c = super.read();
}
prevprev = prev;
prev = c;
return c;
| 341
| 81
| 422
|
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/ClippedTrack.java
|
ClippedTrack
|
getDecodingTimeEntries
|
class ClippedTrack extends AbstractTrack {
private Track origTrack;
private int fromSample;
private int toSample;
/**
* Wraps an existing track and masks out a number of samples.
* Works like {@link java.util.List#subList(int, int)}.
*
* @param origTrack the original <code>Track</code>
* @param fromSample first sample in the new <code>Track</code> - beginning with 0
* @param toSample first sample not in the new <code>Track</code> - beginning with 0
*/
public ClippedTrack(Track origTrack, long fromSample, long toSample) {
super("crop(" + origTrack.getName() + ")");
this.origTrack = origTrack;
assert fromSample <= Integer.MAX_VALUE;
assert toSample <= Integer.MAX_VALUE;
this.fromSample = (int) fromSample;
this.toSample = (int) toSample;
}
static List<TimeToSampleBox.Entry> getDecodingTimeEntries(List<TimeToSampleBox.Entry> origSamples, long fromSample, long toSample) {<FILL_FUNCTION_BODY>}
static List<CompositionTimeToSample.Entry> getCompositionTimeEntries(List<CompositionTimeToSample.Entry> origSamples, long fromSample, long toSample) {
if (origSamples != null && !origSamples.isEmpty()) {
long current = 0;
ListIterator<CompositionTimeToSample.Entry> e = origSamples.listIterator();
ArrayList<CompositionTimeToSample.Entry> nuList = new ArrayList<CompositionTimeToSample.Entry>();
// Skip while not yet reached:
CompositionTimeToSample.Entry currentEntry;
while ((currentEntry = e.next()).getCount() + current <= fromSample) {
current += currentEntry.getCount();
}
// Take just a bit from the next
if (currentEntry.getCount() + current >= toSample) {
nuList.add(new CompositionTimeToSample.Entry((int) (toSample - fromSample), currentEntry.getOffset()));
return nuList; // done in one step
} else {
nuList.add(new CompositionTimeToSample.Entry((int) (currentEntry.getCount() + current - fromSample), currentEntry.getOffset()));
}
current += currentEntry.getCount();
while (e.hasNext() && (currentEntry = e.next()).getCount() + current < toSample) {
nuList.add(currentEntry);
current += currentEntry.getCount();
}
nuList.add(new CompositionTimeToSample.Entry((int) (toSample - current), currentEntry.getOffset()));
return nuList;
} else {
return null;
}
}
public void close() throws IOException {
origTrack.close();
}
public List<Sample> getSamples() {
return origTrack.getSamples().subList(fromSample, toSample);
}
public List<SampleEntry> getSampleEntries() {
return origTrack.getSampleEntries();
}
public synchronized long[] getSampleDurations() {
long[] decodingTimes = new long[toSample - fromSample];
System.arraycopy(origTrack.getSampleDurations(), fromSample, decodingTimes, 0, decodingTimes.length);
return decodingTimes;
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return getCompositionTimeEntries(origTrack.getCompositionTimeEntries(), fromSample, toSample);
}
synchronized public long[] getSyncSamples() {
if (origTrack.getSyncSamples() != null) {
long[] origSyncSamples = origTrack.getSyncSamples();
int i = 0, j = origSyncSamples.length;
while (i < origSyncSamples.length && origSyncSamples[i] < fromSample) {
i++;
}
while (j > 0 && toSample < origSyncSamples[j - 1]) {
j--;
}
long[] syncSampleArray = new long[j - i];
System.arraycopy(origTrack.getSyncSamples(), i, syncSampleArray, 0, j - i);
for (int k = 0; k < syncSampleArray.length; k++) {
syncSampleArray[k] -= fromSample;
}
return syncSampleArray;
}
return null;
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
if (origTrack.getSampleDependencies() != null && !origTrack.getSampleDependencies().isEmpty()) {
return origTrack.getSampleDependencies().subList(fromSample, toSample);
} else {
return null;
}
}
public TrackMetaData getTrackMetaData() {
return origTrack.getTrackMetaData();
}
public String getHandler() {
return origTrack.getHandler();
}
public SubSampleInformationBox getSubsampleInformationBox() {
return origTrack.getSubsampleInformationBox();
}
}
|
if (origSamples != null && !origSamples.isEmpty()) {
long current = 0;
ListIterator<TimeToSampleBox.Entry> e = origSamples.listIterator();
LinkedList<TimeToSampleBox.Entry> nuList = new LinkedList<TimeToSampleBox.Entry>();
// Skip while not yet reached:
TimeToSampleBox.Entry currentEntry;
while ((currentEntry = e.next()).getCount() + current <= fromSample) {
current += currentEntry.getCount();
}
// Take just a bit from the next
if (currentEntry.getCount() + current >= toSample) {
nuList.add(new TimeToSampleBox.Entry(toSample - fromSample, currentEntry.getDelta()));
return nuList; // done in one step
} else {
nuList.add(new TimeToSampleBox.Entry(currentEntry.getCount() + current - fromSample, currentEntry.getDelta()));
}
current += currentEntry.getCount();
while (e.hasNext() && (currentEntry = e.next()).getCount() + current < toSample) {
nuList.add(currentEntry);
current += currentEntry.getCount();
}
nuList.add(new TimeToSampleBox.Entry(toSample - current, currentEntry.getDelta()));
return nuList;
} else {
return null;
}
| 1,305
| 348
| 1,653
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/DTSTrackImpl.java
|
LookAhead
|
getSample
|
class LookAhead {
private final int corePresent;
long bufferStartPos;
int inBufferPos = 0;
DataSource dataSource;
long dataEnd;
ByteBuffer buffer;
long start;
LookAhead(DataSource dataSource, long bufferStartPos, long dataSize, int corePresent) throws IOException {
this.dataSource = dataSource;
this.bufferStartPos = bufferStartPos;
this.dataEnd = dataSize + bufferStartPos;
this.corePresent = corePresent;
fillBuffer();
}
public ByteBuffer findNextStart() throws IOException {
try {
// If core DTS stream is present then sync word is 0x7FFE8001
// otherwise 0x64582025
while (corePresent == 1 ? !this.nextFourEquals0x7FFE8001() : !nextFourEquals0x64582025()) {
this.discardByte();
}
this.discardNext4AndMarkStart();
while (corePresent == 1 ? !this.nextFourEquals0x7FFE8001orEof() : !nextFourEquals0x64582025orEof()) {
this.discardQWord();
}
return this.getSample();
} catch (EOFException e) {
return null;
}
}
private void fillBuffer() throws IOException {
System.err.println("Fill Buffer");
buffer = dataSource.map(bufferStartPos, Math.min(dataEnd - bufferStartPos, BUFFER));
}
private boolean nextFourEquals0x64582025() throws IOException {
return nextFourEquals((byte) 100, (byte) 88, (byte) 32, (byte) 37);
}
private boolean nextFourEquals0x7FFE8001() throws IOException {
return nextFourEquals((byte) 127, (byte) -2, (byte) -128, (byte) 1);
}
private boolean nextFourEquals(byte a, byte b, byte c, byte d) throws IOException {
if (buffer.limit() - inBufferPos >= 4) {
return ((buffer.get(inBufferPos) == a &&
buffer.get(inBufferPos + 1) == b &&
buffer.get(inBufferPos + 2) == c &&
(buffer.get(inBufferPos + 3) == d)));
}
if (bufferStartPos + inBufferPos + 4 >= dataSource.size()) {
throw new EOFException();
}
return false;
}
private boolean nextFourEquals0x64582025orEof() throws IOException {
return nextFourEqualsOrEof((byte) 100, (byte) 88, (byte) 32, (byte) 37);
}
private boolean nextFourEquals0x7FFE8001orEof() throws IOException {
return nextFourEqualsOrEof((byte) 127, (byte) -2, (byte) -128, (byte) 1);
}
private boolean nextFourEqualsOrEof(byte a, byte b, byte c, byte d) throws IOException {
if (buffer.limit() - inBufferPos >= 4) {
if (((bufferStartPos + inBufferPos) % (1024 * 1024)) == 0) {
System.err.println("" + ((bufferStartPos + inBufferPos) / 1024 / 1024));
}
return ((buffer.get(inBufferPos) == a /*0x7F */ &&
buffer.get(inBufferPos + 1) == b/*0xfe*/ &&
buffer.get(inBufferPos + 2) == c /*0x80*/ &&
(buffer.get(inBufferPos + 3) == d)));
} else {
if (bufferStartPos + inBufferPos + 4 > dataEnd) {
return bufferStartPos + inBufferPos == dataEnd;
} else {
bufferStartPos = start;
inBufferPos = 0;
fillBuffer();
return nextFourEquals0x7FFE8001();
}
}
}
private void discardByte() {
inBufferPos += 1;
}
private void discardQWord() {
inBufferPos += 4;
}
private void discardNext4AndMarkStart() {
start = bufferStartPos + inBufferPos;
inBufferPos += 4;
}
private ByteBuffer getSample() {<FILL_FUNCTION_BODY>}
}
|
if (start >= bufferStartPos) {
((Buffer)buffer).position((int) (start - bufferStartPos));
Buffer sample = buffer.slice();
((Buffer)sample).limit((int) (inBufferPos - (start - bufferStartPos)));
return (ByteBuffer) sample;
} else {
throw new RuntimeException("damn! NAL exceeds buffer");
// this can only happen if NAL is bigger than the buffer
}
| 1,176
| 113
| 1,289
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/DivideTimeScaleTrack.java
|
DivideTimeScaleTrack
|
adjustCtts
|
class DivideTimeScaleTrack implements Track {
Track source;
private int timeScaleDivisor;
public DivideTimeScaleTrack(Track source, int timeScaleDivisor) {
this.source = source;
this.timeScaleDivisor = timeScaleDivisor;
}
public void close() throws IOException {
source.close();
}
public List<SampleEntry> getSampleEntries() {
return source.getSampleEntries();
}
public long[] getSampleDurations() {
long[] scaled = new long[source.getSampleDurations().length];
for (int i = 0; i < source.getSampleDurations().length; i++) {
scaled[i] = source.getSampleDurations()[i] / timeScaleDivisor;
}
return scaled;
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return adjustCtts();
}
public long[] getSyncSamples() {
return source.getSyncSamples();
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return source.getSampleDependencies();
}
public TrackMetaData getTrackMetaData() {
TrackMetaData trackMetaData = (TrackMetaData) source.getTrackMetaData().clone();
trackMetaData.setTimescale(source.getTrackMetaData().getTimescale() / this.timeScaleDivisor);
return trackMetaData;
}
public String getHandler() {
return source.getHandler();
}
public List<Sample> getSamples() {
return source.getSamples();
}
List<CompositionTimeToSample.Entry> adjustCtts() {<FILL_FUNCTION_BODY>}
public SubSampleInformationBox getSubsampleInformationBox() {
return source.getSubsampleInformationBox();
}
public long getDuration() {
long duration = 0;
for (long delta : getSampleDurations()) {
duration += delta;
}
return duration;
}
@Override
public String toString() {
return "MultiplyTimeScaleTrack{" +
"source=" + source +
'}';
}
public String getName() {
return "timscale(" + source.getName() + ")";
}
public List<Edit> getEdits() {
return source.getEdits();
}
public Map<GroupEntry, long[]> getSampleGroups() {
return source.getSampleGroups();
}
}
|
List<CompositionTimeToSample.Entry> origCtts = this.source.getCompositionTimeEntries();
if (origCtts != null) {
List<CompositionTimeToSample.Entry> entries2 = new ArrayList<CompositionTimeToSample.Entry>(origCtts.size());
for (CompositionTimeToSample.Entry entry : origCtts) {
entries2.add(new CompositionTimeToSample.Entry(entry.getCount(), entry.getOffset() / timeScaleDivisor));
}
return entries2;
} else {
return null;
}
| 654
| 151
| 805
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/MultiplyTimeScaleTrack.java
|
MultiplyTimeScaleTrack
|
adjustCtts
|
class MultiplyTimeScaleTrack implements Track {
Track source;
private int timeScaleFactor;
public MultiplyTimeScaleTrack(Track source, int timeScaleFactor) {
this.source = source;
this.timeScaleFactor = timeScaleFactor;
}
static List<CompositionTimeToSample.Entry> adjustCtts(List<CompositionTimeToSample.Entry> source, int timeScaleFactor) {<FILL_FUNCTION_BODY>}
public void close() throws IOException {
source.close();
}
public List<SampleEntry> getSampleEntries() {
return source.getSampleEntries();
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return adjustCtts(source.getCompositionTimeEntries(), timeScaleFactor);
}
public long[] getSyncSamples() {
return source.getSyncSamples();
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return source.getSampleDependencies();
}
public TrackMetaData getTrackMetaData() {
TrackMetaData trackMetaData = (TrackMetaData) source.getTrackMetaData().clone();
trackMetaData.setTimescale(source.getTrackMetaData().getTimescale() * this.timeScaleFactor);
return trackMetaData;
}
public String getHandler() {
return source.getHandler();
}
public List<Sample> getSamples() {
return source.getSamples();
}
public long[] getSampleDurations() {
long[] scaled = new long[source.getSampleDurations().length];
for (int i = 0; i < source.getSampleDurations().length; i++) {
scaled[i] = source.getSampleDurations()[i] * timeScaleFactor;
}
return scaled;
}
public SubSampleInformationBox getSubsampleInformationBox() {
return source.getSubsampleInformationBox();
}
public long getDuration() {
return source.getDuration() * timeScaleFactor;
}
@Override
public String toString() {
return "MultiplyTimeScaleTrack{" +
"source=" + source +
'}';
}
public String getName() {
return "timscale(" + source.getName() + ")";
}
public List<Edit> getEdits() {
return source.getEdits();
}
public Map<GroupEntry, long[]> getSampleGroups() {
return source.getSampleGroups();
}
}
|
if (source != null) {
List<CompositionTimeToSample.Entry> entries2 = new ArrayList<CompositionTimeToSample.Entry>(source.size());
for (CompositionTimeToSample.Entry entry : source) {
entries2.add(new CompositionTimeToSample.Entry(entry.getCount(), timeScaleFactor * entry.getOffset()));
}
return entries2;
} else {
return null;
}
| 665
| 113
| 778
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/ReplaceSampleTrack.java
|
ReplaceASingleEntryList
|
get
|
class ReplaceASingleEntryList extends AbstractList<Sample> {
@Override
public Sample get(int index) {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return ReplaceSampleTrack.this.origTrack.getSamples().size();
}
}
|
if (ReplaceSampleTrack.this.sampleNumber == index) {
return ReplaceSampleTrack.this.sampleContent;
} else {
return ReplaceSampleTrack.this.origTrack.getSamples().get(index);
}
| 79
| 61
| 140
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/SilenceTrackImpl.java
|
SilenceTrackImpl
|
getDuration
|
class SilenceTrackImpl implements Track {
private Track source;
private List<Sample> samples = new LinkedList<Sample>();
private long[] decodingTimes;
private String name;
public SilenceTrackImpl(Track ofType, long ms) {
source = ofType;
name = "" + ms + "ms silence";
assert ofType.getSampleEntries().size() == 1: "";
if ("mp4a".equals(ofType.getSampleEntries().get(0).getType())) {
int numFrames = l2i(getTrackMetaData().getTimescale() * ms / 1000 / 1024);
decodingTimes = new long[numFrames];
Arrays.fill(decodingTimes, getTrackMetaData().getTimescale() * ms / numFrames / 1000);
while (numFrames-- > 0) {
samples.add(new SampleImpl((ByteBuffer) ((Buffer)ByteBuffer.wrap(new byte[]{
0x21, 0x10, 0x04, 0x60, (byte) 0x8c, 0x1c,
})).rewind(), ofType.getSampleEntries().get(0)));
}
} else {
throw new RuntimeException("Tracks of type " + ofType.getClass().getSimpleName() + " are not supported");
}
}
public void close() throws IOException {
// nothing to close
}
public List<SampleEntry> getSampleEntries() {
return source.getSampleEntries();
}
public long[] getSampleDurations() {
return decodingTimes;
}
public long getDuration() {<FILL_FUNCTION_BODY>}
public TrackMetaData getTrackMetaData() {
return source.getTrackMetaData();
}
public String getHandler() {
return source.getHandler();
}
public List<Sample> getSamples() {
return samples;
}
public SubSampleInformationBox getSubsampleInformationBox() {
return null;
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return null;
}
public long[] getSyncSamples() {
return null;
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return null;
}
public String getName() {
return name;
}
public List<Edit> getEdits() {
return null;
}
public Map<GroupEntry, long[]> getSampleGroups() {
return source.getSampleGroups();
}
}
|
long duration = 0;
for (long delta : decodingTimes) {
duration += delta;
}
return duration;
| 671
| 36
| 707
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/TextTrackImpl.java
|
TextTrackImpl
|
getSamples
|
class TextTrackImpl extends AbstractTrack {
TrackMetaData trackMetaData = new TrackMetaData();
TextSampleEntry tx3g;
List<Line> subs = new LinkedList<Line>();
List<Sample> samples;
public TextTrackImpl() {
super("subtitles");
tx3g = new TextSampleEntry("tx3g");
tx3g.setDataReferenceIndex(1);
tx3g.setStyleRecord(new TextSampleEntry.StyleRecord());
tx3g.setBoxRecord(new TextSampleEntry.BoxRecord());
FontTableBox ftab = new FontTableBox();
ftab.setEntries(Collections.singletonList(new FontTableBox.FontRecord(1, "Serif")));
tx3g.addBox(ftab);
trackMetaData.setCreationTime(new Date());
trackMetaData.setModificationTime(new Date());
trackMetaData.setTimescale(1000); // Text tracks use millieseconds
}
public List<Line> getSubs() {
return subs;
}
public void close() throws IOException {
// nothing to close
}
public synchronized List<Sample> getSamples() {<FILL_FUNCTION_BODY>}
public List<SampleEntry> getSampleEntries() {
return Collections.<SampleEntry>singletonList(tx3g);
}
public long[] getSampleDurations() {
List<Long> decTimes = new ArrayList<Long>();
long lastEnd = 0;
for (Line sub : subs) {
long silentTime = sub.from - lastEnd;
if (silentTime > 0) {
decTimes.add(silentTime);
} else if (silentTime < 0) {
throw new Error("Subtitle display times may not intersect");
}
decTimes.add(sub.to - sub.from);
lastEnd = sub.to;
}
long[] decTimesArray = new long[decTimes.size()];
int index = 0;
for (Long decTime : decTimes) {
decTimesArray[index++] = decTime;
}
return decTimesArray;
}
public List<CompositionTimeToSample.Entry> getCompositionTimeEntries() {
return null;
}
public long[] getSyncSamples() {
return null;
}
public List<SampleDependencyTypeBox.Entry> getSampleDependencies() {
return null;
}
public TrackMetaData getTrackMetaData() {
return trackMetaData;
}
public String getHandler() {
return "sbtl";
}
public SubSampleInformationBox getSubsampleInformationBox() {
return null;
}
public static class Line {
long from;
long to;
String text;
public Line(long from, long to, String text) {
this.from = from;
this.to = to;
this.text = text;
}
public long getFrom() {
return from;
}
public String getText() {
return text;
}
public long getTo() {
return to;
}
}
}
|
if (samples == null) {
samples = new ArrayList<>();
long lastEnd = 0;
for (Line sub : subs) {
long silentTime = sub.from - lastEnd;
if (silentTime > 0) {
samples.add(new SampleImpl(ByteBuffer.wrap(new byte[]{0, 0}), tx3g));
} else if (silentTime < 0) {
throw new Error("Subtitle display times may not intersect");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeShort(sub.text.getBytes("UTF-8").length);
dos.write(sub.text.getBytes("UTF-8"));
dos.close();
} catch (IOException e) {
throw new Error("VM is broken. Does not support UTF-8");
}
samples.add(new SampleImpl(ByteBuffer.wrap(baos.toByteArray()), tx3g));
lastEnd = sub.to;
}
}
return samples;
| 824
| 269
| 1,093
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/encryption/CencDecryptingSampleEntryTransformer.java
|
CencDecryptingSampleEntryTransformer
|
transform
|
class CencDecryptingSampleEntryTransformer {
private HashMap<SampleEntry, SampleEntry> cache = new HashMap<>();
SampleEntry transform(SampleEntry se) {<FILL_FUNCTION_BODY>}
}
|
SampleEntry decSe = cache.get(se);
if (decSe == null) {
OriginalFormatBox frma;
if (se.getType().equals("enca")) {
frma = Path.getPath((AudioSampleEntry) se, "sinf/frma");
} else if (se.getType().equals("encv")) {
frma = Path.getPath((VisualSampleEntry) se, "sinf/frma");
} else {
return se; // it's no encrypted SampleEntry - do nothing
}
if (frma == null) {
throw new RuntimeException("Could not find frma box");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// This creates a copy cause I can't change the original instance
se.getBox(Channels.newChannel(baos));
decSe = (SampleEntry) new IsoFile(new ByteBufferByteChannel(ByteBuffer.wrap(baos.toByteArray()))).getBoxes().get(0);
} catch (IOException e) {
throw new RuntimeException("Dumping stsd to memory failed");
}
if (decSe instanceof AudioSampleEntry) {
((AudioSampleEntry) decSe).setType(frma.getDataFormat());
} else if (decSe instanceof VisualSampleEntry) {
((VisualSampleEntry) decSe).setType(frma.getDataFormat());
} else {
throw new RuntimeException("I don't know " + decSe.getType());
}
List<Box> nuBoxes = new LinkedList<>();
for (Box box : decSe.getBoxes()) {
if (!box.getType().equals("sinf")) {
nuBoxes.add(box);
}
}
decSe.setBoxes(nuBoxes);
cache.put(se, decSe);
}
return decSe;
| 57
| 473
| 530
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/encryption/CencDecryptingSampleList.java
|
CencDecryptingSampleList
|
get
|
class CencDecryptingSampleList extends AbstractList<Sample> {
private RangeStartMap<Integer, SampleEntry> sampleEntries;
private List<CencSampleAuxiliaryDataFormat> sencInfo;
private RangeStartMap<Integer, SecretKey> keys = new RangeStartMap<>();
private List<Sample> parent;
public CencDecryptingSampleList(
RangeStartMap<Integer, SecretKey> keys,
RangeStartMap<Integer, SampleEntry> sampleEntries,
List<Sample> parent,
List<CencSampleAuxiliaryDataFormat> sencInfo
) {
this.sampleEntries = sampleEntries;
this.sencInfo = sencInfo;
this.keys = keys;
this.parent = parent;
}
private String getSchemeType(SampleEntry s) {
SchemeTypeBox schm = Path.getPath((Container) s, "sinf/schm");
assert schm != null : "Cannot get cipher without schemetypebox";
return schm.getSchemeType();
}
private Cipher getCipher(SecretKey sk, byte[] iv, SampleEntry se) {
byte[] fullIv = new byte[16];
System.arraycopy(iv, 0, fullIv, 0, iv.length);
// The IV
try {
String schemeType = getSchemeType(se);
if ("cenc".equals(schemeType) || "piff".equals(schemeType)) {
Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
c.init(Cipher.DECRYPT_MODE, sk, new IvParameterSpec(fullIv));
return c;
} else if ("cbc1".equals(schemeType)) {
Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
c.init(Cipher.DECRYPT_MODE, sk, new IvParameterSpec(fullIv));
return c;
} else {
throw new RuntimeException("Only cenc & cbc1 is supported as encryptionAlgo");
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
}
@Override
public Sample get(int index) {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return parent.size();
}
}
|
if (keys.get(index) != null) {
Sample encSample = parent.get(index);
final ByteBuffer encSampleBuffer = encSample.asByteBuffer();
((Buffer)encSampleBuffer).rewind();
final ByteBuffer decSampleBuffer = ByteBuffer.allocate(encSampleBuffer.limit());
final CencSampleAuxiliaryDataFormat sencEntry = sencInfo.get(index);
Cipher cipher = getCipher(keys.get(index), sencEntry.iv, encSample.getSampleEntry());
try {
if (sencEntry.pairs != null && sencEntry.pairs.length > 0) {
for (CencSampleAuxiliaryDataFormat.Pair pair : sencEntry.pairs) {
final int clearBytes = pair.clear();
final int encrypted = l2i(pair.encrypted());
byte[] clears = new byte[clearBytes];
encSampleBuffer.get(clears);
decSampleBuffer.put(clears);
if (encrypted > 0) {
byte[] encs = new byte[encrypted];
encSampleBuffer.get(encs);
final byte[] decr = cipher.update(encs);
decSampleBuffer.put(decr);
}
}
if (encSampleBuffer.remaining() > 0) {
System.err.println("Decrypted sample " + index + " but still data remaining: " + encSample.getSize());
}
decSampleBuffer.put(cipher.doFinal());
} else {
byte[] fullyEncryptedSample = new byte[encSampleBuffer.limit()];
encSampleBuffer.get(fullyEncryptedSample);
String schemeType = getSchemeType(encSample.getSampleEntry());
if ("cbc1".equals(schemeType)) {
int encryptedLength = fullyEncryptedSample.length / 16 * 16;
decSampleBuffer.put(cipher.doFinal(fullyEncryptedSample, 0, encryptedLength));
decSampleBuffer.put(fullyEncryptedSample, encryptedLength, fullyEncryptedSample.length - encryptedLength);
} else if ("cenc".equals(schemeType)) {
decSampleBuffer.put(cipher.doFinal(fullyEncryptedSample));
} else if ("piff".equals(schemeType)) {
decSampleBuffer.put(cipher.doFinal(fullyEncryptedSample));
} else {
throw new RuntimeException("unknown encryption algo");
}
}
((Buffer)encSampleBuffer).rewind();
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException(e);
}
((Buffer)decSampleBuffer).rewind();
return new SampleImpl(decSampleBuffer, sampleEntries.get(index));
} else {
return parent.get(index);
}
| 622
| 698
| 1,320
|
<methods>public boolean add(org.mp4parser.muxer.Sample) ,public void add(int, org.mp4parser.muxer.Sample) ,public boolean addAll(int, Collection<? extends org.mp4parser.muxer.Sample>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract org.mp4parser.muxer.Sample get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<org.mp4parser.muxer.Sample> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<org.mp4parser.muxer.Sample> listIterator() ,public ListIterator<org.mp4parser.muxer.Sample> listIterator(int) ,public org.mp4parser.muxer.Sample remove(int) ,public org.mp4parser.muxer.Sample set(int, org.mp4parser.muxer.Sample) ,public List<org.mp4parser.muxer.Sample> subList(int, int) <variables>protected transient int modCount
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/encryption/CencDecryptingTrackImpl.java
|
CencDecryptingTrackImpl
|
init
|
class CencDecryptingTrackImpl extends AbstractTrack {
private CencDecryptingSampleList samples;
private CencEncryptedTrack original;
private LinkedHashSet<SampleEntry> sampleEntries = new LinkedHashSet<>();
public CencDecryptingTrackImpl(CencEncryptedTrack original, SecretKey sk) {
super("dec(" + original.getName() + ")");
this.original = original;
Map<UUID, SecretKey> keys = new HashMap<>();
for (SampleEntry sampleEntry : original.getSampleEntries()) {
TrackEncryptionBox tenc = Path.getPath((Container)sampleEntry, "sinf[0]/schi[0]/tenc[0]");
assert tenc != null;
keys.put(tenc.getDefault_KID(), sk);
}
init(keys);
}
public CencDecryptingTrackImpl(CencEncryptedTrack original, Map<UUID, SecretKey> keys) {
super("dec(" + original.getName() + ")");
this.original = original;
init(keys);
}
private void init(Map<UUID, SecretKey> keys) {<FILL_FUNCTION_BODY>}
public void close() throws IOException {
original.close();
}
public long[] getSyncSamples() {
return original.getSyncSamples();
}
public List<SampleEntry> getSampleEntries() {
return new ArrayList<>(sampleEntries);
}
public long[] getSampleDurations() {
return original.getSampleDurations();
}
public TrackMetaData getTrackMetaData() {
return original.getTrackMetaData();
}
public String getHandler() {
return original.getHandler();
}
public List<Sample> getSamples() {
return samples;
}
@Override
public Map<GroupEntry, long[]> getSampleGroups() {
return original.getSampleGroups();
}
}
|
CencDecryptingSampleEntryTransformer tx = new CencDecryptingSampleEntryTransformer();
List<Sample> encSamples = original.getSamples();
RangeStartMap<Integer, SecretKey> indexToKey = new RangeStartMap<>();
RangeStartMap<Integer, SampleEntry> indexToSampleEntry = new RangeStartMap<>();
SampleEntry previousSampleEntry = null;
for (int i = 0; i < encSamples.size(); i++) {
Sample encSample = encSamples.get(i);
SampleEntry current = encSample.getSampleEntry();
sampleEntries.add(tx.transform(encSample.getSampleEntry()));
if (previousSampleEntry != current) {
indexToSampleEntry.put(i, current);
TrackEncryptionBox tenc = Path.getPath((Container) encSample.getSampleEntry(), "sinf[0]/schi[0]/tenc[0]");
if (tenc != null) {
indexToKey.put(i, keys.get(tenc.getDefault_KID()));
} else {
indexToKey.put(i, null);
}
}
previousSampleEntry = current;
}
samples = new CencDecryptingSampleList(indexToKey, indexToSampleEntry, encSamples, original.getSampleEncryptionEntries());
| 504
| 338
| 842
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/encryption/CencEncryptingSampleEntryTransformer.java
|
CencEncryptingSampleEntryTransformer
|
transform
|
class CencEncryptingSampleEntryTransformer {
private HashMap<SampleEntry, SampleEntry> cache = new HashMap<>();
public SampleEntry transform(SampleEntry se, String encryptionAlgo, UUID defaultKeyId) {<FILL_FUNCTION_BODY>}
}
|
SampleEntry encSampleEntry = cache.get(se);
if (encSampleEntry == null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
se.getBox(Channels.newChannel(baos));
encSampleEntry= (SampleEntry) new IsoFile(new ByteBufferByteChannel(ByteBuffer.wrap(baos.toByteArray()))).getBoxes().get(0);
} catch (IOException e) {
throw new RuntimeException("Dumping stsd to memory failed");
}
// stsd is now a copy of the original stsd. Not very efficient but we don't have to do that a hundred times ...
OriginalFormatBox originalFormatBox = new OriginalFormatBox();
originalFormatBox.setDataFormat(se.getType());
ProtectionSchemeInformationBox sinf = new ProtectionSchemeInformationBox();
sinf.addBox(originalFormatBox);
SchemeTypeBox schm = new SchemeTypeBox();
schm.setSchemeType(encryptionAlgo);
schm.setSchemeVersion(0x00010000);
sinf.addBox(schm);
SchemeInformationBox schi = new SchemeInformationBox();
TrackEncryptionBox trackEncryptionBox = new TrackEncryptionBox();
trackEncryptionBox.setDefaultIvSize(8);
trackEncryptionBox.setDefaultAlgorithmId(0x01);
trackEncryptionBox.setDefault_KID(defaultKeyId);
schi.addBox(trackEncryptionBox);
sinf.addBox(schi);
if (se instanceof AudioSampleEntry) {
((AudioSampleEntry) encSampleEntry).setType("enca");
((AudioSampleEntry) encSampleEntry).addBox(sinf);
} else if (se instanceof VisualSampleEntry) {
((VisualSampleEntry) encSampleEntry).setType("encv");
((VisualSampleEntry) encSampleEntry).addBox(sinf);
} else {
throw new RuntimeException("I don't know how to cenc " + se.getType());
}
cache.put(se, encSampleEntry);
}
return encSampleEntry;
| 69
| 538
| 607
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/encryption/CencEncryptingSampleList.java
|
EncryptedSampleImpl
|
writeTo
|
class EncryptedSampleImpl implements Sample {
private final Sample clearSample;
private int index;
private EncryptedSampleImpl(
Sample clearSample,
int index
) {
this.clearSample = clearSample;
this.index = index;
}
public void writeTo(WritableByteChannel channel) throws IOException {<FILL_FUNCTION_BODY>}
public long getSize() {
return clearSample.getSize();
}
public ByteBuffer asByteBuffer() {
ByteBuffer sample = (ByteBuffer) ((Buffer)clearSample.asByteBuffer()).rewind();
ByteBuffer encSample = ByteBuffer.allocate(sample.limit());
SampleEntry se = sampleEntries.get(index);
KeyIdKeyPair keyIdKeyPair = keys.get(index);
CencSampleAuxiliaryDataFormat entry = auxiliaryDataFormats.get(index);
SchemeTypeBox schm = Path.getPath((Container) se, "sinf[0]/schm[0]");
assert schm != null;
String encryptionAlgo = schm.getSchemeType();
Cipher cipher = ciphers.get(encryptionAlgo);
initCipher(cipher, entry.iv, keyIdKeyPair.getKey());
try {
if (entry.pairs != null) {
for (CencSampleAuxiliaryDataFormat.Pair pair : entry.pairs) {
byte[] clears = new byte[pair.clear()];
sample.get(clears);
encSample.put(clears);
if (pair.encrypted() > 0) {
byte[] toBeEncrypted = new byte[l2i(pair.encrypted())];
sample.get(toBeEncrypted);
assert (toBeEncrypted.length % 16) == 0;
byte[] encrypted = cipher.update(toBeEncrypted);
assert encrypted.length == toBeEncrypted.length;
encSample.put(encrypted);
}
}
} else {
byte[] fullyEncryptedSample = new byte[sample.limit()];
sample.get(fullyEncryptedSample);
if ("cbc1".equals(encryptionAlgo)) {
int encryptedLength = fullyEncryptedSample.length / 16 * 16;
encSample.put(cipher.doFinal(fullyEncryptedSample, 0, encryptedLength));
encSample.put(fullyEncryptedSample, encryptedLength, fullyEncryptedSample.length - encryptedLength);
} else if ("cenc".equals(encryptionAlgo)) {
encSample.put(cipher.doFinal(fullyEncryptedSample));
}
}
((Buffer)sample).rewind();
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException(e);
}
((Buffer)encSample).rewind();
return encSample;
}
@Override
public SampleEntry getSampleEntry() {
return sampleEntries.get(index);
}
}
|
ByteBuffer sample = (ByteBuffer)((Buffer)clearSample.asByteBuffer()).rewind();
SampleEntry se = sampleEntries.get(index);
KeyIdKeyPair keyIdKeyPair = keys.get(index);
CencSampleAuxiliaryDataFormat entry = auxiliaryDataFormats.get(index);
SchemeTypeBox schm = Path.getPath((Container) se, "sinf[0]/schm[0]");
assert schm != null;
String encryptionAlgo = schm.getSchemeType();
Cipher cipher = ciphers.get(encryptionAlgo);
initCipher(cipher, entry.iv, keyIdKeyPair.getKey());
try {
if (entry.pairs != null && entry.pairs.length > 0) {
byte[] fullSample = new byte[sample.limit()];
sample.get(fullSample);
int offset = 0;
for (CencSampleAuxiliaryDataFormat.Pair pair : entry.pairs) {
offset += pair.clear();
if (pair.encrypted() > 0) {
cipher.update(fullSample,
offset,
l2i(pair.encrypted()),
fullSample,
offset);
offset += pair.encrypted();
}
}
channel.write(ByteBuffer.wrap(fullSample));
} else {
byte[] fullyEncryptedSample = new byte[sample.limit()];
sample.get(fullyEncryptedSample);
if ("cbc1".equals(encryptionAlgo)) {
int encryptedLength = fullyEncryptedSample.length / 16 * 16;
channel.write(ByteBuffer.wrap(cipher.doFinal(fullyEncryptedSample, 0, encryptedLength)));
channel.write(ByteBuffer.wrap(fullyEncryptedSample, encryptedLength, fullyEncryptedSample.length - encryptedLength));
} else if ("cenc".equals(encryptionAlgo)) {
channel.write(ByteBuffer.wrap(cipher.doFinal(fullyEncryptedSample)));
}
}
((Buffer)sample).rewind();
} catch (IllegalBlockSizeException | BadPaddingException | ShortBufferException e) {
throw new RuntimeException(e);
}
| 752
| 554
| 1,306
|
<methods>public boolean add(org.mp4parser.muxer.Sample) ,public void add(int, org.mp4parser.muxer.Sample) ,public boolean addAll(int, Collection<? extends org.mp4parser.muxer.Sample>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract org.mp4parser.muxer.Sample get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<org.mp4parser.muxer.Sample> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<org.mp4parser.muxer.Sample> listIterator() ,public ListIterator<org.mp4parser.muxer.Sample> listIterator(int) ,public org.mp4parser.muxer.Sample remove(int) ,public org.mp4parser.muxer.Sample set(int, org.mp4parser.muxer.Sample) ,public List<org.mp4parser.muxer.Sample> subList(int, int) <variables>protected transient int modCount
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/H264TrackImpl.java
|
FirstVclNalDetector
|
isFirstInNew
|
class FirstVclNalDetector {
int frame_num;
int pic_parameter_set_id;
boolean field_pic_flag;
boolean bottom_field_flag;
int nal_ref_idc;
int pic_order_cnt_type;
int delta_pic_order_cnt_bottom;
int pic_order_cnt_lsb;
int delta_pic_order_cnt_0;
int delta_pic_order_cnt_1;
boolean idrPicFlag;
int idr_pic_id;
public FirstVclNalDetector(ByteBuffer nal, int nal_ref_idc, int nal_unit_type) {
InputStream bs = cleanBuffer(new ByteBufferBackedInputStream(nal));
SliceHeader sh = new SliceHeader(bs, spsIdToSps, ppsIdToPps, nal_unit_type == 5);
this.frame_num = sh.frame_num;
this.pic_parameter_set_id = sh.pic_parameter_set_id;
this.field_pic_flag = sh.field_pic_flag;
this.bottom_field_flag = sh.bottom_field_flag;
this.nal_ref_idc = nal_ref_idc;
this.pic_order_cnt_type = spsIdToSps.get(ppsIdToPps.get(sh.pic_parameter_set_id).seq_parameter_set_id).pic_order_cnt_type;
this.delta_pic_order_cnt_bottom = sh.delta_pic_order_cnt_bottom;
this.pic_order_cnt_lsb = sh.pic_order_cnt_lsb;
this.delta_pic_order_cnt_0 = sh.delta_pic_order_cnt_0;
this.delta_pic_order_cnt_1 = sh.delta_pic_order_cnt_1;
this.idr_pic_id = sh.idr_pic_id;
}
boolean isFirstInNew(FirstVclNalDetector nu) {<FILL_FUNCTION_BODY>}
}
|
if (nu.frame_num != frame_num) {
return true;
}
if (nu.pic_parameter_set_id != pic_parameter_set_id) {
return true;
}
if (nu.field_pic_flag != field_pic_flag) {
return true;
}
if (nu.field_pic_flag) {
if (nu.bottom_field_flag != bottom_field_flag) {
return true;
}
}
if (nu.nal_ref_idc != nal_ref_idc) {
return true;
}
if (nu.pic_order_cnt_type == 0 && pic_order_cnt_type == 0) {
if (nu.pic_order_cnt_lsb != pic_order_cnt_lsb) {
return true;
}
if (nu.delta_pic_order_cnt_bottom != delta_pic_order_cnt_bottom) {
return true;
}
}
if (nu.pic_order_cnt_type == 1 && pic_order_cnt_type == 1) {
if (nu.delta_pic_order_cnt_0 != delta_pic_order_cnt_0) {
return true;
}
if (nu.delta_pic_order_cnt_1 != delta_pic_order_cnt_1) {
return true;
}
}
if (nu.idrPicFlag != idrPicFlag) {
return true;
}
if (nu.idrPicFlag && idrPicFlag) {
if (nu.idr_pic_id != idr_pic_id) {
return true;
}
}
return false;
| 553
| 462
| 1,015
|
<methods>public void <init>(org.mp4parser.muxer.DataSource, boolean) ,public void <init>(org.mp4parser.muxer.DataSource) ,public void close() throws java.io.IOException,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public long[] getSampleDurations() ,public long[] getSyncSamples() ,public org.mp4parser.muxer.TrackMetaData getTrackMetaData() <variables>public static int BUFFER,protected List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> ctts,private org.mp4parser.muxer.DataSource dataSource,protected long[] decodingTimes,protected List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> sdtp,protected List<java.lang.Integer> stss,protected org.mp4parser.muxer.TrackMetaData trackMetaData,boolean tripleZeroIsEndOfSequence
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/SliceHeader.java
|
SliceHeader
|
toString
|
class SliceHeader {
public int first_mb_in_slice;
public SliceType slice_type;
public int pic_parameter_set_id;
public int colour_plane_id;
public int frame_num;
public boolean field_pic_flag = false;
public boolean bottom_field_flag = false;
public int idr_pic_id;
public int pic_order_cnt_lsb;
public int delta_pic_order_cnt_bottom;
public int delta_pic_order_cnt_0;
public int delta_pic_order_cnt_1;
public PictureParameterSet pps;
public SeqParameterSet sps;
public SliceHeader(InputStream is, Map<Integer, SeqParameterSet> spss, Map<Integer, PictureParameterSet> ppss, boolean IdrPicFlag) {
try {
is.read();
CAVLCReader reader = new CAVLCReader(is);
first_mb_in_slice = reader.readUE("SliceHeader: first_mb_in_slice");
int sliceTypeInt = reader.readUE("SliceHeader: slice_type");
switch (sliceTypeInt) {
case 0:
case 5:
slice_type = SliceType.P;
break;
case 1:
case 6:
slice_type = SliceType.B;
break;
case 2:
case 7:
slice_type = SliceType.I;
break;
case 3:
case 8:
slice_type = SliceType.SP;
break;
case 4:
case 9:
slice_type = SliceType.SI;
break;
}
pic_parameter_set_id = reader.readUE("SliceHeader: pic_parameter_set_id");
pps = ppss.get(pic_parameter_set_id);
if (pps == null) {
String ids = "";
for (Integer integer : spss.keySet()) {
ids += integer + ", ";
}
throw new RuntimeException("PPS with ids " + ids + " available but not " + pic_parameter_set_id);
}
sps = spss.get(pps.seq_parameter_set_id);
if (sps.residual_color_transform_flag) {
colour_plane_id = reader.readU(2, "SliceHeader: colour_plane_id");
}
frame_num = reader.readU(sps.log2_max_frame_num_minus4 + 4, "SliceHeader: frame_num");
if (!sps.frame_mbs_only_flag) {
field_pic_flag = reader.readBool("SliceHeader: field_pic_flag");
if (field_pic_flag) {
bottom_field_flag = reader.readBool("SliceHeader: bottom_field_flag");
}
}
if (IdrPicFlag) {
idr_pic_id = reader.readUE("SliceHeader: idr_pic_id");
}
if (sps.pic_order_cnt_type == 0) {
pic_order_cnt_lsb = reader.readU(sps.log2_max_pic_order_cnt_lsb_minus4 + 4, "SliceHeader: pic_order_cnt_lsb");
if (pps.bottom_field_pic_order_in_frame_present_flag && !field_pic_flag) {
delta_pic_order_cnt_bottom = reader.readSE("SliceHeader: delta_pic_order_cnt_bottom");
}
}
if (sps.pic_order_cnt_type == 1 && !sps.delta_pic_order_always_zero_flag) {
delta_pic_order_cnt_0 = reader.readSE("delta_pic_order_cnt_0");
if (pps.bottom_field_pic_order_in_frame_present_flag && !field_pic_flag) {
delta_pic_order_cnt_1 = reader.readSE("delta_pic_order_cnt_1");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public enum SliceType {
P, B, I, SP, SI
}
}
|
return "SliceHeader{" +
"first_mb_in_slice=" + first_mb_in_slice +
", slice_type=" + slice_type +
", pic_parameter_set_id=" + pic_parameter_set_id +
", colour_plane_id=" + colour_plane_id +
", frame_num=" + frame_num +
", field_pic_flag=" + field_pic_flag +
", bottom_field_flag=" + bottom_field_flag +
", idr_pic_id=" + idr_pic_id +
", pic_order_cnt_lsb=" + pic_order_cnt_lsb +
", delta_pic_order_cnt_bottom=" + delta_pic_order_cnt_bottom +
'}';
| 1,146
| 207
| 1,353
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/BTree.java
|
BTree
|
addString
|
class BTree {
private BTree zero;
private BTree one;
private Object value;
public void addString(String path, Object value) {<FILL_FUNCTION_BODY>}
public BTree down(int b) {
if (b == 0)
return zero;
else
return one;
}
public Object getValue() {
return value;
}
}
|
if (path.length() == 0) {
this.value = value;
return;
}
char charAt = path.charAt(0);
BTree branch;
if (charAt == '0') {
if (zero == null)
zero = new BTree();
branch = zero;
} else {
if (one == null)
one = new BTree();
branch = one;
}
branch.addString(path.substring(1), value);
| 108
| 128
| 236
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/CharCache.java
|
CharCache
|
append
|
class CharCache {
private char[] cache;
private int pos;
public CharCache(int capacity) {
cache = new char[capacity];
}
public void append(String str) {<FILL_FUNCTION_BODY>}
public String toString() {
return new String(cache, 0, pos);
}
public void clear() {
pos = 0;
}
public void append(char c) {
if (pos < cache.length - 1) {
cache[pos] = c;
pos++;
}
}
public int length() {
return pos;
}
}
|
char[] chars = str.toCharArray();
int available = cache.length - pos;
int toWrite = chars.length < available ? chars.length : available;
System.arraycopy(chars, 0, cache, pos, toWrite);
pos += toWrite;
| 170
| 74
| 244
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/Debug.java
|
Debug
|
print8x8
|
class Debug {
public final static boolean debug = false;
public final static void print8x8(int[] output) {
int i = 0;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
System.out.printf("%3d, ", output[i]);
i++;
}
System.out.println();
}
}
public final static void print8x8(short[] output) {<FILL_FUNCTION_BODY>}
public final static void print8x8(ShortBuffer output) {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
System.out.printf("%3d, ", output.get());
}
System.out.println();
}
}
public static void print(short[] table) {
int i = 0;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
System.out.printf("%3d, ", table[i]);
i++;
}
System.out.println();
}
}
public static void trace(String format, Object... args) {
// System.out.printf("> " + format + "\n", args);
}
public static void print(int i) {
if (debug)
System.out.print(i);
}
public static void print(String string) {
if (debug)
System.out.print(string);
}
public static void println(String string) {
if (debug)
System.out.println(string);
}
}
|
int i = 0;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
System.out.printf("%3d, ", output[i]);
i++;
}
System.out.println();
}
| 449
| 79
| 528
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/AspectRatio.java
|
AspectRatio
|
fromValue
|
class AspectRatio {
public static final AspectRatio Extended_SAR = new AspectRatio(255);
private int value;
private AspectRatio(int value) {
this.value = value;
}
public static AspectRatio fromValue(int value) {<FILL_FUNCTION_BODY>}
public int getValue() {
return value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AspectRatio{");
sb.append("value=").append(value);
sb.append('}');
return sb.toString();
}
}
|
if (value == Extended_SAR.value) {
return Extended_SAR;
}
return new AspectRatio(value);
| 172
| 41
| 213
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/ChromaFormat.java
|
ChromaFormat
|
fromId
|
class ChromaFormat {
public static final ChromaFormat MONOCHROME = new ChromaFormat(0, 0, 0);
public static final ChromaFormat YUV_420 = new ChromaFormat(1, 2, 2);
public static final ChromaFormat YUV_422 = new ChromaFormat(2, 2, 1);
public static final ChromaFormat YUV_444 = new ChromaFormat(3, 1, 1);
private int id;
private int subWidth;
private int subHeight;
public ChromaFormat(int id, int subWidth, int subHeight) {
this.id = id;
this.subWidth = subWidth;
this.subHeight = subHeight;
}
public static ChromaFormat fromId(int id) {<FILL_FUNCTION_BODY>}
public int getId() {
return id;
}
public int getSubWidth() {
return subWidth;
}
public int getSubHeight() {
return subHeight;
}
@Override
public String toString() {
return "ChromaFormat{" + "\n" +
"id=" + id + ",\n" +
" subWidth=" + subWidth + ",\n" +
" subHeight=" + subHeight +
'}';
}
}
|
if (id == MONOCHROME.id) {
return MONOCHROME;
} else if (id == YUV_420.id) {
return YUV_420;
} else if (id == YUV_422.id) {
return YUV_422;
} else if (id == YUV_444.id) {
return YUV_444;
}
return null;
| 361
| 121
| 482
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/HRDParameters.java
|
HRDParameters
|
toString
|
class HRDParameters {
public int cpb_cnt_minus1;
public int bit_rate_scale;
public int cpb_size_scale;
public int[] bit_rate_value_minus1;
public int[] cpb_size_value_minus1;
public boolean[] cbr_flag;
public int initial_cpb_removal_delay_length_minus1;
public int cpb_removal_delay_length_minus1;
public int dpb_output_delay_length_minus1;
public int time_offset_length;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "HRDParameters{" +
"cpb_cnt_minus1=" + cpb_cnt_minus1 +
", bit_rate_scale=" + bit_rate_scale +
", cpb_size_scale=" + cpb_size_scale +
", bit_rate_value_minus1=" + Arrays.toString(bit_rate_value_minus1) +
", cpb_size_value_minus1=" + Arrays.toString(cpb_size_value_minus1) +
", cbr_flag=" + Arrays.toString(cbr_flag) +
", initial_cpb_removal_delay_length_minus1=" + initial_cpb_removal_delay_length_minus1 +
", cpb_removal_delay_length_minus1=" + cpb_removal_delay_length_minus1 +
", dpb_output_delay_length_minus1=" + dpb_output_delay_length_minus1 +
", time_offset_length=" + time_offset_length +
'}';
| 169
| 269
| 438
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/ScalingList.java
|
ScalingList
|
toString
|
class ScalingList {
public int[] scalingList;
public boolean useDefaultScalingMatrixFlag;
public static ScalingList read(CAVLCReader is, int sizeOfScalingList)
throws IOException {
ScalingList sl = new ScalingList();
sl.scalingList = new int[sizeOfScalingList];
int lastScale = 8;
int nextScale = 8;
for (int j = 0; j < sizeOfScalingList; j++) {
if (nextScale != 0) {
int deltaScale = is.readSE("deltaScale");
nextScale = (lastScale + deltaScale + 256) % 256;
sl.useDefaultScalingMatrixFlag = (j == 0 && nextScale == 0);
}
sl.scalingList[j] = nextScale == 0 ? lastScale : nextScale;
lastScale = sl.scalingList[j];
}
return sl;
}
public void write(CAVLCWriter out) throws IOException {
if (useDefaultScalingMatrixFlag) {
out.writeSE(0, "SPS: ");
return;
}
int lastScale = 8;
int nextScale = 8;
for (int j = 0; j < scalingList.length; j++) {
if (nextScale != 0) {
int deltaScale = scalingList[j] - lastScale - 256;
out.writeSE(deltaScale, "SPS: ");
}
lastScale = scalingList[j];
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ScalingList{" +
"scalingList=" + scalingList +
", useDefaultScalingMatrixFlag=" + useDefaultScalingMatrixFlag +
'}';
| 416
| 48
| 464
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/ScalingMatrix.java
|
ScalingMatrix
|
toString
|
class ScalingMatrix {
public ScalingList[] ScalingList4x4;
public ScalingList[] ScalingList8x8;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ScalingMatrix{" +
"ScalingList4x4=" + (ScalingList4x4 == null ? null : Arrays.asList(ScalingList4x4)) + "\n" +
", ScalingList8x8=" + (ScalingList8x8 == null ? null : Arrays.asList(ScalingList8x8)) + "\n" +
'}';
| 62
| 101
| 163
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/model/VUIParameters.java
|
VUIParameters
|
toString
|
class VUIParameters {
public boolean aspect_ratio_info_present_flag;
public int sar_width;
public int sar_height;
public boolean overscan_info_present_flag;
public boolean overscan_appropriate_flag;
public boolean video_signal_type_present_flag;
public int video_format;
public boolean video_full_range_flag;
public boolean colour_description_present_flag;
public int colour_primaries;
public int transfer_characteristics;
public int matrix_coefficients;
public boolean chroma_loc_info_present_flag;
public int chroma_sample_loc_type_top_field;
public int chroma_sample_loc_type_bottom_field;
public boolean timing_info_present_flag;
public int num_units_in_tick;
public int time_scale;
public boolean fixed_frame_rate_flag;
public boolean low_delay_hrd_flag;
public boolean pic_struct_present_flag;
public HRDParameters nalHRDParams;
public HRDParameters vclHRDParams;
public BitstreamRestriction bitstreamRestriction;
public AspectRatio aspect_ratio;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public static class BitstreamRestriction {
public boolean motion_vectors_over_pic_boundaries_flag;
public int max_bytes_per_pic_denom;
public int max_bits_per_mb_denom;
public int log2_max_mv_length_horizontal;
public int log2_max_mv_length_vertical;
public int num_reorder_frames;
public int max_dec_frame_buffering;
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BitstreamRestriction{");
sb.append("motion_vectors_over_pic_boundaries_flag=").append(motion_vectors_over_pic_boundaries_flag);
sb.append(", max_bytes_per_pic_denom=").append(max_bytes_per_pic_denom);
sb.append(", max_bits_per_mb_denom=").append(max_bits_per_mb_denom);
sb.append(", log2_max_mv_length_horizontal=").append(log2_max_mv_length_horizontal);
sb.append(", log2_max_mv_length_vertical=").append(log2_max_mv_length_vertical);
sb.append(", num_reorder_frames=").append(num_reorder_frames);
sb.append(", max_dec_frame_buffering=").append(max_dec_frame_buffering);
sb.append('}');
return sb.toString();
}
}
}
|
return "VUIParameters{" + "\n" +
"aspect_ratio_info_present_flag=" + aspect_ratio_info_present_flag + "\n" +
", sar_width=" + sar_width + "\n" +
", sar_height=" + sar_height + "\n" +
", overscan_info_present_flag=" + overscan_info_present_flag + "\n" +
", overscan_appropriate_flag=" + overscan_appropriate_flag + "\n" +
", video_signal_type_present_flag=" + video_signal_type_present_flag + "\n" +
", video_format=" + video_format + "\n" +
", video_full_range_flag=" + video_full_range_flag + "\n" +
", colour_description_present_flag=" + colour_description_present_flag + "\n" +
", colour_primaries=" + colour_primaries + "\n" +
", transfer_characteristics=" + transfer_characteristics + "\n" +
", matrix_coefficients=" + matrix_coefficients + "\n" +
", chroma_loc_info_present_flag=" + chroma_loc_info_present_flag + "\n" +
", chroma_sample_loc_type_top_field=" + chroma_sample_loc_type_top_field + "\n" +
", chroma_sample_loc_type_bottom_field=" + chroma_sample_loc_type_bottom_field + "\n" +
", timing_info_present_flag=" + timing_info_present_flag + "\n" +
", num_units_in_tick=" + num_units_in_tick + "\n" +
", time_scale=" + time_scale + "\n" +
", fixed_frame_rate_flag=" + fixed_frame_rate_flag + "\n" +
", low_delay_hrd_flag=" + low_delay_hrd_flag + "\n" +
", pic_struct_present_flag=" + pic_struct_present_flag + "\n" +
", nalHRDParams=" + nalHRDParams + "\n" +
", vclHRDParams=" + vclHRDParams + "\n" +
", bitstreamRestriction=" + bitstreamRestriction + "\n" +
", aspect_ratio=" + aspect_ratio + "\n" +
'}';
| 715
| 621
| 1,336
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/read/BitstreamReader.java
|
BitstreamReader
|
moreRBSPData
|
class BitstreamReader {
protected static int bitsRead;
protected CharCache debugBits = new CharCache(50);
int nBit;
private InputStream is;
private int curByte;
private int nextByte;
public BitstreamReader(InputStream is) throws IOException {
this.is = is;
curByte = is.read();
nextByte = is.read();
}
public boolean readBool() throws IOException {
return read1Bit() == 1;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#read1Bit()
*/
public int read1Bit() throws IOException {
if (nBit == 8) {
advance();
if (curByte == -1) {
return -1;
}
}
int res = (curByte >> (7 - nBit)) & 1;
nBit++;
debugBits.append(res == 0 ? '0' : '1');
++bitsRead;
return res;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#readNBit(int)
*/
public long readNBit(int n) throws IOException {
if (n > 64)
throw new IllegalArgumentException("Can not readByte more then 64 bit");
long val = 0;
for (int i = 0; i < n; i++) {
val <<= 1;
val |= read1Bit();
}
return val;
}
private void advance() throws IOException {
curByte = nextByte;
nextByte = is.read();
nBit = 0;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#readByte()
*/
public int readByte() throws IOException {
if (nBit > 0) {
advance();
}
int res = curByte;
advance();
return res;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#moreRBSPData()
*/
public boolean moreRBSPData() throws IOException {<FILL_FUNCTION_BODY>}
public long getBitPosition() {
return (bitsRead * 8 + (nBit % 8));
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#readRemainingByte()
*/
public long readRemainingByte() throws IOException {
return readNBit(8 - nBit);
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#next_bits(int)
*/
public int peakNextBits(int n) throws IOException {
if (n > 8)
throw new IllegalArgumentException("N should be less then 8");
if (nBit == 8) {
advance();
if (curByte == -1) {
return -1;
}
}
int[] bits = new int[16 - nBit];
int cnt = 0;
for (int i = nBit; i < 8; i++) {
bits[cnt++] = (curByte >> (7 - i)) & 0x1;
}
for (int i = 0; i < 8; i++) {
bits[cnt++] = (nextByte >> (7 - i)) & 0x1;
}
int result = 0;
for (int i = 0; i < n; i++) {
result <<= 1;
result |= bits[i];
}
return result;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#byte_aligned()
*/
public boolean isByteAligned() {
return (nBit % 8) == 0;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.RBSPInputStream#close()
*/
public void close() throws IOException {
}
public int getCurBit() {
return nBit;
}
}
|
if (nBit == 8) {
advance();
}
int tail = 1 << (8 - nBit - 1);
int mask = ((tail << 1) - 1);
boolean hasTail = (curByte & mask) == tail;
return !(curByte == -1 || (nextByte == -1 && hasTail));
| 1,199
| 89
| 1,288
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/read/CAVLCReader.java
|
CAVLCReader
|
readCE
|
class CAVLCReader extends BitstreamReader {
public CAVLCReader(InputStream is) throws IOException {
super(is);
}
public long readNBit(int n, String message) throws IOException {
long val = readNBit(n);
trace(message, String.valueOf(val));
return val;
}
/**
* Read unsigned exp-golomb code
*
* @return
* @throws java.io.IOException
* @throws java.io.IOException
*/
private int readUE() throws IOException {
int cnt = 0;
while (read1Bit() == 0)
cnt++;
int res = 0;
if (cnt > 0) {
long val = readNBit(cnt);
res = (int) ((1 << cnt) - 1 + val);
}
return res;
}
/*
* (non-Javadoc)
*
* @see
* ua.org.jplayer.javcodec.h264.H264BitInputStream#readUE(java.lang.String)
*/
public int readUE(String message) throws IOException {
int res = readUE();
trace(message, String.valueOf(res));
return res;
}
public int readSE(String message) throws IOException {
int val = readUE();
int sign = ((val & 0x1) << 1) - 1;
val = ((val >> 1) + (val & 0x1)) * sign;
trace(message, String.valueOf(val));
return val;
}
public boolean readBool(String message) throws IOException {
boolean res = read1Bit() == 0 ? false : true;
trace(message, res ? "1" : "0");
return res;
}
public int readU(int i, String string) throws IOException {
return (int) readNBit(i, string);
}
public byte[] read(int payloadSize) throws IOException {
byte[] result = new byte[payloadSize];
for (int i = 0; i < payloadSize; i++) {
result[i] = (byte) readByte();
}
return result;
}
public boolean readAE() {
// TODO: do it!!
throw new UnsupportedOperationException("Stan");
}
public int readTE(int max) throws IOException {
if (max > 1)
return readUE();
return ~read1Bit() & 0x1;
}
public int readAEI() {
// TODO: do it!!
throw new UnsupportedOperationException("Stan");
}
public int readME(String string) throws IOException {
return readUE(string);
}
public Object readCE(BTree bt, String message) throws IOException {<FILL_FUNCTION_BODY>}
public int readZeroBitCount(String message) throws IOException {
int count = 0;
while (read1Bit() == 0)
count++;
trace(message, String.valueOf(count));
return count;
}
public void readTrailingBits() throws IOException {
read1Bit();
readRemainingByte();
}
private void trace(String message, String val) {
StringBuilder traceBuilder = new StringBuilder();
int spaces;
String pos = String.valueOf(bitsRead - debugBits.length());
spaces = 8 - pos.length();
traceBuilder.append("@" + pos);
for (int i = 0; i < spaces; i++)
traceBuilder.append(' ');
traceBuilder.append(message);
spaces = 100 - traceBuilder.length() - debugBits.length();
for (int i = 0; i < spaces; i++)
traceBuilder.append(' ');
traceBuilder.append(debugBits);
traceBuilder.append(" (" + val + ")");
debugBits.clear();
println(traceBuilder.toString());
}
}
|
while (true) {
int bit = read1Bit();
bt = bt.down(bit);
if (bt == null) {
throw new RuntimeException("Illegal code");
}
Object i = bt.getValue();
if (i != null) {
trace(message, i.toString());
return i;
}
}
| 1,041
| 95
| 1,136
|
<methods>public void <init>(java.io.InputStream) throws java.io.IOException,public void close() throws java.io.IOException,public long getBitPosition() ,public int getCurBit() ,public boolean isByteAligned() ,public boolean moreRBSPData() throws java.io.IOException,public int peakNextBits(int) throws java.io.IOException,public int read1Bit() throws java.io.IOException,public boolean readBool() throws java.io.IOException,public int readByte() throws java.io.IOException,public long readNBit(int) throws java.io.IOException,public long readRemainingByte() throws java.io.IOException<variables>protected static int bitsRead,private int curByte,protected org.mp4parser.muxer.tracks.h264.parsing.CharCache debugBits,private java.io.InputStream is,int nBit,private int nextByte
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/write/BitstreamWriter.java
|
BitstreamWriter
|
writeCurByte
|
class BitstreamWriter {
private final OutputStream os;
private int[] curByte = new int[8];
private int curBit;
public BitstreamWriter(OutputStream out) {
this.os = out;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.H264BitOutputStream#flush()
*/
public void flush() throws IOException {
for (int i = curBit; i < 8; i++) {
curByte[i] = 0;
}
curBit = 0;
writeCurByte();
}
private void writeCurByte() throws IOException {<FILL_FUNCTION_BODY>}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.H264BitOutputStream#write1Bit(int)
*/
public void write1Bit(int value) throws IOException {
Debug.print(value);
if (curBit == 8) {
curBit = 0;
writeCurByte();
}
curByte[curBit++] = value;
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.H264BitOutputStream#writeNBit(long,
* int)
*/
public void writeNBit(long value, int n) throws IOException {
for (int i = 0; i < n; i++) {
write1Bit((int) (value >> (n - i - 1)) & 0x1);
}
}
/*
* (non-Javadoc)
*
* @see
* ua.org.jplayer.javcodec.h264.H264BitOutputStream#writeRemainingZero()
*/
public void writeRemainingZero() throws IOException {
writeNBit(0, 8 - curBit);
}
/*
* (non-Javadoc)
*
* @see ua.org.jplayer.javcodec.h264.H264BitOutputStream#writeByte(int)
*/
public void writeByte(int b) throws IOException {
os.write(b);
}
}
|
int toWrite = (curByte[0] << 7) | (curByte[1] << 6) | (curByte[2] << 5)
| (curByte[3] << 4) | (curByte[4] << 3) | (curByte[5] << 2)
| (curByte[6] << 1) | curByte[7];
os.write(toWrite);
| 599
| 97
| 696
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/h264/parsing/write/CAVLCWriter.java
|
CAVLCWriter
|
writeUE
|
class CAVLCWriter extends BitstreamWriter {
public CAVLCWriter(OutputStream out) {
super(out);
}
public void writeU(int value, int n, String string) throws IOException {
Debug.print(string + "\t");
writeNBit(value, n);
Debug.println("\t" + value);
}
public void writeUE(int value) throws IOException {<FILL_FUNCTION_BODY>}
public void writeUE(int value, String string) throws IOException {
Debug.print(string + "\t");
writeUE(value);
Debug.println("\t" + value);
}
public void writeSE(int value, String string) throws IOException {
Debug.print(string + "\t");
writeUE((value << 1) * (value < 0 ? -1 : 1) + (value > 0 ? 1 : 0));
Debug.println("\t" + value);
}
public void writeBool(boolean value, String string) throws IOException {
Debug.print(string + "\t");
write1Bit(value ? 1 : 0);
Debug.println("\t" + value);
}
public void writeU(int i, int n) throws IOException {
writeNBit(i, n);
}
public void writeNBit(long value, int n, String string) throws IOException {
Debug.print(string + "\t");
for (int i = 0; i < n; i++) {
write1Bit((int) (value >> (n - i - 1)) & 0x1);
}
Debug.println("\t" + value);
}
public void writeTrailingBits() throws IOException {
write1Bit(1);
writeRemainingZero();
flush();
}
public void writeSliceTrailingBits() {
throw new IllegalStateException("todo");
}
}
|
int bits = 0;
int cumul = 0;
for (int i = 0; i < 15; i++) {
if (value < cumul + (1 << i)) {
bits = i;
break;
}
cumul += (1 << i);
}
writeNBit(0, bits);
write1Bit(1);
writeNBit(value - cumul, bits);
| 481
| 108
| 589
|
<methods>public void <init>(java.io.OutputStream) ,public void flush() throws java.io.IOException,public void write1Bit(int) throws java.io.IOException,public void writeByte(int) throws java.io.IOException,public void writeNBit(long, int) throws java.io.IOException,public void writeRemainingZero() throws java.io.IOException<variables>private int curBit,private int[] curByte,private final non-sealed java.io.OutputStream os
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/mjpeg/OneJpegPerIframe.java
|
OneJpegPerIframe
|
getSamples
|
class OneJpegPerIframe extends AbstractTrack {
private File[] jpegs;
private TrackMetaData trackMetaData = new TrackMetaData();
private long[] sampleDurations;
private long[] syncSamples;
private VisualSampleEntry mp4v;
public OneJpegPerIframe(String name, File[] jpegs, Track alignTo) throws IOException {
super(name);
this.jpegs = jpegs;
if (alignTo.getSyncSamples().length != jpegs.length) {
throw new RuntimeException("Number of sync samples doesn't match the number of stills (" + alignTo.getSyncSamples().length + " vs. " + jpegs.length + ")");
}
BufferedImage a = ImageIO.read(jpegs[0]);
trackMetaData.setWidth(a.getWidth());
trackMetaData.setHeight(a.getHeight());
trackMetaData.setTimescale(alignTo.getTrackMetaData().getTimescale());
long[] sampleDurationsToiAlignTo = alignTo.getSampleDurations();
long[] syncSamples = alignTo.getSyncSamples();
int currentSyncSample = 1;
long duration = 0;
sampleDurations = new long[syncSamples.length];
for (int i = 1; i < sampleDurationsToiAlignTo.length; i++) {
if (currentSyncSample < syncSamples.length && i == syncSamples[currentSyncSample]) {
sampleDurations[currentSyncSample - 1] = duration;
duration = 0;
currentSyncSample++;
}
duration += sampleDurationsToiAlignTo[i];
}
sampleDurations[sampleDurations.length - 1] = duration;
mp4v = new VisualSampleEntry("mp4v");
ESDescriptorBox esds = new ESDescriptorBox();
esds.setData(ByteBuffer.wrap(Hex.decodeHex("038080801B000100048080800D6C11000000000A1CB4000A1CB4068080800102")));
esds.setEsDescriptor((ESDescriptor) ObjectDescriptorFactory.createFrom(-1, ByteBuffer.wrap(Hex.decodeHex("038080801B000100048080800D6C11000000000A1CB4000A1CB4068080800102"))));
mp4v.addBox(esds);
this.syncSamples = new long[jpegs.length];
for (int i = 0; i < this.syncSamples.length; i++) {
this.syncSamples[i] = i + 1;
}
double earliestTrackPresentationTime = 0;
boolean acceptDwell = true;
boolean acceptEdit = true;
for (Edit edit : alignTo.getEdits()) {
if (edit.getMediaTime() == -1 && !acceptDwell) {
throw new RuntimeException("Cannot accept edit list for processing (1)");
}
if (edit.getMediaTime() >= 0 && !acceptEdit) {
throw new RuntimeException("Cannot accept edit list for processing (2)");
}
if (edit.getMediaTime() == -1) {
earliestTrackPresentationTime += edit.getSegmentDuration();
} else /* if edit.getMediaTime() >= 0 */ {
earliestTrackPresentationTime -= (double) edit.getMediaTime() / edit.getTimeScale();
acceptEdit = false;
acceptDwell = false;
}
}
if (alignTo.getCompositionTimeEntries() != null && alignTo.getCompositionTimeEntries().size() > 0) {
long currentTime = 0;
int[] ptss = CompositionTimeToSample.blowupCompositionTimes(alignTo.getCompositionTimeEntries());
for (int j = 0; j < ptss.length && j < 50; j++) {
ptss[j] += currentTime;
currentTime += alignTo.getSampleDurations()[j];
}
Arrays.sort(ptss);
earliestTrackPresentationTime += (double) ptss[0] / alignTo.getTrackMetaData().getTimescale();
}
if (earliestTrackPresentationTime < 0) {
getEdits().add(new Edit((long) (-earliestTrackPresentationTime * getTrackMetaData().getTimescale()), getTrackMetaData().getTimescale(), 1.0, (double) getDuration() / getTrackMetaData().getTimescale()));
} else if (earliestTrackPresentationTime > 0) {
getEdits().add(new Edit(-1, getTrackMetaData().getTimescale(), 1.0, earliestTrackPresentationTime));
getEdits().add(new Edit(0, getTrackMetaData().getTimescale(), 1.0, (double) getDuration() / getTrackMetaData().getTimescale()));
}
}
public List<SampleEntry> getSampleEntries() {
return Collections.<SampleEntry>singletonList(mp4v);
}
public long[] getSampleDurations() {
return sampleDurations;
}
public TrackMetaData getTrackMetaData() {
return trackMetaData;
}
public String getHandler() {
return "vide";
}
@Override
public long[] getSyncSamples() {
return syncSamples;
}
public List<Sample> getSamples() {<FILL_FUNCTION_BODY>}
public void close() throws IOException {
}
}
|
return new AbstractList<Sample>() {
@Override
public int size() {
return jpegs.length;
}
@Override
public Sample get(final int index) {
return new Sample() {
ByteBuffer sample = null;
public void writeTo(WritableByteChannel channel) throws IOException {
RandomAccessFile raf = new RandomAccessFile(jpegs[index], "r");
raf.getChannel().transferTo(0, raf.length(), channel);
raf.close();
}
public long getSize() {
return jpegs[index].length();
}
public ByteBuffer asByteBuffer() {
if (sample == null) {
try {
RandomAccessFile raf = new RandomAccessFile(jpegs[index], "r");
sample = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, raf.length());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return sample;
}
@Override
public SampleEntry getSampleEntry() {
return mp4v;
}
};
}
};
| 1,464
| 306
| 1,770
|
<methods>public void <init>(java.lang.String) ,public List<org.mp4parser.boxes.iso14496.part12.CompositionTimeToSample.Entry> getCompositionTimeEntries() ,public long getDuration() ,public List<org.mp4parser.muxer.Edit> getEdits() ,public java.lang.String getName() ,public List<org.mp4parser.boxes.iso14496.part12.SampleDependencyTypeBox.Entry> getSampleDependencies() ,public Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> getSampleGroups() ,public org.mp4parser.boxes.iso14496.part12.SubSampleInformationBox getSubsampleInformationBox() ,public long[] getSyncSamples() <variables>List<org.mp4parser.muxer.Edit> edits,java.lang.String name,Map<org.mp4parser.boxes.samplegrouping.GroupEntry,long[]> sampleGroups
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/ttml/TtmlSegmenter.java
|
TtmlSegmenter
|
pushDown
|
class TtmlSegmenter {
public static List<Document> split(Document doc, int splitTimeInSeconds) throws XPathExpressionException {
int splitTime = splitTimeInSeconds * 1000;
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression xp = xpath.compile("//*[name()='p']");
boolean thereIsMore;
List<Document> subDocs = new ArrayList<Document>();
do {
long segmentStartTime = subDocs.size() * splitTime;
long segmentEndTime = (subDocs.size() + 1) * splitTime;
Document d = (Document) doc.cloneNode(true);
NodeList timedNodes = (NodeList) xp.evaluate(d, XPathConstants.NODESET);
thereIsMore = false;
for (int i = 0; i < timedNodes.getLength(); i++) {
Node p = timedNodes.item(i);
long startTime = getStartTime(p);
long endTime = getEndTime(p);
//p.appendChild(d.createComment(toTimeExpression(startTime) + " -> " + toTimeExpression(endTime)));
if (startTime < segmentStartTime && endTime > segmentStartTime) {
changeTime(p, "begin", segmentStartTime - startTime);
startTime = segmentStartTime;
}
if (startTime >= segmentStartTime && startTime < segmentEndTime && endTime > segmentEndTime) {
changeTime(p, "end", segmentEndTime - endTime);
startTime = segmentStartTime;
endTime = segmentEndTime;
}
if (startTime > segmentEndTime) {
thereIsMore = true;
}
if (!(startTime >= segmentStartTime && endTime <= segmentEndTime)) {
Node parent = p.getParentNode();
parent.removeChild(p);
} else {
changeTime(p, "begin", -segmentStartTime);
changeTime(p, "end", -segmentStartTime);
}
}
trimWhitespace(d);
XPathExpression bodyXP = xpath.compile("/*[name()='tt']/*[name()='body'][1]");
Element body = (Element) bodyXP.evaluate(d, XPathConstants.NODE);
String beginTime = body.getAttribute("begin");
String endTime = body.getAttribute("end");
if (beginTime == null || "".equals(beginTime)) {
body.setAttribute("begin", toTimeExpression(segmentStartTime));
} else {
changeTime(body, "begin", segmentStartTime);
}
if (endTime == null || "".equals(endTime)) {
body.setAttribute("end", toTimeExpression(segmentEndTime));
} else {
changeTime(body, "end", segmentEndTime);
}
subDocs.add(d);
} while (thereIsMore);
return subDocs;
}
public static void changeTime(Node p, String attribute, long amount) {
if (p.getAttributes() != null && p.getAttributes().getNamedItem(attribute) != null) {
String oldValue = p.getAttributes().getNamedItem(attribute).getNodeValue();
long nuTime = toTime(oldValue) + amount;
int frames = 0;
if (oldValue.contains(".")) {
frames = -1;
} else {
// todo more precision! 44 ~= 23 frames per second.
// that should be ok for non high framerate content
// actually I'd have to get the ttp:frameRateMultiplier
// and the ttp:frameRate attribute to calculate at which frame to show the sub
frames = (int) (nuTime - (nuTime / 1000) * 1000) / 44;
}
p.getAttributes().getNamedItem(attribute).setNodeValue(toTimeExpression(nuTime, frames));
}
}
public static Document normalizeTimes(Document doc) throws XPathExpressionException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
xpath.setNamespaceContext(TtmlHelpers.NAMESPACE_CONTEXT);
XPathExpression xp = xpath.compile("//*[name()='p']");
NodeList timedNodes = (NodeList) xp.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < timedNodes.getLength(); i++) {
Node p = timedNodes.item(i);
pushDown(p);
}
for (int i = 0; i < timedNodes.getLength(); i++) {
Node p = timedNodes.item(i);
removeAfterPushDown(p, "begin");
removeAfterPushDown(p, "end");
}
return doc;
}
private static void pushDown(Node p) {<FILL_FUNCTION_BODY>}
private static void removeAfterPushDown(Node p, String begin) {
Node current = p;
while ((current = current.getParentNode()) != null) {
if (current.getAttributes() != null && current.getAttributes().getNamedItem(begin) != null) {
current.getAttributes().removeNamedItem(begin);
}
}
}
public static void trimWhitespace(Node node) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); ++i) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
child.setTextContent(child.getTextContent().trim());
}
trimWhitespace(child);
}
}
}
|
long time = 0;
Node current = p;
while ((current = current.getParentNode()) != null) {
if (current.getAttributes() != null && current.getAttributes().getNamedItem("begin") != null) {
time += toTime(current.getAttributes().getNamedItem("begin").getNodeValue());
}
}
if (p.getAttributes() != null && p.getAttributes().getNamedItem("begin") != null) {
p.getAttributes().getNamedItem("begin").setNodeValue(toTimeExpression(time + toTime(p.getAttributes().getNamedItem("begin").getNodeValue())));
}
if (p.getAttributes() != null && p.getAttributes().getNamedItem("end") != null) {
p.getAttributes().getNamedItem("end").setNodeValue(toTimeExpression(time + toTime(p.getAttributes().getNamedItem("end").getNodeValue())));
}
| 1,508
| 242
| 1,750
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/webvtt/sampleboxes/AbstractCueBox.java
|
AbstractCueBox
|
getBox
|
class AbstractCueBox implements Box {
String content = "";
String type;
public AbstractCueBox(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public long getSize() {
return 8 + Utf8.utf8StringLengthInBytes(content);
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {<FILL_FUNCTION_BODY>}
public String getType() {
return type;
}
}
|
ByteBuffer header = ByteBuffer.allocate(l2i(getSize()));
IsoTypeWriter.writeUInt32(header, getSize());
header.put(IsoFile.fourCCtoBytes(getType()));
header.put(Utf8.convert(content));
writableByteChannel.write((ByteBuffer)((Buffer)header).rewind());
| 167
| 92
| 259
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/webvtt/sampleboxes/VTTCueBox.java
|
VTTCueBox
|
getSize
|
class VTTCueBox implements Box {
CueSourceIDBox cueSourceIDBox; // optional source ID
CueIDBox cueIDBox; // optional
CueTimeBox cueTimeBox; // optional current time indication
CueSettingsBox cueSettingsBox; // optional, cue settings
CuePayloadBox cuePayloadBox; // the (mandatory) cue payload lines
public VTTCueBox() {
}
public long getSize() {<FILL_FUNCTION_BODY>}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, getSize());
header.put(IsoFile.fourCCtoBytes(getType()));
writableByteChannel.write((ByteBuffer) ((Buffer)header).rewind());
if (cueSourceIDBox != null) {
cueSourceIDBox.getBox(writableByteChannel);
}
if (cueIDBox != null) {
cueIDBox.getBox(writableByteChannel);
}
if (cueTimeBox != null) {
cueTimeBox.getBox(writableByteChannel);
}
if (cueSettingsBox != null) {
cueSettingsBox.getBox(writableByteChannel);
}
if (cuePayloadBox != null) {
cuePayloadBox.getBox(writableByteChannel);
}
}
public CueSourceIDBox getCueSourceIDBox() {
return cueSourceIDBox;
}
public void setCueSourceIDBox(CueSourceIDBox cueSourceIDBox) {
this.cueSourceIDBox = cueSourceIDBox;
}
public CueIDBox getCueIDBox() {
return cueIDBox;
}
public void setCueIDBox(CueIDBox cueIDBox) {
this.cueIDBox = cueIDBox;
}
public CueTimeBox getCueTimeBox() {
return cueTimeBox;
}
public void setCueTimeBox(CueTimeBox cueTimeBox) {
this.cueTimeBox = cueTimeBox;
}
public CueSettingsBox getCueSettingsBox() {
return cueSettingsBox;
}
public void setCueSettingsBox(CueSettingsBox cueSettingsBox) {
this.cueSettingsBox = cueSettingsBox;
}
public CuePayloadBox getCuePayloadBox() {
return cuePayloadBox;
}
public void setCuePayloadBox(CuePayloadBox cuePayloadBox) {
this.cuePayloadBox = cuePayloadBox;
}
public String getType() {
return "vtcc";
}
}
|
return 8 +
(cueSourceIDBox != null ? cueSourceIDBox.getSize() : 0) +
(cueIDBox != null ? cueIDBox.getSize() : 0) +
(cueTimeBox != null ? cueTimeBox.getSize() : 0) +
(cueSettingsBox != null ? cueSettingsBox.getSize() : 0) +
(cuePayloadBox != null ? cuePayloadBox.getSize() : 0);
| 742
| 133
| 875
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/muxer/src/main/java/org/mp4parser/muxer/tracks/webvtt/sampleboxes/VTTEmptyCueBox.java
|
VTTEmptyCueBox
|
getBox
|
class VTTEmptyCueBox implements Box {
public VTTEmptyCueBox() {
}
public long getSize() {
return 8;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {<FILL_FUNCTION_BODY>}
public String getType() {
return "vtte";
}
}
|
ByteBuffer header = ByteBuffer.allocate(8);
IsoTypeWriter.writeUInt32(header, getSize());
header.put(IsoFile.fourCCtoBytes(getType()));
writableByteChannel.write((ByteBuffer)((Buffer) header).rewind());
| 101
| 73
| 174
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/extensions/CompositionTimeSampleExtension.java
|
CompositionTimeSampleExtension
|
create
|
class CompositionTimeSampleExtension implements SampleExtension {
public static Map<Long, CompositionTimeSampleExtension> pool =
Collections.synchronizedMap(new HashMap<Long, CompositionTimeSampleExtension>());
private long ctts;
public static CompositionTimeSampleExtension create(long offset) {<FILL_FUNCTION_BODY>}
/**
* This value provides the offset between decoding time and composition time. The offset is expressed as
* signed long such that CT(n) = DT(n) + CTTS(n). This method is
*
* @return offset between decoding time and composition time.
*/
public long getCompositionTimeOffset() {
return ctts;
}
@Override
public String toString() {
return "ctts=" + ctts;
}
}
|
CompositionTimeSampleExtension c = pool.get(offset);
if (c == null) {
c = new CompositionTimeSampleExtension();
c.ctts = offset;
pool.put(offset, c);
}
return c;
| 209
| 65
| 274
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/extensions/DefaultSampleFlagsTrackExtension.java
|
DefaultSampleFlagsTrackExtension
|
create
|
class DefaultSampleFlagsTrackExtension implements TrackExtension {
public static Map<Long, SampleFlagsSampleExtension> pool =
Collections.synchronizedMap(new HashMap<Long, SampleFlagsSampleExtension>());
private byte isLeading, sampleDependsOn, sampleIsDependedOn, sampleHasRedundancy, samplePaddingValue;
private boolean sampleIsNonSyncSample;
private int sampleDegradationPriority;
public static DefaultSampleFlagsTrackExtension create(
byte isLeading, byte sampleDependsOn, byte sampleIsDependedOn,
byte sampleHasRedundancy, byte samplePaddingValue, boolean sampleIsNonSyncSample, int sampleDegradationPriority) {<FILL_FUNCTION_BODY>}
public byte getIsLeading() {
return isLeading;
}
public void setIsLeading(int isLeading) {
this.isLeading = (byte) isLeading;
}
public byte getSampleDependsOn() {
return sampleDependsOn;
}
public void setSampleDependsOn(int sampleDependsOn) {
this.sampleDependsOn = (byte) sampleDependsOn;
}
public byte getSampleIsDependedOn() {
return sampleIsDependedOn;
}
public void setSampleIsDependedOn(int sampleIsDependedOn) {
this.sampleIsDependedOn = (byte) sampleIsDependedOn;
}
public byte getSampleHasRedundancy() {
return sampleHasRedundancy;
}
public void setSampleHasRedundancy(int sampleHasRedundancy) {
this.sampleHasRedundancy = (byte) sampleHasRedundancy;
}
public byte getSamplePaddingValue() {
return samplePaddingValue;
}
public void setSamplePaddingValue(byte samplePaddingValue) {
this.samplePaddingValue = samplePaddingValue;
}
public boolean isSampleIsNonSyncSample() {
return sampleIsNonSyncSample;
}
public void setSampleIsNonSyncSample(boolean sampleIsNonSyncSample) {
this.sampleIsNonSyncSample = sampleIsNonSyncSample;
}
public boolean isSyncSample() {
return !sampleIsNonSyncSample;
}
public int getSampleDegradationPriority() {
return sampleDegradationPriority;
}
public void setSampleDegradationPriority(int sampleDegradationPriority) {
this.sampleDegradationPriority = sampleDegradationPriority;
}
}
|
DefaultSampleFlagsTrackExtension c = new DefaultSampleFlagsTrackExtension();
c.isLeading = isLeading;
c.sampleDependsOn = sampleDependsOn;
c.sampleIsDependedOn = sampleIsDependedOn;
c.sampleHasRedundancy = sampleHasRedundancy;
c.samplePaddingValue = samplePaddingValue;
c.sampleIsNonSyncSample = sampleIsNonSyncSample;
c.sampleDegradationPriority = sampleDegradationPriority;
return c;
| 643
| 131
| 774
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/extensions/DimensionTrackExtension.java
|
DimensionTrackExtension
|
toString
|
class DimensionTrackExtension implements TrackExtension {
int width;
int height;
public DimensionTrackExtension(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "width=" + width + ", height=" + height;
| 162
| 20
| 182
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/extensions/NameTrackExtension.java
|
NameTrackExtension
|
create
|
class NameTrackExtension implements TrackExtension {
private String name;
public static NameTrackExtension create(String name) {<FILL_FUNCTION_BODY>}
public String getName() {
return name;
}
}
|
NameTrackExtension nameTrackExtension = new NameTrackExtension();
nameTrackExtension.name = name;
return nameTrackExtension;
| 60
| 34
| 94
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/extensions/SampleFlagsSampleExtension.java
|
SampleFlagsSampleExtension
|
create
|
class SampleFlagsSampleExtension implements SampleExtension {
public static Map<Long, SampleFlagsSampleExtension> pool =
Collections.synchronizedMap(new HashMap<Long, SampleFlagsSampleExtension>());
private byte isLeading, sampleDependsOn, sampleIsDependedOn, sampleHasRedundancy, samplePaddingValue;
private boolean sampleIsNonSyncSample;
private int sampleDegradationPriority;
public static SampleFlagsSampleExtension create(
byte isLeading, byte sampleDependsOn, byte sampleIsDependedOn,
byte sampleHasRedundancy, byte samplePaddingValue, boolean sampleIsNonSyncSample, int sampleDegradationPriority) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "isLeading=" + isLeading +
", dependsOn=" + sampleDependsOn +
", isDependedOn=" + sampleIsDependedOn +
", hasRedundancy=" + sampleHasRedundancy +
", paddingValue=" + samplePaddingValue +
", isSyncSample=" + !sampleIsNonSyncSample +
", sampleDegradationPriority=" + sampleDegradationPriority;
}
public byte getIsLeading() {
return isLeading;
}
public void setIsLeading(byte isLeading) {
this.isLeading = isLeading;
}
public byte getSampleDependsOn() {
return sampleDependsOn;
}
public void setSampleDependsOn(int sampleDependsOn) {
this.sampleDependsOn = (byte) sampleDependsOn;
}
public byte getSampleIsDependedOn() {
return sampleIsDependedOn;
}
public void setSampleIsDependedOn(int sampleIsDependedOn) {
this.sampleIsDependedOn = (byte) sampleIsDependedOn;
}
public byte getSampleHasRedundancy() {
return sampleHasRedundancy;
}
public void setSampleHasRedundancy(byte sampleHasRedundancy) {
this.sampleHasRedundancy = sampleHasRedundancy;
}
public byte getSamplePaddingValue() {
return samplePaddingValue;
}
public void setSamplePaddingValue(byte samplePaddingValue) {
this.samplePaddingValue = samplePaddingValue;
}
public boolean isSampleIsNonSyncSample() {
return sampleIsNonSyncSample;
}
public void setSampleIsNonSyncSample(boolean sampleIsNonSyncSample) {
this.sampleIsNonSyncSample = sampleIsNonSyncSample;
}
public boolean isSyncSample() {
return !sampleIsNonSyncSample;
}
public int getSampleDegradationPriority() {
return sampleDegradationPriority;
}
public void setSampleDegradationPriority(int sampleDegradationPriority) {
this.sampleDegradationPriority = sampleDegradationPriority;
}
}
|
long key = isLeading + (sampleDependsOn << 2) + (sampleIsDependedOn << 4) + (sampleHasRedundancy << 6);
key += (samplePaddingValue << 8);
key += (sampleDegradationPriority << 11);
key += (sampleIsNonSyncSample ? 1 : 0) << 27;
SampleFlagsSampleExtension c = pool.get(key);
if (c == null) {
c = new SampleFlagsSampleExtension();
c.isLeading = isLeading;
c.sampleDependsOn = sampleDependsOn;
c.sampleIsDependedOn = sampleIsDependedOn;
c.sampleHasRedundancy = sampleHasRedundancy;
c.samplePaddingValue = samplePaddingValue;
c.sampleIsNonSyncSample = sampleIsNonSyncSample;
c.sampleDegradationPriority = sampleDegradationPriority;
pool.put(key, c);
}
return c;
| 757
| 246
| 1,003
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/H264AnnexBTrack.java
|
NalStreamTokenizer
|
getNext
|
class NalStreamTokenizer {
private static Logger LOG = LoggerFactory.getLogger(NalStreamTokenizer.class.getName());
MyByteArrayOutputStream next = new MyByteArrayOutputStream();
int pattern = 0;
private InputStream inputStream;
public NalStreamTokenizer(InputStream inputStream) {
this.inputStream = inputStream;
}
public byte[] getNext() throws IOException {<FILL_FUNCTION_BODY>}
}
|
//System.err.println("getNext() called");
if (LOG.isDebugEnabled()) {
LOG.debug("getNext() called");
}
int c;
while ((c = inputStream.read()) != -1) {
if (!(pattern == 2 && c == 3)) {
next.write(c);
if (pattern == 0 && c == 0) {
pattern = 1;
} else if (pattern == 1 && c == 0) {
pattern = 2;
} else if (pattern == 2 && c == 0) {
byte[] s = next.toByteArrayLess3();
next.reset();
if (s != null) {
return s;
}
} else if (pattern == 2 && c == 1) {
byte[] s = next.toByteArrayLess3();
next.reset();
pattern = 0;
if (s != null) {
return s;
}
} else if (pattern != 0) {
pattern = 0;
}
} else {
pattern = 0;
}
}
byte[] s = next.toByteArray();
next.reset();
if (s.length > 0) {
return s;
} else {
return null;
}
| 120
| 329
| 449
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public synchronized void configure() ,public java.lang.String getHandler() ,public java.lang.String getLanguage() ,public static org.mp4parser.streaming.input.h264.H264NalUnitHeader getNalUnitHeader(java.nio.ByteBuffer) ,public org.mp4parser.boxes.iso14496.part12.SampleDescriptionBox getSampleDescriptionBox() ,public long getTimescale() ,public void setFrametick(int) ,public void setTimescale(int) <variables>private static org.slf4j.Logger LOG,List<java.nio.ByteBuffer> buffered,boolean configured,org.mp4parser.streaming.input.h264.spspps.PictureParameterSet currentPictureParameterSet,org.mp4parser.streaming.input.h264.spspps.SeqParameterSet currentSeqParameterSet,List<org.mp4parser.streaming.StreamingSample> decFrameBuffer,List<org.mp4parser.streaming.StreamingSample> decFrameBuffer2,int frametick,org.mp4parser.streaming.input.h264.H264NalConsumingTrack.FirstVclNalDetector fvnd,int max_dec_frame_buffering,LinkedHashMap<java.lang.Integer,org.mp4parser.streaming.input.h264.spspps.PictureParameterSet> ppsIdToPps,LinkedHashMap<java.lang.Integer,java.nio.ByteBuffer> ppsIdToPpsBytes,org.mp4parser.streaming.input.h264.H264NalUnitHeader sliceNalUnitHeader,BlockingQueue<org.mp4parser.streaming.input.h264.spspps.SeqParameterSet> spsForConfig,LinkedHashMap<java.lang.Integer,org.mp4parser.streaming.input.h264.spspps.SeqParameterSet> spsIdToSps,LinkedHashMap<java.lang.Integer,java.nio.ByteBuffer> spsIdToSpsBytes,org.mp4parser.boxes.iso14496.part12.SampleDescriptionBox stsd,int timescale
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/PictureOrderCountType0SampleExtension.java
|
PictureOrderCountType0SampleExtension
|
toString
|
class PictureOrderCountType0SampleExtension implements SampleExtension {
int picOrderCntMsb;
int picOrderCountLsb;
public PictureOrderCountType0SampleExtension(SliceHeader currentSlice, PictureOrderCountType0SampleExtension previous) {
int prevPicOrderCntLsb = 0;
int prevPicOrderCntMsb = 0;
if (previous != null) {
prevPicOrderCntLsb = previous.picOrderCountLsb;
prevPicOrderCntMsb = previous.picOrderCntMsb;
}
int max_pic_order_count_lsb = (1 << (currentSlice.sps.log2_max_pic_order_cnt_lsb_minus4 + 4));
// System.out.print(" pic_order_cnt_lsb " + pic_order_cnt_lsb + " " + max_pic_order_count);
picOrderCountLsb = currentSlice.pic_order_cnt_lsb;
picOrderCntMsb = 0;
if ((picOrderCountLsb < prevPicOrderCntLsb) &&
((prevPicOrderCntLsb - picOrderCountLsb) >= (max_pic_order_count_lsb / 2))) {
picOrderCntMsb = prevPicOrderCntMsb + max_pic_order_count_lsb;
} else if ((picOrderCountLsb > prevPicOrderCntLsb) &&
((picOrderCountLsb - prevPicOrderCntLsb) > (max_pic_order_count_lsb / 2))) {
picOrderCntMsb = prevPicOrderCntMsb - max_pic_order_count_lsb;
} else {
picOrderCntMsb = prevPicOrderCntMsb;
}
}
public int getPoc() {
return picOrderCntMsb + picOrderCountLsb;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "picOrderCntMsb=" + picOrderCntMsb + ", picOrderCountLsb=" + picOrderCountLsb;
| 519
| 38
| 557
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/AspectRatio.java
|
AspectRatio
|
fromValue
|
class AspectRatio {
public static final AspectRatio Extended_SAR = new AspectRatio(255);
private int value;
private AspectRatio(int value) {
this.value = value;
}
public static AspectRatio fromValue(int value) {<FILL_FUNCTION_BODY>}
public int getValue() {
return value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AspectRatio{");
sb.append("value=").append(value);
sb.append('}');
return sb.toString();
}
}
|
if (value == Extended_SAR.value) {
return Extended_SAR;
}
return new AspectRatio(value);
| 172
| 41
| 213
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/ByteBufferBitreader.java
|
ByteBufferBitreader
|
readNBit
|
class ByteBufferBitreader {
ByteBuffer buffer;
int nBit;
private int currentByte;
private int nextByte;
public ByteBufferBitreader(ByteBuffer buffer) {
this.buffer = buffer;
currentByte = get();
nextByte = get();
}
public int get() {
try {
int i = buffer.get();
i = i < 0 ? i + 256 : i;
return i;
} catch (BufferUnderflowException e) {
return -1;
}
}
public int read1Bit() throws IOException {
if (nBit == 8) {
advance();
if (currentByte == -1) {
return -1;
}
}
int res = (currentByte >> (7 - nBit)) & 1;
nBit++;
return res;
}
private void advance() throws IOException {
currentByte = nextByte;
nextByte = get();
nBit = 0;
}
public int readUE() throws IOException {
int cnt = 0;
while (read1Bit() == 0) {
cnt++;
}
int res = 0;
if (cnt > 0) {
res = (int) ((1 << cnt) - 1 + readNBit(cnt));
}
return res;
}
public long readNBit(int n) throws IOException {<FILL_FUNCTION_BODY>}
public boolean readBool() throws IOException {
return read1Bit() != 0;
}
public int readSE() throws IOException {
int val = readUE();
int sign = ((val & 0x1) << 1) - 1;
val = ((val >> 1) + (val & 0x1)) * sign;
return val;
}
public boolean moreRBSPData() throws IOException {
if (nBit == 8) {
advance();
}
int tail = 1 << (8 - nBit - 1);
int mask = ((tail << 1) - 1);
boolean hasTail = (currentByte & mask) == tail;
return !(currentByte == -1 || (nextByte == -1 && hasTail));
}
}
|
if (n > 64)
throw new IllegalArgumentException("Can not readByte more then 64 bit");
long val = 0;
for (int i = 0; i < n; i++) {
val <<= 1;
val |= read1Bit();
}
return val;
| 580
| 80
| 660
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/ChromaFormat.java
|
ChromaFormat
|
fromId
|
class ChromaFormat {
public static ChromaFormat MONOCHROME = new ChromaFormat(0, 0, 0);
public static ChromaFormat YUV_420 = new ChromaFormat(1, 2, 2);
public static ChromaFormat YUV_422 = new ChromaFormat(2, 2, 1);
public static ChromaFormat YUV_444 = new ChromaFormat(3, 1, 1);
private int id;
private int subWidth;
private int subHeight;
public ChromaFormat(int id, int subWidth, int subHeight) {
this.id = id;
this.subWidth = subWidth;
this.subHeight = subHeight;
}
public static ChromaFormat fromId(int id) {<FILL_FUNCTION_BODY>}
public int getId() {
return id;
}
public int getSubWidth() {
return subWidth;
}
public int getSubHeight() {
return subHeight;
}
@Override
public String toString() {
return "ChromaFormat{" + "\n" +
"id=" + id + ",\n" +
" subWidth=" + subWidth + ",\n" +
" subHeight=" + subHeight +
'}';
}
}
|
if (id == MONOCHROME.id) {
return MONOCHROME;
} else if (id == YUV_420.id) {
return YUV_420;
} else if (id == YUV_422.id) {
return YUV_422;
} else if (id == YUV_444.id) {
return YUV_444;
}
return null;
| 357
| 121
| 478
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/HRDParameters.java
|
HRDParameters
|
toString
|
class HRDParameters {
public int cpb_cnt_minus1;
public int bit_rate_scale;
public int cpb_size_scale;
public int[] bit_rate_value_minus1;
public int[] cpb_size_value_minus1;
public boolean[] cbr_flag;
public int initial_cpb_removal_delay_length_minus1;
public int cpb_removal_delay_length_minus1;
public int dpb_output_delay_length_minus1;
public int time_offset_length;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "HRDParameters{" +
"cpb_cnt_minus1=" + cpb_cnt_minus1 +
", bit_rate_scale=" + bit_rate_scale +
", cpb_size_scale=" + cpb_size_scale +
", bit_rate_value_minus1=" + Arrays.toString(bit_rate_value_minus1) +
", cpb_size_value_minus1=" + Arrays.toString(cpb_size_value_minus1) +
", cbr_flag=" + Arrays.toString(cbr_flag) +
", initial_cpb_removal_delay_length_minus1=" + initial_cpb_removal_delay_length_minus1 +
", cpb_removal_delay_length_minus1=" + cpb_removal_delay_length_minus1 +
", dpb_output_delay_length_minus1=" + dpb_output_delay_length_minus1 +
", time_offset_length=" + time_offset_length +
'}';
| 169
| 269
| 438
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/ScalingList.java
|
ScalingList
|
read
|
class ScalingList {
public int[] scalingList;
public boolean useDefaultScalingMatrixFlag;
public static ScalingList read(ByteBufferBitreader is, int sizeOfScalingList)
throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "ScalingList{" +
"scalingList=" + scalingList +
", useDefaultScalingMatrixFlag=" + useDefaultScalingMatrixFlag +
'}';
}
}
|
ScalingList sl = new ScalingList();
sl.scalingList = new int[sizeOfScalingList];
int lastScale = 8;
int nextScale = 8;
for (int j = 0; j < sizeOfScalingList; j++) {
if (nextScale != 0) {
int deltaScale = is.readSE();
nextScale = (lastScale + deltaScale + 256) % 256;
sl.useDefaultScalingMatrixFlag = (j == 0 && nextScale == 0);
}
sl.scalingList[j] = nextScale == 0 ? lastScale : nextScale;
lastScale = sl.scalingList[j];
}
return sl;
| 130
| 181
| 311
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/ScalingMatrix.java
|
ScalingMatrix
|
toString
|
class ScalingMatrix {
public ScalingList[] ScalingList4x4;
public ScalingList[] ScalingList8x8;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ScalingMatrix{" +
"ScalingList4x4=" + (ScalingList4x4 == null ? null : Arrays.asList(ScalingList4x4)) + "\n" +
", ScalingList8x8=" + (ScalingList8x8 == null ? null : Arrays.asList(ScalingList8x8)) + "\n" +
'}';
| 62
| 101
| 163
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/SliceHeader.java
|
SliceHeader
|
toString
|
class SliceHeader {
public int first_mb_in_slice;
public SliceType slice_type;
public int pic_parameter_set_id;
public int colour_plane_id;
public int frame_num;
public boolean field_pic_flag = false;
public boolean bottom_field_flag = false;
public int idr_pic_id = -1;
public int pic_order_cnt_lsb;
public int delta_pic_order_cnt_bottom;
public int delta_pic_order_cnt_0;
public int delta_pic_order_cnt_1;
public PictureParameterSet pps;
public SeqParameterSet sps;
public SliceHeader(ByteBuffer in, Map<Integer, SeqParameterSet> spss, Map<Integer, PictureParameterSet> ppss, boolean IdrPicFlag) {
try {
((Buffer)in).position(1);
ByteBufferBitreader reader = new ByteBufferBitreader(in);
first_mb_in_slice = reader.readUE();
int sliceTypeInt = reader.readUE();
switch (sliceTypeInt) {
case 0:
case 5:
slice_type = SliceType.P;
break;
case 1:
case 6:
slice_type = SliceType.B;
break;
case 2:
case 7:
slice_type = SliceType.I;
break;
case 3:
case 8:
slice_type = SliceType.SP;
break;
case 4:
case 9:
slice_type = SliceType.SI;
break;
}
pic_parameter_set_id = reader.readUE();
pps = ppss.get(pic_parameter_set_id);
if (pps == null) {
String ids = "";
for (Integer integer : ppss.keySet()) {
ids += integer + ", ";
}
throw new RuntimeException("PPS with ids " + ids + " available but not " + pic_parameter_set_id);
}
sps = spss.get(pps.seq_parameter_set_id);
if (sps == null) {
String ids = "";
for (Integer integer : spss.keySet()) {
ids += integer + ", ";
}
throw new RuntimeException("SPS with ids " + ids + " available but not " + pps.seq_parameter_set_id);
}
if (sps.residual_color_transform_flag) {
colour_plane_id = (int) reader.readNBit(2);
}
frame_num = (int) reader.readNBit(sps.log2_max_frame_num_minus4 + 4);
if (!sps.frame_mbs_only_flag) {
field_pic_flag = reader.readBool();
if (field_pic_flag) {
bottom_field_flag = reader.readBool();
}
}
if (IdrPicFlag) {
idr_pic_id = reader.readUE();
}
if (sps.pic_order_cnt_type == 0) {
pic_order_cnt_lsb = (int) reader.readNBit(sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
if (pps.bottom_field_pic_order_in_frame_present_flag && !field_pic_flag) {
delta_pic_order_cnt_bottom = reader.readSE();
}
}
if (sps.pic_order_cnt_type == 1 && !sps.delta_pic_order_always_zero_flag) {
delta_pic_order_cnt_0 = reader.readSE();
if (pps.bottom_field_pic_order_in_frame_present_flag && !field_pic_flag) {
delta_pic_order_cnt_1 = reader.readSE();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public enum SliceType {
P, B, I, SP, SI
}
}
|
return "SliceHeader{" +
"first_mb_in_slice=" + first_mb_in_slice +
", slice_type=" + slice_type +
", pic_parameter_set_id=" + pic_parameter_set_id +
", colour_plane_id=" + colour_plane_id +
", frame_num=" + frame_num +
", field_pic_flag=" + field_pic_flag +
", bottom_field_flag=" + bottom_field_flag +
", idr_pic_id=" + idr_pic_id +
", pic_order_cnt_lsb=" + pic_order_cnt_lsb +
", delta_pic_order_cnt_bottom=" + delta_pic_order_cnt_bottom +
'}';
| 1,112
| 207
| 1,319
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/h264/spspps/VUIParameters.java
|
BitstreamRestriction
|
toString
|
class BitstreamRestriction {
public boolean motion_vectors_over_pic_boundaries_flag;
public int max_bytes_per_pic_denom;
public int max_bits_per_mb_denom;
public int log2_max_mv_length_horizontal;
public int log2_max_mv_length_vertical;
public int num_reorder_frames;
public int max_dec_frame_buffering;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final StringBuilder sb = new StringBuilder("BitstreamRestriction{");
sb.append("motion_vectors_over_pic_boundaries_flag=").append(motion_vectors_over_pic_boundaries_flag);
sb.append(", max_bytes_per_pic_denom=").append(max_bytes_per_pic_denom);
sb.append(", max_bits_per_mb_denom=").append(max_bits_per_mb_denom);
sb.append(", log2_max_mv_length_horizontal=").append(log2_max_mv_length_horizontal);
sb.append(", log2_max_mv_length_vertical=").append(log2_max_mv_length_vertical);
sb.append(", num_reorder_frames=").append(num_reorder_frames);
sb.append(", max_dec_frame_buffering=").append(max_dec_frame_buffering);
sb.append('}');
return sb.toString();
| 138
| 254
| 392
|
<no_super_class>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/input/mp4/DiscardingByteArrayOutputStream.java
|
DiscardingByteArrayOutputStream
|
grow
|
class DiscardingByteArrayOutputStream extends OutputStream {
/**
* The buffer where data is stored.
*/
protected byte buf[];
/**
* The number of valid bytes in the buffer.
*/
protected int count;
protected long startOffset = 0;
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
*/
public DiscardingByteArrayOutputStream() {
this(32);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size.
* @throws IllegalArgumentException if size is negative.
*/
public DiscardingByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: "
+ size);
}
buf = new byte[size];
}
public byte[] get(long start, int count) {
byte[] result = new byte[count];
try {
System.arraycopy(buf, l2i(start - startOffset), result, 0, count);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("start: " + start + " count: " + count + " startOffset:" + startOffset + " count:" + count + " len(buf):" + buf.length + " (start - startOffset):" + (start - startOffset));
throw e;
}
return result;
}
/**
* Increases the capacity if necessary to ensure that it can hold
* at least the number of elements specified by the minimum
* capacity argument.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if {@code minCapacity < 0}. This is
* interpreted as a request for the unsatisfiably large capacity
* {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.
*/
private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buf.length > 0)
grow(minCapacity);
}
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {<FILL_FUNCTION_BODY>}
/**
* Writes the specified byte to this byte array output stream.
*
* @param b the byte to be written.
*/
public synchronized void write(int b) {
ensureCapacity(count + 1);
buf[count] = (byte) b;
count += 1;
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this byte array output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
*/
public synchronized void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) - b.length > 0)) {
throw new IndexOutOfBoundsException();
}
ensureCapacity(count + len);
System.arraycopy(b, off, buf, count, len);
count += len;
}
/**
* Resets the <code>count</code> field of this byte array output
* stream to zero, so that all currently accumulated output in the
* output stream is discarded. The output stream can be used again,
* reusing the already allocated buffer space.
*
* @see java.io.ByteArrayInputStream#count
*/
public synchronized void reset() {
count = 0;
}
/**
* Creates a newly allocated byte array. Its size is the current
* size of this output stream and the valid contents of the buffer
* have been copied into it.
*
* @return the current contents of this output stream, as a byte array.
* @see java.io.ByteArrayOutputStream#size()
*/
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number
* of valid bytes in this output stream.
* @see java.io.ByteArrayOutputStream#count
*/
public synchronized int size() {
return count;
}
/**
* Converts the buffer's contents into a string decoding bytes using the
* platform's default character set. The length of the new String
* is a function of the character set, and hence may not be equal to the
* size of the buffer.
* This method always replaces malformed-input and unmappable-character
* sequences with the default replacement string for the platform's
* default character set. The {@linkplain java.nio.charset.CharsetDecoder}
* class should be used when more control over the decoding process is
* required.
*
* @return String decoded from the buffer's contents.
* @since JDK1.1
*/
public synchronized String toString() {
return new String(buf, 0, count);
}
/**
* Closing a ByteArrayOutputStream has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an IOException.
*/
public void close() throws IOException {
}
/**
* Returns the last index that is available.
*
* @return the overall size (not taking discarded bytes into account)
*/
public synchronized long available() {
return startOffset + count;
}
public synchronized void discardTo(long n) {
//System.err.println("discard up to pos " + n);
System.arraycopy(buf, l2i(n - startOffset), buf, 0, l2i(buf.length - (n - startOffset)));
count -= (n - startOffset);
startOffset = n;
}
}
|
// overflow-conscious code
int oldCapacity = buf.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity < 0) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
buf = Arrays.copyOf(buf, newCapacity);
| 1,615
| 121
| 1,736
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
sannies_mp4parser
|
mp4parser/streaming/src/main/java/org/mp4parser/streaming/output/mp4/DefaultBoxes.java
|
DefaultBoxes
|
createTkhd
|
class DefaultBoxes {
public Box createFtyp() {
List<String> minorBrands = new LinkedList<String>();
minorBrands.add("isom");
minorBrands.add("iso2");
minorBrands.add("avc1");
minorBrands.add("iso6");
minorBrands.add("mp41");
return new FileTypeBox("isom", 512, minorBrands);
}
protected Box createMdiaHdlr(StreamingTrack streamingTrack) {
HandlerBox hdlr = new HandlerBox();
hdlr.setHandlerType(streamingTrack.getHandler());
return hdlr;
}
protected Box createMdia(StreamingTrack streamingTrack) {
MediaBox mdia = new MediaBox();
mdia.addBox(createMdhd(streamingTrack));
mdia.addBox(createMdiaHdlr(streamingTrack));
mdia.addBox(createMinf(streamingTrack));
return mdia;
}
abstract protected Box createMdhd(StreamingTrack streamingTrack);
abstract protected Box createMvhd();
protected Box createMinf(StreamingTrack streamingTrack) {
MediaInformationBox minf = new MediaInformationBox();
if (streamingTrack.getHandler().equals("vide")) {
minf.addBox(new VideoMediaHeaderBox());
} else if (streamingTrack.getHandler().equals("soun")) {
minf.addBox(new SoundMediaHeaderBox());
} else if (streamingTrack.getHandler().equals("text")) {
minf.addBox(new NullMediaHeaderBox());
} else if (streamingTrack.getHandler().equals("subt")) {
minf.addBox(new SubtitleMediaHeaderBox());
} else if (streamingTrack.getHandler().equals("hint")) {
minf.addBox(new HintMediaHeaderBox());
} else if (streamingTrack.getHandler().equals("sbtl")) {
minf.addBox(new NullMediaHeaderBox());
}
minf.addBox(createDinf());
minf.addBox(createStbl(streamingTrack));
return minf;
}
protected Box createStbl(StreamingTrack streamingTrack) {
SampleTableBox stbl = new SampleTableBox();
stbl.addBox(streamingTrack.getSampleDescriptionBox());
stbl.addBox(new TimeToSampleBox());
stbl.addBox(new SampleToChunkBox());
stbl.addBox(new SampleSizeBox());
stbl.addBox(new StaticChunkOffsetBox());
return stbl;
}
protected DataInformationBox createDinf() {
DataInformationBox dinf = new DataInformationBox();
DataReferenceBox dref = new DataReferenceBox();
dinf.addBox(dref);
DataEntryUrlBox url = new DataEntryUrlBox();
url.setFlags(1);
dref.addBox(url);
return dinf;
}
protected Box createTrak(StreamingTrack streamingTrack) {
TrackBox trackBox = new TrackBox();
trackBox.addBox(createTkhd(streamingTrack));
trackBox.addBox(createMdia(streamingTrack));
return trackBox;
}
protected Box createTkhd(StreamingTrack streamingTrack) {<FILL_FUNCTION_BODY>}
}
|
TrackHeaderBox tkhd = new TrackHeaderBox();
tkhd.setTrackId(streamingTrack.getTrackExtension(TrackIdTrackExtension.class).getTrackId());
DimensionTrackExtension dte = streamingTrack.getTrackExtension(DimensionTrackExtension.class);
if (dte != null) {
tkhd.setHeight(dte.getHeight());
tkhd.setWidth(dte.getWidth());
}
return tkhd;
| 862
| 120
| 982
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-active-record/src/main/java/com/baomidou/mybatisplus/samples/ar/entity/User.java
|
User
|
pkVal
|
class User extends Model<User> {
private Long id;
private String name;
private Integer age;
private String email;
@Override
public Serializable pkVal() {<FILL_FUNCTION_BODY>}
}
|
/**
* AR 模式这个必须有,否则 xxById 的方法都将失效!
* 另外 UserMapper 也必须 AR 依赖该层注入,有可无 XML
*/
return id;
| 62
| 57
| 119
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-assembly/src/main/java/com/baomidou/mybatisplus/samples/assembly/controller/UserController.java
|
UserController
|
test
|
class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@Autowired
private IUserService userService;
// 测试地址 http://localhost:8080/test
@RequestMapping(value = "test")
public String test(){<FILL_FUNCTION_BODY>}
}
|
User user = new User();
user.setEmail("papapapap@qq.com");
user.setAge(18);
user.setName("啪啪啪");
userService.save(user);
List<User> list = userService.list(new LambdaQueryWrapper<>(new User()).select(User::getId, User::getName));
list.forEach(u -> LOGGER.info("当前用户数据:{}", u));
return "papapapap@qq.com";
| 93
| 131
| 224
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-association/src/main/java/com/baomidou/mybatisplus/samples/association/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
/**
* 注入主键生成器
*/
@Bean
public IKeyGenerator keyGenerator(){
return new H2KeyGenerator();
}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
| 107
| 53
| 160
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-ddl-mysql/src/main/java/com/baomidou/mybatisplus/samples/ddl/mysql/MysqlDdl.java
|
MysqlDdl
|
getSqlFiles
|
class MysqlDdl extends SimpleDdl {
/**
* 执行 SQL 脚本方式
*/
@Override
public List<String> getSqlFiles() {<FILL_FUNCTION_BODY>}
}
|
return Arrays.asList(
// 测试存储过程
"db/test_procedure.sql#$$",
// 内置包方式
"db/tag-schema.sql",
"db/tag-data.sql"
// 文件绝对路径方式(修改为你电脑的地址)
// "D:\\sql\\tag-data.sql"
);
| 59
| 104
| 163
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/MyLogicSqlInjector.java
|
MyLogicSqlInjector
|
getMethodList
|
class MyLogicSqlInjector extends DefaultSqlInjector {
/**
* 如果只需增加方法,保留MP自带方法
* 可以super.getMethodList() 再add
* @return
*/
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
methodList.add(new DeleteAll("deleteAll"));
methodList.add(new MyInsertAll("myInsertAll"));
methodList.add(new MysqlInsertAllBatch("mysqlInsertAllBatch"));
methodList.add(new SelectById());
return methodList;
| 101
| 93
| 194
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/MyMetaObjectHandler.java
|
MyMetaObjectHandler
|
insertFill
|
class MyMetaObjectHandler implements MetaObjectHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);
@Override
public void insertFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>}
@Override
public void updateFill(MetaObject metaObject) {
LOGGER.info("nothing to fill ....");
}
}
|
LOGGER.info("start insert fill ....");
//避免使用metaObject.setValue()
this.strictInsertFill(metaObject, "createTime", Timestamp.class, new Timestamp(System.currentTimeMillis()));
| 102
| 57
| 159
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
/**
* 自定义 SqlInjector
* 里面包含自定义的全局方法
*/
@Bean
public MyLogicSqlInjector myLogicSqlInjector() {
return new MyLogicSqlInjector();
}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
| 115
| 75
| 190
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/methods/DeleteAll.java
|
DeleteAll
|
injectMappedStatement
|
class DeleteAll extends AbstractMethod {
public DeleteAll(String methodName) {
super(methodName);
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
/* 执行 SQL ,动态 SQL 参考类 SqlMethod */
String sql = "delete from " + tableInfo.getTableName();
/* mapper 接口方法名一致 */
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addDeleteMappedStatement(mapperClass, methodName, sqlSource);
| 81
| 90
| 171
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/methods/MyInsertAll.java
|
MyInsertAll
|
injectMappedStatement
|
class MyInsertAll extends AbstractMethod {
public MyInsertAll(String methodName) {
super(methodName);
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
String sql = "insert into %s %s values %s";
StringBuilder fieldSql = new StringBuilder();
fieldSql.append(tableInfo.getKeyColumn()).append(",");
StringBuilder valueSql = new StringBuilder();
valueSql.append("#{").append(tableInfo.getKeyProperty()).append("},");
tableInfo.getFieldList().forEach(x->{
fieldSql.append(x.getColumn()).append(",");
valueSql.append("#{").append(x.getProperty()).append("},");
});
fieldSql.delete(fieldSql.length()-1, fieldSql.length());
fieldSql.insert(0, "(");
fieldSql.append(")");
valueSql.insert(0, "(");
valueSql.delete(valueSql.length()-1, valueSql.length());
valueSql.append(")");
SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sql, tableInfo.getTableName(), fieldSql.toString(), valueSql.toString()), modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, methodName, sqlSource, new NoKeyGenerator(), null, null);
| 83
| 290
| 373
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-deluxe/src/main/java/com/baomidou/mybatisplus/samples/deluxe/methods/MysqlInsertAllBatch.java
|
MysqlInsertAllBatch
|
prepareFieldSql
|
class MysqlInsertAllBatch extends AbstractMethod {
public MysqlInsertAllBatch(String methodName) {
super(methodName);
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
final String sql = "<script>insert into %s %s values %s</script>";
final String fieldSql = prepareFieldSql(tableInfo);
final String valueSql = prepareValuesSqlForMysqlBatch(tableInfo);
final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, methodName, sqlSource, new NoKeyGenerator(), null, null);
}
private String prepareFieldSql(TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
private String prepareValuesSqlForMysqlBatch(TableInfo tableInfo) {
final StringBuilder valueSql = new StringBuilder();
valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},"));
valueSql.delete(valueSql.length() - 1, valueSql.length());
valueSql.append("</foreach>");
return valueSql.toString();
}
}
|
StringBuilder fieldSql = new StringBuilder();
fieldSql.append(tableInfo.getKeyColumn()).append(",");
tableInfo.getFieldList().forEach(x -> {
fieldSql.append(x.getColumn()).append(",");
});
fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
fieldSql.insert(0, "(");
fieldSql.append(")");
return fieldSql.toString();
| 422
| 116
| 538
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-dynamic-tablename/src/main/java/com/baomidou/mybatisplus/samples/dytablename/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
// 获取参数方法
Map<String, Object> paramMap = RequestDataHelper.getRequestData();
paramMap.forEach((k, v) -> System.err.println(k + "----" + v));
String year = "_2018";
int random = new Random().nextInt(10);
if (random % 2 == 1) {
year = "_2019";
}
return tableName + year;
});
interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
// 3.4.3.2 作废该方式
// dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
return interceptor;
| 46
| 252
| 298
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-dynamic-tablename/src/main/java/com/baomidou/mybatisplus/samples/dytablename/config/RequestDataHelper.java
|
RequestDataHelper
|
getRequestData
|
class RequestDataHelper {
/**
* 请求参数存取
*/
private static final ThreadLocal<Map<String, Object>> REQUEST_DATA = new ThreadLocal<>();
/**
* 设置请求参数
*
* @param requestData 请求参数 MAP 对象
*/
public static void setRequestData(Map<String, Object> requestData) {
REQUEST_DATA.set(requestData);
}
/**
* 获取请求参数
*
* @param param 请求参数
* @return 请求参数 MAP 对象
*/
public static <T> T getRequestData(String param) {<FILL_FUNCTION_BODY>}
/**
* 获取请求参数
*
* @return 请求参数 MAP 对象
*/
public static Map<String, Object> getRequestData() {
return REQUEST_DATA.get();
}
}
|
Map<String, Object> dataMap = getRequestData();
if (CollectionUtils.isNotEmpty(dataMap)) {
return (T) dataMap.get(param);
}
return null;
| 234
| 54
| 288
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-execution-analysis/src/main/java/com/baomidou/samples/execution/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
| 46
| 53
| 99
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-id-generator/src/main/java/com/baomidou/samples/incrementer/CustomIdGenerator.java
|
CustomIdGenerator
|
nextId
|
class CustomIdGenerator implements IdentifierGenerator {
private final AtomicLong al = new AtomicLong(1);
@Override
public Long nextId(Object entity) {<FILL_FUNCTION_BODY>}
}
|
//可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成.
String bizKey = entity.getClass().getName();
log.info("bizKey:{}", bizKey);
MetaObject metaObject = SystemMetaObject.forObject(entity);
String name = (String) metaObject.getValue("name");
final long id = al.getAndAdd(1);
log.info("为{}生成主键值->:{}", name, id);
return id;
| 57
| 144
| 201
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-jsonb/src/main/java/com/baomidou/mybatisplus/samples/jsonb/entity/JsonbTypeHandler.java
|
JsonbTypeHandler
|
setNonNullParameter
|
class JsonbTypeHandler extends JacksonTypeHandler {
private static final PGobject jsonObject = new PGobject();
public JsonbTypeHandler(Class<?> type) {
super(type);
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
if (ps != null) {
jsonObject.setType("jsonb");
jsonObject.setValue(toJson(parameter));
ps.setObject(i, jsonObject);
}
| 103
| 52
| 155
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-jsonb/src/main/java/com/baomidou/mybatisplus/samples/jsonb/entity/TestContent.java
|
TestContent
|
of
|
class TestContent {
private String title;
private String content;
public static TestContent of(String title, String content) {<FILL_FUNCTION_BODY>}
}
|
TestContent tc = new TestContent();
tc.setTitle(title);
tc.setContent(content);
return tc;
| 47
| 40
| 87
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-mysql/src/main/java/com/baomidou/mybatisplus/samples/mysql/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
globalConfig
|
class MybatisPlusConfig {
@Bean("mybatisSqlSession")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, GlobalConfig globalConfig) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
/* 数据源 */
sqlSessionFactory.setDataSource(dataSource);
/* 枚举扫描 */
sqlSessionFactory.setTypeEnumsPackage("com.baomidou.mybatisplus.samples.mysql.enums");
/* xml扫描 */
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:/mapper/*.xml"));
/* 扫描 typeHandler */
// sqlSessionFactory.setTypeHandlersPackage("com.baomidou.mybatisplus.samples.mysql.type");
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
/* 驼峰转下划线 */
configuration.setMapUnderscoreToCamelCase(true);
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
sqlSessionFactory.setPlugins(mybatisPlusInterceptor);
/* map 下划线转驼峰 */
configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
sqlSessionFactory.setConfiguration(configuration);
/* 自动填充插件 */
globalConfig.setMetaObjectHandler(new MysqlMetaObjectHandler());
sqlSessionFactory.setGlobalConfig(globalConfig);
return sqlSessionFactory.getObject();
}
@Bean
public GlobalConfig globalConfig() {<FILL_FUNCTION_BODY>}
}
|
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setColumnFormat("`%s`"));
DefaultSqlInjector logicSqlInjector = new DefaultSqlInjector() {
/**
* 注入自定义全局方法
*/
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
// 不要逻辑删除字段, 不要乐观锁字段, 不要填充策略是 UPDATE 的字段
methodList.add(new InsertBatchSomeColumn(t -> !t.isLogicDelete() && !t.isVersion() && t.getFieldFill() != FieldFill.UPDATE));
// 不要填充策略是 INSERT 的字段, 不要字段名是 column4 的字段
methodList.add(new AlwaysUpdateSomeColumnById(t -> t.getFieldFill() != FieldFill.INSERT && !t.getProperty().equals("column4")));
return methodList;
}
};
conf.setSqlInjector(logicSqlInjector);
return conf;
| 488
| 307
| 795
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-mysql/src/main/java/com/baomidou/mybatisplus/samples/mysql/config/MysqlMetaObjectHandler.java
|
MysqlMetaObjectHandler
|
insertFill
|
class MysqlMetaObjectHandler implements MetaObjectHandler {
/**
* 测试 user 表 name 字段为空自动填充
*/
@Override
public void insertFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>}
@Override
public void updateFill(MetaObject metaObject) {
System.out.println("*************************");
System.out.println("update of mysql fill");
System.out.println("*************************");
//测试实体没有的字段,配置在公共填充,不应该set到实体里面
this.strictUpdateFill(metaObject, "updateDatetime1", LocalDateTime.class, LocalDateTime.now())
.strictUpdateFill(metaObject, "updateDatetime", LocalDateTime.class, LocalDateTime.now());
}
}
|
System.out.println("*************************");
System.out.println("insert of mysql fill");
System.out.println("*************************");
// 测试下划线
Object createDatetime = this.getFieldValByName("createDatetime", metaObject);
System.out.println("createDatetime=" + createDatetime);
if (createDatetime == null) {
//测试实体没有的字段,配置在公共填充,不应该set到实体里面
this.strictInsertFill(metaObject, "createDatetime1", LocalDateTime.class, LocalDateTime.now())
.strictInsertFill(metaObject, "createDatetime", LocalDateTime.class, LocalDateTime.now());
}
| 201
| 176
| 377
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-no-spring/src/main/java/com/baomidou/mybatisplus/no/spring/NoSpring.java
|
NoSpring
|
dataSource
|
class NoSpring {
private static SqlSessionFactory sqlSessionFactory = initSqlSessionFactory();
public static void main(String[] args) {
try (SqlSession session = sqlSessionFactory.openSession(true)) {
PersonMapper mapper = session.getMapper(PersonMapper.class);
Person person = new Person().setName("老李");
mapper.insert(person);
System.out.println("结果: " + mapper.selectById(person.getId()));
}
}
public static SqlSessionFactory initSqlSessionFactory() {
DataSource dataSource = dataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("Production", transactionFactory, dataSource);
MybatisConfiguration configuration = new MybatisConfiguration(environment);
configuration.addMapper(PersonMapper.class);
configuration.setLogImpl(StdOutImpl.class);
return new MybatisSqlSessionFactoryBuilder().build(configuration);
}
public static DataSource dataSource() {<FILL_FUNCTION_BODY>}
}
|
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver(org.h2.Driver.class.getName());
dataSource.setUrl("jdbc:h2:mem:test");
dataSource.setUsername("root");
dataSource.setPassword("test");
try {
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
statement.execute("create table person (" +
"id BIGINT NOT NULL," +
"name VARCHAR(30) NULL," +
"age INT NULL," +
"PRIMARY KEY (id)" +
")");
} catch (SQLException e) {
e.printStackTrace();
}
return dataSource;
| 264
| 185
| 449
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-optimistic-locker/src/main/java/com/baomidou/mybatisplus/samples/optlocker/config/MybatisPlusOptLockerConfig.java
|
MybatisPlusOptLockerConfig
|
mybatisPlusInterceptor
|
class MybatisPlusOptLockerConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
| 49
| 54
| 103
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-pagination/src/main/java/com/baomidou/mybatisplus/samples/pagination/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
// @Bean
// public ConfigurationCustomizer configurationCustomizer() {
// return configuration -> configuration.setUseDeprecatedExecutor(false);
// }
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
| 133
| 59
| 192
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-quickstart-springmvc/src/main/java/com/baomidou/mybatisplus/samples/quickstart/springmvc/MpConfig.java
|
MpConfig
|
globalConfiguration
|
class MpConfig {
@Bean
public GlobalConfig globalConfiguration() {<FILL_FUNCTION_BODY>}
}
|
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerators(Arrays.asList(
// h2 1.x 的写法(默认 2.x 的写法)
new IKeyGenerator() {
@Override
public String executeSql(String incrementerName) {
return "select " + incrementerName + ".nextval";
}
@Override
public DbType dbType() {
return DbType.POSTGRE_SQL;
}
}
)));
return conf;
| 34
| 153
| 187
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-reduce-springmvc/src/main/java/com/baomidou/mybatisplus/samples/reduce/springmvc/configurations/DbConfigurations.java
|
DbConfigurations
|
globalConfiguration
|
class DbConfigurations {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
@Bean
public GlobalConfig globalConfiguration() {<FILL_FUNCTION_BODY>}
}
|
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerators(Arrays.asList(
// h2 1.x 的写法(默认 2.x 的写法)
new IKeyGenerator() {
@Override
public String executeSql(String incrementerName) {
return "select " + incrementerName + ".nextval";
}
@Override
public DbType dbType() {
return DbType.POSTGRE_SQL;
}
}
)));
return conf;
| 125
| 153
| 278
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-reduce-springmvc/src/main/java/org/mybatis/spring/annotation/AutoMapperScannerRegistrar.java
|
AutoMapperScannerRegistrar
|
registerBeanDefinitions
|
class AutoMapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
private ResourceLoader resourceLoader;
/**
* {@inheritDoc}
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* {@inheritDoc}
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes mapperScanAttrs = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(AutoMapperScan.class.getName()));
if (mapperScanAttrs != null) {
registerBeanDefinitions(mapperScanAttrs, registry);
}
}
void registerBeanDefinitions(AnnotationAttributes annoAttrs, BeanDefinitionRegistry registry) {<FILL_FUNCTION_BODY>}
/**
* A {@link org.mybatis.spring.annotation.MapperScannerRegistrar} for {@link MapperScans}.
*
* @since 2.0.0
*/
static class RepeatingRegistrar extends AutoMapperScannerRegistrar {
/**
* {@inheritDoc}
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
AnnotationAttributes mapperScansAttrs = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(AutoMapperScans.class.getName()));
if (mapperScansAttrs != null) {
Arrays.stream(mapperScansAttrs.getAnnotationArray("value"))
.forEach(mapperScanAttrs -> registerBeanDefinitions(mapperScanAttrs, registry));
}
}
}
}
|
ClassPathAutoMapperScanner scanner = new ClassPathAutoMapperScanner(registry);
// this check is needed in Spring 3.1
Optional.ofNullable(resourceLoader).ifPresent(scanner::setResourceLoader);
Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
if (!Annotation.class.equals(annotationClass)) {
scanner.setAnnotationClass(annotationClass);
}
Class<?> markerInterface = annoAttrs.getClass("markerInterface");
if (!Class.class.equals(markerInterface)) {
scanner.setMarkerInterface(markerInterface);
}
Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
if (!BeanNameGenerator.class.equals(generatorClass)) {
scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass));
}
Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
scanner.setMapperFactoryBeanClass(mapperFactoryBeanClass);
}
scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));
scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));
List<String> basePackages = new ArrayList<>();
basePackages.addAll(
Arrays.stream(annoAttrs.getStringArray("value"))
.filter(StringUtils::hasText)
.collect(Collectors.toList()));
basePackages.addAll(
Arrays.stream(annoAttrs.getStringArray("basePackages"))
.filter(StringUtils::hasText)
.collect(Collectors.toList()));
basePackages.addAll(
Arrays.stream(annoAttrs.getClassArray("basePackageClasses"))
.map(ClassUtils::getPackageName)
.collect(Collectors.toList()));
scanner.registerFilters();
List<String> beanPackages = new ArrayList<>();
beanPackages.addAll(
Arrays.stream(annoAttrs.getStringArray("beanPackages"))
.filter(StringUtils::hasText)
.collect(Collectors.toList()));
if (basePackages.isEmpty()) {
return;
}
scanner.setBeanPackages(StringUtils.toStringArray(beanPackages));
if( annoAttrs.get("excludedBeans") != null){
List<String> excludingBeans = new ArrayList<>();
excludingBeans.addAll(
Arrays.stream(annoAttrs.getStringArray("excludedBeans"))
.filter(StringUtils::hasText)
.collect(Collectors.toList()));
scanner.setExcludedBeans(StringUtils.toStringArray(excludingBeans));
}
scanner.setSuperMapperName(annoAttrs.getString("superMapperClassName"));
//获取生成目录
String tmpPackage = annoAttrs.getString("makeMapperPackage");
String makeMapperPackage = "".equals(tmpPackage) ? basePackages.get(0) : tmpPackage;
//在开始扫描之前 先扫描所有的 beanPackages里面的bean类,然后在目标目录生成mapper类
scanner.scanBeans(makeMapperPackage, StringUtils.toStringArray(beanPackages));
scanner.setMakeMapperPackage(makeMapperPackage);
scanner.doScan(StringUtils.toStringArray(basePackages));
| 453
| 912
| 1,365
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-sql-injector/src/main/java/com/baomidou/samples/injector/base/MySqlInjector.java
|
MySqlInjector
|
getMethodList
|
class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
//增加自定义方法
methodList.add(new DeleteAll("deleteAll"));
methodList.add(new FindOne("findOne"));
/**
* 以下 3 个为内置选装件
* 头 2 个支持字段筛选函数
*/
// 例: 不要指定了 update 填充的字段
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
methodList.add(new AlwaysUpdateSomeColumnById());
methodList.add(new LogicDeleteByIdWithFill());
return methodList;
| 59
| 184
| 243
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-sql-injector/src/main/java/com/baomidou/samples/injector/methods/DeleteAll.java
|
DeleteAll
|
injectMappedStatement
|
class DeleteAll extends AbstractMethod {
public DeleteAll(String methodName) {
super(methodName);
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
/* 执行 SQL ,动态 SQL 参考类 SqlMethod */
String sql = "delete from " + tableInfo.getTableName();
/* mapper 接口方法名一致 */
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addDeleteMappedStatement(mapperClass, methodName, sqlSource);
| 81
| 90
| 171
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-sql-injector/src/main/java/com/baomidou/samples/injector/methods/FindOne.java
|
FindOne
|
injectMappedStatement
|
class FindOne extends AbstractMethod {
public FindOne(String methodName) {
super(methodName);
}
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {<FILL_FUNCTION_BODY>}
}
|
/* 执行 SQL ,动态 SQL 参考类 SqlMethod */
String sql = "select * from " + tableInfo.getTableName()
+ " where " + tableInfo.getKeyColumn() + "=#{" + tableInfo.getKeyProperty() + "}";
/* mapper 接口方法名一致 */
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return addSelectMappedStatementForTable(mapperClass, methodName, sqlSource, tableInfo);
| 81
| 125
| 206
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-tenant/src/main/java/com/baomidou/mybatisplus/samples/tenant/config/MybatisPlusConfig.java
|
MybatisPlusConfig
|
mybatisPlusInterceptor
|
class MybatisPlusConfig {
/**
* 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
// @Bean
// public ConfigurationCustomizer configurationCustomizer() {
// return configuration -> configuration.setUseDeprecatedExecutor(false);
// }
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
@Override
public Expression getTenantId() {
return new LongValue(1);
}
// 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
@Override
public boolean ignoreTable(String tableName) {
return !"sys_user".equalsIgnoreCase(tableName);
}
}));
// 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
// 用了分页插件必须设置 MybatisConfiguration#useDeprecatedExecutor = false
// interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
| 137
| 226
| 363
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-typehandler/src/main/java/com/baomidou/mybatisplus/samples/typehandler/WalletListTypeHandler.java
|
WalletListTypeHandler
|
parse
|
class WalletListTypeHandler extends JacksonTypeHandler {
public WalletListTypeHandler(Class<?> type) {
super(type);
}
@Override
public Object parse(String json) {<FILL_FUNCTION_BODY>}
}
|
try {
return getObjectMapper().readValue(json, new TypeReference<List<Wallet>>() {
});
} catch (IOException e) {
throw new RuntimeException(e);
}
| 67
| 53
| 120
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-sample-typehandler/src/main/java/com/baomidou/mybatisplus/samples/typehandler/config/MpJsonConfig.java
|
MpJsonConfig
|
mybatisPlusInterceptor
|
class MpJsonConfig implements CommandLineRunner {
/**
* 可以set进去自己的
*/
@Override
public void run(String... args) throws Exception {
JacksonTypeHandler.setObjectMapper(new ObjectMapper());
GsonTypeHandler.setGson(new Gson());
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
| 113
| 53
| 166
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-startup-analysis/src/main/java/com/baomidou/MybatisPlusConfig.java
|
MybatisPlusConfig
|
sqlInjector
|
class MybatisPlusConfig {
@Value("${mybatis.plus.parallel:false}")
private boolean parallel;
// 模拟并行注入性能测试(请注意,低版本的mybatis缓存的为hashmap结构,并不能并行注入,mp3.5.6开始通过mybatis源码修改为了ConcurrentHashMap)
@Bean
public ISqlInjector sqlInjector() {<FILL_FUNCTION_BODY>}
}
|
if (parallel) {
System.out.println("并行注入.");
} else {
System.out.println("串行注入.");
}
return new DefaultSqlInjector() {
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0);
if (modelClass != null) {
String className = mapperClass.toString();
Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
if (!mapperRegistryCache.contains(className)) {
TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass);
List<AbstractMethod> methodList = this.getMethodList(builderAssistant.getConfiguration(), mapperClass, tableInfo);
if (CollectionUtils.isNotEmpty(methodList)) {
if(parallel){
//TODO 修改为并行注入看看
methodList.stream().parallel().forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
} else {
methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
}
} else {
logger.debug(className + ", No effective injection method was found.");
}
mapperRegistryCache.add(className);
}
}
}
};
| 125
| 382
| 507
|
<no_super_class>
|
baomidou_mybatis-plus-samples
|
mybatis-plus-samples/mybatis-plus-startup-analysis/src/main/java/com/baomidou/StartupAnalysisApplication.java
|
StartupAnalysisApplication
|
run
|
class StartupAnalysisApplication implements CommandLineRunner {
@Autowired
private SqlSessionFactory sqlSessionFactory;
public static void main(String[] args) {
SpringApplication.run(StartupAnalysisApplication.class, args);
}
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Configuration configuration = sqlSessionFactory.getConfiguration();
System.out.println("注册Mapper数量:" + configuration.getMapperRegistry().getMappers().size());
System.out.println("注册MappedStatements数量:" + configuration.getMappedStatements().size());
| 93
| 67
| 160
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter1/src/main/java/nia/chapter1/BlockingIoExample.java
|
BlockingIoExample
|
serve
|
class BlockingIoExample {
/**
* Listing 1.1 Blocking I/O example
* */
public void serve(int portNumber) throws IOException {<FILL_FUNCTION_BODY>}
private String processRequest(String request){
return "Processed";
}
}
|
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Done".equals(request)) {
break;
}
response = processRequest(request);
out.println(response);
}
| 79
| 135
| 214
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter1/src/main/java/nia/chapter1/ConnectExample.java
|
ConnectExample
|
connect
|
class ConnectExample {
private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel();
/**
* Listing 1.3 Asynchronous connect
*
* Listing 1.4 Callback in action
* */
public static void connect() {<FILL_FUNCTION_BODY>}
}
|
Channel channel = CHANNEL_FROM_SOMEWHERE; //reference form somewhere
// Does not block
ChannelFuture future = channel.connect(
new InetSocketAddress("192.168.0.1", 25));
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
ByteBuf buffer = Unpooled.copiedBuffer(
"Hello", Charset.defaultCharset());
ChannelFuture wf = future.channel()
.writeAndFlush(buffer);
// ...
} else {
Throwable cause = future.cause();
cause.printStackTrace();
}
}
});
| 86
| 187
| 273
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter10/src/main/java/nia/chapter10/SafeByteToMessageDecoder.java
|
SafeByteToMessageDecoder
|
decode
|
class SafeByteToMessageDecoder extends ByteToMessageDecoder {
private static final int MAX_FRAME_SIZE = 1024;
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
int readable = in.readableBytes();
if (readable > MAX_FRAME_SIZE) {
in.skipBytes(readable);
throw new TooLongFrameException("Frame too big!");
}
// do something
// ...
| 78
| 66
| 144
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter10/src/main/java/nia/chapter10/WebSocketConvertHandler.java
|
WebSocketConvertHandler
|
decode
|
class WebSocketConvertHandler extends
MessageToMessageCodec<WebSocketFrame,
WebSocketConvertHandler.MyWebSocketFrame> {
@Override
protected void encode(ChannelHandlerContext ctx,
WebSocketConvertHandler.MyWebSocketFrame msg,
List<Object> out) throws Exception {
ByteBuf payload = msg.getData().duplicate().retain();
switch (msg.getType()) {
case BINARY:
out.add(new BinaryWebSocketFrame(payload));
break;
case TEXT:
out.add(new TextWebSocketFrame(payload));
break;
case CLOSE:
out.add(new CloseWebSocketFrame(true, 0, payload));
break;
case CONTINUATION:
out.add(new ContinuationWebSocketFrame(payload));
break;
case PONG:
out.add(new PongWebSocketFrame(payload));
break;
case PING:
out.add(new PingWebSocketFrame(payload));
break;
default:
throw new IllegalStateException(
"Unsupported websocket msg " + msg);}
}
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg,
List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
public static final class MyWebSocketFrame {
public enum FrameType {
BINARY,
CLOSE,
PING,
PONG,
TEXT,
CONTINUATION
}
private final FrameType type;
private final ByteBuf data;
public MyWebSocketFrame(FrameType type, ByteBuf data) {
this.type = type;
this.data = data;
}
public FrameType getType() {
return type;
}
public ByteBuf getData() {
return data;
}
}
}
|
ByteBuf payload = msg.content().duplicate().retain();
if (msg instanceof BinaryWebSocketFrame) {
out.add(new MyWebSocketFrame(
MyWebSocketFrame.FrameType.BINARY, payload));
} else
if (msg instanceof CloseWebSocketFrame) {
out.add(new MyWebSocketFrame (
MyWebSocketFrame.FrameType.CLOSE, payload));
} else
if (msg instanceof PingWebSocketFrame) {
out.add(new MyWebSocketFrame (
MyWebSocketFrame.FrameType.PING, payload));
} else
if (msg instanceof PongWebSocketFrame) {
out.add(new MyWebSocketFrame (
MyWebSocketFrame.FrameType.PONG, payload));
} else
if (msg instanceof TextWebSocketFrame) {
out.add(new MyWebSocketFrame (
MyWebSocketFrame.FrameType.TEXT, payload));
} else
if (msg instanceof ContinuationWebSocketFrame) {
out.add(new MyWebSocketFrame (
MyWebSocketFrame.FrameType.CONTINUATION, payload));
} else
{
throw new IllegalStateException(
"Unsupported websocket msg " + msg);
}
| 480
| 310
| 790
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/ChunkedWriteHandlerInitializer.java
|
ChunkedWriteHandlerInitializer
|
initChannel
|
class ChunkedWriteHandlerInitializer
extends ChannelInitializer<Channel> {
private final File file;
private final SslContext sslCtx;
public ChunkedWriteHandlerInitializer(File file, SslContext sslCtx) {
this.file = file;
this.sslCtx = sslCtx;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public final class WriteStreamHandler
extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception {
super.channelActive(ctx);
ctx.writeAndFlush(
new ChunkedStream(new FileInputStream(file)));
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new WriteStreamHandler());
| 195
| 65
| 260
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/CmdHandlerInitializer.java
|
CmdHandlerInitializer
|
initChannel
|
class CmdHandlerInitializer extends ChannelInitializer<Channel> {
private static final byte SPACE = (byte)' ';
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public static final class Cmd {
private final ByteBuf name;
private final ByteBuf args;
public Cmd(ByteBuf name, ByteBuf args) {
this.name = name;
this.args = args;
}
public ByteBuf name() {
return name;
}
public ByteBuf args() {
return args;
}
}
public static final class CmdDecoder extends LineBasedFrameDecoder {
public CmdDecoder(int maxLength) {
super(maxLength);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer)
throws Exception {
ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
if (frame == null) {
return null;
}
int index = frame.indexOf(frame.readerIndex(),
frame.writerIndex(), SPACE);
return new Cmd(frame.slice(frame.readerIndex(), index),
frame.slice(index + 1, frame.writerIndex()));
}
}
public static final class CmdHandler
extends SimpleChannelInboundHandler<Cmd> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Cmd msg)
throws Exception {
// Do something with the command
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new CmdDecoder(64 * 1024));
pipeline.addLast(new CmdHandler());
| 385
| 49
| 434
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/FileRegionWriteHandler.java
|
FileRegionWriteHandler
|
channelActive
|
class FileRegionWriteHandler extends ChannelInboundHandlerAdapter {
private static final Channel CHANNEL_FROM_SOMEWHERE = new NioSocketChannel();
private static final File FILE_FROM_SOMEWHERE = new File("");
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>}
}
|
File file = FILE_FROM_SOMEWHERE; //get reference from somewhere
Channel channel = CHANNEL_FROM_SOMEWHERE; //get reference from somewhere
//...
FileInputStream in = new FileInputStream(file);
FileRegion region = new DefaultFileRegion(
in.getChannel(), 0, file.length());
channel.writeAndFlush(region).addListener(
new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future)
throws Exception {
if (!future.isSuccess()) {
Throwable cause = future.cause();
// Do something
}
}
});
| 89
| 160
| 249
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/HttpAggregatorInitializer.java
|
HttpAggregatorInitializer
|
initChannel
|
class HttpAggregatorInitializer extends ChannelInitializer<Channel> {
private final boolean isClient;
public HttpAggregatorInitializer(boolean isClient) {
this.isClient = isClient;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ChannelPipeline pipeline = ch.pipeline();
if (isClient) {
pipeline.addLast("codec", new HttpClientCodec());
} else {
pipeline.addLast("codec", new HttpServerCodec());
}
pipeline.addLast("aggregator",
new HttpObjectAggregator(512 * 1024));
| 83
| 90
| 173
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/HttpCompressionInitializer.java
|
HttpCompressionInitializer
|
initChannel
|
class HttpCompressionInitializer extends ChannelInitializer<Channel> {
private final boolean isClient;
public HttpCompressionInitializer(boolean isClient) {
this.isClient = isClient;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ChannelPipeline pipeline = ch.pipeline();
if (isClient) {
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast("decompressor",
new HttpContentDecompressor());
} else {
pipeline.addLast("codec", new HttpServerCodec());
pipeline.addLast("compressor",
new HttpContentCompressor());
}
| 83
| 103
| 186
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/HttpPipelineInitializer.java
|
HttpPipelineInitializer
|
initChannel
|
class HttpPipelineInitializer extends ChannelInitializer<Channel> {
private final boolean client;
public HttpPipelineInitializer(boolean client) {
this.client = client;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ChannelPipeline pipeline = ch.pipeline();
if (client) {
pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder());
} else {
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
}
| 79
| 94
| 173
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/HttpsCodecInitializer.java
|
HttpsCodecInitializer
|
initChannel
|
class HttpsCodecInitializer extends ChannelInitializer<Channel> {
private final SslContext context;
private final boolean isClient;
public HttpsCodecInitializer(SslContext context, boolean isClient) {
this.context = context;
this.isClient = isClient;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine = context.newEngine(ch.alloc());
pipeline.addFirst("ssl", new SslHandler(engine));
if (isClient) {
pipeline.addLast("codec", new HttpClientCodec());
} else {
pipeline.addLast("codec", new HttpServerCodec());
}
| 109
| 95
| 204
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/IdleStateHandlerInitializer.java
|
IdleStateHandlerInitializer
|
initChannel
|
class IdleStateHandlerInitializer extends ChannelInitializer<Channel>
{
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public static final class HeartbeatHandler
extends ChannelInboundHandlerAdapter {
private static final ByteBuf HEARTBEAT_SEQUENCE =
Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(
"HEARTBEAT", CharsetUtil.ISO_8859_1));
@Override
public void userEventTriggered(ChannelHandlerContext ctx,
Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate())
.addListener(
ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
super.userEventTriggered(ctx, evt);
}
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
pipeline.addLast(new HeartbeatHandler());
| 238
| 58
| 296
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/LengthBasedInitializer.java
|
LengthBasedInitializer
|
initChannel
|
class LengthBasedInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public static final class FrameHandler
extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelRead0(ChannelHandlerContext ctx,
ByteBuf msg) throws Exception {
// Do something with the frame
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new LengthFieldBasedFrameDecoder(64 * 1024, 0, 8));
pipeline.addLast(new FrameHandler());
| 108
| 59
| 167
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/LineBasedHandlerInitializer.java
|
LineBasedHandlerInitializer
|
initChannel
|
class LineBasedHandlerInitializer extends ChannelInitializer<Channel>
{
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public static final class FrameHandler
extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelRead0(ChannelHandlerContext ctx,
ByteBuf msg) throws Exception {
// Do something with the data extracted from the frame
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(64 * 1024));
pipeline.addLast(new FrameHandler());
| 114
| 49
| 163
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/MarshallingInitializer.java
|
MarshallingInitializer
|
initChannel
|
class MarshallingInitializer extends ChannelInitializer<Channel> {
private final MarshallerProvider marshallerProvider;
private final UnmarshallerProvider unmarshallerProvider;
public MarshallingInitializer(
UnmarshallerProvider unmarshallerProvider,
MarshallerProvider marshallerProvider) {
this.marshallerProvider = marshallerProvider;
this.unmarshallerProvider = unmarshallerProvider;
}
@Override
protected void initChannel(Channel channel) throws Exception {<FILL_FUNCTION_BODY>}
public static final class ObjectHandler
extends SimpleChannelInboundHandler<Serializable> {
@Override
public void channelRead0(
ChannelHandlerContext channelHandlerContext,
Serializable serializable) throws Exception {
// Do something
}
}
}
|
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new MarshallingDecoder(unmarshallerProvider));
pipeline.addLast(new MarshallingEncoder(marshallerProvider));
pipeline.addLast(new ObjectHandler());
| 203
| 63
| 266
|
<no_super_class>
|
normanmaurer_netty-in-action
|
netty-in-action/chapter11/src/main/java/nia/chapter11/ProtoBufInitializer.java
|
ProtoBufInitializer
|
initChannel
|
class ProtoBufInitializer extends ChannelInitializer<Channel> {
private final MessageLite lite;
public ProtoBufInitializer(MessageLite lite) {
this.lite = lite;
}
@Override
protected void initChannel(Channel ch) throws Exception {<FILL_FUNCTION_BODY>}
public static final class ObjectHandler
extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg)
throws Exception {
// Do something with the object
}
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ProtobufVarint32FrameDecoder());
pipeline.addLast(new ProtobufEncoder());
pipeline.addLast(new ProtobufDecoder(lite));
pipeline.addLast(new ObjectHandler());
| 147
| 76
| 223
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.