/*## (c) SECURITY EXPLORATIONS    2018 poland                                #*/
/*##     http://www.security-explorations.com                                #*/

/* THIS SOFTWARE IS PROTECTED BY DOMESTIC AND INTERNATIONAL COPYRIGHT LAWS    */
/* UNAUTHORISED COPYING OF THIS SOFTWARE IN EITHER SOURCE OR BINARY FORM IS   */
/* EXPRESSLY FORBIDDEN. ANY USE, INCLUDING THE REPRODUCTION, MODIFICATION,    */
/* DISTRIBUTION, TRANSMISSION, RE-PUBLICATION, STORAGE OR DISPLAY OF ANY      */
/* PART OF THE SOFTWARE, FOR COMMERCIAL OR ANY OTHER PURPOSES REQUIRES A      */
/* VALID LICENSE FROM THE COPYRIGHT HOLDER.                                   */

/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS    */
/* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,*/
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    */
/* SECURITY EXPLORATIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF  */
/* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE     */
/* SOFTWARE.                                                                  */

import java.lang.*;
import java.util.*;
import javax.tv.service.*;
import org.davic.mpeg.TransportStream;
import org.davic.net.dvb.*;

public class ECMFilter extends MPEGFilter {
 int channel;
 private byte data[];
 private Object syncobj;

 private ECMFilter(String name,int onid,int tsid,int pid,int channel) {
  super(name,onid,tsid,pid);
  this.channel=channel;
  data=null;
  syncobj=new Object();
 }

 public boolean match(byte data[]) {
  if (new_data(data)) return true;
   else return false;
 }

 public void action(byte data[]) {
  this.data=data;

  synchronized(syncobj) {
   syncobj.notify();
  }
 }

 public byte[] get_data() throws Throwable {
  synchronized(syncobj) {
   syncobj.wait();
  }

  return data;
 }
 
 public boolean stop() {
  boolean res=super.stop();

  this.data=null;

  synchronized(syncobj) {
   syncobj.notify();
  }

  return res;
 }

 public static ECMFilter create(int channel) {
  ECMFilter f=null;

  try {
   TransportStream ts=MPEGSniffer.current_ts();

   int tsid=ts.getTransportStreamId();

   Service srv=SrvUtils.srv_by_channel(channel);

   if (srv!=null) {
    int ca_pid=SrvUtils.get_ca_pid(srv);

    if (ca_pid>0) {
     DvbLocator dvblocator=(DvbLocator)srv.getLocator();

     int onid=dvblocator.getOriginalNetworkId();

     if (dvblocator.getTransportStreamId()==tsid) {
      String name="ECM Filter [\""+srv.getName()+"\",pid=0x"+Utils.hex_value(ca_pid,4)+"]";
      ApiMonitor.log(name);

      f=new ECMFilter(name,onid,tsid,ca_pid,channel);
     }
    }
   }
  } catch(Throwable t) {}

  return f;
 }

}
