diff --git a/gst-plugins-bad/gst/mpegpsmux/mpegpsmux_h264.c b/gst-plugins-bad/gst/mpegpsmux/mpegpsmux_h264.c
old mode 100644
new mode 100755
index 18de9cd4d5f0f6151ab7962523462ab06d45c988..2b1078bff54f4c8f9748244e9d086825bf72c55a
--- a/gst-plugins-bad/gst/mpegpsmux/mpegpsmux_h264.c
+++ b/gst-plugins-bad/gst/mpegpsmux/mpegpsmux_h264.c
@@ -97,12 +97,20 @@ mpegpsmux_prepare_h264 (GstBuffer * buf, MpegPsPadData * data, MpegPsMux * mux)
 {
   guint8 nal_length_size = 0;
   guint8 startcode[4] = { 0x00, 0x00, 0x00, 0x01 };
-  GstBuffer *out_buf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buf) * 2);
+  gint buf_len = 0;
+  GstBuffer *out_buf = NULL;
   gint offset = 4, i = 0, nb_sps = 0, nb_pps = 0;
   gsize out_offset = 0, in_offset = 0;
 
   GST_DEBUG_OBJECT (mux, "Preparing H264 buffer for output");
 
+  /*If PS header and system header are bigger than the size of the buffer,
+      that might cause a crash of the application.*/
+  buf_len = (GST_BUFFER_SIZE (buf) > PSMUX_MIN_PS_HDR_LEN) ?
+    (2 * GST_BUFFER_SIZE (buf)):
+    (GST_BUFFER_SIZE (buf) + PSMUX_MIN_PS_HDR_LEN + 1);
+  out_buf = gst_buffer_new_and_alloc (buf_len);
+
   /* We want the same metadata */
   gst_buffer_copy_metadata (out_buf, buf, GST_BUFFER_COPY_ALL);
 
diff --git a/gst-plugins-bad/gst/mpegpsmux/psmuxcommon.h b/gst-plugins-bad/gst/mpegpsmux/psmuxcommon.h
old mode 100644
new mode 100755
index 5c7cecb3427728c7d3f7aaacc7c5d35a2b9fce88..15019f25d0031443a6a38d16a795d65b3a3e30a3
--- a/gst-plugins-bad/gst/mpegpsmux/psmuxcommon.h
+++ b/gst-plugins-bad/gst/mpegpsmux/psmuxcommon.h
@@ -85,6 +85,7 @@ G_BEGIN_DECLS
 #define PSMUX_PROGRAM_END               0xb9
 
 #define PSMUX_MIN_ES_DESC_LEN 8
+#define PSMUX_MIN_PS_HDR_LEN 32
 
 /* Frequency for PCR representation */
 #define PSMUX_SYS_CLOCK_FREQ (27000000L)
